-
Notifications
You must be signed in to change notification settings - Fork 244
/
TwitchHelper.cs
706 lines (625 loc) · 33.6 KB
/
TwitchHelper.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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TwitchDownloaderCore.Properties;
using TwitchDownloaderCore.TwitchObjects;
namespace TwitchDownloaderCore
{
public static class TwitchHelper
{
private static HttpClient httpClient = new HttpClient();
private static readonly string[] bttvZeroWidth = { "SoSnowy", "IceCold", "SantaHat", "TopHat", "ReinDeer", "CandyCane", "cvMask", "cvHazmat" };
public static async Task<GqlVideoResponse> GetVideoInfo(int videoId)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{video(id:\\\"" + videoId + "\\\"){title,thumbnailURLs(height:180,width:320),createdAt,lengthSeconds,owner{id,displayName}}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GqlVideoResponse>(response);
}
public static async Task<JObject> GetVideoToken(int videoId, string authToken)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"operationName\":\"PlaybackAccessToken_Template\",\"query\":\"query PlaybackAccessToken_Template($login: String!, $isLive: Boolean!, $vodID: ID!, $isVod: Boolean!, $playerType: String!) { streamPlaybackAccessToken(channelName: $login, params: {platform: \\\"web\\\", playerBackend: \\\"mediaplayer\\\", playerType: $playerType}) @include(if: $isLive) { value signature __typename } videoPlaybackAccessToken(id: $vodID, params: {platform: \\\"web\\\", playerBackend: \\\"mediaplayer\\\", playerType: $playerType}) @include(if: $isVod) { value signature __typename }}\",\"variables\":{\"isLive\":false,\"login\":\"\",\"isVod\":true,\"vodID\":\"" + videoId + "\",\"playerType\":\"embed\"}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
if (authToken != null && authToken != "")
request.Headers.Add("Authorization", "OAuth " + authToken);
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return JObject.Parse(response);
}
public static async Task<string[]> GetVideoPlaylist(int videoId, string token, string sig)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri(String.Format("http://usher.twitch.tv/vod/{0}?nauth={1}&nauthsig={2}&allow_source=true&player=twitchweb", videoId, token, sig)),
Method = HttpMethod.Get
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string playlist = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return playlist.Split('\n');
}
public static async Task<GqlClipResponse> GetClipInfo(object clipId)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{clip(slug:\\\"" + clipId + "\\\"){title,thumbnailURL,createdAt,durationSeconds,broadcaster{id,displayName},videoOffsetSeconds,video{id}}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GqlClipResponse>(response);
}
public static async Task<JArray> GetClipLinks(object clipId)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("[{\"operationName\":\"VideoAccessToken_Clip\",\"variables\":{\"slug\":\"" + clipId + "\"},\"extensions\":{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11\"}}}]", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
JArray result = JArray.Parse(response);
return result;
}
public static async Task<GqlVideoSearchResponse> GetGqlVideos(string channelName, string cursor = "", int limit = 50)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{user(login:\\\"" + channelName + "\\\"){videos(first: " + limit + "" + (cursor == "" ? "" : ",after:\\\"" + cursor + "\\\"") + ") { edges { node { title, id, lengthSeconds, previewThumbnailURL(height: 180, width: 320), createdAt, viewCount }, cursor }, pageInfo { hasNextPage, hasPreviousPage }, totalCount }}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GqlVideoSearchResponse>(response);
}
public static async Task<GqlClipSearchResponse> GetGqlClips(string channelName, string period = "LAST_WEEK", string cursor = "", int limit = 50)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{user(login:\\\"" + channelName + "\\\"){clips(first: " + limit + ", after: \\\"" + cursor + "\\\", criteria: { period: " + period + " }) { edges { cursor, node { id, slug, title, createdAt, durationSeconds, thumbnailURL, viewCount } }, pageInfo { hasNextPage, hasPreviousPage } }}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<GqlClipSearchResponse>(response);
}
public static async Task<EmoteResponse> GetThirdPartyEmoteData(string streamerId, bool getBttv, bool getFfz, bool getStv)
{
EmoteResponse emoteReponse = new EmoteResponse();
if (getBttv)
{
JArray BTTV = JArray.Parse(await httpClient.GetStringAsync("https://api.betterttv.net/3/cached/emotes/global"));
if (streamerId != null)
{
//Channel might not have BTTV emotes
try
{
JObject bttvChannel = JObject.Parse(await httpClient.GetStringAsync("https://api.betterttv.net/3/cached/users/twitch/" + streamerId));
BTTV.Merge(bttvChannel["channelEmotes"]);
BTTV.Merge(bttvChannel["sharedEmotes"]);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
foreach (var emote in BTTV)
{
string id = emote["id"].ToString();
string name = emote["code"].ToString();
string mime = emote["imageType"].ToString();
string url = String.Format("https://cdn.betterttv.net/emote/{0}/[scale]x", id);
emoteReponse.BTTV.Add(new EmoteResponseItem() { Id = id, Code = name, ImageType = mime, ImageUrl = url, IsZeroWidth = bttvZeroWidth.Contains(name) });
}
}
if (getFfz)
{
JArray FFZ = JArray.Parse(await httpClient.GetStringAsync("https://api.betterttv.net/3/cached/frankerfacez/emotes/global"));
if (streamerId != null)
{
//Channel might not have FFZ emotes
try
{
FFZ.Merge(JArray.Parse(await httpClient.GetStringAsync("https://api.betterttv.net/3/cached/frankerfacez/users/twitch/" + streamerId)));
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
foreach (var emote in FFZ)
{
string id = emote["id"].ToString();
string name = emote["code"].ToString();
string mime = emote["imageType"].ToString();
string url = String.Format("https://cdn.betterttv.net/frankerfacez_emote/{0}/[scale]", id);
emoteReponse.FFZ.Add(new EmoteResponseItem() { Id = id, Code = name, ImageType = mime, ImageUrl = url });
}
}
if (getStv)
{
JObject globalEmoteObject = JObject.Parse(await httpClient.GetStringAsync("https://7tv.io/v3/emote-sets/global"));
JArray stvEmotes = (JArray)globalEmoteObject["emotes"];
if (streamerId != null)
{
//Channel might not have 7TV emotes
try
{
JObject streamerEmoteObject = JObject.Parse(await httpClient.GetStringAsync(string.Format("https://7tv.io/v3/users/twitch/{0}", streamerId)));
stvEmotes.Merge((JArray)streamerEmoteObject["emote_set"]["emotes"]);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
foreach (var stvEmote in stvEmotes)
{
string emoteId = stvEmote["id"].ToString();
string emoteName = stvEmote["name"].ToString();
JObject emoteData = (JObject)stvEmote["data"];
JObject emoteHost = (JObject)emoteData["host"];
JArray emoteFiles = (JArray)emoteHost["files"];
if (emoteFiles.Count == 0) // Sometimes there are no hosted files for the emote
{
continue;
}
string emoteFormat = "avif";
foreach (var fileItem in emoteFiles)
{
// prefer webp
if (fileItem["format"].ToString().ToLower().Equals("webp"))
{
emoteFormat = "webp";
break;
}
}
string emoteUrl = string.Format("https:{0}/{1}.{2}", emoteHost["url"].ToString(), "[scale]x", emoteFormat);
StvEmoteFlags emoteFlags = (StvEmoteFlags)(int)emoteData["flags"];
bool emoteIsListed = (bool)emoteData["listed"];
EmoteResponseItem emoteResponse = new() { Id = emoteId, Code = emoteName, ImageType = emoteFormat, ImageUrl = emoteUrl };
if ((emoteFlags & StvEmoteFlags.ZeroWidth) == StvEmoteFlags.ZeroWidth)
{
emoteResponse.IsZeroWidth = true;
}
if ((emoteFlags & StvEmoteFlags.ContentTwitchDisallowed) == StvEmoteFlags.ContentTwitchDisallowed || (emoteFlags & StvEmoteFlags.Private) == StvEmoteFlags.Private)
{
continue;
}
if (emoteIsListed)
{
emoteReponse.STV.Add(emoteResponse);
}
}
}
return emoteReponse;
}
public static async Task<List<TwitchEmote>> GetThirdPartyEmotes(int streamerId, string cacheFolder, EmbeddedData embeddedData = null, bool bttv = true, bool ffz = true, bool stv = true, bool offline = false)
{
List<TwitchEmote> returnList = new List<TwitchEmote>();
List<string> alreadyAdded = new List<string>();
// Load our embedded data from file
if (embeddedData != null && embeddedData.thirdParty != null)
{
foreach (EmbedEmoteData emoteData in embeddedData.thirdParty)
{
try
{
TwitchEmote newEmote = new TwitchEmote(emoteData.data, EmoteProvider.ThirdParty, emoteData.imageScale, emoteData.id, emoteData.name);
returnList.Add(newEmote);
alreadyAdded.Add(emoteData.name);
}
catch { }
}
}
// Directly return if we are in offline, no need for a network request
if (offline)
{
return returnList;
}
string bttvFolder = Path.Combine(cacheFolder, "bttv");
string ffzFolder = Path.Combine(cacheFolder, "ffz");
string stvFolder = Path.Combine(cacheFolder, "stv");
EmoteResponse emoteDataResponse = await GetThirdPartyEmoteData(streamerId.ToString(), bttv, ffz, stv);
if (bttv)
{
if (!Directory.Exists(bttvFolder))
TwitchHelper.CreateDirectory(bttvFolder);
foreach (var emote in emoteDataResponse.BTTV)
{
if (alreadyAdded.Contains(emote.Code))
continue;
try
{
TwitchEmote newEmote = new TwitchEmote(await GetImage(bttvFolder, emote.ImageUrl.Replace("[scale]", "2"), emote.Id, "2", emote.ImageType), EmoteProvider.ThirdParty, 2, emote.Id, emote.Code);
if (emote.IsZeroWidth)
newEmote.IsZeroWidth = true;
returnList.Add(newEmote);
alreadyAdded.Add(emote.Code);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
}
if (ffz)
{
if (!Directory.Exists(ffzFolder))
TwitchHelper.CreateDirectory(ffzFolder);
foreach (var emote in emoteDataResponse.FFZ)
{
if (alreadyAdded.Contains(emote.Code))
continue;
try
{
TwitchEmote newEmote = new TwitchEmote(await GetImage(ffzFolder, emote.ImageUrl.Replace("[scale]", "2"), emote.Id, "2", emote.ImageType), EmoteProvider.ThirdParty, 2, emote.Id, emote.Code);
returnList.Add(newEmote);
alreadyAdded.Add(emote.Code);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
}
if (stv)
{
if (!Directory.Exists(stvFolder))
TwitchHelper.CreateDirectory(stvFolder);
foreach (var emote in emoteDataResponse.STV)
{
if (alreadyAdded.Contains(emote.Code))
continue;
try
{
TwitchEmote newEmote = new TwitchEmote(await GetImage(stvFolder, emote.ImageUrl.Replace("[scale]", "2"), emote.Id, "2", emote.ImageType), EmoteProvider.ThirdParty, 2, emote.Id, emote.Code);
if (emote.IsZeroWidth)
newEmote.IsZeroWidth = true;
returnList.Add(newEmote);
alreadyAdded.Add(emote.Code);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
}
return returnList;
}
public static async Task<List<TwitchEmote>> GetEmotes(List<Comment> comments, string cacheFolder, EmbeddedData embeddedData = null, bool offline = false)
{
List<TwitchEmote> returnList = new List<TwitchEmote>();
List<string> alreadyAdded = new List<string>();
List<string> failedEmotes = new List<string>();
string emoteFolder = Path.Combine(cacheFolder, "emotes");
if (!Directory.Exists(emoteFolder))
TwitchHelper.CreateDirectory(emoteFolder);
// Load our embedded emotes
if (embeddedData != null && embeddedData.firstParty != null)
{
foreach (EmbedEmoteData emoteData in embeddedData.firstParty)
{
try
{
TwitchEmote newEmote = new TwitchEmote(emoteData.data, EmoteProvider.FirstParty, emoteData.imageScale, emoteData.id, emoteData.name);
returnList.Add(newEmote);
alreadyAdded.Add(emoteData.id);
}
catch { }
}
}
// Directly return if we are in offline, no need for a network request
if (offline)
{
return returnList;
}
foreach (var comment in comments)
{
if (comment.message.fragments == null)
continue;
foreach (var fragment in comment.message.fragments)
{
if (fragment.emoticon != null)
{
string id = fragment.emoticon.emoticon_id;
if (!alreadyAdded.Contains(id) && !failedEmotes.Contains(id))
{
try
{
byte[] bytes = await GetImage(emoteFolder, String.Format("https://static-cdn.jtvnw.net/emoticons/v2/{0}/default/dark/2.0", id), id, "2", "png");
TwitchEmote newEmote = new TwitchEmote(bytes, EmoteProvider.FirstParty, 2, id, id);
alreadyAdded.Add(id);
returnList.Add(newEmote);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
failedEmotes.Add(id);
}
}
}
}
}
return returnList;
}
public static async Task<List<ChatBadge>> GetChatBadges(int streamerId, string cacheFolder, EmbeddedData embeddedData = null, bool offline = false)
{
List<ChatBadge> returnList = new List<ChatBadge>();
List<string> alreadyAdded = new List<string>();
// Load our embedded data from file
if (embeddedData != null && embeddedData.twitchBadges != null)
{
foreach (EmbedChatBadge data in embeddedData.twitchBadges)
{
ChatBadge newBadge = new ChatBadge(data.name, data.versions);
returnList.Add(newBadge);
alreadyAdded.Add(data.name);
}
}
// Directly return if we are in offline, no need for a network request
if (offline)
{
return returnList;
}
// TODO: this currently only does twitch badges, but we could also support FFZ, BTTV, 7TV, etc badges!
// TODO: would want to make this configurable as we do for emotes though...
JObject globalBadges = JObject.Parse(await httpClient.GetStringAsync("https://badges.twitch.tv/v1/badges/global/display"));
JObject subBadges = JObject.Parse(await httpClient.GetStringAsync($"https://badges.twitch.tv/v1/badges/channels/{streamerId}/display"));
string badgeFolder = Path.Combine(cacheFolder, "badges");
if (!Directory.Exists(badgeFolder))
TwitchHelper.CreateDirectory(badgeFolder);
foreach (var badge in subBadges["badge_sets"].Union(globalBadges["badge_sets"]))
{
JProperty jBadgeProperty = badge.ToObject<JProperty>();
string name = jBadgeProperty.Name;
if (alreadyAdded.Contains(name))
continue;
try
{
Dictionary<string, byte[]> versions = new Dictionary<string, byte[]>();
foreach (var version in badge.First["versions"])
{
JProperty jVersionProperty = version.ToObject<JProperty>();
string versionString = jVersionProperty.Name;
string downloadUrl = version.First["image_url_2x"].ToString();
string[] id_parts = downloadUrl.Split('/');
string id = id_parts[id_parts.Length - 2];
byte[] bytes = await GetImage(badgeFolder, downloadUrl, id, "2", "png");
versions.Add(versionString, bytes);
}
returnList.Add(new ChatBadge(name, versions));
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
return returnList;
}
public static async Task<Dictionary<string, SKBitmap>> GetTwitterEmojis(string cacheFolder)
{
Dictionary<string, SKBitmap> returnCache = new Dictionary<string, SKBitmap>();
string emojiFolder = Path.Combine(cacheFolder, "emojis");
Regex emojiExtensions = new Regex(@"\.(png|PNG)");
if (!Directory.Exists(emojiFolder))
TwitchHelper.CreateDirectory(emojiFolder);
int emojiCount = Directory.GetFiles(emojiFolder).Where(i => emojiExtensions.IsMatch(i)).Count();
//Twemoji 14 has 3689 emoji images
if (emojiCount < 3689)
{
string emojiZipPath = Path.Combine(emojiFolder, Path.GetRandomFileName());
byte[] emojiZipData = Resources.twemoji_14_0_0;
await File.WriteAllBytesAsync(emojiZipPath, emojiZipData);
using (ZipArchive archive = ZipFile.OpenRead(emojiZipPath))
{
var emojiAssetsPath = Path.Combine("twemoji-14.0.0", "assets", "72x72");
var emojis = archive.Entries.Where(x => Path.GetDirectoryName(x.FullName) == emojiAssetsPath && !String.IsNullOrWhiteSpace(x.Name));
foreach (var emoji in emojis)
{
string filePath = Path.Combine(emojiFolder, emoji.Name.ToUpper().Replace("-", " "));
if (!File.Exists(filePath))
{
try
{
emoji.ExtractToFile(filePath);
}
catch { }
}
}
}
if (File.Exists(emojiZipPath))
{
File.Delete(emojiZipPath);
}
}
List<string> emojiList = Directory.GetFiles(emojiFolder).Where(i => emojiExtensions.IsMatch(i)).ToList();
foreach (var emojiPath in emojiList)
{
SKBitmap emojiImage = SKBitmap.Decode(await File.ReadAllBytesAsync(emojiPath));
returnCache.Add(Path.GetFileNameWithoutExtension(emojiPath), emojiImage);
}
return returnCache;
}
public static async Task<List<CheerEmote>> GetBits(string cacheFolder, string channel_id = "", EmbeddedData embeddedData = null, bool offline = false)
{
List<CheerEmote> returnList = new List<CheerEmote>();
List<string> alreadyAdded = new List<string>();
// Load our embedded data from file
if (embeddedData != null && embeddedData.twitchBits != null)
{
foreach (EmbedCheerEmote data in embeddedData.twitchBits)
{
List<KeyValuePair<int, TwitchEmote>> tierList = new List<KeyValuePair<int, TwitchEmote>>();
CheerEmote newEmote = new CheerEmote() { prefix = data.prefix, tierList = tierList };
foreach (KeyValuePair<int, EmbedEmoteData> tier in data.tierList)
{
TwitchEmote tierEmote = new TwitchEmote(tier.Value.data, EmoteProvider.FirstParty, tier.Value.imageScale, tier.Value.id, tier.Value.name);
tierList.Add(new KeyValuePair<int, TwitchEmote>(tier.Key, tierEmote));
}
returnList.Add(newEmote);
alreadyAdded.Add(data.prefix);
}
}
// Directly return if we are in offline, no need for a network request
if (offline)
{
return returnList;
}
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{cheerConfig{groups{nodes{id, prefix, tiers{bits}}, templateURL}},user(id:\\\"" + channel_id + "\\\"){cheer{cheerGroups{nodes{id,prefix,tiers{bits}},templateURL}}}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
GqlCheerResponse cheerResponse = JsonConvert.DeserializeObject<GqlCheerResponse>(response);
string bitFolder = Path.Combine(cacheFolder, "bits");
if (!Directory.Exists(bitFolder))
TwitchHelper.CreateDirectory(bitFolder);
if (cheerResponse != null && cheerResponse.data != null)
{
List<CheerGroup> groupList = new List<CheerGroup>();
foreach (CheerGroup group in cheerResponse.data.cheerConfig.groups)
{
groupList.Add(group);
}
if (cheerResponse.data.user != null && cheerResponse.data.user.cheer != null && cheerResponse.data.user.cheer.cheerGroups != null)
{
foreach (var group in cheerResponse.data.user.cheer.cheerGroups)
{
groupList.Add(group);
}
}
foreach (CheerGroup group in groupList)
{
string templateURL = group.templateURL;
foreach (CheerNode node in group.nodes)
{
string prefix = node.prefix;
if (alreadyAdded.Contains(prefix))
continue;
try
{
List<KeyValuePair<int, TwitchEmote>> tierList = new List<KeyValuePair<int, TwitchEmote>>();
CheerEmote newEmote = new CheerEmote() { prefix = prefix, tierList = tierList };
foreach (Tier tier in node.tiers)
{
int minBits = tier.bits;
string url = templateURL.Replace("PREFIX", node.prefix.ToLower()).Replace("BACKGROUND", "dark").Replace("ANIMATION", "animated").Replace("TIER", tier.bits.ToString()).Replace("SCALE.EXTENSION", "2.gif");
TwitchEmote emote = new TwitchEmote(await GetImage(bitFolder, url, node.id + tier.bits, "2", "gif"), EmoteProvider.FirstParty, 2, prefix + minBits, prefix + minBits);
tierList.Add(new KeyValuePair<int, TwitchEmote>(minBits, emote));
}
returnList.Add(newEmote);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
}
}
}
return returnList;
}
public static DirectoryInfo CreateDirectory(string path)
{
DirectoryInfo directoryInfo = Directory.CreateDirectory(path);
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
SetDirectoryPermissions(path);
}
}
catch { }
return directoryInfo;
}
public static void SetDirectoryPermissions(string path)
{
var folderInfo = new Mono.Unix.UnixFileInfo(path);
folderInfo.FileAccessPermissions = Mono.Unix.FileAccessPermissions.AllPermissions;
folderInfo.Refresh();
}
public static int TimestampToSeconds(string input)
{
//There might be a better way to do this, gets string 0h0m0s and returns timespan
TimeSpan returnSpan = new TimeSpan(0);
string[] inputArray = input.Remove(input.Length - 1).Replace('h', ':').Replace('m', ':').Split(':');
returnSpan = returnSpan.Add(TimeSpan.FromSeconds(Int32.Parse(inputArray[inputArray.Length - 1])));
if (inputArray.Length > 1)
returnSpan = returnSpan.Add(TimeSpan.FromMinutes(Int32.Parse(inputArray[inputArray.Length - 2])));
if (inputArray.Length > 2)
returnSpan = returnSpan.Add(TimeSpan.FromHours(Int32.Parse(inputArray[inputArray.Length - 3])));
return (int)returnSpan.TotalSeconds;
}
public static async Task<string> GetStreamerName(int id)
{
try
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://gql.twitch.tv/gql"),
Method = HttpMethod.Post,
Content = new StringContent("{\"query\":\"query{user(id:\\\"" + id.ToString() + "\\\"){login}}\",\"variables\":{}}", Encoding.UTF8, "application/json")
};
request.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");
string response = await (await httpClient.SendAsync(request)).Content.ReadAsStringAsync();
JObject res = JObject.Parse(response);
return res["data"]["user"]["login"].ToString();
}
catch { return ""; }
}
public static async Task<byte[]> GetImage(string cachePath, string imageUrl, string imageId, string imageScale, string imageType)
{
byte[] imageBytes = null;
string filePath = Path.Combine(cachePath, imageId + "_" + imageScale + "." + imageType);
if (File.Exists(filePath))
{
try
{
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] bytes = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
await stream.ReadAsync(bytes, 0, bytes.Length);
//Check if image file is not corrupt
if (bytes.Length > 0)
{
using SKImage image = SKImage.FromEncodedData(bytes);
if (image != null)
{
imageBytes = bytes;
}
else
{
//Try to delete the corrupted image
try
{
stream.Dispose();
File.Delete(filePath);
}
catch { }
}
}
}
}
catch (IOException)
{
//File being written to by parallel process? Maybe. Can just fallback to HTTP request.
}
}
if (imageBytes != null)
return imageBytes;
imageBytes = await httpClient.GetByteArrayAsync(imageUrl);
//Let's save this image to the cache
try
{
using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
stream.Write(imageBytes, 0, imageBytes.Length);
}
}
catch { }
return imageBytes;
}
}
}