-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
1710 lines (1648 loc) · 101 KB
/
Program.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using dwango.nicolive.chat.service.edge;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace jkcnsl
{
class Program
{
const string UserAgent = "Mozilla/5.0";
static readonly string DeviceName = "Console (" +
(OperatingSystem.IsWindows() ? "Windows" :
OperatingSystem.IsMacOS() ? "Mac" :
OperatingSystem.IsLinux() ? "Linux" : "Unknown") + ")";
const int LoginAttemptIntervalSec = 3600;
const int MaxAcceptableWebSocketPayloadSize = 32768;
const int MaxAcceptableProtoBufChunkSize = 1048576;
const int HttpGetTimeoutSec = 8;
const int WebSocketTimeoutSec = 15;
const int MixedStreamReconnectionSec = 20;
// HttpClientは使いまわす。クッキーは共有しない
static HttpClient _httpClientInstance;
static HttpClient HttpClientInstance
{
get
{
if (_httpClientInstance == null)
{
_httpClientInstance = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.All,
UseCookies = false
}) { Timeout = TimeSpan.FromSeconds(HttpGetTimeoutSec) };
}
return _httpClientInstance;
}
}
// .nicovideo.jpのメッセージサーバ専用
static HttpClient _nicovideoClientInstance;
static HttpClient NicovideoClientInstance
{
get
{
if (_nicovideoClientInstance == null)
{
_nicovideoClientInstance = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.All,
UseCookies = false
});
}
return _nicovideoClientInstance;
}
}
static readonly BlockingCollection<string> ResponseLines = new BlockingCollection<string>();
static bool _nicovideoLoginChecked = false;
class StreamMixingInfo
{
public bool dropForwardedChat;
public bool ignoreUnspecifiedDestinationPost;
public TimeSpan nicovideoServerUnixTime = TimeSpan.Zero;
public int nicovideoServerUnixTimeTick;
public TimeSpan refugeServerUnixTime = TimeSpan.Zero;
public int refugeServerUnixTimeTick;
}
static void Main(string[] args)
{
Process parentProcess;
if (args.Length == 2 && args[0] == "-p")
{
// 親プロセスの不正終了を監視する
try
{
parentProcess = Process.GetProcessById(int.Parse(args[1]));
parentProcess.EnableRaisingEvents = true;
parentProcess.Exited += (sender, e) =>
{
// 非常時なので雑に落とす
Trace.WriteLine("Parent process exited!");
Environment.Exit(1);
};
}
catch (Exception e)
{
Trace.WriteLine(e.ToString());
}
}
else if (args.Length != 0)
{
Trace.WriteLine("Invalid argument!");
return;
}
Console.InputEncoding = Encoding.UTF8;
Console.OutputEncoding = Encoding.UTF8;
var commands = new BlockingCollection<string>();
var quitCts = new CancellationTokenSource();
Task processTask = Task.Run(async () =>
{
try
{
// 標準入力の各行の先頭文字を命令、それ以外を引数とするコマンドを処理し、結果を標準出力する
// 汎用のコマンド:
// '+' 処理中のコマンドに入力を与える。処理中でなければ何もしない
// 'c' 処理中のコマンドを終了させる。処理中でなければ何もしない
// 結果:
// '-' 出力
// '.' 処理が終了した
// '!' 処理が異常終了した
// '?' 不明なコマンドだった
foreach (string comm in commands.GetConsumingEnumerable(quitCts.Token))
{
quitCts.Token.ThrowIfCancellationRequested();
switch (comm.FirstOrDefault())
{
case 'A':
if (comm == "Ai")
{
await NicovideoLoginAsync(commands, quitCts.Token);
}
else if (comm == "Ao")
{
await NicovideoLogoutAsync(quitCts.Token);
}
else
{
ResponseLines.Add("!");
}
break;
case 'G':
{
string[] arg = comm.Substring(1).Split(new char[] { ' ' }, 2);
await GetHttpGetStringAsync(arg[0], arg.Length >= 2 ? arg[1] : "", quitCts.Token);
}
break;
case 'L':
{
string[] arg = comm.Substring(1).Split(new char[] { ' ' }, 2);
ResponseLines.Add(await GetNicovideoStreamAsync(arg[0], arg.Length >= 2 ? arg[1] : "", commands, new StreamMixingInfo(), quitCts.Token));
}
break;
case 'R':
{
string[] arg = comm.Substring(1).Split(new char[] { ' ' }, 4);
// 避難所の種類によって解釈を変える。現在は"R1""R2"のみ
if (arg.Length < 2 || (arg[0] != "1" && arg[0] != "2"))
{
ResponseLines.Add("!");
break;
}
if (arg[0] == "2" && arg.Length >= 3)
{
// 混合
await GetNicovideoRefugeMixedStreamAsync(arg[1], arg[2], arg.Length >= 4 ? arg[3] : "", commands, quitCts.Token);
break;
}
// 避難所のみ。"R2"のときは混合時と同様に転送されたコメントを捨てる
ResponseLines.Add(await GetRefugeStreamAsync(arg[1], commands, new StreamMixingInfo { dropForwardedChat = arg[0] == "2" }, quitCts.Token));
}
break;
case 'S':
{
string[] arg = comm.Substring(1).Split(new char[] { ' ' }, 2);
if (arg.Length < 2)
{
if (arg[0] == "nicovideo_cookie")
{
// クッキーを削除
_nicovideoLoginChecked = false;
Settings.Instance.nicovideo_cookie = null;
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "nicovideo_mfa_cookie")
{
_nicovideoLoginChecked = false;
Settings.Instance.nicovideo_mfa_cookie = null;
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "mail")
{
// 設定を削除
Settings.Instance.nicovideo_cookie = null;
Settings.Instance.nicovideo_mfa_cookie = null;
Settings.Instance.mail = null;
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "password")
{
Settings.Instance.nicovideo_cookie = null;
Settings.Instance.nicovideo_mfa_cookie = null;
Settings.Instance.password = null;
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "useragent")
{
Settings.Instance.useragent = null;
}
else if (arg[0] == "device_name")
{
Settings.Instance.device_name = null;
}
else if (arg[0].Length == 0)
{
// すべての設定を出力
if (Settings.Instance.nicovideo_cookie != null)
{
ResponseLines.Add("-nicovideo_cookie " + Settings.Instance.nicovideo_cookie);
}
if (Settings.Instance.nicovideo_mfa_cookie != null)
{
ResponseLines.Add("-nicovideo_mfa_cookie " + Settings.Instance.nicovideo_mfa_cookie);
}
if (Settings.Instance.mail != null)
{
ResponseLines.Add("-mail " + Settings.Instance.mail);
}
if (Settings.Instance.password != null)
{
// 3文字だけ表示
string maskedPassword = Settings.Instance.password;
if (maskedPassword.Length > 3)
{
maskedPassword = maskedPassword.Substring(0, 3) + new string('*', maskedPassword.Length - 3);
}
ResponseLines.Add("-password " + maskedPassword);
}
ResponseLines.Add("-useragent " + (Settings.Instance.useragent ?? UserAgent));
ResponseLines.Add("-device_name " + (Settings.Instance.device_name ?? DeviceName));
ResponseLines.Add("-trust_device " + (Settings.Instance.distrust_device ? "false" : "true"));
ResponseLines.Add("-last_login_attempt " + Settings.Instance.last_login_attempt);
ResponseLines.Add(".");
break;
}
else
{
ResponseLines.Add("!");
break;
}
}
else
{
// 設定を変更
if (arg[0] == "mail")
{
_nicovideoLoginChecked = false;
Settings.Instance.nicovideo_cookie = null;
Settings.Instance.nicovideo_mfa_cookie = null;
Settings.Instance.mail = arg[1];
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "password")
{
_nicovideoLoginChecked = false;
Settings.Instance.nicovideo_cookie = null;
Settings.Instance.nicovideo_mfa_cookie = null;
Settings.Instance.password = arg[1];
Settings.Instance.last_login_attempt = 0;
}
else if (arg[0] == "useragent")
{
Settings.Instance.useragent = arg[1];
}
else if (arg[0] == "device_name")
{
Settings.Instance.device_name = arg[1];
}
else if (arg[0] == "trust_device")
{
Settings.Instance.distrust_device = arg[1] != "true";
}
else
{
ResponseLines.Add("!");
break;
}
}
Settings.Instance.Save();
ResponseLines.Add(".");
}
break;
case '+':
case 'c':
break;
default:
ResponseLines.Add("?");
break;
}
}
}
catch { }
});
// 確実に終了するため標準出力は別スレッド
Task writeTask = Task.Run(() =>
{
try
{
foreach (string response in ResponseLines.GetConsumingEnumerable(quitCts.Token))
{
quitCts.Token.ThrowIfCancellationRequested();
Console.WriteLine(response);
}
}
catch { }
});
// 標準入力はブロックさせずに読み続ける
for (; ; )
{
string comm = Console.ReadLine();
if (comm == null || comm.FirstOrDefault() == 'q')
{
Trace.WriteLine("Quit");
// 終了
break;
}
commands.Add(comm);
}
quitCts.Cancel();
// すこし待つ
Task.WaitAll(new Task[] { processTask, writeTask }, TimeSpan.FromSeconds(8));
}
/// <summary>汎用のHTTP-GET</summary>
static async Task GetHttpGetStringAsync(string uri, string cookie, CancellationToken ct)
{
string ret;
try
{
ret = await HttpClientGetStringAsync(uri, cookie, ct);
}
catch
{
ct.ThrowIfCancellationRequested();
ResponseLines.Add("!");
return;
}
foreach (string r in ret.Replace("\r", "").Split('\n'))
{
ResponseLines.Add("-" + r);
}
ResponseLines.Add(".");
}
/// <summary>実況ストリーム(混合)</summary>
static async Task GetNicovideoRefugeMixedStreamAsync(string webSocketUrl, string lvId, string nicovideoCookie, BlockingCollection<string> commands, CancellationToken ct)
{
bool closing = false;
var nicovideoCommands = new BlockingCollection<string>();
var refugeCommands = new BlockingCollection<string>();
var pollingAsync = async () =>
{
while (!closing)
{
// 入力を複写して転送
string comm;
while (commands.TryTake(out comm))
{
closing = closing || comm.FirstOrDefault() == 'c';
nicovideoCommands.Add(comm);
refugeCommands.Add(comm);
}
await Task.Delay(100, ct);
}
};
var mixingInfo = new StreamMixingInfo
{
dropForwardedChat = true,
ignoreUnspecifiedDestinationPost = true
};
bool nicovideoConnected = false;
bool nicovideoInitialized = false;
bool refugeConnected = false;
bool refugeInitialized = false;
var nicovideoAsync = async () =>
{
// 入力の指示により閉じられるか両方未接続になるまで
do
{
nicovideoConnected = true;
nicovideoInitialized = true;
bool failed = await GetNicovideoStreamAsync(lvId, nicovideoCookie, nicovideoCommands, mixingInfo, ct) != ".";
nicovideoConnected = false;
// 適当なタグをでっちあげて切断を通知
ResponseLines.Add("-<x_disconnect status=\"" + (failed ? 1 : 0) + "\" />");
for (int wait = MixedStreamReconnectionSec * 5; !closing && (!refugeInitialized || refugeConnected) && wait > 0; wait--)
{
await Task.Delay(200, ct);
// 入力を捨てる
string comm;
while (nicovideoCommands.TryTake(out comm)) { }
}
}
while (!closing && (!refugeInitialized || refugeConnected));
closing = true;
};
var refugeAsync = async () =>
{
// 入力の指示により閉じられるか両方未接続になるまで
do
{
refugeConnected = true;
refugeInitialized = true;
bool failed = await GetRefugeStreamAsync(webSocketUrl, refugeCommands, mixingInfo, ct) != ".";
refugeConnected = false;
// 適当なタグをでっちあげて切断を通知
ResponseLines.Add("-<x_disconnect status=\"" + (failed ? 1 : 0) + "\" refuge=\"1\" />");
for (int wait = MixedStreamReconnectionSec * 5; !closing && (!nicovideoInitialized || nicovideoConnected) && wait > 0; wait--)
{
await Task.Delay(200, ct);
// 入力を捨てる
string comm;
while (refugeCommands.TryTake(out comm)) { }
}
}
while (!closing && (!nicovideoInitialized || nicovideoConnected));
closing = true;
};
await Task.WhenAll(new Task[] { pollingAsync(), nicovideoAsync(), refugeAsync() });
ResponseLines.Add(".");
}
/// <summary>実況ストリーム(.nicovideo.jp)</summary>
static async Task<string> GetNicovideoStreamAsync(string lvId, string cookie, BlockingCollection<string> commands, StreamMixingInfo mixingInfo, CancellationToken ct)
{
string webSocketUrl = null;
WatchEmbeddedUser embeddedUser = null;
if (Regex.IsMatch(lvId, "^(?:ch|co|lv)[0-9]+$"))
{
// 視聴セッション情報を取得
try
{
// ログイン情報が設定されているときcookie引数は使わない
cookie = await GetNicovideoLoginCookieAsync(null, ct) ?? cookie;
string ret = await HttpClientGetStringAsync("https://live.nicovideo.jp/watch/" + lvId, cookie, ct);
Match match = Regex.Match(ret, "<script(?= )([^>]*? id=\"embedded-data\"[^>]*)>");
if (match.Success)
{
match = Regex.Match(match.Groups[1].Value, " data-props=\"([^\"]*)\"");
if (match.Success)
{
var js = new DataContractJsonSerializerWrapper<WatchEmbedded>();
WatchEmbedded embedded = js.ReadValue(Encoding.UTF8.GetBytes(HttpUtility.HtmlDecode(match.Groups[1].Value)));
// 一応ドメインを検査しておく(スクレイピングなので。また、cookieを送信するため)
if (embedded.site != null && embedded.site.relive != null &&
Regex.IsMatch(embedded.site.relive.webSocketUrl ?? "", @"^wss://[0-9A-Za-z.-]+\.nicovideo\.jp/"))
{
webSocketUrl = embedded.site.relive.webSocketUrl;
embeddedUser = embedded.user;
}
}
}
}
catch (Exception e)
{
ct.ThrowIfCancellationRequested();
Trace.WriteLine(e.ToString());
}
}
if (webSocketUrl == null)
{
return "!";
}
using (var watchSession = new ClientWebSocket())
using (var msEntry = new MemoryStream())
using (var msSegment = new MemoryStream())
using (var msPrefetch = new MemoryStream())
using (var closeCts = new CancellationTokenSource())
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, closeCts.Token))
{
Task pollingTask = null;
Task<WebSocketReceiveResult> watchRecvTask = null;
Task entryTask = null;
Task segmentTask = null;
Task prefetchTask = null;
Stream entryStream = null;
Stream segmentStream = null;
Stream prefetchStream = null;
HttpClient client = null;
bool clientIsSameSite = false;
try
{
// Frameworkはここで例外になる("error"が返るのでUAは必須)
watchSession.Options.SetRequestHeader("User-Agent", Settings.Instance.useragent ?? UserAgent);
watchSession.Options.SetRequestHeader("Accept", "*/*");
// 視聴ページから接続するようなコンテキスト
watchSession.Options.SetRequestHeader("Cache-Control", "no-cache");
watchSession.Options.SetRequestHeader("Origin", "https://live.nicovideo.jp");
watchSession.Options.SetRequestHeader("Sec-Fetch-Dest", "empty");
watchSession.Options.SetRequestHeader("Sec-Fetch-Mode", "websocket");
watchSession.Options.SetRequestHeader("Sec-Fetch-Site", "same-site");
if (cookie.Length > 0)
{
watchSession.Options.SetRequestHeader("Cookie", cookie);
}
// 視聴セッションに接続
await DoWebSocketAction(async ct => await watchSession.ConnectAsync(new Uri(webSocketUrl), ct), ct);
await DoWebSocketAction(async ct => await watchSession.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(
"{\"type\":\"startWatching\",\"data\":{\"reconnect\":false}}")),
WebSocketMessageType.Text, true, ct), ct);
string viewUri = null;
var vposBaseUnixTime = TimeSpan.Zero;
string hashedUserId = null;
int keepSeatIntervalSec = 0;
int keepSeatTick = 0;
var readEntryBuf = new byte[512];
var readSegmentBuf = new byte[512];
var readPrefetchBuf = new byte[512];
var watchBuf = new byte[MaxAcceptableWebSocketPayloadSize];
int watchCount = 0;
var serverUnixTime = TimeSpan.Zero;
int serverUnixTimeTick = 0;
bool wroteFirstChat = false;
bool wroteLiveChat = false;
var jsWatchSessionPost = new DataContractJsonSerializerWrapper<WatchSessionPost>();
var jsWatchSessionResult = new DataContractJsonSerializerWrapper<WatchSessionResult>();
var jsWatchSessionResultForError = new DataContractJsonSerializerWrapper<WatchSessionResultForError>();
var jsWatchSessionResultForMessageServer = new DataContractJsonSerializerWrapper<WatchSessionResultForMessageServer>();
var jsWatchSessionResultForSeat = new DataContractJsonSerializerWrapper<WatchSessionResultForSeat>();
var jsWatchSessionResultForServerTime = new DataContractJsonSerializerWrapper<WatchSessionResultForServerTime>();
string nextAt = "now";
bool closed = false;
while (!closed && (viewUri == null || entryTask != null || nextAt != null))
{
var gracefulClose = async () =>
{
if (!closed)
{
await DoWebSocketAction(async ct => await watchSession.CloseAsync(WebSocketCloseStatus.NormalClosure, "", ct), ct);
closed = true;
}
};
bool watchReceived = false;
ChunkedMessage chunkedMessage = null;
{
ct.ThrowIfCancellationRequested();
int keepSeatElapsed = ((Environment.TickCount & int.MaxValue) - keepSeatTick) & int.MaxValue;
if (keepSeatIntervalSec > 0 && keepSeatElapsed > keepSeatIntervalSec * 1000)
{
// 座席を維持
Trace.WriteLine("keepSeat");
await DoWebSocketAction(async ct => await watchSession.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(
"{\"type\":\"keepSeat\"}")), WebSocketMessageType.Text, true, ct), ct);
keepSeatTick = Environment.TickCount & int.MaxValue;
}
pollingTask = pollingTask ?? Task.Delay(200, linkedCts.Token);
watchRecvTask = watchRecvTask ?? watchSession.ReceiveAsync(new ArraySegment<byte>(watchBuf, watchCount, watchBuf.Length - watchCount), linkedCts.Token);
if (entryTask == null && viewUri != null)
{
if (client == null)
{
client = NicovideoClientInstance;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.useragent ?? UserAgent);
client.DefaultRequestHeaders.Add("Accept", "*/*");
// 視聴ページからフェッチするようなコンテキスト。おそらくCDN送りになるのでプライベートな情報はつけない
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
client.DefaultRequestHeaders.Add("Origin", "https://live.nicovideo.jp");
client.DefaultRequestHeaders.Add("Referer", "https://live.nicovideo.jp/");
client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");
client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
clientIsSameSite = Regex.IsMatch(viewUri, @"^https://[0-9A-Za-z.-]+\.nicovideo\.jp/");
client.DefaultRequestHeaders.Add("Sec-Fetch-Site", clientIsSameSite ? "same-site" : "cross-site");
}
// プレイリスト接続開始
entryTask = client.GetStreamAsync(viewUri + "?at=" + nextAt, linkedCts.Token);
nextAt = null;
}
Task completedTask = await Task.WhenAny((new Task[] { pollingTask, watchRecvTask, entryTask, segmentTask, prefetchTask }).Where(a => a != null));
if (completedTask == pollingTask)
{
// 定期的に入力をチェック
await pollingTask;
pollingTask = null;
string comm;
while (commands.TryTake(out comm))
{
if (comm.FirstOrDefault() == 'c')
{
// 閉じる
await gracefulClose();
break;
}
string dest_, color_, font_, position_, size_, text_;
bool isAnonymous_;
if (comm.FirstOrDefault() == '+' &&
ParsePostComment(comm.Substring(1), out dest_, out color_, out font_, out isAnonymous_, out position_, out size_, out text_) &&
(dest_ == "nico" || !mixingInfo.ignoreUnspecifiedDestinationPost))
{
// コメント投稿
if ((dest_ == "nico" || dest_ == null) && vposBaseUnixTime > TimeSpan.Zero && serverUnixTime >= vposBaseUnixTime)
{
// vposは10msec単位。内部時計のずれに影響されないようにサーバ時刻を基準に補正
int vpos = (int)(serverUnixTime - vposBaseUnixTime).TotalSeconds * 100 + (((Environment.TickCount & int.MaxValue) - serverUnixTimeTick) & int.MaxValue) / 10;
var ms = new MemoryStream();
jsWatchSessionPost.WriteValue(ms, new WatchSessionPost()
{
data = new WatchSessionPostData()
{
color = color_,
font = font_,
isAnonymous = isAnonymous_,
position = position_,
size = size_,
text = text_,
vpos = vpos
},
type = "postComment"
});
byte[] post = ms.ToArray();
Trace.WriteLine(Encoding.UTF8.GetString(post));
await DoWebSocketAction(async ct => await watchSession.SendAsync(new ArraySegment<byte>(post), WebSocketMessageType.Text, true, ct), ct);
}
else
{
// 投稿拒否
ResponseLines.Add("-<chat_result status=\"1\" />");
}
}
}
}
else if (completedTask == watchRecvTask)
{
WebSocketReceiveResult ret = await watchRecvTask;
watchRecvTask = null;
if (ret.MessageType != WebSocketMessageType.Text || watchCount + ret.Count >= watchBuf.Length)
{
// 終了または処理できないフレーム。閉じる
await gracefulClose();
}
else
{
watchCount += ret.Count;
watchReceived = ret.EndOfMessage;
}
}
else if (completedTask == entryTask)
{
if (entryStream == null)
{
// プレイリスト接続完了
entryStream = await (Task<Stream>)entryTask;
entryTask = ReadProtoBufChunkAsync(entryStream, msEntry, readEntryBuf, linkedCts.Token);
}
else
{
MemoryStream ms = await (Task<MemoryStream>)entryTask;
entryTask = null;
if (ms == null)
{
// プレイリスト切断
entryStream.Close();
entryStream = null;
Trace.WriteLine("Playlist stream closed");
}
else
{
// チャンク取得完了
var chunkedEntry = ProtoBuf.Serializer.Deserialize<ChunkedEntry>(ms);
if (chunkedEntry.next != null)
{
nextAt = chunkedEntry.next.at.ToString();
Trace.WriteLine("Playlist next.at = " + nextAt);
}
if (chunkedEntry.segment != null)
{
string segmentUri = chunkedEntry.segment.uri;
Trace.WriteLine("segment.uri = " + segmentUri);
if (Regex.IsMatch(segmentUri, @"^https://[0-9A-Za-z.-]+\.nicovideo\.jp/") != clientIsSameSite)
{
// リクエストヘッダの内容と矛盾してしまうため
throw new NotImplementedException("The domain category of segment.uri is inconsistent with the request header.");
}
// ライブ用途なので速やかに接続開始する
if (segmentTask == null)
{
segmentTask = client.GetStreamAsync(segmentUri, linkedCts.Token);
}
else if (prefetchTask == null)
{
if (prefetchStream != null)
{
prefetchStream.Close();
prefetchStream = null;
Trace.WriteLine("Prefetch skipped");
}
prefetchTask = client.GetStreamAsync(segmentUri, linkedCts.Token);
Trace.WriteLine("Prefetch started");
}
}
entryTask = ReadProtoBufChunkAsync(entryStream, msEntry, readEntryBuf, linkedCts.Token);
}
}
}
else if (completedTask == segmentTask)
{
if (segmentStream == null)
{
// セグメント接続完了
segmentStream = await (Task<Stream>)segmentTask;
segmentTask = ReadProtoBufChunkAsync(segmentStream, msSegment, readSegmentBuf, linkedCts.Token);
}
else
{
MemoryStream ms = await (Task<MemoryStream>)segmentTask;
segmentTask = null;
if (ms == null)
{
// セグメント切断
segmentStream.Close();
Trace.WriteLine("Segment stream closed");
// プリフェッチタスクを引き継ぐ
segmentTask = prefetchTask;
segmentStream = prefetchStream;
prefetchTask = null;
prefetchStream = null;
if (segmentTask == null && segmentStream != null)
{
// プリフェッチ済み
chunkedMessage = ProtoBuf.Serializer.Deserialize<ChunkedMessage>(msPrefetch);
segmentTask = ReadProtoBufChunkAsync(segmentStream, msSegment, readSegmentBuf, linkedCts.Token);
}
}
else
{
chunkedMessage = ProtoBuf.Serializer.Deserialize<ChunkedMessage>(ms);
segmentTask = ReadProtoBufChunkAsync(segmentStream, msSegment, readSegmentBuf, linkedCts.Token);
}
}
}
else
{
if (prefetchStream == null)
{
// プリフェッチセグメント接続完了
prefetchStream = await (Task<Stream>)prefetchTask;
prefetchTask = ReadProtoBufChunkAsync(prefetchStream, msPrefetch, readPrefetchBuf, linkedCts.Token);
}
else if (await (Task<MemoryStream>)prefetchTask == null)
{
// プリフェッチセグメント切断
prefetchTask = null;
prefetchStream.Close();
prefetchStream = null;
Trace.WriteLine("Prefetch stream closed");
}
else
{
// プリフェッチ完了
prefetchTask = null;
Trace.WriteLine("Prefetch done");
}
}
}
if (watchReceived)
{
WatchSessionResult message = jsWatchSessionResult.ReadValue(watchBuf, 0, watchCount);
switch (message.type)
{
case "disconnect":
case "reconnect":
Trace.WriteLine(message.type);
// とりあえず再接続要求も切断扱い
await gracefulClose();
break;
case "error":
Trace.WriteLine("error");
{
WatchSessionResultError error = jsWatchSessionResultForError.ReadValue(watchBuf, 0, watchCount).data;
if (error != null)
{
Trace.WriteLine(Encoding.UTF8.GetString(watchBuf, 0, watchCount));
if (error.code == "INVALID_MESSAGE")
{
ResponseLines.Add("-<chat_result status=\"1\" />");
}
else if (error.code == "COMMENT_POST_NOT_ALLOWED")
{
ResponseLines.Add("-<chat_result status=\"4\" />");
}
}
}
break;
case "messageServer":
Trace.WriteLine("messageServer");
// メッセージサーバの接続先情報
{
WatchSessionResultMessageServer messageServer = jsWatchSessionResultForMessageServer.ReadValue(watchBuf, 0, watchCount).data;
if (messageServer != null)
{
if (messageServer.vposBaseTime != null && vposBaseUnixTime <= TimeSpan.Zero)
{
DateTime d;
if (DateTime.TryParse(messageServer.vposBaseTime, CultureInfo.InvariantCulture, out d))
{
vposBaseUnixTime = d.ToUniversalTime() - new DateTime(1970, 1, 1);
}
}
viewUri = viewUri ?? messageServer.viewUri;
hashedUserId = hashedUserId ?? messageServer.hashedUserId;
// 適当なタグをでっちあげてxmlに変換。本来の"room"メッセージは廃止された
ResponseLines.Add(("-<x_room" +
" thread_id=\"" + lvId + "_" + (long)vposBaseUnixTime.TotalSeconds + "\"" +
(hashedUserId != null ? " hashed_user_id=\"" + HtmlEncodeAmpLtGt(hashedUserId, true) + "\"" : "") +
(embeddedUser != null && embeddedUser.id != null ? " user_id=\"" + HtmlEncodeAmpLtGt(embeddedUser.id, true) + "\"" : "") +
(embeddedUser != null && embeddedUser.nickname != null ? " nickname=\"" + HtmlEncodeAmpLtGt(embeddedUser.nickname, true) + "\"" : "") +
(embeddedUser != null && embeddedUser.isLoggedIn ? " is_logged_in=\"1\"" : "") +
" />").Replace("\n", " ").Replace("\r", " "));
}
}
break;
case "ping":
Trace.WriteLine("ping-pong");
await DoWebSocketAction(async ct => await watchSession.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(
"{\"type\":\"pong\"}")), WebSocketMessageType.Text, true, ct), ct);
break;
case "postCommentResult":
Trace.WriteLine("postCommentResult");
// コメント投稿に成功
ResponseLines.Add("-<chat_result status=\"0\" />");
break;
case "seat":
Trace.WriteLine("seat");
{
WatchSessionResultSeat seat = jsWatchSessionResultForSeat.ReadValue(watchBuf, 0, watchCount).data;
if (seat != null)
{
keepSeatIntervalSec = Math.Min((int)seat.keepIntervalSec, 1000);
keepSeatTick = Environment.TickCount & int.MaxValue;
}
}
break;
case "serverTime":
Trace.WriteLine("serverTime");
{
WatchSessionResultServerTime serverTime = jsWatchSessionResultForServerTime.ReadValue(watchBuf, 0, watchCount).data;
if (serverTime != null && serverTime.currentMs != null)
{
DateTime d;
if (DateTime.TryParse(serverTime.currentMs, CultureInfo.InvariantCulture, out d))
{
serverUnixTime = d.ToUniversalTime() - new DateTime(1970, 1, 1);
serverUnixTimeTick = Environment.TickCount & int.MaxValue;
mixingInfo.nicovideoServerUnixTime = serverUnixTime;
mixingInfo.nicovideoServerUnixTimeTick = serverUnixTimeTick;
}
}
}
break;
}
watchCount = 0;
}
if (chunkedMessage != null)
{
if (chunkedMessage.message != null && chunkedMessage.message.chat != null &&
chunkedMessage.meta != null && chunkedMessage.meta.at != null &&
serverUnixTime > TimeSpan.Zero)
{
TimeSpan at = chunkedMessage.meta.at.Value.ToUniversalTime() - new DateTime(1970, 1, 1);
if (!wroteLiveChat && at >= serverUnixTime)
{
if (wroteFirstChat)
{
// 適当なタグをでっちあげて過去のコメントの出力終了を通知
ResponseLines.Add("-<x_past_chat_end />");
}
wroteFirstChat = true;
wroteLiveChat = true;
}
else if (!wroteFirstChat)
{
// 適当なタグをでっちあげて過去のコメントの出力開始を通知
ResponseLines.Add("-<x_past_chat_begin />");
wroteFirstChat = true;
}
// 混合時は不整合を避けるため片方のサーバ時刻をdate属性値に使う
if (wroteLiveChat && mixingInfo.refugeServerUnixTime > TimeSpan.Zero)
{
at = mixingInfo.nicovideoServerUnixTime +
TimeSpan.FromMilliseconds(((Environment.TickCount & int.MaxValue) - mixingInfo.nicovideoServerUnixTimeTick) & int.MaxValue);
}
var chat = chunkedMessage.message.chat;
string mail = "";
if (chat.modifier != null)
{
if (chat.modifier.full_color != null)
{
mail += " #" + ((chat.modifier.full_color.r << 16 |
chat.modifier.full_color.g << 8 |
chat.modifier.full_color.b) & 0xFFFFFF).ToString("x6");
}
else if (chat.modifier.named_color != default)
{
mail += " " + chat.modifier.named_color;
}
if (chat.modifier.position != default)
{
mail += " " + chat.modifier.position;
}
if (chat.modifier.size != default)
{
mail += " " + chat.modifier.size;
}
if (chat.modifier.font != default)
{
mail += " " + chat.modifier.font;
}
if (chat.modifier.opacity != default)
{
mail += " " + chat.modifier.opacity;
}
}
// xml形式に変換(もっと賢い方法ありそうだが属性の順序など維持したいので…)
ResponseLines.Add(("-<chat" +
" thread=\"" + lvId + "_" + (long)vposBaseUnixTime.TotalSeconds + "\"" +
" no=\"" + chat.no +
"\" vpos=\"" + chat.vpos +
"\" date=\"" + (long)at.TotalSeconds +
"\" date_usec=\"" + (at.Milliseconds * 1000 + at.Microseconds) + "\"" +
(mail.Length > 0 ? " mail=\"" + HtmlEncodeAmpLtGt(mail.Substring(1).ToLowerInvariant(), true) + "\"" : "") +
(chat.hashed_user_id == hashedUserId ? " yourpost=\"1\"" : "") +
" user_id=\"" + HtmlEncodeAmpLtGt(chat.raw_user_id == 0 ? chat.hashed_user_id : chat.raw_user_id.ToString(), true) + "\"" +
(chat.account_status == dwango.nicolive.chat.data.Chat.AccountStatus.Premium ? " premium=\"1\"" : "") +
(chat.raw_user_id == 0 ? " anonymity=\"1\"" : "") +
">" + HtmlEncodeAmpLtGt(chat.content) + "</chat>").Replace("\n", " ").Replace("\r", " "));
}
// TODO: nicoadなどは落ち着いたら対応
}
}
}
catch (Exception e)
{
ct.ThrowIfCancellationRequested();
Trace.WriteLine(e.ToString());
return "!";
}
finally
{
// タスクをすべて回収
closeCts.Cancel();
try
{
await Task.WhenAll((new Task[] { pollingTask, watchRecvTask, entryTask, segmentTask, prefetchTask }).Where(a => a != null));
}
catch { }
// HTTPストリームはusingしていないのでここで閉じる
if (prefetchStream != null)
{
prefetchStream.Close();
}
if (segmentStream != null)
{
segmentStream.Close();
}
if (entryStream != null)
{
entryStream.Close();
}
}
}
return ".";
}
/// <summary>実況ストリーム(避難所)</summary>