-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_fetch.js
More file actions
1312 lines (1154 loc) · 52 KB
/
api_fetch.js
File metadata and controls
1312 lines (1154 loc) · 52 KB
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
const {google} = require('googleapis');
Database = require('arangojs').Database;
fs = require('fs');
//Save stuff on exit
// process.on('exit', code => {
// console.log("Caught exit signal, saving remaining channels in file");
//
// fs.writeFileSync("./RemainingChannels.txt", channelQueue.toString(), "utf-8");
// });
const apiKey = fs.readFileSync('./.apiKey', 'utf8');
const arangoPass = fs.readFileSync('./.arangoPass', 'utf8');
// Initialise the database variable
//TODO: Change accordingly for ginkgo
db = new Database('http+tcp://webocd.dbis.rwth-aachen.de:8529');
db.useBasicAuth("root", "");
//TODO: Change accordingly for ginkgo, this also potentially goes for the 'Channels/' part in the save[...] functions
db.useDatabase('Youtube');
const channelCollectionName = 'Channels';
channelCollection = db.collection(channelCollectionName);
subsCollection = db.collection('subscribed_by');
likesCollection = db.collection('videosLiked_by');
commentsCollection = db.collection('videosCommented_by');
favoritesCollection = db.collection('videosFavorited_by');
// Initialise the Youtube library with an api key
const youtube = google.youtube({
version: 'v3',
auth: apiKey // API key
});
// Queue class for the channelQueue
class Queue {
constructor() {
this.items = [];
}
isEmpty() {
if (this.items.length === 0) {
return true;
} else {
return false;
}
}
front() {
if (this.isEmpty()) {
throw "Front() Error: Queue was empty!"
}
return this.items[0];
}
toString() {
return this.items.toString();
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) {
throw "Dequeue() Error: Queue was empty!"
}
this.items.shift();
}
}
// Queue used to go through youtube channels
let channelQueue = new Queue();
let unlikelyChildQueue = new Queue();
// Map to store page tokens
let commentThreadPages = new Map();
function mapToString(map) {
let str = "";
let i = 0;
for (let [key, value] of map.entries()) {
i++;
if (i < map.size) {
str = str.concat(key + ":" + value + ",");
} else {
str = str.concat(key + ":" + value);
}
}
return str;
}
function mapFromStringList(strList) {
let map = new Map();
let pos = 0;
for (let x of strList) {
const tmpList = x.split(":");
map.set(tmpList[0], tmpList[1]);
}
return map;
}
async function collectChannelInfo(id) {
return youtube.channels.list({
"part": [
"statistics, contentDetails"
],
"id": id
});
}
// Returns a channel object in the form of [isPotInfl: Boolean, channelInfo: channelJSON]
async function collectChannel(id) {
let channelInfo = collectChannelInfo(id); // Collect basic channel information
let channel = channelInfo.then(async function (resp) {
if (resp.data.items[0].statistics.subscriberCount >= 5000) // Check whether channel is potential Influencer
{
let channelDetInfo = youtube.channels.list({ // Fetch detailed info
"part": [
"snippet, topicDetails, status"
],
"id": id
});
let channel = channelDetInfo.then(function (response) {
resp.data.items.push(response.data.items[0]);
return resp.data.items;
});
//channel.channelInfo = resp.data;
//console.log(channel.channelInfo.items[0]);
//let channel = {isPotInfl: true, channelInfo: resp};
return [true, await channel]; // Return that the channel is an influencer along with basic and detailed info
}
//channel.isPotInfl = false;
//channel.channelInfo = resp.data;
//console.log(channel.channelInfo.items[0]);
//let channel = {isPotInfl: true, channelInfo: resp};
return [false, resp.data.items];//[false, resp]; // If not, just return that the channel is not an influencer along with the basic info
});
return await channel;
}
async function collectSubscriptions(id, pageToken) {
if (pageToken === undefined) {
return youtube.subscriptions.list({
"part": [
"snippet"
],
"order": "relevance",
"channelId": id,
"maxResults": 50
});
} else {
return youtube.subscriptions.list({
"part": [
"snippet"
],
"order": "relevance",
"channelId": id,
"pageToken": pageToken,
"maxResults": 50
});
}
}
//TODO: Maybe also have a pageToken-ready method
async function collectPlaylists(id) {
return youtube.playlists.list({
"part": [
"snippet"
],
"channelId": id,
"maxResults": 25
});
}
// Retrieves channelIds from items of a specified playlist(s) at specified page. Multiple id's can be given through separating them with commas in the id string
async function collectPlaylistItems(id, pageToken) {
if (pageToken === undefined) {
if (id.indexOf(',') === -1) {
return youtube.playlistItems.list({
"part": [
"snippet"
],
"playlistId": id,
"maxResults": 50
});
} else {
return youtube.playlistItems.list({
"part": [
"snippet"
],
"id": id,
"maxResults": 50
});
}
} else {
if (id.indexOf(',') === -1) {
return youtube.playlistItems.list({
"part": [
"snippet"
],
"playlistId": id,
"pageToken": pageToken,
"maxResults": 50
});
} else {
return youtube.playlistItems.list({
"part": [
"snippet"
],
"id": id,
"pageToken": pageToken,
"maxResults": 50
});
}
}
}
// Retrieves a list/array of videoId's mentioned in playlist and the next page token by pageToken
async function collectVideoIdsFromPlaylist(id, pageToken) {
let playlistItems = collectPlaylistItems(id, pageToken);
let videos = playlistItems.then(function (resp) {
let tmpList = [];
for (let x of resp.data.items) {
//console.log(x.snippet.title);
if (tmpList.includes(x.snippet.resourceId.videoId) === false) {
tmpList.push(x.snippet.resourceId.videoId);
}
}
return [tmpList, resp.data.nextPageToken];
});
return await videos;
}
// Retrieves a list/array of video infos from their id's and page token
async function collectVideoInfosFromIDList(idList, pageToken) {
if (pageToken === undefined) {
return youtube.videos.list({
"part": [
"snippet"
],
"id": idList,
"maxResults": 50
});
} else {
return youtube.videos.list({
"part": [
"snippet"
],
//"fields" : ["snippet/channelId"],
"id": idList,
"maxResults": 50,
"pageToken": pageToken
});
}
}
// Retrieves a list/array of channelId's mentioned in playlist by id and page token
async function collectChannelsFromPlaylist(id, pageToken) {
let channelList = [];
let videos = collectVideoIdsFromPlaylist(id, pageToken);
let videoInfos = videos.then(async function (resp) {
let videoIds = resp[0].toString();
let videoInfo = collectVideoInfosFromIDList(videoIds);
return await videoInfo.then(function (resp) {
return resp.data;
});
});
for (let x of await videoInfos.items) {
//console.log(x.snippet.title);
if (channelList.includes(x.snippet.channelId) === false) {
channelList.push(x.snippet.channelId);
}
}
return [channelList, videoInfos.nextPageToken];
}
// Not done, but likes way too often private, because that is the default privacy status
//Returns the id of the likes playlist by channelId. Throws error if not found
async function collectLikes(id) {
let playlists = collectPlaylists(id);
let likes = playlists.then(function (resp) {
for (let x of resp.data.items) {
if (x.snippet.title === 'Likes') {
return x.id;
}
}
throw 'No Likes found';
});
return await likes;
}
// Likes way too often private, because that is the default privacy status. Therefore also favorites
//Returns the id of the favorites playlist by channelId. Throws error if not found
async function collectFavorites(id) {
let playlists = collectPlaylists(id);
let favourites = playlists.then(function (resp) {
for (let x of resp.data.items) {
if (x.snippet.title === 'Favorites') {
return x.id;
}
}
throw 'No Favourites found';
});
return await favourites;
}
//Retrieves CommentThreads led by a top level comment by Channel Id. These can be both for the videos and the channel
async function collectCommentThreads(id, pageToken) {
if (pageToken === undefined) {
return youtube.commentThreads.list({
"part": [
"snippet"
],
"allThreadsRelatedToChannelId": id,
"maxResults": 50
});
} else {
return youtube.commentThreads.list({
"part": [
"snippet"
],
"allThreadsRelatedToChannelId": id,
"pageToken": pageToken,
"maxResults": 50
});
}
}
//TODO: Modify method such that it tries to neglect negative comments
//Retrieves channelIds from comment-threads related to a specific channel
function collectChannelIdsFromComments(commentThreads) {
let channelIDList = [];
for (let x of commentThreads.data.items) {
if (x.snippet.topLevelComment.snippet.authorChannelId !== undefined) {
if (channelIDList.includes(x.snippet.topLevelComment.snippet.authorChannelId.value) === false) {
channelIDList.push(x.snippet.topLevelComment.snippet.authorChannelId.value);
}
}
}
return channelIDList;
}
//Retrieves uploader channelIds from video-list
function collectChannelIdsFromVideoInfos(videoInfos) {
let channelIDList = [];
for (let x of videoInfos.data.items) {
if (x.snippet.channelId !== undefined) {
if (channelIDList.includes(x.snippet.channelId) === false) {
channelIDList.push(x.snippet.channelId);
}
}
}
return channelIDList;
}
// Saves a channel in the database. Pretty much just takes the channel JSON object and cleans it up a bit
async function saveChannel(channel) {
const key = channel[1][0].id;
const contentDetails = {
relatedPlaylists:
{
likes: channel[1][0].contentDetails.relatedPlaylists.likes,
favorites: channel[1][0].contentDetails.relatedPlaylists.favorites,
}
};
const statistics = {
viewCount: parseInt(channel[1][0].statistics.viewCount),
commentCount: parseInt(channel[1][0].statistics.commentCount),
subscriberCount: parseInt(channel[1][0].statistics.subscriberCount),
hiddenSubscriberCount: channel[1][0].statistics.hiddenSubscriberCount,
videoCount: parseInt(channel[1][0].statistics.videoCount),
};
let doc =
{
_key: key,
contentDetails: contentDetails,
statistics: statistics
};
let snippet, topicDetails, status;
if (channel[0] === true) {
snippet = {
title: channel[1][1].snippet.title,
description: channel[1][1].snippet.description,
publishedAt: channel[1][1].snippet.publishedAt,
defaultLanguage: channel[1][1].snippet.defaultLanguage,
country: channel[1][1].snippet.country
};
if (channel[1][1].topicDetails !== undefined) {
topicDetails = {
topicCategories: channel[1][1].topicDetails.topicCategories
}
} else {
topicDetails = "";
}
status = {
privacyStatus: channel[1][1].status.privacyStatus, // only public ones are relevant
isLinked: channel[1][1].status.isLinked, // true is important, otherwise topic channel
madeForKids: channel[1][1].status.madeForKids
}
doc =
{
_key: key,
snippet: snippet,
contentDetails: contentDetails,
statistics: statistics,
topicDetails: topicDetails,
status: status
};
}
await channelCollection.save(doc).then(
meta => console.log('Channel saved:', meta._rev),
err => {
throw err;
}
);
}
//TODO: Maybe also collect activity Details. At the moment this seems too costly, however
async function saveSubscription(subscription) {
const doc = {
_key: subscription.id,
_from: channelCollectionName + '/' + subscription.snippet.resourceId.channelId,
_to: channelCollectionName + '/' + subscription.snippet.channelId,
publishedAt: subscription.snippet.publishedAt,
// description: subscription.snippet.description,
// contentDetails: {
// activityType: subscription.contentDetails.activityType,
// },
};
await subsCollection.save(doc).then(
meta => console.log('Subscription saved:', meta._rev),
err => {
throw err
}
);
}
async function saveFavorite(channelId, favoritedVideo) {
const doc = {
_key: channelId + favoritedVideo.id + favoritedVideo.snippet.channelId,
_from: channelCollectionName + '/' + favoritedVideo.snippet.channelId,
_to: channelCollectionName + '/' + channelId,
videoID: favoritedVideo.id,
videoTitle: favoritedVideo.snippet.title,
videoTags: favoritedVideo.snippet.tags
};
await favoritesCollection.save(doc).then(
meta => console.log('Favorite saved:', meta._rev),
err => {
throw err
}
);
}
async function saveLike(channelId, likedVideo) {
const doc = {
_key: channelId + likedVideo.id + likedVideo.snippet.channelId,
_from: channelCollectionName + '/' + likedVideo.snippet.channelId,
_to: channelCollectionName + '/' + channelId,
videoID: likedVideo.id
};
await likesCollection.save(doc).then(
meta => console.log('Like saved:', meta._rev),
err => {
throw err
}
);
}
async function saveComment(commentThread) {
const doc = {
_key: commentThread.id,
_from: channelCollectionName + '/' + commentThread.snippet.topLevelComment.snippet.channelId,
_to: channelCollectionName + '/' + commentThread.snippet.topLevelComment.snippet.authorChannelId.value,
videoID: commentThread.snippet.topLevelComment.snippet.videoId,
value: commentThread.snippet.topLevelComment.snippet.textDisplay
};
//console.log('saving the comment');
await commentsCollection.save(doc).then(
meta => console.log('Comment saved:', meta._rev),
err => {
throw err
}
);
//console.log('saved(?) the comment');
}
function waitUntilNextDay() {
let date = new Date();
const currDay = date.getUTCDay();
console.log('Saving Channels');
// Save remaining Channels
fs.writeFileSync("./RemainingChannels.txt", channelQueue.toString(), "utf-8");
fs.writeFileSync("./CommentPageTokens.txt", mapToString(commentThreadPages), "utf-8");
console.log('Waiting until the quota is full again');
// Wait until the next UTC day
while (date.getUTCDay() === currDay) {
date = new Date();
}
// After a new UTC day has started, we have to wait another 7 hours for the PST day to start since that is when the quota resets, we wait an extra one just to be sure
date = new Date();
let waitedHours = 0;
let currHours = date.getUTCHours();
while (waitedHours <= 7) {
date = new Date();
if (currHours !== date.getUTCHours()) // An hour has passed if true
{
waitedHours++;
currHours = date.getUTCHours();
}
}
}
//Check for Connection to Youtube Data API through collecting Ryan's World
async function waitForConnection() {
while (true) {
try {
await collectChannel('UChGJGhZ9SOOHvBB0Y4DOO_w');
break;
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
break;
} else if (err.code !== 'ENOTFOUND') {
throw err;
}
}
}
}
//Check for Database Connection through trying to save Ryan's World
async function waitForDatabaseConnection() {
while (true) {
try {
const doc = {
"_id": channelCollectionName + "/UChGJGhZ9SOOHvBB0Y4DOO_w",
"_key": "UChGJGhZ9SOOHvBB0Y4DOO_w",
"snippet": {
"title": "Ryan's World",
"description": "Welcome To Ryan's World!!! Ryan loves doing lots of fun things like pretend play, science experiments, music videos, skits, challenges, DIY arts and crafts and more!!! \nMost of the toys we used to review are being donated to local charity \n\nRyan's Toys & Clothing at Walmart and Target!\n\nRyan's World \nRyan's Family Review: https://www.youtube.com/channel/UCsaOzYsyshyrYL4SHCTI8xw\nCombo Panda: https://www.youtube.com/channel/UCb69PhsHzsorirJDlxaIXlg\nGus The Gummy Gator: https://www.youtube.com/channel/UCZkSuKAy5kMnZXoxo1PrmJQ\nVTubers: https://www.youtube.com/channel/UCwOGO9gT1y0IvzPqKal4loQ\nThe Studio Space: https://www.youtube.com/channel/UCRgCbwOa1f76Ec_eRBhhezA\nFor Media Inquiries: Ryansworld@rogersandcowan.com\nFor Business Inquiries: ryantoysreviewbiz@gmail.com",
"publishedAt": "2015-03-17T00:18:47Z",
"country": "US"
},
"contentDetails": {
"relatedPlaylists": {
"likes": "LLhGJGhZ9SOOHvBB0Y4DOO_w",
"favorites": ""
}
},
"statistics": {
"viewCount": "40052271189",
"commentCount": "0",
"subscriberCount": "25600000",
"hiddenSubscriberCount": false,
"videoCount": "1754"
},
"topicDetails": {
"topicCategories": [
"https://en.wikipedia.org/wiki/Hobby",
"https://en.wikipedia.org/wiki/Food",
"https://en.wikipedia.org/wiki/Entertainment",
"https://en.wikipedia.org/wiki/Film",
"https://en.wikipedia.org/wiki/Lifestyle_(sociology)"
]
},
"status": {
"privacyStatus": "public",
"isLinked": true,
"madeForKids": true
}
};
await channelCollection.save(doc).then(
meta => console.log('Channel saved:', meta._rev),
err => {
throw err;
}
);
break;
} catch (err) {
if (err.code === 409 && err.errorNum === 1210) { //Conflicting keys, meaning channel exists already
break;
} else if (err.code !== 'ECONNREFUSED') {
throw err;
}
}
}
}
//TODO: Better handling for unexpected errors and errors while saving objects
//TODO: Maybe don't add already saved Channels to Queue, or multiplicity can still be used as collecting more followers from that influencer
//TODO: Maybe further decide decide on page range
//TODO: Test new comment filter
async function scheduler(seedUsers) {
channelQueue.items = seedUsers;
let saveCounter = 0;
let channel = {};
let commentThreads = {};
let subscriptions = {};
let favorites = {};
let favoritedVideoIds = {};
let favoritedVideos = {};
//let likes = {}; No Channel really has public likes, so don't use that for now
let channelAlready = false;
// Regexes to filter for child influencers and to filter out non-helpful big channels
let regExp = /\b[Ff]amily|[Pp]lay|\b[Aa]ges?[^-]|\b[Cc]hild(?:dren)?\b|\b[Mm]om(?:my)?\b|\b[Mm]um\b|\b[Dd]ad(?:dy)?\b|\b[Pp]arent|\b[Dd]ress-up\b|[Yy]ears?\sold|[Tt]oy|\b[Pp]retend\b|Roblox|[Bb]rother\b|[Ss]ister\b/;
let regExpDeutsch = /\b[Ff]amilie|[Ss]piel|\bAlter\b|\bKind(?:er)?\b|\bMam(?:mi|ma)?\b|\bPap(?:pa|pi)?\b|\bEltern|\b[Vv]erkleiden\b/;
let regExpExclude = /\b[Oo]fficial\s(?:[Yy]outube)?\s[Cc]annel|\b[Oo]fficial\s(?:(?:[Cc]annel)|(?:[Pp]resence))/; // Seemingly often done by Shows or Celebrities not coming from Youtube
// Debug parts here
//console.log(channelQueue.toString());
let debugCounter = 0;
while (channelQueue.length !== 0) {
channelAlready = false;
commentThreads = {data: {items: []}};
subscriptions = {data: {items: []}};
saveCounter++;
// Debug part here
// debugCounter++;
console.log("Collecting Channel");
// Check if Channel already exists in database
for (let i = 0; i < 1; i++) {
try {
await channelCollection.document(channelQueue.front()).then(function (doc) {
channelAlready = true;
doc.id = channelQueue.front();
//console.log(doc);
channel = [false, [doc]]; //[{id: channelQueue.front()}]
if (doc.statistics.subscriberCount >= 5000) {
channel = [true, [doc, doc]];
//console.log(channel[1]);
}
})
} catch (err) {
if (err.code === 'ECONNREFUSED') {
await waitForDatabaseConnection();
i--;
}
// Else, the channel just wasn't found so collect it.
}
}
// Don't collect channel when already collected
if (channelAlready === false) {
let notFound = false;
// Try to collect the channel and, when quota exceeded, try again the next day
for (let i = 0; i < 1; i++) {
try {
channel = await collectChannel(channelQueue.front());
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 'ENOTFOUND') {
await waitForConnection();
i--;
} else if (err.code === 400 || err.code === 404) {
channelQueue.dequeue();
console.log('Channel not found, skipping');
//Fill with less "interesting" influencers if out of potential children or only-subscribers
if (channelQueue.isEmpty() === true && unlikelyChildQueue.isEmpty() === false) {
console.log('Retrieving from unlikelyChildQueue');
channelQueue.enqueue(unlikelyChildQueue.front())
unlikelyChildQueue.dequeue();
}
notFound = true;
} else {
console.log(err)
}
}
}
// Skip if channel not found
if (notFound === true) {
continue;
}
// Try to save the channel
for (let i = 0; i < 1; i++) {
try {
await saveChannel(channel);
} catch (err) {
if (err.code === 409 && err.errorNum === 1210) { //Conflicting keys, meaning channel exists already
console.log("Channel was already saved - this should not have happened");
channelAlready = true;
} else if (err.code === 'ECONNREFUSED') {
await waitForDatabaseConnection();
i--;
} else {
console.log(err);
}
}
}
}
console.log("Channel done");
// If the channel is an influencer candidate, also ignore those with topic or rather old practice of VEVO in title of channels
if (channel[0] === true && channel[1][1].snippet.title.includes('Topic') === false && channel[1][1].snippet.title.includes('VEVO') === false) {
//Check whether channel is a potential child or has children involved and if no, ignore that one and save it for later
if (channelQueue.items.length !== 1 && regExp.test(channel[1][1].snippet.description) === false && regExpDeutsch.test(channel[1][1].snippet.description) === false) {
//Some channels are official presences of musicians or none-Youtube celebrities, even though we might loose some child influencers like that, many of those can be deleted to concentrate on more important channels or just subscribers
if (regExpExclude.test(channel[1][1].snippet.description) === false) {
console.log('Moving Channel to unlikelyChildQueue');
unlikelyChildQueue.enqueue(channelQueue.front());
channelQueue.dequeue();
if (channelQueue.isEmpty() === true) {
channelQueue.enqueue(unlikelyChildQueue.front());
}
continue;
} else {
console.log('Deleting unhelpful channel');
channelQueue.dequeue();
}
}
console.log("Collecting Comments");
let nextPage = undefined;
// If the channel has been visited before, then some comment pages will already exist in the Database, so jump forward to the unsaved ones
if (commentThreadPages.has(channel[1][0].id) === true) {
nextPage = commentThreadPages.get(channel[1][0].id);
console.log('Moving on from nextPageToken: ' + nextPage);
}
// Try to collect some pages with each up to 50 commentThreads related to the channel and, when quota exceeded, try again the next day
for (let i = 0; i < 5; i++) {
try {
await collectCommentThreads(channel[1][0].id, nextPage).then(function (dat) {
//TODO: Maybe check for duplicates here already
// Can actually happen without the API returning an error code, see UCChKgkwqZm41sgqv3KyX8Hg for example
if (i === 0 && dat.data.items.length === 0) {
console.log('Empty comment List encountered, stopping comment collection');
i += 5;
}
commentThreads.data.items = commentThreads.data.items.concat(dat.data.items);
if (dat.data.nextPageToken === undefined) { // End the Loop if no more pages exist
i += 5;
} else {
nextPage = dat.data.nextPageToken;
}
});
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 403 && (err.errors[0].reason === "commentsDisabled" || err.errors[0].reason === "forbidden")) {
console.log('(Some) comments disabled');
break;
} else if (err.code === 400 && err.errors[0].reason === "invalidPageToken") {
console.log('Page Token (became) invalid, trying without'); // This should happen if a channels comments have not been visited for a long time by the script, but the api doc says nothing about whether it will happen at all
commentThreadPages.delete(channel[1][0].id);
nextPage = undefined;
i--;
} else if (err.code === 404) {
switch (err.errors[0].reason) {
case "channelNotFound":
i += 5;
break;
case "commentThreadNotFound":
break;
default:
console.log(err);
break;
}
} else if (err.code === 'ENOTFOUND') {
await waitForConnection(); // Wait until connection is back
i--;
} else {
console.log(err);
}
}
}
// Insert page token into comment thread map in case of revisiting later
if (nextPage !== undefined) {
commentThreadPages.set(channel[1][0].id, nextPage);
}
// Save the top level comments of those threads
for (let i = 0; i < commentThreads.data.items.length; i++) {
try {
await saveComment(commentThreads.data.items[i]);
} catch (err) {
if (err.code === 409 && err.errorNum === 1210) { // Conflicting keys, meaning comment exists already
console.log("Comment was already saved");
// Remove channelId from comment so that channelIds don't get added to the queue through already saved comments
commentThreads.data.items[i].snippet.topLevelComment.snippet.authorChannelId = undefined;
} else if (err.code === 'ECONNREFUSED') {
await waitForDatabaseConnection();
i--;
} else {
console.log(err);
}
}
}
// Add Comment authors to channelQueue
const authorChannels = collectChannelIdsFromComments(commentThreads);
for (let x of authorChannels) {
// Filter out self mentions
if (x !== channel[1][0].id) {
channelQueue.enqueue(x);
}
}
console.log("Comments done");
} else {
console.log("Collecting Favorites");
//Try to collect the id of the favorites playlist of the channel and, when quota exceeded, try again the next day
for (let i = 0; i < 1; i++) {
try {
favorites = "";
favorites = await collectFavorites(channel[1][0].id); //Throws an error when none found, so then favorites stays ""
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 'ENOTFOUND') {
await waitForConnection();
i--;
} else if ((err.code === 403 && (err.errors[0].reason === "channelClosed" || err.errors[0].reason === "channelSuspended")) || (err.code === 404 && err.errors[0].reason === "channelNotFound")) {
console.log('Channel not available: ' + err.errors[0].reason);
} else {
console.log(err);
}
}
}
//Then try to collect up to 50 favorited videos of the current channel and, when quota exceeded, try again the next day
if (favorites !== "") {
for (let i = 0; i < 1; i++) {
try {
favoritedVideoIds = await collectVideoIdsFromPlaylist(favorites);
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 'ENOTFOUND') {
await waitForConnection();
i--;
} else {
console.log(err);
}
}
}
//Then try to collect up to 50 "favorited" channels of the current channel through those videos and, when quota exceeded, try again the next day
for (let i = 0; i < 1; i++) {
try {
if (favoritedVideoIds !== "") {
favoritedVideos = await collectVideoInfosFromIDList(favoritedVideoIds[0]);
} else {
favoritedVideos = {data: {items: []}};
}
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 'ENOTFOUND') {
await waitForConnection();
i--;
} else {
console.log(err);
}
}
}
//Save the favourites
for (let i = 0; i < favoritedVideos.data.items.length; i++) {
try {
await saveFavorite(channel[1][0].id, favoritedVideos.data.items[i]);
} catch (err) {
if (err.code === 409 && err.errorNum === 1210) { //Conflicting keys, meaning channel exists already
console.log("Favourite was already saved");
// Remove channelId from video so that channelIds don't get added to the queue through already saved favourites
favoritedVideos.data.items[i].snippet.channelId = undefined;
} else if (err.code === 'ECONNREFUSED') {
await waitForDatabaseConnection();
i--;
} else {
console.log(err);
}
}
}
//List of favourited channelIds
let uploaderChannels = collectChannelIdsFromVideoInfos(favoritedVideos);
// Add favorited channelIds to queue
for (let x of uploaderChannels) {
// Filter out self mentions
if (x !== channel[1][0].id) {
channelQueue.enqueue(x);
}
}
}
console.log('Favorites done');
}
// As we only collect the first 100 subscriptions and therefore don't save the pageTokens, we don't have to do this part again when the channel was already visited
if (channelAlready === false) {
console.log("Collecting Subscriptions");
//Try to collect some pages with up to 100 subscriptions total of the channel(sorted by relevance) and, when quota exceeded, try again the next day
let nextPage = undefined;
for (let i = 0; i < 2; i++) {
try {
await collectSubscriptions(channel[1][0].id, nextPage).then(function (dat) {
subscriptions.data.items = subscriptions.data.items.concat(dat.data.items);
if (dat.data.nextPageToken === undefined) {
i++;
} else {
nextPage = dat.data.nextPageToken;
}
});
} catch (err) {
if (err.code === 403 && err.errors[0].reason === "quotaExceeded") {
waitUntilNextDay();
i--;
} else if (err.code === 403 && err.errors[0].reason === "subscriptionForbidden") {
break;
} else if (err.code === 'ENOTFOUND') {
await waitForConnection();
i--;
} else if ((err.code === 403 && (err.errors[0].reason === "accountClosed" || err.errors[0].reason === "accountSuspended")) || (err.code === 404 && err.errors[0].reason === "subscriberNotFound")) {
console.log('Channel not available: ' + err.errors[0].reason);
} else {
console.log(err);
}
}
}
//Save the subscriptions
for (let i = 0; i < subscriptions.data.items.length; i++) {
//console.log("Saving Subscription " + x.id);
try {
await saveSubscription(subscriptions.data.items[i])
if (subscriptions.data.items[i].snippet.resourceId.channelId !== undefined) {
channelQueue.enqueue(subscriptions.data.items[i].snippet.resourceId.channelId);
}
} catch (err) {
if (err.code === 409 && err.errorNum === 1210) { //Conflicting keys, meaning subscription exists already