This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.Methods.cs
654 lines (566 loc) · 23.6 KB
/
MainForm.Methods.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using System.Timers;
using YTLiveChatFilter.Common;
using YTLiveChatFilter.Extensions;
using YTLiveChatFilter.Models;
using YTLiveChatFilter.Properties;
namespace YTLiveChatFilter;
// 阻擋設計工具。
partial class DesignerBlocker { };
public partial class MainForm
{
/// <summary>
/// 自定義初始化
/// </summary>
private void CustomInit()
{
InitBanWords();
InitTimer();
InitControls();
}
/// <summary>
/// 初始化控制項
/// </summary>
private void InitControls()
{
LVersion.InvokeIfRequired(action: () =>
{
Version? version = Assembly.GetExecutingAssembly().GetName().Version;
string verText = version != null ? $"v{version}" : "無";
// 設定版本號顯示。
LVersion.Text = $"版本號:{verText}";
});
CBUseOAuth20.InvokeIfRequired(action: () =>
{
CBUseOAuth20.Checked = Settings.Default.UseOAuth20;
});
TBAPIKey.InvokeIfRequired(action: () =>
{
TBAPIKey.Text = Settings.Default.APIKey;
});
TBClientSecretFilePath.InvokeIfRequired(action: () =>
{
TBClientSecretFilePath.Text = Settings.Default.ClientSecretPath;
});
TBVideoID.InvokeIfRequired(action: () =>
{
TBVideoID.Select();
});
TBBanWords.InvokeIfRequired(action: () =>
{
TBBanWords.Text = Settings.Default.BanWords;
});
CBBanTemporary.InvokeIfRequired(action: () =>
{
CBBanTemporary.Checked = Settings.Default.BanTemporary;
});
CBBanPermanent.InvokeIfRequired(action: () =>
{
CBBanPermanent.Checked = Settings.Default.BanPermanent;
});
CBDeleteMessage.InvokeIfRequired(action: () =>
{
CBDeleteMessage.Checked = Settings.Default.DeleteMessage;
});
NUPBanDuration.InvokeIfRequired(action: () =>
{
NUPBanDuration.Value = Settings.Default.BanDuration;
});
TBSuspiciousChannelIds.InvokeIfRequired(action: () =>
{
TBSuspiciousChannelIds.ContextMenuStrip = CustomFunction.GetContextMenuStrip(
text: Text,
suspiciousChannels: SuspiciousChannels,
appIcon: Resources.app_icon,
TBSuspiciousChannelIds: TBSuspiciousChannelIds,
TBLog: TBLog);
});
SetControlState(enable: true);
}
/// <summary>
/// 初始化 banWords
/// </summary>
private void InitBanWords()
{
TBBanWords.InvokeIfRequired(action: () =>
{
if (string.IsNullOrEmpty(value: Settings.Default.BanWords))
{
string value = Settings.Default.DefaultBanWords;
string[] defaultDeniedWords = value.Split(
separator: new char[] { ',' },
options: StringSplitOptions.RemoveEmptyEntries);
TBBanWords.Text = string.Join(
separator: Environment.NewLine,
value: defaultDeniedWords);
CustomFunction.WriteLog(
control: TBLog,
message: "已從設定檔案內載入預設的封鎖的字詞。");
}
});
}
/// <summary>
/// 初始化 SharedTimer
/// </summary>
private void InitTimer()
{
SharedTimer.Elapsed += async (object? sender, ElapsedEventArgs e) =>
{
try
{
if (SharedYouTubeService != null)
{
bool banTemporary = false,
banPermanent = false,
deleteMessage = false,
useOAuth20 = false;
int banDuration = 300;
CBUseOAuth20.InvokeIfRequired(action: () =>
{
useOAuth20 = CBUseOAuth20.Checked;
});
CBBanTemporary.InvokeIfRequired(action: () =>
{
banTemporary = CBBanTemporary.Checked;
});
CBBanPermanent.InvokeIfRequired(action: () =>
{
banPermanent = CBBanPermanent.Checked;
});
CBDeleteMessage.InvokeIfRequired(action: () =>
{
deleteMessage = CBDeleteMessage.Checked;
});
NUPBanDuration.InvokeIfRequired(action: () =>
{
banDuration = Convert.ToInt32(value: NUPBanDuration.Value);
});
LiveChatMessagesResp response = await YTLiveChatUtil.GetLiveChatMessagesResp(
youTubeService: SharedYouTubeService,
liveChatId: SharedLiveChatID,
pageToken: SharedNextPageToken,
control: TBLog);
SharedNextPageToken = response.NextPageToken;
SharedPollingIntervalMillis = Convert.ToDouble(value: response.PollingIntervalMillis);
CustomFunction.WriteLog(
control: TBLog,
message: $"在 {SharedPollingIntervalMillis} 毫秒後進行下一次資料抓取。");
FilterMessages(
items: response.Items,
deleteMessage: deleteMessage,
banTemporary: banTemporary,
banPermanent: banPermanent,
banDuration: banDuration,
useOAuth20: useOAuth20);
if (!string.IsNullOrEmpty(value: SharedNextPageToken))
{
SharedTimer.Interval = Convert.ToDouble(value: response.PollingIntervalMillis);
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "SharedNextPageToken 為空值,停止作業。");
BtnStop_Click(sender: null, e: null);
}
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "SharedYTSvc 為 null,停止作業。");
BtnStop_Click(sender: null, e: null);
}
}
catch (Exception ex)
{
CustomFunction.WriteLog(
control: TBLog,
message: ex.Message);
BtnStop_Click(sender: null, e: null);
}
};
}
/// <summary>
/// 取得第一個
/// </summary>
/// <param name="apiKey">字串,金鑰</param>
/// <param name="clientSecretFilePath">字串,client_secret.json 檔案的路徑</param>
/// <param name="videoId">字串,影片的 ID</param>
/// <param name="deleteMessage">布林值,是否刪除訊息</param>
/// <param name="banTemporary">布林值,是否暫時停用</param>
/// <param name="banPermanent">布林值,是否永久封鎖</param>
/// <param name="banDuration">數值,封鎖秒數</param>
/// <param name="useOAuth20">布林值,是否使用 OAuth 2.0 用戶端 ID</param>
/// <returns>Task</returns>
private async Task GetFirstLiveChatMessagesResp(
string apiKey,
string clientSecretFilePath,
string videoId,
bool deleteMessage,
bool banTemporary,
bool banPermanent,
int banDuration,
bool useOAuth20)
{
SharedYouTubeService = await YTLiveChatUtil.GetYouTubeService(
appName: Settings.Default.AppName,
apiKey: apiKey,
clientSecretFilePath: clientSecretFilePath,
useOAuth20: useOAuth20);
SharedLiveChatID = await YTLiveChatUtil.GetLiveChatID(
youTubeService: SharedYouTubeService,
videoId: videoId,
control: TBLog);
if (!string.IsNullOrEmpty(value: SharedLiveChatID))
{
LiveChatMessagesResp response = await YTLiveChatUtil.GetLiveChatMessagesResp(
youTubeService: SharedYouTubeService,
liveChatId: SharedLiveChatID,
pageToken: string.Empty,
control: TBLog);
SharedNextPageToken = response.NextPageToken;
SharedPollingIntervalMillis = Convert.ToDouble(value: response.PollingIntervalMillis);
CustomFunction.WriteLog(
control: TBLog,
message: $"在 {SharedPollingIntervalMillis} 毫秒後進行下一次資料抓取。");
FilterMessages(
items: response.Items,
deleteMessage: deleteMessage,
banTemporary: banTemporary,
banPermanent: banPermanent,
banDuration: banDuration,
useOAuth20: useOAuth20);
if (!string.IsNullOrEmpty(value: SharedNextPageToken))
{
SharedTimer.Interval = SharedPollingIntervalMillis;
SharedTimer.Start();
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "SharedNextPageToken 為空值,停止作業。");
BtnStop_Click(sender: null, e: null);
}
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "該直播已結束。");
BtnStop_Click(sender: null, e: null);
}
}
/// <summary>
/// 過濾訊息
/// </summary>
/// <param name="items">IList<LiveChatMessage>?</param>
/// <param name="deleteMessage">布林值,是否刪除訊息</param>
/// <param name="banTemporary">布林值,是否暫時停用</param>
/// <param name="banPermanent">布林值,是否永久封鎖</param>
/// <param name="banDuration">數值,封鎖秒數</param>
/// <param name="useOAuth20">布林值,是否使用 OAuth 2.0 用戶端 ID</param>
private async void FilterMessages(
IList<LiveChatMessage>? items,
bool deleteMessage,
bool banTemporary,
bool banPermanent,
int banDuration,
bool useOAuth20)
{
if (items != null)
{
// 使用頻道 ID 進行 Grouping。
IEnumerable<IGrouping<string, LiveChatMessage>> groupedDataSet =
items.GroupBy(keySelector: n => n.AuthorDetails.ChannelId);
// 逐個組合處理。
foreach (IGrouping<string, LiveChatMessage> dataSet in groupedDataSet)
{
// 逐筆訊息處理。
foreach (LiveChatMessage data in dataSet)
{
bool isDetected = false;
string logTemplate = Environment.NewLine +
$"---{Environment.NewLine}" +
$"頻道網址:{{0}}{Environment.NewLine}" +
$"頻道 ID:{{1}}{Environment.NewLine}" +
$"使用者:{{2}}{Environment.NewLine}" +
$"訊息 ID:{{3}}{Environment.NewLine}" +
$"訊息內容:{{4}}{Environment.NewLine}" +
$"---";
string channelId = data.AuthorDetails.ChannelId;
string originAuthorName = data.AuthorDetails.DisplayName;
string authorName = data.AuthorDetails.DisplayName.ToLowerInvariant();
string messageId = data.Id;
string originMessage = data.Snippet.DisplayMessage;
string message = data.Snippet.DisplayMessage.ToLowerInvariant();
string log = string.Format(
format: logTemplate,
args: new[] {
$"https://www.youtube.com/channel/{channelId}",
channelId,
originAuthorName,
messageId,
originMessage
});
// 檢查使用者的名稱。
isDetected = CustomFunction.CheckBanWords(
control: TBLog,
key: dataSet.Key,
channelId: channelId,
originAuthorName: originAuthorName,
value: authorName,
banWords: BanWords,
log: log,
suspiciousChannelIds: SuspiciousChannelIds,
suspiciousChannels: SuspiciousChannels,
action: () =>
{
UpdateTBSuspiciousChannelIds();
},
isAuthor: true);
// 當 isDetected 為 false 時才執行。
if (!isDetected)
{
// 檢查訊息的內容。
isDetected = CustomFunction.CheckBanWords(
control: TBLog,
key: dataSet.Key,
channelId: channelId,
originAuthorName: originAuthorName,
value: message,
banWords: BanWords,
log: log,
suspiciousChannelIds: SuspiciousChannelIds,
suspiciousChannels: SuspiciousChannels,
action: () =>
{
UpdateTBSuspiciousChannelIds();
},
isAuthor: false);
}
if (isDetected)
{
if (useOAuth20)
{
try
{
bool isChatOwner = data.AuthorDetails.IsChatOwner ?? false;
bool isChatModerator = data.AuthorDetails.IsChatModerator ?? false;
_ = data.AuthorDetails.IsChatSponsor ?? false;
_ = data.AuthorDetails.IsVerified ?? false;
// 針對「擁有者」以及「管理員」不進行過濾。
if (!isChatOwner && !isChatModerator)
{
// 刪除訊息。
if (deleteMessage)
{
// 會回傳空值。
_ = await YTLiveChatUtil.DeleteMessage(
youTubeService: SharedYouTubeService,
messageId: messageId,
control: TBLog);
CustomFunction.WriteLog(
control: TBLog,
message: $"已刪除含有封鎖的字詞的訊息。(訊息 ID:{messageId})");
}
// 封鎖使用者。
if (banTemporary || banPermanent)
{
LiveChatBan liveChatBan = YTLiveChatUtil.CreatLiveChatBan(
liveChatId: SharedLiveChatID,
channelId: channelId,
banPermanent: banPermanent,
banDuration: banDuration);
LiveChatBan? banResult = await YTLiveChatUtil.BanUser(
youTubeService: SharedYouTubeService,
liveChatBan: liveChatBan,
control: TBLog);
// 不會含有 "BanDurationSeconds"。
if (banResult != null)
{
string banType = banPermanent ? "加入至隱藏的使用者" : "暫時停用";
string banDurationStr = banPermanent ? "" : $" {banDuration} 秒";
string channel = $"{banResult.Snippet.BannedUserDetails.DisplayName}" +
$"({banResult.Snippet.BannedUserDetails.ChannelId})";
string resultLog = $"已將使用者 {channel} {banType}{banDurationStr}";
CustomFunction.WriteLog(
control: TBLog,
message: resultLog);
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "YTLiveChatUtil.BanUser() 回傳的 banResult 是 null。");
}
}
}
else
{
string role = "無關人員";
if (isChatModerator)
{
role = "管理員";
}
if (isChatOwner)
{
role = "擁有者";
}
string msgHasSpecialRole = $"頻道「{originAuthorName}({channelId})」" +
$"是此頻道的「{role}」,故忽略不進行後續的處理。";
CustomFunction.WriteLog(
control: TBLog,
message: msgHasSpecialRole);
}
}
catch (Exception ex)
{
CustomFunction.WriteLog(
control: TBLog,
message: ex.Message);
}
}
else
{
string msgNotUseOAtuth = "因為您使用「API 金鑰」," +
"所以只會將頻道的 ID 加入至可疑的頻道 ID 清單內。";
CustomFunction.WriteLog(
control: TBLog,
message: msgNotUseOAtuth);
}
break;
}
}
}
}
else
{
CustomFunction.WriteLog(
control: TBLog,
message: "傳入 FilterMessages() 的 items 是 null。");
}
}
/// <summary>
/// 更新 TBSuspiciousChannelIds
/// </summary>
private void UpdateTBSuspiciousChannelIds()
{
TBSuspiciousChannelIds.InvokeIfRequired(action: () =>
{
TBSuspiciousChannelIds.Text = string.Join(
separator: Environment.NewLine,
values: SuspiciousChannelIds);
});
}
/// <summary>
/// 設定控制項的狀態
/// </summary>
/// <param name="enable">布林值,啟用,預設值為 true</param>
private void SetControlState(bool enable = true)
{
TBClientSecretFilePath.InvokeIfRequired(action: () =>
{
TBClientSecretFilePath.Enabled = enable;
});
bool useOAuth20 = false;
CBUseOAuth20.InvokeIfRequired(action: () =>
{
CBUseOAuth20.Enabled = enable;
useOAuth20 = CBUseOAuth20.Checked;
});
TBAPIKey.InvokeIfRequired(action: () =>
{
TBAPIKey.Enabled = !useOAuth20;
});
TBClientSecretFilePath.InvokeIfRequired(action: () =>
{
TBClientSecretFilePath.Enabled = enable && useOAuth20;
});
BtnSelectClientSecretFile.InvokeIfRequired(action: () =>
{
BtnSelectClientSecretFile.Enabled = enable && useOAuth20;
});
CBBanTemporary.InvokeIfRequired(action: () =>
{
CBBanTemporary.Enabled = useOAuth20;
});
CBBanPermanent.InvokeIfRequired(action: () =>
{
CBBanPermanent.Enabled = useOAuth20;
});
CBDeleteMessage.InvokeIfRequired(action: () =>
{
CBDeleteMessage.Enabled = useOAuth20;
});
NUPBanDuration.InvokeIfRequired(action: () =>
{
NUPBanDuration.Enabled = useOAuth20;
});
TBVideoID.InvokeIfRequired(action: () =>
{
TBVideoID.Enabled = enable;
});
BtnStart.InvokeIfRequired(action: () =>
{
BtnStart.Enabled = enable;
});
BtnStop.InvokeIfRequired(action: () =>
{
BtnStop.Enabled = !enable;
});
BtnClear.InvokeIfRequired(action: () =>
{
BtnClear.Enabled = enable;
});
}
/// <summary>
/// 清除變數
/// </summary>
private void ResetVariables()
{
SharedLiveChatID = string.Empty;
SharedNextPageToken = string.Empty;
SharedPollingIntervalMillis = 0.0;
SharedYouTubeService = null;
SharedCancellationToken = null;
}
/// <summary>
/// 檢查應用程式的版本
/// </summary>
private async void CheckAppVersion()
{
using HttpClient httpClient = SharedHttpClientFactory.CreateClient();
UpdateNotifier.CheckResult checkResult = await UpdateNotifier.CheckVersion(httpClient);
if (!string.IsNullOrEmpty(checkResult.MessageText))
{
CustomFunction.WriteLog(TBLog, checkResult.MessageText);
}
if (checkResult.HasNewVersion &&
!string.IsNullOrEmpty(checkResult.DownloadUrl))
{
DialogResult dialogResult = MessageBox.Show($"您是否要下載新版本 v{checkResult.VersionText}?",
Text,
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question);
if (dialogResult == DialogResult.OK)
{
CustomFunction.OpenBrowser(checkResult.DownloadUrl);
}
}
if (checkResult.NetVersionIsOdler &&
!string.IsNullOrEmpty(checkResult.DownloadUrl))
{
DialogResult dialogResult = MessageBox.Show($"您是否要下載舊版本 v{checkResult.VersionText}?",
Text,
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question);
if (dialogResult == DialogResult.OK)
{
CustomFunction.OpenBrowser(checkResult.DownloadUrl);
}
}
}
}