-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVideoPage.xaml.cs
1923 lines (1606 loc) · 72.1 KB
/
VideoPage.xaml.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.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using Windows.UI.Xaml.Media;
using Newtonsoft.Json.Linq;
using Windows.UI.Notifications;
using System.IO;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using System.Diagnostics;
using Windows.UI.Xaml.Documents;
using System.Text.RegularExpressions;
using Windows.UI.Xaml.Input;
using Windows.UI;
using System.Text;
using Windows.Security.Authentication.Web;
using System.Net.Http.Headers;
using Windows.ApplicationModel.Activation;
using Windows.Phone.UI.Input;
namespace ValleyTube
{
public sealed partial class VideoPage : Page
{
private string videoId;
private string aurthorId;
private string continuationToken;
private DispatcherTimer syncTimer;
private bool isSyncing = false;
private VideoResult nextVideo;
private List<SponsorBlockSegment> sponsorSegments;
private LikedVideosManager likedVideosManager = new LikedVideosManager();
private WatchLaterManager watchLaterManager = new WatchLaterManager();
public VideoPage()
{
this.InitializeComponent();
InitializeSyncTimer();
SubscriptionManager.LoadSubscriptions();
ToggleCommentInputPanel();
UpdateLikeButtonState();
UpdateWatchLaterButtonState();
VideoWidthRes();
}
private void VideoWidthRes()
{
double screenHeight = Window.Current.Bounds.Height;
double desiredHeight = screenHeight * 0.35;
double screenWidth = Window.Current.Bounds.Width;
double desiredWidth = screenWidth * 0.9;
VideoPlayer.Height = desiredHeight;
VideoPlayer.Width = desiredWidth;
}
private void InitializeSyncTimer()
{
syncTimer = new DispatcherTimer();
syncTimer.Interval = TimeSpan.FromMilliseconds(200);
syncTimer.Tick += SyncTimer_Tick;
}
private void SyncTimer_Tick(object sender, object e)
{
if (AudioPlayer.Source != null)
{
SyncAudioWithVideo();
}
if (Settings.isSponserBlock)
{
SkipSponsorSegments();
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter != null)
{
string parameter = e.Parameter as string;
if (!string.IsNullOrWhiteSpace(parameter))
{
videoId = parameter;
System.Diagnostics.Debug.WriteLine("Navigated to VideoPage with videoId: " + videoId);
await LoadVideoDetails();
await LoadRelatedVideos();
LoadLikesDislikesData(videoId);
LoadComments();
}
else
{
System.Diagnostics.Debug.WriteLine("Error: Parameter is not a valid string or is empty.");
}
}
else
{
System.Diagnostics.Debug.WriteLine("Error: e.Parameter is null.");
}
}
public async Task HandleAuthenticationResult(WebAuthenticationResult result)
{
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
string responseData = result.ResponseData;
string authorizationCode = ExtractAuthorizationCode(responseData);
Settings.AccessToken = await GetAccessToken(authorizationCode);
if (!string.IsNullOrEmpty(Settings.AccessToken))
{
System.Diagnostics.Debug.WriteLine("User authenticated successfully.");
}
}
else
{
System.Diagnostics.Debug.WriteLine("Authentication failed: " + result.ResponseStatus);
}
}
public async void LoadLikesDislikesData(string videoId)
{
var url = $"{Settings.ReturnDislikeInstance}/Votes?videoId={videoId}";
using (var httpClient = new HttpClient())
{
try
{
var response = await httpClient.GetStringAsync(url);
if (response.StartsWith("<"))
{
System.Diagnostics.Debug.WriteLine("Received HTML instead of JSON. Response: " + response);
LikesTextBlock.Text = "[N/A] Likes";
DislikesTextBlock.Text = "[N/A] Dislikes";
return;
}
var jsonData = JObject.Parse(response);
var likes = (int)jsonData["likes"];
var dislikes = (int)jsonData["dislikes"];
LikesTextBlock.Text = $"{likes:N0} Likes - ";
DislikesTextBlock.Text = $"{dislikes:N0} Dislikes";
}
catch (HttpRequestException ex)
{
LikesTextBlock.Text = "[N/A] Likes";
DislikesTextBlock.Text = "[N/A] Dislikes";
System.Diagnostics.Debug.WriteLine($"Error fetching data: {ex.Message}");
}
catch (JsonReaderException ex)
{
LikesTextBlock.Text = "[N/A] Likes";
DislikesTextBlock.Text = "[N/A] Dislikes";
System.Diagnostics.Debug.WriteLine($"Error parsing JSON: {ex.Message}");
}
catch (Exception ex)
{
LikesTextBlock.Text = "[N/A] Likes";
DislikesTextBlock.Text = "[N/A] Dislikes";
System.Diagnostics.Debug.WriteLine($"Unexpected error: {ex.Message}");
}
}
}
private async Task<List<SponsorBlockSegment>> GetSponsorSegments(string videoId)
{
string sponsorBlockUrl = Settings.SponserBlockInstance + "/api/skipSegments?videoID=" + videoId;
using (var httpClient = new HttpClient())
{
try
{
var response = await httpClient.GetStringAsync(sponsorBlockUrl);
var segments = JsonConvert.DeserializeObject<List<SponsorBlockSegment>>(response);
foreach (var segment in segments)
{
System.Diagnostics.Debug.WriteLine($"SponsorBlock Segment: Start - {segment.Segment[0]}, End - {segment.Segment[1]}, Category - {segment.Category}");
}
return segments;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error fetching SponsorBlock segments: " + ex.Message);
return new List<SponsorBlockSegment>();
}
}
}
private async Task LoadVideoDetails()
{
string videoUrl = Settings.InvidiousInstance + "/api/v1/videos/" + videoId;
using (var httpClient = new HttpClient())
{
try
{
var response = await httpClient.GetStringAsync(videoUrl);
var video = JsonConvert.DeserializeObject<VideoDetail>(response);
VideoTitle.Text = video.Title;
aurthorId = video.authorId;
long unixTimestamp = long.Parse(video.published);
long views = long.Parse(video.viewCount);
string formattedDate = Utils.ConvertUnixTimestampToRelativeTime(unixTimestamp);
string formattedViews = Utils.AddCommasToNumber(views);
string formattedTags = Utils.ConvertKeywordsToCommaSeparated(video.Keywords);
DateTextBlock.Text = formattedDate;
AuthorTextBlock.Text = video.author + " - ";
ViewTextBlock.Text = " - " + formattedViews + " views";
SetDescriptionText(video.Description);
GenreTextBlock.Text = "Genre: " + video.genre;
TagsTextBlock.Text = "Tags: " + formattedTags;
InitializeSubscriptionButton(video.VideoId);
Uri videoUri = null;
Uri audioUri = null;
var selectedQuality = Settings.SelectedQuality;
System.Diagnostics.Debug.WriteLine("Selected Quality: " + selectedQuality);
sponsorSegments = await GetSponsorSegments(videoId);
if (selectedQuality.EndsWith("-innertube"))
{
string innerTubeVideoUrl = Settings.InnerTubeBase + "/youtubei/v1/player?key=" + Settings.InnerTubeAPIKey;
DateTime currentUtcDateTime = DateTime.UtcNow;
long signature_timestamp = (long)(currentUtcDateTime - new DateTime(1970, 1, 1)).TotalSeconds;
var contextData = new
{
videoId = videoId,
context = new
{
client = new
{
hl = "en",
gl = "US",
clientName = "IOS",
clientVersion = "19.29.1",
deviceMake = "Apple",
deviceModel = "iPhone",
osName = "iOS",
userAgent = "com.google.ios.youtube/19.29.1 (iPhone16,2; U; CPU iOS 17_5_1 like Mac OS X;)",
osVersion = "17.5.1.21F90"
}
},
playbackContext = new
{
contentPlaybackContext = new
{
signatureTimestamp = signature_timestamp
}
}
};
string jsonContent = JsonConvert.SerializeObject(contextData);
var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
var innerTubeResponse = await httpClient.PostAsync(innerTubeVideoUrl, requestContent);
innerTubeResponse.EnsureSuccessStatusCode();
var innerTubeData = await innerTubeResponse.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine("InnerTube API Response: " + innerTubeData);
var innerTubeVideo = JsonConvert.DeserializeObject<InnerTubeVideoDetail>(innerTubeData);
if (innerTubeVideo.streamingData != null && innerTubeVideo.streamingData.adaptiveFormats != null)
{
var innerTubeFormat = innerTubeVideo.streamingData.adaptiveFormats.FirstOrDefault(f => f.itag == 140);
var videoFormats = innerTubeVideo.streamingData.adaptiveFormats.Select(f => new ValleyTube.Format
{
itag = f.itag,
url = f.url,
height = f.height,
width = f.width,
mimeType = f.mimeType
}).ToList();
string cleanedQuality = selectedQuality.Replace("-innertube", "");
Uri audioUrl;
Uri bestVideoUrl = GetBestInnerTubeVideoUri(videoFormats, cleanedQuality, out audioUrl);
System.Diagnostics.Debug.WriteLine("Best Video URI: " + (bestVideoUrl != null ? bestVideoUrl.AbsoluteUri : "Not Found"));
if (bestVideoUrl != null)
{
System.Diagnostics.Debug.WriteLine("Using InnerTube Video URL: " + bestVideoUrl.AbsoluteUri);
VideoPlayer.Source = bestVideoUrl;
if (innerTubeFormat != null)
{
var innerTubeAudioUri = new Uri(innerTubeFormat.url);
AudioPlayer.Source = innerTubeAudioUri;
System.Diagnostics.Debug.WriteLine("Using InnerTube Audio URL: " + innerTubeAudioUri.AbsoluteUri);
}
VideoPlayer.MediaOpened += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Video started playing.");
if (audioUrl != null)
{
AudioPlayer.Source = audioUrl;
AudioPlayer.Play();
}
};
VideoPlayer.MediaFailed += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Media failed to play. Error: " + args.ErrorMessage);
};
VideoPlayer.Play();
}
else
{
System.Diagnostics.Debug.WriteLine("No suitable video format found.");
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error loading video details: " + ex.Message);
}
}
else
{
if (selectedQuality == "360p-direct")
{
string videoUrlString = string.Format(Settings.InvidiousInstance + "/latest_version?id={0}&itag=18&local=true", video.VideoId);
videoUri = new Uri(videoUrlString);
System.Diagnostics.Debug.WriteLine("Using Direct Video URL: " + videoUri.AbsoluteUri);
}
else if (selectedQuality == "360p-format-stream")
{
var adaptiveFormat = video.formatStreams.FirstOrDefault(f => f.qualityLabel == "360p");
if (adaptiveFormat != null)
{
videoUri = new Uri(adaptiveFormat.url);
System.Diagnostics.Debug.WriteLine("Using Adaptive Video URL: " + videoUri.AbsoluteUri);
}
else
{
System.Diagnostics.Debug.WriteLine("No 360p-adaptive format found.");
}
}
else
{
videoUri = GetBestVideoUri(video.adaptiveFormats, selectedQuality, out audioUri);
System.Diagnostics.Debug.WriteLine("Best Video URI: " + (videoUri != null ? videoUri.AbsoluteUri : "Not Found"));
if (audioUri != null)
{
System.Diagnostics.Debug.WriteLine("Audio URI: " + audioUri.AbsoluteUri);
}
}
}
VideoPlayer.MediaFailed += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Media failed to play. Error: " + args.ErrorMessage);
};
if (videoUri != null)
{
VideoPlayer.Source = videoUri;
VideoPlayer.MediaOpened += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Video started playing.");
if (audioUri != null)
{
AudioPlayer.Source = audioUri;
AudioPlayer.Play();
}
};
VideoPlayer.Play();
}
else
{
System.Diagnostics.Debug.WriteLine("No valid video URL found.");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error loading video details: " + ex.Message);
}
}
}
private void SetDescriptionText(string description)
{
DescriptionRichTextBlock.Blocks.Clear();
string urlPattern = @"(http|https)://[^\s]+";
MatchCollection matches = Regex.Matches(description, urlPattern);
var paragraph = new Paragraph();
int lastIndex = 0;
foreach (Match match in matches)
{
if (match.Index > lastIndex)
{
var run = new Run();
run.Text = description.Substring(lastIndex, match.Index - lastIndex);
paragraph.Inlines.Add(run);
}
var hyperlink = new Hyperlink
{
Foreground = new SolidColorBrush(Windows.UI.Colors.LightBlue)
};
var linkRun = new Run();
linkRun.Text = match.Value;
hyperlink.Inlines.Add(linkRun);
hyperlink.Click += (s, e) =>
{
Windows.System.Launcher.LaunchUriAsync(new Uri(match.Value));
};
paragraph.Inlines.Add(hyperlink);
lastIndex = match.Index + match.Length;
}
if (lastIndex < description.Length)
{
var remainingRun = new Run();
remainingRun.Text = description.Substring(lastIndex);
paragraph.Inlines.Add(remainingRun);
}
DescriptionRichTextBlock.Blocks.Add(paragraph);
}
public class QualityRange
{
public int MinQuality { get; set; }
public int MaxQuality { get; set; }
public QualityRange(int min, int max)
{
MinQuality = min;
MaxQuality = max;
}
}
private Uri GetBestVideoUri(IEnumerable<VideoFormat> formats, string selectedQuality, out Uri audioUri)
{
audioUri = null;
if (formats == null)
{
System.Diagnostics.Debug.WriteLine("No video formats available.");
return null;
}
var qualityRanges = new Dictionary<string, QualityRange>();
qualityRanges.Add("144", new QualityRange(100, 199));
qualityRanges.Add("240", new QualityRange(200, 299));
qualityRanges.Add("360", new QualityRange(300, 399));
qualityRanges.Add("480", new QualityRange(400, 599));
qualityRanges.Add("720", new QualityRange(600, 799));
qualityRanges.Add("1080", new QualityRange(800, 1100));
if (!qualityRanges.ContainsKey(selectedQuality))
{
System.Diagnostics.Debug.WriteLine("Selected quality '" + selectedQuality + "' is not defined in quality ranges.");
return null;
}
int minQuality = qualityRanges[selectedQuality].MinQuality;
int maxQuality = qualityRanges[selectedQuality].MaxQuality;
VideoFormat bestFormat = null;
foreach (VideoFormat format in formats)
{
if (format.encoding == "h264")
{
int quality = ParseQuality(format.qualityLabel);
if (quality >= minQuality && quality <= maxQuality)
{
if (bestFormat == null || ParseQuality(format.qualityLabel) > ParseQuality(bestFormat.qualityLabel))
{
bestFormat = format;
}
}
}
}
if (bestFormat != null)
{
System.Diagnostics.Debug.WriteLine("Selected video quality: " + bestFormat.qualityLabel);
System.Diagnostics.Debug.WriteLine("Selected video itag: " + bestFormat.itag);
var videoUri = new Uri(bestFormat.url);
foreach (VideoFormat format in formats)
{
if (format.itag == "140")
{
audioUri = new Uri(format.url);
System.Diagnostics.Debug.WriteLine("Selected audio track URL: " + audioUri.AbsoluteUri);
break;
}
}
return videoUri;
}
System.Diagnostics.Debug.WriteLine("No suitable video format found.");
return null;
}
private Uri GetBestInnerTubeVideoUri(IEnumerable<Format> videoFormats, string selectedQuality, out Uri audioUri)
{
audioUri = null;
if (videoFormats == null || !videoFormats.Any())
{
System.Diagnostics.Debug.WriteLine("No video formats available.");
return null;
}
int targetHeight;
if (!int.TryParse(new string(selectedQuality.Where(char.IsDigit).ToArray()), out targetHeight))
{
System.Diagnostics.Debug.WriteLine("Invalid quality format. Falling back to default height of 144.");
targetHeight = 144;
}
Format bestFormat = null;
int minHeightDifference = int.MaxValue;
System.Diagnostics.Debug.WriteLine("Available video formats:");
foreach (var format in videoFormats)
{
System.Diagnostics.Debug.WriteLine($"itag={format.itag}, mimeType={format.mimeType}, height={format.height}, url={format.url}");
}
foreach (Format format in videoFormats)
{
System.Diagnostics.Debug.WriteLine($"Checking format: itag={format.itag}, mimeType={format.mimeType}, height={format.height}, url={format.url}");
if (format.mimeType.Contains("mp4") && format.mimeType.Contains("video"))
{
int height;
if (int.TryParse(format.height, out height))
{
int heightDifference = Math.Abs(height - targetHeight);
if (heightDifference < minHeightDifference)
{
minHeightDifference = heightDifference;
bestFormat = format;
System.Diagnostics.Debug.WriteLine($"Found better format: itag={format.itag}, height={height}");
}
}
else
{
System.Diagnostics.Debug.WriteLine($"Skipping format, height invalid: itag={format.itag}, height={format.height}");
}
}
else
{
System.Diagnostics.Debug.WriteLine($"Skipping format, not a valid video/mp4: itag={format.itag}, mimeType={format.mimeType}");
}
}
if (bestFormat != null)
{
System.Diagnostics.Debug.WriteLine("Selected video quality: " + bestFormat.qualityLabel);
System.Diagnostics.Debug.WriteLine("Selected video itag: " + bestFormat.itag);
Uri videoUri = new Uri(bestFormat.url);
foreach (Format format in videoFormats)
{
if (format != null && format.itag == 140)
{
audioUri = new Uri(format.url);
System.Diagnostics.Debug.WriteLine("Selected audio track URL: " + audioUri.AbsoluteUri);
break;
}
}
return videoUri;
}
System.Diagnostics.Debug.WriteLine("No suitable video format found.");
return null;
}
private bool IsQualityInRange(string qualityLabel, int minQuality, int maxQuality)
{
int parsedQuality = ParseQuality(qualityLabel);
return parsedQuality >= minQuality && parsedQuality <= maxQuality;
}
private int ParseQuality(string qualityLabel)
{
if (qualityLabel.EndsWith("p"))
{
qualityLabel = qualityLabel.Substring(0, qualityLabel.Length - 1);
}
string numericPart = "";
foreach (char c in qualityLabel)
{
if (char.IsDigit(c))
{
numericPart += c;
}
}
int quality;
if (int.TryParse(numericPart, out quality))
{
return quality;
}
return 0;
}
private void LoadComments(string sortBy = "top", string source = "youtube")
{
string commentsUrl = Settings.InvidiousInstanceComments + "/api/v1/comments/" + videoId +
"?sort_by=" + sortBy +
"&source=" + source;
if (!string.IsNullOrEmpty(continuationToken))
{
commentsUrl += "&continuation=" + continuationToken;
}
System.Diagnostics.Debug.WriteLine("Request URL: " + commentsUrl);
using (var httpClient = new HttpClient())
{
try
{
var responseTask = httpClient.GetAsync(commentsUrl);
responseTask.Wait();
var response = responseTask.Result;
if (response.IsSuccessStatusCode)
{
var responseDataTask = response.Content.ReadAsStringAsync();
responseDataTask.Wait();
var responseData = responseDataTask.Result;
var commentsData = JsonConvert.DeserializeObject<CommentsResponse>(responseData);
if (commentsData != null && commentsData.comments != null)
{
if (continuationToken == null)
{
CommentsListView.ItemsSource = commentsData.comments;
}
else
{
var currentItems = CommentsListView.ItemsSource as List<Comment>;
if (currentItems != null)
{
currentItems.AddRange(commentsData.comments);
CommentsListView.ItemsSource = null;
CommentsListView.ItemsSource = currentItems;
}
}
continuationToken = commentsData.continuation;
}
else
{
System.Diagnostics.Debug.WriteLine("No comments found.");
}
}
else
{
System.Diagnostics.Debug.WriteLine(String.Format("Error loading comments: {0} - {1}", response.StatusCode, response.ReasonPhrase));
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error loading comments: " + ex.Message);
}
}
}
private void CommentsScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var scrollViewer = sender as ScrollViewer;
if (scrollViewer != null)
{
System.Diagnostics.Debug.WriteLine($"ScrollViewer VerticalOffset: {scrollViewer.VerticalOffset}");
System.Diagnostics.Debug.WriteLine($"ScrollViewer ScrollableHeight: {scrollViewer.ScrollableHeight}");
double threshold = scrollViewer.ScrollableHeight * 0.1;
if (scrollViewer.VerticalOffset >= scrollViewer.ScrollableHeight - threshold)
{
System.Diagnostics.Debug.WriteLine("Reached the threshold, loading more comments.");
LoadComments();
}
else
{
System.Diagnostics.Debug.WriteLine("Not close enough to the bottom to load more comments.");
}
}
}
private async Task LoadRelatedVideos()
{
string relatedVideosUrl = Settings.InvidiousInstance + "/api/v1/videos/" + videoId;
System.Diagnostics.Debug.WriteLine("Requesting URL: " + relatedVideosUrl);
using (var httpClient = new HttpClient())
{
try
{
var response = await httpClient.GetStringAsync(relatedVideosUrl);
var videoData = JsonConvert.DeserializeObject<VideoDetail>(response);
if (videoData == null)
{
System.Diagnostics.Debug.WriteLine("Failed to deserialize video data.");
return;
}
if (videoData.recommendedVideos != null && videoData.recommendedVideos.Any())
{
RelatedVideosListView.ItemsSource = videoData.recommendedVideos;
nextVideo = videoData.recommendedVideos.First();
}
else
{
System.Diagnostics.Debug.WriteLine("No recommended videos found.");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error loading related videos: " + ex.Message);
}
}
}
private int GetQuality(string qualityLabel)
{
if (string.IsNullOrEmpty(qualityLabel))
{
return 0;
}
if (qualityLabel.EndsWith("p"))
{
string qualityWithoutP = qualityLabel.Substring(0, qualityLabel.Length - 1);
int quality;
if (int.TryParse(qualityWithoutP, out quality))
{
return quality;
}
}
return 0;
}
private void GoToNextVideo()
{
if (nextVideo != null)
{
System.Diagnostics.Debug.WriteLine("Navigating to next video with ID: " + nextVideo.VideoId);
Frame.Navigate(typeof(VideoPage), nextVideo.VideoId);
MainPage.SaveHistory(nextVideo);
}
else
{
System.Diagnostics.Debug.WriteLine("No next video available.");
}
}
private async void SkipSponsorSegments()
{
if (sponsorSegments == null || !sponsorSegments.Any())
{
SponsorSkipMessageTextBlock.Visibility = Visibility.Collapsed;
return;
}
var currentPosition = VideoPlayer.Position.TotalSeconds;
int skippedSegmentsCount = 0;
foreach (var segment in sponsorSegments)
{
if (currentPosition >= segment.Segment[0] && currentPosition <= segment.Segment[1])
{
TimeSpan skipToTime = TimeSpan.FromSeconds(segment.Segment[1]);
System.Diagnostics.Debug.WriteLine($"Skipping sponsor segment from {segment.Segment[0]} to {segment.Segment[1]}");
VideoPlayer.Position = skipToTime;
if (AudioPlayer.Source != null)
{
AudioPlayer.Position = skipToTime;
}
skippedSegmentsCount++;
if (Settings.showSponserSkipMessage)
{
ShowToastNotification("Skipped sponsor segment!");
}
break;
}
}
}
private void ToggleCommentInputPanel()
{
string youtubeApiKey = Settings.YouTubeAPIKey;
if (string.IsNullOrEmpty(youtubeApiKey))
{
CommentInputPanel.Visibility = Visibility.Collapsed;
System.Diagnostics.Debug.WriteLine("YouTube API key is missing. Comment input panel hidden.");
}
else
{
CommentInputPanel.Visibility = Visibility.Visible;
System.Diagnostics.Debug.WriteLine("YouTube API key is available. Comment input panel visible.");
}
}
private string GetAuthorizationUrl()
{
return $"https://accounts.google.com/o/oauth2/auth?client_id={Settings.ClientId}&redirect_uri={Settings.RedirectUri}&scope={Settings.Scope}&response_type=code";
}
private async void AuthenticateUser()
{
string authUrl = GetAuthorizationUrl();
var startUri = new Uri(authUrl);
var endUri = new Uri(Settings.RedirectUri);
WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri);
}
private string ExtractAuthorizationCode(string responseData)
{
var uri = new Uri(responseData);
string query = uri.Query;
var queryParams = new Dictionary<string, string>();
foreach (var pair in query.TrimStart('?').Split('&'))
{
var parts = pair.Split('=');
if (parts.Length == 2)
{
queryParams[parts[0]] = Uri.UnescapeDataString(parts[1]);
}
}
return queryParams.ContainsKey("code") ? queryParams["code"] : null;
}
private async void LikeButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(Settings.AccessToken))
{
AuthenticateUser();
if (string.IsNullOrEmpty(Settings.AccessToken))
{
System.Diagnostics.Debug.WriteLine("User is not authenticated after attempting to log in.");
return;
}
}
if (likedVideosManager.IsVideoLiked(videoId))
{
await UnlikeVideo(videoId);
likedVideosManager.RemoveLikedVideo(videoId);
LikeButton.Content = "Like";
}
else
{
await LikeVideo(videoId);
likedVideosManager.AddLikedVideo(videoId);
LikeButton.Content = "Unlike";
}
UpdateLikeButtonState();
}
private void UpdateLikeButtonState()
{
if (likedVideosManager.IsVideoLiked(videoId))
{
LikeButton.Content = "Unlike";
}
else
{
LikeButton.Content = "Like";
}
}
private async void WatchLaterButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(Settings.AccessToken))
{
AuthenticateUser();
return;
}
if (watchLaterManager.IsVideoInWatchLater(videoId))
{
await RemoveFromWatchLater(videoId);
watchLaterManager.RemoveWatchLaterVideo(videoId);
WatchLaterButton.Content = "Add to Watch Later";
System.Diagnostics.Debug.WriteLine($"Removed Video ID: '{videoId}' from Watch Later.");
}
else
{
await AddToWatchLater(videoId);
watchLaterManager.AddWatchLaterVideo(videoId);
WatchLaterButton.Content = "Remove from Watch Later";
System.Diagnostics.Debug.WriteLine($"Added Video ID: '{videoId}' to Watch Later.");
}
UpdateWatchLaterButtonState();
}
private async Task AddToWatchLater(string videoId)
{
System.Diagnostics.Debug.WriteLine($"Adding Video ID: '{videoId}' to Watch Later");
if (string.IsNullOrEmpty(videoId))
{
System.Diagnostics.Debug.WriteLine("Video ID is missing.");
return;
}
string addToWatchLaterUrl = "https://youtube.googleapis.com/youtube/v3/playlistItems?key=" + Settings.YouTubeAPIKey;
var requestBody = new
{
snippet = new