-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathYouTube_Channel.dpr
1510 lines (1313 loc) · 61.4 KB
/
YouTube_Channel.dpr
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
{$I YOUTUBE_PLUGIN_DEFINES.INC}
{********************************************************************
| This Source Code is subject to the terms of the |
| Mozilla Public License, v. 2.0. If a copy of the MPL was not |
| distributed with this file, You can obtain one at |
| https://mozilla.org/MPL/2.0/. |
| |
| Software distributed under the License is distributed on an |
| "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or |
| implied. See the License for the specific language governing |
| rights and limitations under the License. |
********************************************************************}
{ This sample code uses the SuperObject library for the JSON parsing:
https://github.com/hgourvest/superobject
And the TNT Delphi Unicode Controls (compatiable with the last free version)
to handle a few unicode tasks.
And optionally, the FastMM/FastCode/FastMove libraries:
http://sourceforge.net/projects/fastmm/
}
library YouTube_Channel;
uses
FastMM4,
FastMove,
FastCode,
Windows,
SysUtils,
Classes,
Forms,
Controls,
DateUtils,
SyncObjs,
Dialogs,
StrUtils,
TNTClasses,
TNTSysUtils,
TNTSystem,
SuperObject,
WinInet,
ShellAPI,
misc_utils_unit,
YouTube_Channel_configureformunit,
ISO_3166_1_alpha_2_unit,
youtube_api;
{$R *.res}
Type
TCategoryPluginRecord =
Record
CategoryInput : PChar;
CategoryID : PChar;
CategoryTitle : PChar;
CategoryThumb : PChar;
DataPath : PChar;
Scrapers : PChar;
TextLines : Integer;
DefaultFlags : Integer;
SortMode : Integer;
End;
PCategoryPluginRecord = ^TCategoryPluginRecord;
TCategoryItemList =
Record
catItems : PChar;
// Format:
// Each entry contains multiple parameters (listed below).
// Entries are separated by the "|" character.
// Any use of the quote character must be encoded as """.
// "Type=[EntryType]","Path=[Path]","Title=[Title]","Description=[Description]","Thumbnail=[Thumbnail]","Date=[Date]","Duration=[Duration]"|"Type=[entryType]","Path=[Path]","Title=[Title]","Description=[Description]","Thumbnail=[Thumbnail]","Date=[Date]","Duration=[Duration]"|etc...
//
// Values:
// [EntryType] : 0 = Playable media
// 1 = Enter folder
// 2 = Append new entries, replace last previous entry (used to trigger the append action).
// 3 = Refresh all entries
// 100 = Live Stream
// 101 = Pending Stream
// [Path] : A UTF8 encoded string containing a file path or URL
// [Title] : A UTF8 encoded string containing the media's title
// [Description] : A UTF8 encoded string containing the media's description
// [Thumbnail] : A UTF8 encoded string containing the media's thumbnail path or URL
// [Date] : A string containing a float number in delphi time encoding representing the publish date and time.
// [Duration] : An floating point value representing the media's duration in seconds.
// [MetaEntry1] : Displayed in the meta-data's Title area
// [MetaEntry2] : Displayed in the meta-data's Date area
// [MetaEntry3] : Displayed in the meta-data's Genre/Type area
// [MetaEntry4] : Displayed in the meta-data's Overview/Description area
// [MetaEntry5] : Displayed in the meta-data's Actors/Media info area
End;
PCategoryItemList = ^TCategoryItemList;
Const
// Category flags
catFlagThumbView : Integer = 1; // Enable thumb view (disabled = list view)
catFlagThumbCrop : Integer = 2; // Crop media thumbnails to fit in display area (otherwise pad thumbnails)
catFlagVideoFramesAsThumb : Integer = 4; // Grab thumbnails from video frame
catFlagDarkenThumbBG : Integer = 8; // [Darken thumbnail area background], depreciated by "OPNavThumbDarkBG".
catFlagJukeBox : Integer = 16; // Jukebox mode enabled
catFlagBGFolderIcon : Integer = 32; // Draw folder icon if the folder has a thumbnail
catFlagScrapeParentFolder : Integer = 64; // Scrape the parent folder if no meta-data was found for the media file
catFlagScrapeMediaInFolder : Integer = 128; // Create folder thumbnails from first media file within the folder (if scraping is disabled or fails)
catFlagTitleFromMetaData : Integer = 256; // Use meta-data title for the thumb's text instead of the file name
catFlagNoScraping : Integer = 512; // Disable all scraping operations for this folder
catFlagRescrapeModified : Integer = 1024; // Rescrape folders if their "modified" date changes
catFlagTVJukeBoxNoScrape : Integer = 2048; // Switched to TV JukeBox list view without having the parent folder scraped first
catFlag1stMediaFolderThumb : Integer = 4096; // Instead of scraping for a folder's name, always use the first media file within the folder instead
catFlagCropCatThumbnail : Integer = 8192; // Crop category thumbnails to fit in display area (otherwise pad thumbnails)
catFlagScrapeDebugMsgs : Integer = 16384; // Show scraper debug messages in meta-data overview
catFlagScrapeMediaTitle : Integer = 32768; // Scrape using media title instead of file name
catFlagNoDurationOverlay : Integer = 65536; // Don't draw the duration/position thumbnail overlay
catFlagNoFormatOverlay : Integer = 131072; // Don't draw the media format thumbnail overlay
catFlagNoReturnResults : Integer = 262144; // Don't expect any result entries from the plugin
srName = 0;
srExt = 1;
srDate = 2;
srSize = 3;
srPath = 4;
srDuration = 5;
srRandom = 6;
strategySearch = 0;
strategyUploadList = 1;
strategyActivities = 2;
strWorldWide : String = 'Worldwide';
strEverything : String = 'Everything';
// Called by Zoom Player to free any resources allocated in the DLL prior to unloading the DLL.
Procedure FreePlugin; stdcall;
var
I : Integer;
S : String;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Free Plugin (before)');{$ENDIF}
// Save Playlist ID to registry
S := '';
For I := 0 to UploadPlaylistList.Count-1 do
Begin
If I = 0 then
S := PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sChannelID+','+PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sPlaylistID else
S := S+'|'+PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sChannelID+','+PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sPlaylistID;
Dispose(PUploadPlaylistIDRecord(UploadPlaylistList[I]));
End;
SetRegString(HKEY_CURRENT_USER,PluginRegKey,RegKeyPlaylistID,S);
UploadPlaylistList.Free;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Free Plugin (after)');{$ENDIF}
end;
// Called by Zoom Player to init any resources.
function InitPlugin : Bool; stdcall;
var
I : Integer;
iPos : Integer;
S : String;
sList : TStringList;
nEntry : PUploadPlaylistIDRecord;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Init Plugin (before)');{$ENDIF}
LoadPluginConfig;
UploadPlaylistList := TList.Create;
S := GetRegString(HKEY_CURRENT_USER,PluginRegKey,RegKeyPlaylistID);
If S <> '' then
Begin
sList := TStringList.Create;
Split(S,'|',sList);
For I := 0 to sList.Count-1 do
Begin
New(nEntry);
iPos := Pos(',',sList[I]);
nEntry^.sChannelID := Copy(sList[I],1,iPos-1);
nEntry^.sPlaylistID := Copy(sList[I],iPos+1,Length(sList[I])-iPos);
UploadPlaylistList.Add(nEntry);
End;
sList.Free;
// Limit cache size to 200 entries by deleting the oldest entries
While UploadPlaylistList.Count > 200 do
Begin
Dispose(PUploadPlaylistIDRecord(UploadPlaylistList[0]));
UploadPlaylistList.Delete(0);
End;
End;
Result := True;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Init Plugin (after)');{$ENDIF}
end;
// Called by Zoom Player to verify if a configuration dialog is available.
// Return True if a dialog exits and False if no configuration dialog exists.
function CanConfigure : Bool; stdcall;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CanConfigure (before)');{$ENDIF}
Result := True;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CanConfigure (after)');{$ENDIF}
end;
// Called by Zoom Player to show the plugin's configuration dialog.
Procedure Configure(CenterOnWindow : HWND; CategoryID : PChar); stdcall;
var
CenterOnRect : TRect;
tmpInt : Integer;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Configure (before)');{$ENDIF}
If GetWindowRect(CenterOnWindow,CenterOnRect) = False then
GetWindowRect(0,CenterOnRect); // Can't find window, center on screen
LoadPluginConfig;
ConfigForm := TConfigForm.Create(nil);
ConfigForm.SetBounds(CenterOnRect.Left+(((CenterOnRect.Right -CenterOnRect.Left)-ConfigForm.Width) div 2),
CenterOnRect.Top +(((CenterOnRect.Bottom-CenterOnRect.Top )-ConfigForm.Height) div 2),ConfigForm.Width,ConfigForm.Height);
ConfigForm.ChannelStrategyCB.ItemIndex := iChannelStrategy;
ConfigForm.ClearCacheButton.Enabled := UploadPlaylistList.Count > 0;
ConfigForm.IncludeNoDurationCB.Checked := bIncludeZeroDuration;
ConfigForm.MaxThumbnailResCB.Checked := bMaxThumbnailRes;
ConfigForm.APIKeyEdit.Text := sCustomAPIKey;
ConfigForm.FilterDurationCB.Checked := bFilterDuration;
ConfigForm.FilterDurationEdit.Text := IntToStr(iFilterDuration);
ConfigForm.VideoFetchCB.ItemIndex := YouTube_VideoFetch;
{$IFDEF PLAYLISTMODE}
ConfigForm.PlaylistChannelTNCB.Visible := True;
ConfigForm.PlaylistChannelTNCB.Checked := bPlaylistChannelTN;
{$ENDIF}
If ConfigForm.ShowModal = mrOK then
Begin
// Save to registry
If iChannelStrategy <> ConfigForm.ChannelStrategyCB.ItemIndex then
Begin
iChannelStrategy := ConfigForm.ChannelStrategyCB.ItemIndex;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyChannelStrategy,iChannelStrategy);
End;
bIncludeZeroDuration := ConfigForm.IncludeNoDurationCB.Checked;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyZeroDuration,Integer(bIncludeZeroDuration));
bMaxThumbnailRes := ConfigForm.MaxThumbnailResCB.Checked;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyMaxThumbnailRes,Integer(bMaxThumbnailRes));
sCustomAPIKey := ConfigForm.APIKeyEdit.Text;
If sCustomAPIKey <> '' then APIKey := sCustomAPIKey else APIKey := APIKeyDefault;
SetRegString(HKEY_CURRENT_USER,PluginRegKey,RegKeyCustomAPIKey,sCustomAPIKey);
bFilterDuration := ConfigForm.FilterDurationCB.Checked;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyFilterDurationEnabled,Integer(bFilterDuration));
iFilterDuration := StrToIntDef(ConfigForm.FilterDurationEdit.Text,61);
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyFilterDurationSeconds,iFilterDuration);
YouTube_VideoFetch := ConfigForm.VideoFetchCB.ItemIndex;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyYouTubeVideoFetch,YouTube_VideoFetch);
{$IFDEF PLAYLISTMODE}
bPlaylistChannelTN := ConfigForm.PlaylistChannelTNCB.Checked;
SetRegDWord(HKEY_CURRENT_USER,PluginRegKey,RegKeyPlaylistChannelTN,Integer(bPlaylistChannelTN));
{$ENDIF}
End;
ConfigForm.Free;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Configure (after)');{$ENDIF}
end;
// Called by Zoom Player to verify if the plugin can refresh itself (name/thumbnail).
function CanRefresh : Bool; stdcall;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CanRefresh (before)');{$ENDIF}
{$IF DEFINED(SEARCHMODE) or DEFINED(TRENDINGMODE)} // YouTube Search Plugin
Result := False;
{$ELSE}
Result := True;
{$IFEND}
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CanRefresh (after)');{$ENDIF}
end;
// Called by Zoom Player to show the refresh the category (name/thumbnail).
Function Refresh(CategoryData : PCategoryPluginRecord) : Integer; stdcall;
var
sCatInput : String;
sTitle : String;
sTitlePL : String;
sPlaylistID : String;
sChannelID : String;
sThumbnail : String;
sCustomURL : String;
I : Integer;
begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Refresh (before)');{$ENDIF}
Result := E_FAIL;
If CategoryData = nil then
Begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Exit on "CategoryData = nil"');{$ENDIF}
Exit;
End;
sCatInput := CategoryData^.CategoryInput;
sPlaylistID := '';
sThumbnail := '';
CategoryData^.CategoryID := '';
CategoryData^.CategoryTitle := '';
CategoryData^.CategoryThumb := '';
CategoryData^.Scrapers := '';
CategoryData^.TextLines := 2;
CategoryData^.SortMode := srDate;
CategoryData^.DefaultFlags := catFlagThumbView or catFlagThumbCrop or catFlagTitleFromMetaData;
If sCatInput <> '' then
Begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Categoty Input: '+sCatInput);{$ENDIF}
{$IFDEF PLAYLISTMODE}
If YouTube_GetPlaylistDetails(sCatInput,sTitlePL,sChannelID,sTitle,sThumbnail,bMaxThumbnailRes) = True then
Begin
If (sTitle <> '') and (sTitlePL <> '') then
Begin
CategoryData^.CategoryTitle := PChar(sTitlePL+' ('+sTitle+')');
Result := S_OK;
If (bPlaylistChannelTN = True) or (sThumbnail = '') then
Begin
// Try to use the channel's bitmap
YouTube_GetChannelDetails(sChannelID,sTitle,sThumbnail,sPlaylistID,sCustomURL,bMaxThumbnailRes);
End;
If sThumbnail <> '' then
CategoryData^.CategoryThumb := PChar(sThumbnail) else
CategoryData^.CategoryThumb := PChar(UTF8Encode(GetCurrentDLLPath)+'YouTube_Playlist.jpg');
End;
End;
{$ELSE}
// Remove playlist ID
I := Pos(',',sCatInput);
If I > 0 then sCatInput := Copy(sCatInput,1,I-1);
// Get Channel Title, Thumbnail & Upload playlist ID
YouTube_GetChannelDetails(sCatInput,sTitle,sThumbnail,sPlaylistID,sCustomURL,bMaxThumbnailRes);
// was used for alternative method of downloading youtube videos, sadly it returned them in a bad order.
If sPlaylistID <> '' then
CategoryData^.CategoryID := PChar(sCatInput+','+sPlaylistID) else
CategoryData^.CategoryID := PChar(sCatInput);
If sTitle <> '' then
Begin
CategoryData^.CategoryTitle := PChar(sTitle);
If sThumbnail <> '' then CategoryData^.CategoryThumb := PChar(sThumbnail);
Result := S_OK;
End;
{$ENDIF}
End
{$IFDEF LOCALTRACE}Else DebugMsgFT(LogInit,'No Channel ID specified!'){$ENDIF};
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Refresh (after)');{$ENDIF}
end;
Function CreateCategory(CenterOnWindow : HWND; CategoryData : PCategoryPluginRecord) : Integer; stdcall;
const
urlTypeNone = 0;
urlTypeUser = 1;
urlTypeChannel = 2;
var
sCatInput : String;
sCatInputLC : String;
sChannelID : String;
sPlaylistID : String;
sTitle : String;
sTitlePL : String;
sCustomURL : String;
sThumbnail : String;
sCatID : String;
sUserName : WideString;
sPos : Integer;
ePos : Integer;
I,I1 : Integer;
sList : TStringList;
uList : TTNTStringList;
uStr : WideString;
nEntry : PUploadPlaylistIDRecord;
Found : Boolean;
iOfs : Integer;
urlType : Integer;
begin
// CategoryInput = URL
// CategoryID = Parsed category ID returned to the player for later calls to GetList.
// CategoryThumb = Thumbnail to use for the category
// TextLines = Number of text lines to display
// SortMode = Sort mode to enable when creating the category (srName .. srRandom)
// Scrapers = Return recommended scraper list
// DefaultFlags = Default category flags for this category
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CreateCategory (before)');{$ENDIF}
Result := E_FAIL;
If CategoryData = nil then
Begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Exit on "CategoryData = nil"');{$ENDIF}
Exit;
End;
sCatInput := CategoryData^.CategoryInput;
//ShowMessageW(sCatInput+ ' / '+UTF8Decode(sCatInput));
sCatInputLC := Lowercase(sCatInput);
sChannelID := '';
sPlaylistID := '';
sThumbnail := '';
CategoryData^.CategoryID := '';
CategoryData^.CategoryTitle := '';
CategoryData^.CategoryThumb := '';
CategoryData^.Scrapers := '';
CategoryData^.TextLines := 2;
CategoryData^.SortMode := srDate;
CategoryData^.DefaultFlags := catFlagThumbView or catFlagThumbCrop or catFlagTitleFromMetaData or catFlagNoFormatOverlay;
{$IFDEF SEARCHMODE}
// **********************************************************************************
// ********************************* YouTube Search *********************************
// **********************************************************************************
CategoryData^.CategoryID := PChar(sCatInput);
CategoryData^.CategoryTitle := PChar({'Search:'+}sCatInput);
CategoryData^.CategoryThumb := PChar(UTF8Encode(GetCurrentDLLPath)+'YouTube_Search.jpg');
Result := S_OK;
{$ELSE}
{$IFDEF TRENDINGMODE}
// **********************************************************************************
// ********************************* YouTube Trends *********************************
// **********************************************************************************
If sCatInput = strWorldWide then
Begin
sCatID := strWorldWide;
End
else
// Convert language name to ISO 3166-1 alpha-2 code
For I := 0 to ISO_3166_1_alpha_2_Count-1 do If sCatInput = ISO_3166_1_alpha_2_str[I] then
Begin
sCatID := ISO_3166_1_alpha_2[I];
Break;
End;
uList := TTNTStringList.Create;
If sCatID <> strWorldWide then
Begin
// YouTube category lists only work per-country, it doesn't work globally
YouTube_GetCategoryIDs(sCatID,uList);
End;
uStr := '';
uList.InsertObject(0,strEverything,TObject(-1));
If misc_utils_unit.InputComboW(CenterOnWindow,'Category :', '', uList,uStr) = True then
Begin
For I := 0 to uList.Count-1 do If uStr = uList[I] then
Begin
sCatID := sCatID+','+IntToStr(Integer(uList.Objects[I]));
CategoryData^.CategoryTitle := PChar(UTF8Encode(EncodeTextTags('Trending: '+uList[I]+' in '+sCatInput,True)));
Break;
End;
CategoryData^.CategoryID := PChar(sCatID);
CategoryData^.CategoryThumb := PChar(UTF8Encode(GetCurrentDLLPath)+'YouTube_Trending.jpg');
Result := S_OK;
End
Else Result := S_FALSE; // prevents an error dialog, used for "cancel".
uList.Free;
// Get list of automatically generated video categories
// https://www.googleapis.com/youtube/v3/videoCategories?part=snippet®ionCode=IL&key=API_KEY
{$ELSE}
{$IFDEF PLAYLISTMODE}
// ***********************************************************************************
// ******************************** YouTube PlayList *********************************
// ***********************************************************************************
sCatID := Trim(sCatInput);
I := Pos('?list=',Lowercase(sCatID));
If I = 0 then I := Pos('&list=',Lowercase(sCatID));
If I > 0 then
Begin
I1 := PosEx('&',Lowercase(sCatID),I+1)-1;
If I1 <= 0 then I1 := Length(sCatID);
sCatID := Copy(sCatID,I+6,I1-(I+5));
If YouTube_GetPlaylistDetails(sCatID,sTitlePL,sChannelID,sTitle,sThumbnail,bMaxThumbnailRes) = True then
Begin
CategoryData^.CategoryID := PChar(sCatID);
If (sTitle <> '') and (sTitlePL <> '') then
Begin
CategoryData^.CategoryTitle := PChar(sTitlePL+' ('+sTitle+')')
End
Else CategoryData^.CategoryTitle := 'Unknown';
If (bPlaylistChannelTN = True) or (sThumbnail = '') then
Begin
// Try to use the channel's bitmap
YouTube_GetChannelDetails(sChannelID,sTitle,sThumbnail,sPlaylistID,sCustomURL,bMaxThumbnailRes);
End;
If sThumbnail <> '' then
CategoryData^.CategoryThumb := PChar(sThumbnail) else
CategoryData^.CategoryThumb := PChar(UTF8Encode(GetCurrentDLLPath)+'YouTube_Playlist.jpg');
Result := S_OK;
End
Else Result := E_FAIL;
End;
{$ELSE}
// ***********************************************************************************
// ********************************* YouTube Channel *********************************
// ***********************************************************************************
If sCatInput <> '' then
Begin
// Try to find the Channel ID by input URL
iOfs := 10;
sPos := Pos('/channel/',sCatInputLC);
If sPos > 0 then
Begin
ePos := PosEx('/',sCatInput,sPos+iOfs);
If ePos > 0 then
sChannelID := Copy(sCatInput,sPos+(iOfs-1),ePos-(sPos+(iOfs-1))) else
sChannelID := Copy(sCatInput,sPos+(iOfs-1),Length(sCatInput)-(sPos+(iOfs-2)));
End
else
Begin
// Try to find the Channel ID by user name in input URL
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Convert User Name to Channel ID');{$ENDIF}
urlType := urlTypeNone;
iOfs := 7;
sPos := Pos('/user/',sCatInputLC);
If sPos = 0 then
Begin
iOfs := 4;
sPos := Pos('/c/',sCatInputLC);
If sPos > 0 then urlType := urlTypeChannel;
End
Else urlType := urlTypeUser;
If sPos > 0 then
Begin
ePos := PosEx('/',sCatInput,sPos+iOfs);
If ePos > 0 then
sUserName := Copy(sCatInput,sPos+(iOfs-1),ePos-(sPos+(iOfs-1))) else
sUserName := Copy(sCatInput,sPos+(iOfs-1),Length(sCatInput)-(sPos+(iOfs-2)));
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'User Name: '+sUserName);{$ENDIF}
Case urlType of
urlTypeUser : If sUserName <> '' then sChannelID := YouTube_ConvertUserNameToChannelID(sUserName);
urlTypeChannel : If sUserName <> '' then sChannelID := YouTube_ConvertChannelNameToChannelID(sUserName);
End;
End
else
Begin
// 20-nov-2022
// Channel with @ identifier
sPos := Pos('/@',sCatInputLC);
If sPos > 0 then
Begin
iOfs := PosEx('/',sCatInputLC,sPos+1);
If iOfs = 0 then
sUserName := Copy(sCatInput,sPos+1,Length(sCatInput)-(sPos)) else
sUserName := Copy(sCatInput,sPos+1,iOfs-(sPos));
sChannelID := YouTube_ConvertChannelNameToChannelID(sUserName);
End;
End;
End;
If sChannelID <> '' then
Begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Channel ID: '+sChannelID);{$ENDIF}
// Get Channel Title, Thumbnail & Upload playlist ID
YouTube_GetChannelDetails(sChannelID,sTitle,sThumbnail,sPlaylistID,sCustomURL,bMaxThumbnailRes);
CategoryData^.CategoryID := PChar(sChannelID);
// Check if we have the UploadID cached
Found := False;
For I := 0 to UploadPlaylistList.Count-1 do If PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sChannelID = sChannelID then
Begin
Found := True;
Break;
End;
// If UploadID is not cached, add it to the cache.
If Found = False then
Begin
New(nEntry);
nEntry^.sChannelID := sChannelID;
nEntry^.sPlaylistID := sPlaylistID;
UploadPlaylistList.Add(nEntry);
End;
If sTitle <> '' then
Begin
CategoryData^.CategoryTitle := PChar(sTitle);
If sThumbnail <> '' then CategoryData^.CategoryThumb := PChar(sThumbnail);
Result := S_OK;
End;
End
{$IFDEF LOCALTRACE}Else DebugMsgFT(LogInit,'No Channel ID detected'){$ENDIF};
End;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'CreateCategory, Result : '+IntToHex(Result,8)+' (after)');{$ENDIF}
end;
function DeleteCategory(CenterOnWindow : HWND; CategoryID,DataPath : PChar) : Integer; stdcall;
begin
Result := S_OK;
end;
Function GetList(CategoryID, CategoryPath, DataPath : PChar; ItemList : PCategoryItemList) : Integer; stdcall;
type
TYouTubeVideoRecord =
Record
ytvFound : Boolean;
ytvType : Integer;
ytvPath : WideString;
ytvChannelName : WideString;
ytvTitle : WideString;
ytvDescription : WideString;
ytvPublished : TDateTime;
ytvThumbnail : String;
ytvDuration : Integer;
ytvViewCount : Integer;
ytvLikeCount : Integer;
//ytvDislikeCount : Integer;
End;
PYouTubeVideoRecord = ^TYouTubeVideoRecord;
function VideoFetchIndexToEnries(Idx : Integer) : Integer;
begin
Case Idx of
0 : Result := 25;
else Result := 50;
End;
end;
var
S,S1 : String;
sID : String;
I,I1 : Integer;
iLen : Integer;
sList : TStringList;
jBase : ISuperObject;
jItems : ISuperObject;
jEntry : ISuperObject;
jSnippet : ISuperObject;
jResourceID : ISuperObject;
dlStatus : String;
dlError : Integer;
sJSON : String;
sURL : String;
sUTF8 : String;
sToken : String;
sItemList : WideString;
sIDList : String;
ytvList : TList;
ytvEntry : PYouTubeVideoRecord;
mStream : TMemoryStream;
sCustomURL : String;
sPlaylistID : String;
xThumbnail : String;
xTitle : String;
sStartTime : String;
sEndTime : String;
sScheduleTime : String;
nEntry : PUploadPlaylistIDRecord;
tz : TTimeZoneInformation;
TZBias : Integer;
{$IFDEF TRENDINGMODE}
iCatType : Integer;
sCatRegion : String;
{$ENDIF}
function SortByPublishDate(Item1, Item2: PYouTubeVideoRecord) : Integer;
begin
{if TZPFileClass(Item1).zplSize = TZPFileClass(Item2).zplSize then
Result := flSortByName(Item1,Item2)
else if TZPFileClass(Item1).zplSize < TZPFileClass(Item2).zplSize then
Result := -1
else
Result := 1;}
If Item1^.ytvPublished > Item2^.ytvPublished then Result := -1 else
If Item1^.ytvPublished < Item2^.ytvPublished then Result := 1 else Result := 0;
end;
procedure WipeYTVentry(Entry : PYouTubeVideoRecord);
begin
ytvEntry^.ytvFound := False;
ytvEntry^.ytvType := typeMedia;
ytvEntry^.ytvPath := '';
ytvEntry^.ytvChannelName := '';
ytvEntry^.ytvTitle := '';
ytvEntry^.ytvDescription := '';
ytvEntry^.ytvPublished := 0;;
ytvEntry^.ytvThumbnail := '';
ytvEntry^.ytvDuration := 0;
ytvEntry^.ytvViewCount := 0;
ytvEntry^.ytvLikeCount := 0;
//ytvEntry^.ytvDislikeCount := 0;
end;
function YTVrecordToString(Entry : PYouTubeVideoRecord) : WideString;
var
sPath : String;
sDuration : String;
sDate : WideString;
sTitle : WideString;
sDescription : WideString;
sMetaLikes : String;
iMetaRating : Integer;
Begin
Case Entry^.ytvType of
typeMedia,
typeLiveStream,
typePendingStream : sPath := 'https://www.youtube.com/watch?v='+Entry^.ytvPath;
else sPath := Entry^.ytvPath;
End;
If Entry^.ytvPublished > 0 then sDate := TimeDifferenceToStr(IncMillisecond(Now,TZBias),Entry^.ytvPublished) else sDate := '';
// #9/TAB is used for right-alignment of text
sMetaLikes :=
IntToStrDelimiter(Entry^.ytvViewCount ,',')+' views\n\n'+
IntToStrDelimiter(Entry^.ytvLikeCount ,',')+' likes'{+
IntToStrDelimiter(Entry^.ytvDislikeCount,',')+' dislikes'};
//If Entry^.ytvChannelName <> '' then sMetaLikes := Entry^.ytvChannelName+'\n\n'+sMetaLikes;
sDuration := EncodeDuration(Entry^.ytvDuration);
sTitle := DecodeTextTags(Entry^.ytvTitle,True);
sDescription := DecodeTextTags(Entry^.ytvDescription,True);
//If Entry^.ytvChannelName <> '' then sTitle := sTitle+' @'+Entry^.ytvChannelName;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Title "'+sTitle+'"');{$ENDIF}
// Generate a rating value based on ratio between likes and dislikes
iMetaRating := 0;
{If Entry^.ytvLikeCount+Entry^.ytvDislikeCount > 0 then
iMetaRating := Round((100*Entry^.ytvLikeCount)/(Entry^.ytvLikeCount+Entry^.ytvDislikeCount));}
// [MetaEntry1] : // Displayed in the meta-data's Title area
// [MetaEntry2] : // Displayed in the meta-data's Date area
// [MetaEntry3] : // Displayed in the meta-data's Duration
// [MetaEntry4] : // Displayed in the meta-data's Genre/Type area
// [MetaEntry5] : // Displayed in the meta-data's Overview/Description area
// [MetaEntry6] : // Displayed in the meta-data's Actors/Media info area
// [MetaRating] : // Meta rating, value of 0-100, 0=disabled
Result := '"Type=' +IntToStr(Entry^.ytvType)+'",'+
'"Path=' +sPath+'",'+
'"Title=' +EncodeTextTags(sTitle,True)+'",'+
'"Description=' +EncodeTextTags(sDescription,True)+'",'+
'"Thumbnail=' +Entry^.ytvThumbnail+'",'+
'"Duration=' +FloatToStr(Entry^.ytvDuration)+'",'+
// user login not implemented, no way to pass the last play position
//'"Position=' +FloatToStr(Entry^.ytvPosition)+'",'+
'"Date=' +FloatToStr(Entry^.ytvPublished)+'",'+
'"MetaEntry1=' +EncodeTextTags(sTitle,True)+'",'+
'"MetaEntry2=' +sDate+'",'+
'"MetaEntry3=' +sDuration+'",'+
'"MetaEntry4=' +Entry^.ytvChannelName+'",'+
'"MetaEntry5=' +EncodeTextTags(sDescription,True)+'",'+
'"MetaEntry6=' +sMetaLikes+'",'+
'"MetaRating=' +IntToStr(iMetaRating)+'"';
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Data "'+Result+'"');{$ENDIF}
End;
begin
// **** Getting upload playlist:
// https://www.googleapis.com/youtube/v3/channels?key=[apikey]&part=contentDetails&id=[ChannelID]
//
// **** Getting playlist data:
// https://www.googleapis.com/youtube/v3/playlistitems?key=[apikey]&part=snippet,id&playlistId=[playlistId]&maxResults='+IntToStr(YouTube_VideoFetch)
// e.g. : https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBieQxSpir6Y2-iYPokdu90UxqM_skzZFo&part=snippet,id&playlistId=UUEK3tT7DcfWGWJpNEDBdWog&maxResults=25
// CategoryID = A unique category identifier, in our case, a YouTube channel's "Channel ID".
// CategoryPath = Used to the pass a path or parameter, in our case, a YouTube channel's next page Token.
// ItemList = Return a list of items and meta-data
// ItemType :
// 0 = Playable item
// 1 = Enter Folder, retrieve new list with additional 'categorypath'.
// 2 = Append items to list, removing this entry
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'GetList (before)');{$ENDIF}
Result := E_FAIL;
sList := TStringList.Create;
ytvList := TList.Create;
sPlaylistID := '';
// Get Timezone information
If GetTimeZoneInformation(tz) = TIME_ZONE_ID_DAYLIGHT then
Begin
TZBias := (tz.Bias+tz.DaylightBias)*60000;
End
Else TZBias := tz.Bias*60000;
//ShowMessage(IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
{$IFDEF SEARCHMODE}
// ******************************************************************
// ************************** Search mode ***************************
// ******************************************************************
//https://www.googleapis.com/youtube/v3/search?part=snippet,id&q=[Search]&type=video&key={YOUR_API_KEY}
sURL := 'https://www.googleapis.com/youtube/v3/search?key='+APIKey+'&q='+URLEncodeUTF8(UTF8Decode(CategoryID))+'&part=snippet,id&order=relevance&type=video&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
//ShowMessageW(CategoryID+' / '+UTF8Decode(CategoryID)+' / '+ URLEncodeUTF8(UTF8Decode(S)));
{$ELSE}
{$IFDEF TRENDINGMODE}
// ******************************************************************
// **************************** Trending ****************************
// ******************************************************************
S := CategoryID;
I := Pos(',',S);
If I > 0 then
Begin
iCatType := StrToIntDef(Copy(S,I+1,Length(S)-I),-1);
sCatRegion := Copy(S,1,I-1);
End
else
Begin
iCatType := -1;
sCatRegion := S;
End;
// Trending in country with specific category
//https://www.googleapis.com/youtube/v3/videos?part=contentDetails&chart=mostPopular&videoCategoryId=10&maxResults=25&key=API_KEY
// Trending in country
//https://www.googleapis.com/youtube/v3/videos?part=contentDetails&chart=mostPopular®ionCode=IN&maxResults=25&key=API_KEY
If sCatRegion <> strWorldwide then S := '®ionCode='+sCatRegion else S := '';
If iCatType > -1 then S := S+'&videoCategoryId='+IntToStr(iCatType);
sURL := 'https://www.googleapis.com/youtube/v3/videos?part=snippet,id&chart=mostPopular'+S+'&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch))+'&key='+APIKey;
{$ELSE}
{$IFDEF PLAYLISTMODE}
// ******************************************************************
// **************************** Play List ***************************
// ******************************************************************
sURL := 'https://www.googleapis.com/youtube/v3/playlistItems?key='+APIKey+'&playlistId='+CategoryID+'&part=snippet,id&order=date&type=video&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
sPlaylistID := CategoryID;
{$ELSE}
// ******************************************************************
// ************************** Channel List **************************
// ******************************************************************
S := CategoryID;
Case iChannelStrategy of
strategySearch : // Search
Begin
// Using Search API
sURL := 'https://www.googleapis.com/youtube/v3/search?key='+APIKey+'&channelId='+S+'&part=snippet,id&order=date&type=video'{+'&safeSearch=none'}+'&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
End;
strategyUploadList : // Use 'Upload' playlist
Begin
// Find the 'upload' playlist ID
For I := 0 to UploadPlaylistList.Count-1 do If S = PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sChannelID then
Begin
// Match found
sPlaylistID := PUploadPlaylistIDRecord(UploadPlaylistList[I])^.sPlaylistID;
Break;
End;
// No Upload PlaylistID, try getting again.
If sPlaylistID = '' then
Begin
YouTube_GetChannelDetails(S,xTitle,xThumbnail,sPlaylistID,sCustomURL,bMaxThumbnailRes);
New(nEntry);
nEntry^.sChannelID := S;
nEntry^.sPlaylistID := sPlaylistID;
UploadPlaylistList.Add(nEntry)
End;
sURL := 'https://www.googleapis.com/youtube/v3/playlistItems?key='+APIKey+'&playlistId='+sPlaylistID+'&part=snippet,id&order=date&type=video&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
End;
strategyActivities : // Use Activities API
Begin
// Using Activities API (very limited, 2 months, around 60 result entries which may not be videos)
sURL := 'https://www.googleapis.com/youtube/v3/activities?key='+APIKey+'&channelId='+S+'&part=snippet,contentDetails&order=date&type=video'{+'&safeSearch=none'}+'&maxResults='+IntToStr(VideoFetchIndexToEnries(YouTube_VideoFetch));
End;
End;
{$ENDIF}
{$ENDIF}
{$ENDIF}
sToken := CategoryPath;
If sToken <> '' then sURL := sURL+'&pageToken='+sToken;
sToken := '';
dlStatus := strUnknown;
dlError := 0;
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Search URL : '+sURL);{$ENDIF}
If DownloadFileToStringList(sURL,sList,dlStatus,dlError,2000) = True then
Begin
If sList.Count > 0 then
Begin
If Pos(strQuotaExceeded,sList.Text) > 0 then
Begin
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'quotaExceeded');{$ENDIF}
If MessageDLG(strQuotaDesc,mtConfirmation,[mbOK,mbCancel],0) = mrOK then
Begin
ShellExecute(0,'open',PChar(strAPIKeyBlogURL),nil,nil,0)
End;
End
else
Begin
sJSON := StringReplace(sList.Text,CRLF,'',[rfReplaceAll]);
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'JSON Search Snippet+ID : '+CRLF+'---'+CRLF+sList.Text+CRLF+'---'+CRLF);{$ENDIF}
jBase := SO(sJSON);
If jBase <> nil then
Begin
sToken := jBase.S['nextPageToken'];
{$IFDEF LOCALTRACE}DebugMsgFT(LogInit,'Next page token : '+sToken);{$ENDIF}
jItems := jBase.O['items'];
If jItems <> nil then
Begin
If jItems.AsArray.Length > 0 then For I := 0 to jItems.AsArray.Length-1 do
Begin
New(ytvEntry);
WipeYTVentry(ytvEntry);
jEntry := jItems.AsArray.O[I];
If jEntry <> nil then
Begin
If sPlaylistID = '' then
Begin
// Parse channel/search/trending
{$IFDEF TRENDINGMODE}
ytvEntry^.ytvPath := jEntry.S['id'];
{$ELSE}
If iChannelStrategy <> strategyActivities then
Begin
jSnippet := jEntry.O['id'];
If jSnippet <> nil then
Begin
ytvEntry^.ytvPath := jSnippet.S['videoId'];
jSnippet.Clear(True);
jSnippet := nil;
End
{$IFDEF LOCALTRACE}Else DebugMsgFT(LogInit,'JSON id object returned nil'){$ENDIF};
End;
{$ENDIF}
jSnippet := jEntry.O['snippet'];
If jSnippet <> nil then
Begin
//{$IF Defined(TRENDINGMODE) or Defined(SEARCHMODE)}
//ytvEntry^.ytvChannelName := UTF8StringToWideString(jSnippet.S['channelTitle']);
ytvEntry^.ytvChannelName := EncodePipe(UTF8StringToWideString(HTMLUnicodeToUTF8(jSnippet.S['channelTitle'])),True);
If ytvEntry^.ytvChannelName = '' then ytvEntry^.ytvChannelName := EncodePipe(UTF8StringToWideString(jSnippet.S['channelTitle']),True);
//{$IFDEF LOCALTRACE}DebugMsgFT('c:\log\youtube_channel_name.txt',jSnippet.S['channelTitle']+' -> '+ytvEntry^.ytvChannelName);{$ENDIF}
//{$IFEND}