forked from pixeltris/TwitchAdSolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.cs
1537 lines (1459 loc) · 73.4 KB
/
utils.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 System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Reflection;
using System.Threading;
using System.Net;
using System.IO;
using System.Diagnostics;
namespace TwitchAdUtils
{
class Program
{
static string ClientID = "kimne78kx3ncx6brgo4mv6wki5h1ko";//ilfexgv3nnljz3isbm257gzwrzr7bi - Xtra for Twitch
static string UserAgentChrome = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36";
static string UserAgentFirefox = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0";
static string UserAgent = UserAgentChrome;
static bool UseOldAccessToken = false;
static bool UseAccessTokenTemplate = false;
static bool ShouldNotifyAdWatched = false;
static bool ShouldNotifyAdWatchedMin = true;
static bool ShouldDenyAd = false;
static bool UseFastBread = true;// fast_bread (EXT-X-TWITCH-PREFETCH)
static string PlayerTypeNormal = "site";//embed squad_secondary squad_primary
static string PlayerTypeMiniNoAd = "picture-by-picture";//"thunderdome";
static string PlayerTypeEmbed = "embed";
static string Platform = "web";
static string PlayerBackend = "mediaplayer";
static string MainM3U8AdditionalParams = "";
static string AdSignifier = "stitched-ad";
static string ProxyUrl = "";
static int TargetResolution = 480;
static TimeSpan LoopDelay = TimeSpan.FromSeconds(1);
enum RunnerMode
{
Normal,
MiniNoAd,
Proxy,
Embed
}
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
if (args.Length >= 1 && args[0] == "build_scripts")
{
// This takes "base.user.js" and updates all of the other scripts based on the cfg values
BuildScripts();
return;
}
if (args.Length >= 1 && args[0] == "m3u8")
{
// Tests modifications of m3u8 files
Console.WriteLine("Starting local server (http://localhost)");
TwitchTestServer testServer = new TwitchTestServer();
testServer.Start(80);
Console.ReadLine();
return;
}
Console.Write("Enter channel name: ");
string channel = Console.ReadLine().ToLower();
Console.WriteLine("Fetching channel '" + channel + "'");
RunImpl(RunnerMode.Normal, channel);
//RunImpl(RunnerMode.Embed, channel);
//RunImpl(RunnerMode.MiniNoAd, channel);
}
static void BuildScripts()
{
string[] deprecated = { };
string baseScriptName = "base";
string suffixConfg = ".cfg";
string suffixUserscript = ".user.js";
string suffixUblock = "-ublock-origin.js";
string baseFile = Path.Combine(baseScriptName, baseScriptName + ".user.js");
if (File.Exists(baseFile))
{
foreach (string dir in Directory.GetDirectories(Environment.CurrentDirectory))
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (dirInfo.Name != baseScriptName && !deprecated.Contains(dirInfo.Name))
{
string cfgFile = Path.Combine(dir, dirInfo.Name + suffixConfg);
string userscriptFile = Path.Combine(dir, dirInfo.Name + suffixUserscript);
string ublockFile = Path.Combine(dir, dirInfo.Name + suffixUblock);
if (File.Exists(userscriptFile) && File.Exists(ublockFile) && File.Exists(cfgFile))
{
Dictionary<string, string> cfgValues = new Dictionary<string, string>();
string[] cfgLines = File.ReadAllLines(cfgFile);
for (int i = 0; i < cfgLines.Length; i++)
{
string line = cfgLines[i];
if (!string.IsNullOrEmpty(line))
{
int spaceIndex = line.IndexOf(' ');
if (spaceIndex > 0)
{
cfgValues["scope." + line.Substring(0, spaceIndex).Trim() + " "] = line.Substring(spaceIndex + 1).Trim();
}
}
}
Console.WriteLine(dir);
foreach (KeyValuePair<string, string> val in cfgValues)
{
Console.WriteLine(val.Key + "= " + val.Value);
}
Console.WriteLine("=============================");
StringBuilder sbUserscript = new StringBuilder();
StringBuilder sbUblock = new StringBuilder();
string[] lines = File.ReadAllLines(baseFile);
bool modifiedOptions = false;
bool foundUserScriptEnd = false;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
string lineTrimmed = line.Trim();
if (lineTrimmed.StartsWith("// Modify options based on mode"))
{
modifiedOptions = true;
}
if (lineTrimmed.StartsWith("// @name "))
{
line = line += " (" + dirInfo.Name + ")";
}
if (lineTrimmed.StartsWith("// @description"))
{
string url = "https://github.com/pixeltris/TwitchAdSolutions/raw/master/" + dirInfo.Name + "/" + dirInfo.Name + suffixUserscript;
sbUserscript.AppendLine("// @updateURL " + url);
sbUserscript.AppendLine("// @downloadURL " + url);
line = line += " (" + dirInfo.Name + ")";
}
if (!modifiedOptions)
{
if (!foundUserScriptEnd)
{
sbUserscript.AppendLine(line);
if (line.Contains("/UserScript"))
{
sbUblock.AppendLine("twitch-videoad.js application/javascript");
foundUserScriptEnd = true;
}
}
else if (lineTrimmed.StartsWith("'use strict'"))
{
sbUserscript.AppendLine(line);
sbUblock.AppendLine(" if ( /(^|\\.)twitch\\.tv$/.test(document.location.hostname) === false ) { return; }");
}
else
{
foreach (KeyValuePair<string, string> val in cfgValues)
{
if (line.Contains(val.Key))
{
line = line.Substring(0, line.IndexOf(val.Key) + val.Key.Length) + "= " + val.Value + ";";
break;
}
}
sbUserscript.AppendLine(line);
sbUblock.AppendLine(line);
}
}
else
{
sbUserscript.AppendLine(line);
sbUblock.AppendLine(line);
}
}
File.WriteAllText(userscriptFile, sbUserscript.ToString());
File.WriteAllText(ublockFile, sbUblock.ToString());
}
}
}
}
using (WebClient wc = new WebClient())
{
string response = null, token = null, sig = null;
wc.Proxy = null;
string code = wc.DownloadString("https://raw.githubusercontent.com/cleanlock/VideoAdBlockForTwitch/master/chrome/remove_video_ads.js");
List<string> lines = code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
for (int i = lines.Count - 1; i >= 0; i--)
{
if (string.IsNullOrWhiteSpace(lines[i]))
{
lines.RemoveAt(i);
}
else
{
lines[i] = " " + lines[i];
}
}
string manifestStr = wc.DownloadString("https://raw.githubusercontent.com/cleanlock/VideoAdBlockForTwitch/master/chrome/manifest.json");
ChromeExtensionManifest manifest = JSONSerializer<ChromeExtensionManifest>.DeSerialize(manifestStr);
Console.WriteLine("vaft: " + manifest.version);
string comment = "// This code is directly copied from https://github.com/cleanlock/VideoAdBlockForTwitch (only change is whitespace is removed for the ublock origin script - also indented)";
StringBuilder sbUserscript = new StringBuilder();
sbUserscript.AppendLine("// ==UserScript==");
sbUserscript.AppendLine("// @name TwitchAdSolutions (vaft)");
sbUserscript.AppendLine("// @namespace https://github.com/pixeltris/TwitchAdSolutions");
sbUserscript.AppendLine("// @version " + manifest.version);
sbUserscript.AppendLine("// @description Multiple solutions for blocking Twitch ads (vaft)");
sbUserscript.AppendLine("// @updateURL https://github.com/pixeltris/TwitchAdSolutions/raw/master/vaft/vaft.user.js");
sbUserscript.AppendLine("// @downloadURL https://github.com/pixeltris/TwitchAdSolutions/raw/master/vaft/vaft.user.js");
sbUserscript.AppendLine("// @author https://github.com/cleanlock/VideoAdBlockForTwitch#credits");
sbUserscript.AppendLine("// @match *://*.twitch.tv/*");
sbUserscript.AppendLine("// @run-at document-start");
sbUserscript.AppendLine("// @grant none");
sbUserscript.AppendLine("// ==/UserScript==");
sbUserscript.AppendLine(comment);
sbUserscript.AppendLine("(function() {");
sbUserscript.AppendLine(" 'use strict';");
StringBuilder sbUblock = new StringBuilder();
sbUblock.AppendLine(comment);
sbUblock.AppendLine("twitch-videoad.js application/javascript");
sbUblock.AppendLine("(function() {");
sbUblock.AppendLine(" if ( /(^|\\.)twitch\\.tv$/.test(document.location.hostname) === false ) { return; }");
foreach (string line in lines)
{
sbUserscript.AppendLine(line);
sbUblock.AppendLine(line);
}
sbUserscript.AppendLine("})();");
sbUblock.AppendLine("})();");
File.WriteAllText(Path.Combine("vaft", "vaft.user.js"), sbUserscript.ToString());
File.WriteAllText(Path.Combine("vaft", "vaft-ublock-origin.js"), sbUblock.ToString());
}
}
static void Run(RunnerMode mode, string channel)
{
Thread thread = new Thread(delegate()
{
RunImpl(mode, channel);
});
thread.IsBackground = true;
thread.Start();
}
static string RunImpl(RunnerMode mode, string channel, bool isFetchingM3U8 = false, bool forceSkipAd = false)
{
string playerType = PlayerTypeNormal;
switch (mode)
{
case RunnerMode.MiniNoAd:
playerType = PlayerTypeMiniNoAd;
break;
case RunnerMode.Embed:
playerType = PlayerTypeEmbed;
break;
}
string cookies = null;
string uniqueId = null;
int cycle = 0;
while (true)
{
if (string.IsNullOrEmpty(cookies))
{
using (CookieAwareWebClient wc = new CookieAwareWebClient())
{
wc.Proxy = null;
wc.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
wc.DownloadString("https://www.twitch.tv/" + channel);
cookies = ProcessCookies(wc.Cookies, out uniqueId);
//Console.WriteLine("unique_id: " + uniqueId);
}
}
if (string.IsNullOrEmpty(uniqueId))
{
Console.WriteLine("unique_id is null");
return null;
}
using (WebClient wc = new WebClient())
{
string response = null, token = null, sig = null;
wc.Proxy = null;
if (mode != RunnerMode.Proxy)
{
if (UseOldAccessToken)
{
wc.Headers.Clear();
wc.Headers["client-id"] = ClientID;
wc.Headers["accept"] = "application/vnd.twitchtv.v5+json; charset=UTF-8";
wc.Headers["accept-encoding"] = "gzip, deflate, br";
wc.Headers["accept-language"] = "en-us";
wc.Headers["content-type"] = "application/json; charset=UTF-8";
wc.Headers["origin"] = "https://www.twitch.tv";
wc.Headers["referer"] = "https://www.twitch.tv/";
wc.Headers["user-agent"] = UserAgent;
wc.Headers["x-requested-with"] = "XMLHttpRequest";
wc.Headers["cookie"] = cookies;
response = wc.DownloadString("https://api.twitch.tv/api/channels/" + channel + "/access_token?oauth_token=undefined&need_https=true&platform=" + Platform + "&player_type=" + playerType + "&player_backend=" + PlayerBackend);
if (!string.IsNullOrEmpty(response))
{
TwitchAccessTokenOld tokenInfo = JSONSerializer<TwitchAccessTokenOld>.DeSerialize(response);
if (tokenInfo != null && !string.IsNullOrEmpty(tokenInfo.token) && !string.IsNullOrEmpty(tokenInfo.sig))
{
token = tokenInfo.token;
sig = tokenInfo.sig;
}
}
}
else
{
wc.Headers.Clear();
wc.Headers["client-id"] = ClientID;
wc.Headers["Device-ID"] = uniqueId;
wc.Headers["accept"] = "*/*";
wc.Headers["accept-encoding"] = "gzip, deflate, br";
wc.Headers["accept-language"] = "en-us";
wc.Headers["content-type"] = "text/plain; charset=UTF-8";
wc.Headers["origin"] = "https://www.twitch.tv";
wc.Headers["referer"] = "https://www.twitch.tv/";
wc.Headers["user-agent"] = UserAgent;
if (UseAccessTokenTemplate)
{
response = wc.UploadString("https://gql.twitch.tv/gql", @"{""operationName"":""PlaybackAccessToken_Template"",""query"":""query PlaybackAccessToken_Template($login: String!, $isLive: Boolean!, $vodID: ID!, $isVod: Boolean!, $playerType: String!) { streamPlaybackAccessToken(channelName: $login, params: {platform: \""" + Platform + @"\"", playerBackend: \""" + PlayerBackend + @"\"", playerType: $playerType}) @include(if: $isLive) { value signature __typename } videoPlaybackAccessToken(id: $vodID, params: {platform: \""" + Platform + @"\"", playerBackend: \""" + PlayerBackend + @"\"", playerType: $playerType}) @include(if: $isVod) { value signature __typename }}"",""variables"":{""isLive"":true,""login"":""" + channel + @""",""isVod"":false,""vodID"":"""",""playerType"":""" + playerType + @"""}}");
}
else
{
response = wc.UploadString("https://gql.twitch.tv/gql", @"{""operationName"":""PlaybackAccessToken"",""variables"":{""isLive"":true,""login"":""" + channel + @""",""isVod"":false,""vodID"":"""",""playerType"":""" + playerType + @"""},""extensions"":{""persistedQuery"":{""version"":1,""sha256Hash"":""0828119ded1c13477966434e15800ff57ddacf13ba1911c129dc2200705b0712""}}}");
}
if (!string.IsNullOrEmpty(response))
{
TwitchAccessToken tokenInfo = JSONSerializer<TwitchAccessToken>.DeSerialize(response);
if (tokenInfo != null && tokenInfo.data != null && tokenInfo.data.streamPlaybackAccessToken != null &&
!string.IsNullOrEmpty(tokenInfo.data.streamPlaybackAccessToken.value) && !string.IsNullOrEmpty(tokenInfo.data.streamPlaybackAccessToken.signature))
{
token = tokenInfo.data.streamPlaybackAccessToken.value;
sig = tokenInfo.data.streamPlaybackAccessToken.signature;
}
}
}
}
if (mode == RunnerMode.Proxy || !string.IsNullOrEmpty(token))
{
string url = null;
if (mode == RunnerMode.Proxy)
{
url = ProxyUrl + channel;
}
else
{
string additionalParams = "";
if (UseFastBread)
{
additionalParams += "&fast_bread=true";
}
url = "https://usher.ttvnw.net/api/channel/hls/" + channel + ".m3u8?allow_source=true" + additionalParams + "&sig=" + sig + "&token=" + System.Web.HttpUtility.UrlEncode(token) + MainM3U8AdditionalParams;
}
if (isFetchingM3U8)
{
if (!forceSkipAd || cycle > 0)
{
return url;
}
}
wc.Headers.Clear();
wc.Headers["accept"] = "application/x-mpegURL, application/vnd.apple.mpegurl, application/json, text/plain";
wc.Headers["host"] = "usher.ttvnw.net";
wc.Headers["cookie"] = "DNT=1;";
wc.Headers["DNT"] = "1";
wc.Headers["user-agent"] = UserAgent;
string encodingsM3u8 = wc.DownloadString(url);
if (!string.IsNullOrEmpty(encodingsM3u8))
{
string[] lines = encodingsM3u8.Split('\n');
string info = lines.FirstOrDefault(x => x.Contains("EXT-X-TWITCH-INFO"));
bool isFuture = false;
if (info != null)
{
Dictionary<string, string> attr = ParseAttributes(info);
string futureStr;
if (attr.TryGetValue("FUTURE", out futureStr))
{
isFuture = bool.Parse(futureStr);
}
}
string streamM3u8Url = lines.FirstOrDefault(x => x.EndsWith(".m3u8"));
if (!string.IsNullOrEmpty(streamM3u8Url))
{
bool foundAd = true;
while (foundAd)
{
string streamM3u8 = wc.DownloadString(streamM3u8Url);
if (!string.IsNullOrEmpty(streamM3u8Url))
{
if (streamM3u8.Contains(AdSignifier))
{
Console.WriteLine("has ad " + DateTime.Now.TimeOfDay + " - " + mode + " - future:" + isFuture);
if (ShouldDenyAd)
{
DeclineAd(uniqueId, streamM3u8, sig, token, true);
DeclineAd(uniqueId, streamM3u8, sig, token, false);
}
}
else
{
Console.WriteLine("no ad " + DateTime.Now.TimeOfDay + " - " + mode + " - future:" + isFuture);
}
if ((streamM3u8.Contains(AdSignifier) || forceSkipAd) &&
(!UseOldAccessToken && (ShouldNotifyAdWatched || forceSkipAd)))
{
NotifyWatchedAd(uniqueId, streamM3u8);
}
}
else
{
Console.WriteLine("Failed to fetch streamM3u8Url");
}
if (!ShouldDenyAd)
{
break;
}
else
{
Thread.Sleep(LoopDelay);
}
}
}
else
{
Console.WriteLine("Failed to find streamM3u8Url");
}
}
else
{
Console.WriteLine("Failed to fetch encodingsM3u8");
}
}
else
{
Console.WriteLine("Failed to get stream token mode:" + mode);
}
}
Thread.Sleep(LoopDelay);
cycle++;
}
}
static Dictionary<string, string> ParseAttributes(string tag)
{
string tagName;
return ParseAttributes(tag, out tagName);
}
static Dictionary<string, string> ParseAttributes(string tag, out string tagName)
{
// TODO: Improve this
Dictionary<string, string> result = new Dictionary<string, string>();
tagName = null;
int tagDataSplitIndex = tag.IndexOf(':');
if (tagDataSplitIndex > 0)
{
tagName = tag.Substring(0, tagDataSplitIndex);
tag = tag.Substring(tagDataSplitIndex + 1);
string[] splitted = tag.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string str in splitted)
{
int index = str.IndexOf('=');
if (index > 0)
{
result[str.Substring(0, index)] = str.Substring(index + 1).Trim('\"');
}
}
}
return result;
}
static TValue GetOrDefault<TKey, TValue>(Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
{
TValue result;
if (dict.TryGetValue(key, out result))
{
return result;
}
return defaultValue;
}
static void DeclineAd(string uniqueId, string streamM3u8, string sig, string token, bool first)
{
string[] lines = streamM3u8.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(AdSignifier))
{
Dictionary<string, string> attr = ParseAttributes(lines[i]);
Dictionary<string, string> vals = new Dictionary<string, string>();
vals["TARG_adSessionID"] = GetOrDefault(attr, "X-TV-TWITCH-AD-AD-SESSION-ID");
vals["TARG_sig"] = sig;
vals["TARG_token"] = token.Replace("\"", "\\\"");
string str = null;
//string str = @"[{""operationName"":""VideoAdRequestDecline"",""variables"":{""context"":{""adSessionID"":""TARG_adSessionID"",""clientContext"":""{\""isAudioOnly\"":false,\""isMiniTheater\"":false,\""isPIP\"":true,\""isUsingExternalPlayback\"":false}"",""isAudioOnly"":false,""isMiniTheater"":false,""isPIP"":false,""isUsingExternalPlayback"":false,""duration"":30,""isVLM"":false,""rollType"":""PREROLL""}},""extensions"":{""persistedQuery"":{""version"":1,""sha256Hash"":""6f5d9fdc36a3c879cca7debdbe21c62d5cac4ad5b30b635263eff68335b96a71""}}}]";
if (first)
str = @"[{""operationName"":""VideoAdRequestDecline"",""variables"":{""context"":{""adSessionID"":""TARG_adSessionID"",""clientContext"":{""isAudioOnly"":false,""isMiniTheater"":false,""isPIP"":false,""isUsingExternalPlayback"":false},""duration"":30,""playerContext"":{""contentType"":""LIVE"",""isAutoPlay"":true,""nauthSig"":""TARG_sig"",""nauthToken"":""TARG_token""},""rollType"":""PREROLL"",""isVLM"":false,""commercialID"":""""}},""extensions"":{""persistedQuery"":{""version"":1,""sha256Hash"":""6f5d9fdc36a3c879cca7debdbe21c62d5cac4ad5b30b635263eff68335b96a71""}}}]";
else
{
vals["TARG_ad_session_id"] = GetOrDefault(attr, "X-TV-TWITCH-AD-AD-SESSION-ID");
vals["TARG_radToken"] = GetOrDefault(attr, "X-TV-TWITCH-AD-RADS-TOKEN");
str = @"[{""operationName"":""ClientSideAdEventHandling_RecordAdEvent"",""variables"":{""input"":{""eventName"":""video_ad_request_declined"",""eventPayload"":""{\""reason_channeladfree\"":false,\""reason_channelsub\"":false,\""reason_vod_ads_disabled\"":false,\""reason_bounty\"":false,\""reason_vod_midroll\"":false,\""reason_stream_broadcaster\"":false,\""reason_embed_promo\"":false,\""reason_p4m\"":false,\""reason_lt\"":false,\""reason_raid\"":false,\""reason_midroll_during_preroll\"":false,\""reason_ratelimit\"":false,\""reason_short_vod\"":false,\""reason_turbo\"":false,\""reason_vod_creator\"":false,\""reason_wp\"":false,\""reason_zagd\"":false,\""reason_zagu\"":false,\""reason_midlimit\"":false,\""reason_amazon_product_page\"":false,\""reason_animated_thumbnails\"":false,\""reason_creative_player\"":false,\""reason_dashboard\"":false,\""reason_facebook\"":false,\""reason_frontpage\"":false,\""reason_highlighter\"":false,\""reason_onboarding\"":false,\""reason_pbyp\"":false,\""reason_squad_stream_secondary_player\"":false,\""reason_thunderdome\"":true,\""reason_embed\"":false,\""twitch_correlator\"":\""\"",\""ad_session_id\"":\""TARG_ad_session_id\"",\""roll_type\"":\""preroll\"",\""time_break\"":30}"",""radToken"":""TARG_radToken""}},""extensions"":{""persistedQuery"":{""version"":1,""sha256Hash"":""7e6c69e6eb59f8ccb97ab73686f3d8b7d85a72a0298745ccd8bfc68e4054ca5b""}}}]";
}
foreach (KeyValuePair<string, string> val in vals)
{
str = str.Replace(val.Key, val.Value);
}
//Console.WriteLine(str);
using (WebClient wc = new WebClient())
{
wc.Proxy = null;
wc.Headers["Client-Id"] = ClientID;
wc.Headers["X-Device-Id"] = uniqueId;
wc.Headers["accept"] = "*/*";
wc.Headers["accept-encoding"] = "gzip, deflate, br";
wc.Headers["accept-language"] = "en-us";
wc.Headers["content-type"] = "text/plain; charset=UTF-8";
wc.Headers["origin"] = "https://www.twitch.tv";
wc.Headers["referer"] = "https://www.twitch.tv/";
wc.Headers["user-agent"] = UserAgent;
string st2 = wc.UploadString("https://gql.twitch.tv/gql", str);
Console.WriteLine(st2);
}
return;
}
}
}
static void SendGqlAdEvent(WebClient wc, string eventName, bool includeAdInfo, int adQuartile, int adPos, Dictionary<string, string> vals)
{
// TARG_eventName TARG_roll_type TARG_radToken TARG_adInfo
// TARG_ad_id TARG_ad_position TARG_duration TARG_creative_id TARG_total_ads TARG_order_id TARG_line_item_id TARG_quartile
string str = @"[{""operationName"":""ClientSideAdEventHandling_RecordAdEvent"",""variables"":{""input"":{""eventName"":""TARG_eventName"",""eventPayload"":""{\""player_mute\"":false,\""player_volume\"":0.5,\""visible\"":true,\""roll_type\"":\""TARG_roll_type\"",\""stitched\"":trueTARG_adInfo}"",""radToken"":""TARG_radToken""}},""extensions"":{""persistedQuery"":{""version"":1,""sha256Hash"":""7e6c69e6eb59f8ccb97ab73686f3d8b7d85a72a0298745ccd8bfc68e4054ca5b""}}}]";
string strAdInfo = @",\""ad_id\"":\""TARG_ad_id\"",\""ad_position\"":TARG_ad_position,\""duration\"":TARG_duration,\""creative_id\"":\""TARG_creative_id\"",\""total_ads\"":TARG_total_ads,\""order_id\"":\""TARG_order_id\"",\""line_item_id\"":\""TARG_line_item_id\""TARG_quartile";
vals["TARG_eventName"] = eventName;
vals["TARG_quartile"] = adQuartile > 0 ? (@",\""quartile\"":" + adQuartile) : string.Empty;
if (includeAdInfo)
{
foreach (KeyValuePair<string, string> val in vals)
{
strAdInfo = strAdInfo.Replace(val.Key, val.Value);
}
vals["TARG_adInfo"] = strAdInfo;
}
else
{
vals["TARG_adInfo"] = "";
}
foreach (KeyValuePair<string, string> val in vals)
{
str = str.Replace(val.Key, val.Value);
}
//Console.WriteLine(str);
Console.WriteLine("SendGqlAdEvent " + eventName + " adinfo: " + includeAdInfo + " quartile: " + adQuartile + " adPos: " + adPos);
wc.UploadString("https://gql.twitch.tv/gql", str);
}
static void NotifyWatchedAd(string uniqueId, string streamM3u8)
{
string[] lines = streamM3u8.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(AdSignifier))
{
Dictionary<string, string> attr = ParseAttributes(lines[i]);
Dictionary<string, string> vals = new Dictionary<string, string>();
vals["TARG_roll_type"] = GetOrDefault(attr, "X-TV-TWITCH-AD-ROLL-TYPE", "preroll").ToLower();
vals["TARG_radToken"] = GetOrDefault(attr, "X-TV-TWITCH-AD-RADS-TOKEN");
vals["TARG_ad_id"] = GetOrDefault(attr, "X-TV-TWITCH-AD-ADVERTISER-ID");
vals["TARG_duration"] = "30";
vals["TARG_creative_id"] = GetOrDefault(attr, "X-TV-TWITCH-AD-CREATIVE-ID");
vals["TARG_total_ads"] = GetOrDefault(attr, "X-TV-TWITCH-AD-POD-LENGTH", "1");
vals["TARG_order_id"] = GetOrDefault(attr, "X-TV-TWITCH-AD-ORDER-ID");
vals["TARG_line_item_id"] = GetOrDefault(attr, "X-TV-TWITCH-AD-LINE-ITEM-ID");
using (WebClient wc = new WebClient())
{
wc.Proxy = null;
wc.Headers["Client-Id"] = ClientID;
wc.Headers["X-Device-Id"] = uniqueId;
wc.Headers["accept"] = "*/*";
wc.Headers["accept-encoding"] = "gzip, deflate, br";
wc.Headers["accept-language"] = "en-us";
wc.Headers["content-type"] = "text/plain; charset=UTF-8";
wc.Headers["origin"] = "https://www.twitch.tv";
wc.Headers["referer"] = "https://www.twitch.tv/";
wc.Headers["user-agent"] = UserAgent;
if (ShouldNotifyAdWatchedMin)
{
SendGqlAdEvent(wc, "video_ad_pod_complete", false, 0, 0, vals);
}
else
{
int totalAds = int.Parse(vals["TARG_total_ads"]);
for (int adPos = 0; adPos < totalAds; adPos++)
{
vals["TARG_ad_position"] = adPos.ToString();
SendGqlAdEvent(wc, "video_ad_impression", true, 0, adPos, vals);
for (int quartile = 1; quartile <= 4; quartile++)
{
SendGqlAdEvent(wc, "video_ad_quartile_complete", true, quartile, adPos, vals);
}
SendGqlAdEvent(wc, "video_ad_pod_complete", false, 0, adPos, vals);
}
}
}
break;
}
}
//Console.WriteLine(streamM3u8);
}
static string ProcessCookies(string str)
{
string uniqueId;
return ProcessCookies(str, out uniqueId);
}
static string ProcessCookies(string str, out string uniqueId)
{
uniqueId = null;
string result = string.Empty;
string[] cookies = str.Split(',');
foreach (string cookie in cookies)
{
if (cookie.Split(';')[0].Contains('='))
{
string[] splitted = cookie.Split(';')[0].Split('=');
if (splitted.Length >= 2 && splitted[0] == "unique_id")
{
uniqueId = splitted[1];
}
result += cookie.Split(';')[0] + ";";
}
}
return result;
}
[DataContract]
public class TwitchAccessTokenOld
{
[DataMember]
public string token { get; set; }
[DataMember]
public string sig { get; set; }
}
[DataContract]
public class TwitchAccessToken
{
[DataMember]
public TwitchAccessToken_data data { get; set; }
}
[DataContract]
public class TwitchAccessToken_data
{
[DataMember]
public TwitchAccessToken_streamPlaybackAccessToken streamPlaybackAccessToken { get; set; }
}
[DataContract]
public class TwitchAccessToken_streamPlaybackAccessToken
{
[DataMember]
public string value { get; set; }
[DataMember]
public string signature { get; set; }
}
[DataContract]
public class ChromeExtensionManifest
{
[DataMember]
public string version { get; set; }
}
class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }
public string Cookies { get; private set; }
public CookieAwareWebClient()
: this(new CookieContainer())
{
}
public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = new CookieContainer();
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
string setCookieHeader = response.Headers.Get("Set-Cookie");
Cookies = setCookieHeader;
return response;
}
}
static class JSONSerializer<TType> where TType : class
{
public static TType DeSerialize(string json)
{
return TinyJson.JSONParser.FromJson<TType>(json);
}
}
class TwitchTestServer
{
const string RecordDir = "recordings";
Dictionary<string, State> states = new Dictionary<string, State>();
class State
{
public bool IsReplay = false;
public string RecordingName = null;
public string RecordingPath = null;
public string ChannelName = null;
public string UrlChRecName { get { return ChannelName + "|" + RecordingName; } }
public string M3U8Normal = null;
public string M3U8Mini = null;
public string M3U8Alt = null;
public Dictionary<string, Dictionary<string, string>> M3U8Map = new Dictionary<string, Dictionary<string, string>>();
public Stopwatch Stopwatch = new Stopwatch();
public State(string channelName, string name)
{
ChannelName = channelName;
RecordingName = name;
RecordingPath = Path.GetFullPath(Path.Combine(RecordDir, name));
try
{
if (!Directory.Exists(RecordingPath))
{
Directory.CreateDirectory(RecordingPath);
}
}
catch
{
}
}
public void Clear()
{
M3U8Map.Clear();
Stopwatch.Restart();
try
{
while (Directory.Exists(RecordingPath))
{
Directory.Delete(RecordingPath, true);
}
}
catch
{
}
try
{
if (!Directory.Exists(RecordingPath))
{
Directory.CreateDirectory(RecordingPath);
}
}
catch
{
}
}
public void Load()
{
M3U8Map.Clear();
Stopwatch.Restart();
IsReplay = true;
}
}
private Thread thread;
private HttpListener listener;
public void Start(int port)
{
Stop();
thread = new Thread(delegate()
{
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + port + "/");
listener.Start();
while (listener != null)
{
try
{
HttpListenerContext context = listener.GetContext();
Process(context);
}
catch
{
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
public void Stop()
{
if (listener != null)
{
try
{
listener.Stop();
}
catch
{
}
listener = null;
}
if (thread != null)
{
try
{
thread.Abort();
}
catch
{
}
thread = null;
}
}
private void Process(HttpListenerContext context)
{
try
{
string url = context.Request.Url.OriginalString;
//Console.WriteLine("req " + DateTime.Now.TimeOfDay + " - " + url);
string response = string.Empty;
string contentType = "text/html";
if (url.Contains("favicon.ico"))
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.OutputStream.Close();
return;
}
byte[] responseBuffer = null;
if (context.Request.Url.Segments.Length == 1 && context.Request.Url.Segments[0] == "/")
{
response = "<html><script src='utils.js'></script></html>";
}
else if (context.Request.Url.Segments.Length == 2 && context.Request.Url.Segments[1] == "utils.js")
{
response = File.ReadAllText("utils.js");
}
else if (context.Request.Url.Segments.Length >= 3)
{
string[] reqTypeSplitted = context.Request.Url.Segments[1].Trim('/').Split('_');
string reqType = reqTypeSplitted[0].ToLower();
string reqStreamType = reqTypeSplitted.Length > 1 ? reqTypeSplitted[1] : null;
string[] splitted = context.Request.Url.Segments[2].Trim('/').ToLower().Replace("%7c", "|").Split('|');
string channelName = splitted[0];
string recordingName = splitted[1];
if (!string.IsNullOrEmpty(channelName) && !string.IsNullOrEmpty(recordingName))
{
State state;
if (!states.TryGetValue(recordingName, out state))
{
states[recordingName] = state = new State(channelName, recordingName);
}
switch (reqType)
{
case "record-begin":
{
state.Clear();
string normal = RunImpl(RunnerMode.Normal, channelName, true);
if (!string.IsNullOrEmpty(normal))
{
string mini = RunImpl(RunnerMode.MiniNoAd, channelName, true);
if (!string.IsNullOrEmpty(mini))
{
//string alt = RunImpl(RunnerMode.Proxy, channelName, true);
//string alt = RunImpl(RunnerMode.Normal, channelName, true, true);
string alt = RunImpl(RunnerMode.Embed, channelName, true);
state.M3U8Normal = normal;
state.M3U8Mini = mini;
state.M3U8Alt = alt;
response = "ok";
}
}
}
break;
case "replay-begin":
{
DirectoryInfo dir = new DirectoryInfo(Path.Combine(RecordDir, recordingName));
if (dir.Exists && dir.GetFiles().Length > 0)
{
state.Load();
response = "ok";
}
}
break;
case "m3u8":
{
string type = reqTypeSplitted[1].ToLower();
string m3u8Url = null;
switch (type)
{
case "normal":
case "output":
m3u8Url = state.M3U8Normal;
break;
case "mini":
m3u8Url = state.M3U8Mini;
break;
case "alt":
m3u8Url = state.M3U8Alt;
break;
}
if (!string.IsNullOrEmpty(m3u8Url))
{
response = GetM3U8(state, m3u8Url, reqStreamType, true);
}
}
break;
case "m3u8-sub":
{
string type = reqTypeSplitted[1].ToLower();
string m3u8Url = null;
if (!state.IsReplay)
{
m3u8Url = GetM3U8Url(state, reqStreamType);
}
if (!string.IsNullOrEmpty(m3u8Url) || state.IsReplay)
{
response = GetM3U8(state, m3u8Url, reqStreamType, false);
}
}
break;
case "m3u8-seg":
{
// TODO: Load segment, return as binary file
}
break;
default:
Console.WriteLine("Unhandled request '" + reqType + "'");
break;
}
}
}
if (responseBuffer == null)
{
responseBuffer = Encoding.UTF8.GetBytes(response == null ? string.Empty : response.ToString());
}
context.Response.ContentType = contentType;
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.ContentLength64 = responseBuffer.Length;
context.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
context.Response.OutputStream.Flush();
context.Response.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception e)
{
Console.WriteLine(e);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
context.Response.OutputStream.Close();
}
private string DownloadM3U8(string url)
{
try
{
using (WebClient wc = new WebClient())
{
wc.Proxy = null;
wc.Headers["accept"] = "application/x-mpegURL, application/vnd.apple.mpegurl, application/json, text/plain";
wc.Headers["host"] = "usher.ttvnw.net";
wc.Headers["cookie"] = "DNT=1;";
wc.Headers["DNT"] = "1";
wc.Headers["user-agent"] = UserAgent;
return wc.DownloadString(url);
}
}
catch (Exception e)
{