-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackUpConnectedVideos.py
461 lines (413 loc) · 12.1 KB
/
backUpConnectedVideos.py
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
import requests,json,sys,re,os,time
import threading
from datetime import datetime
from VideoIDHelper import *
from collections import deque
from bs4 import BeautifulSoup
def reportProgress():
global t
if toGather != 1:
print("Processed {}/{} videos.".format(i,toGather))
else:
print("Processed 0/1 video.")
t=threading.Timer(10.0, reportProgress)
t.start()
def reportGathering():
global t
print("{} links gathered so far...".format(len(m)))
t=threading.Timer(10.0, reportGathering)
t.start()
def reportMode1():
global t
print("Backed Up {}/{}".format(successes,len(m)))
t=threading.Timer(10.0, reportMode1)
t.start()
#Globals
m={}
q=deque()
i=0
toGather=0
t = threading.Timer(10.0, reportProgress, [i,toGather])
hardLimitSet=False
hardLimit = 0
channelLock=False
channel=""
invld={}
mode1 = False
successes=0
#Note variable should be unused in playlistannotations
def makeRequest(partialURL,parameter,ID):
pars = {"parameter" : ID}
return requests.get(partialURL, params=pars)
def makeRequestWithoutParameter(URL):
return requests.get(URL)
def backUpAnnotations(ID):
return makeRequestWithoutParameter("http://web.archive.org/save/https://www.youtube.com/annotations_invideo?video_id={}".format(ID))
def snapShotPage(ID):
return makeRequest("http://web.archive.org/save/https://www.youtube.com/watch","v",ID)
def annotationsBackedUp(ID):
return makeRequestWithoutParameter("http://archive.org/wayback/available?url=https://www.youtube.com/annotations_invideo?video_id={}".format(ID))
def snapShotTaken(ID):
return makeRequestWithoutParameter("http://archive.org/wayback/available?url=https://www.youtube.com/watch?v={}".format(ID))
def main():
global i,toGather,successes,mode1
first = True
argument = ""
print( "Hello today is: " + str(datetime.now().month) + "/" + str(datetime.now().day))
#print( "Remember that we have time until: " + "1/15" + "for Annotations and Credits; and until " + "1/31" +" for Episodes (presumably PST 0:00) " )
print( "Remember that we have time until: " + "1/15" + "for the Annotations (presumably PST 0:00) " )
while first or argument == "":
#argument ="horse"
argument = input("Type in a URL to video or its ID: ")
if argument == "":
print("Program Terminated")
break
else:
#Check for the initial link
vID = idExtractor(argument)
#print("vID: {}".format(vID))
r = annotationsBackedUp(vID)
if 'closest' in r.json()["archived_snapshots"]:
print('That link seems to have been saved.')
isY = input('But if you want to make sure that all sublinks have also been saved type y\n')
if isY.rstrip().strip() != "y":
continue
hardLimitSet = False
#err = setHardLimit()
#if err ==1:
# continue
setHardLimit()
channelLock = False
err = setChannelLock()
if err ==1:
continue
mode1 = False
setMode()
Break = False
while True:
err = activateChannelLock(vID)
if err == 1:
print("an error occured while trying to access the video's channel")
action=""
while action!='r' and action!='a':
action = input("Type r to retry or a to abort:\n")
action = action.rstrip().strip()
if action == 'r':
continue
if action == 'a':
Break = True
break
break
if Break:
continue
err = gatherStartingFrom(vID)
t.cancel()
if err == 1:
if mode1:
print("DONE!")
print("{}/{} backed up!".format(successes,len(m)))
continue
#mode 2
if not mode1:
toGather = len(m)
print("Discovered {} videos...".format(toGather))
i=0
#successes=0
Break=False
reportProgress()
#t.start()
for ID in m:
while True:
code = backUp(ID)
if code == 1:
t.cancel()
print("https://www.youtube.com/watch?v={} wasn't saved properly".format(ID))
action=""
while action!='r' and action!='a' and action!='i':
action = input("Type r to retry,i to ignore or a to abort:\n")
action = action.rstrip().strip()
if action == 'r':
reportProgress()
continue
if action == 'i':
reportProgress()
i+=1
break
if action == 'a':
Break=True
i+=1
break
elif code == 2:
print("https://www.youtube.com/watch?v={} is unavailable, skipping...".format(ID))
i+=1
break
else:
m[ID]=True
i+=1
successes+=1
break
if Break:
break
t.cancel()
if toGather == 1:
print("{}/{} is now backed up!".format(successes,toGather))
print("{}/{} are now backed up!".format(successes,toGather))
#mode 1
else:
print("DONE!")
print("{}/{} backed up!".format(successes,len(m)))
def gatherStartingFrom(vID):
global m,q,invld,mode1,successes
Break=False
successes=0
m={}
q=deque()
q.append(vID)
m[vID] = False
invld={}
if not mode1:
print("Gathering links... This might take a while...")
reportGathering()
else:
print("Starting up...")
reportMode1()
while len(q) != 0 and not (hardLimitSet and len(m) >= hardLimit):
#print("LEN:{}".format(len(q)))
head = q.pop()
code = gather(head)
#check for errors
if code == 1:
print("An error occured while trying to gather the videos...")
action=""
t.cancel()
while action!='r' and action!='a':
action = input("Type r to retry or a to abort:\n")
action = action.rstrip().strip()
if action == 'r':
#reset this
if mode1: reportMode1()
else: reportGathering()
q.append(head)
continue
if action == 'a':
return 1
break
#q.pop()
elif mode1:
while True:
code = backUp(head)
if code == 1:
t.cancel()
print("https://www.youtube.com/watch?v={} wasn't saved properly".format(head))
action=""
while action!='r' and action!='a' and action!='i':
action = input("Type r to retry,i to ignore or a to abort:\n")
action = action.rstrip().strip()
if action == 'r':
reportMode1()
continue
if action == 'i':
reportMode1()
#i+=1
break
if action == 'a':
Break=True
#i+=1
break
elif code == 2:
print("https://www.youtube.com/watch?v={} is unavailable, skipping...".format(head))
#i+=1
break
else:
m[head]=True
#i+=1
successes+=1
break
if Break:
t.cancel()
return 1
#print (m)
if (hardLimitSet and len(m) >= hardLimit):
print("HARDLIMIT of {} reached! Scan halted!".format(len(m)))
print("Backing up already scanned videos...")
if mode1:
while len(q) != 0:
code = gather(head)
#check for errors
if code == 1:
print("An error occured while backing up the videos...")
action=""
t.cancel()
while action!='r' and action!='a':
action = input("Type r to retry or a to abort:\n")
action = action.rstrip().strip()
if action == 'r':
#reset this
if mode1: reportMode1()
else: reportGathering()
q.append(head)
continue
if action == 'a':
return 1
break
return 0
def gather(vID):
#OPEN vID's ANNOTATIONS BY REQUEST
#Done
#SCAN FOR ANYTHING THAT HAS /WATCH or the shortened URL
#Done
#TRY TO ADD TO M
#IF CAN ADD TO M ADD TO Q
#done
#IF CAN'T ADD TO M MOVE ON
#done
#RETURN 1 if ERROR IS RAISED
#done
try:
r = requests.get("https://www.youtube.com/annotations_invideo?video_id={}".format(vID))
#print("https://www.youtube.com/annotations_invideo?video_id={}".format(vID))
#xml = ""
xml = str(r.text)
soup = BeautifulSoup(xml, 'xml')
#print(soup.prettify()[:300])
#filteredSoup = [ x.attrs for x in soup.find_all(type=['text','highlight'])]
#filteredSoup = [ x['value'] for x in soup.find_all('url') if (x['value'].find('/watch') != -1 or x['value'].find('.be') != -1)]
filteredSoup=[ idExtractor(x['value']) for x in soup.find_all('url') if (x['value'].find('/watch') != -1 or x['value'].find('.be') != -1) ]
#shortUrls=[ idExtractor(x['value']) for x in soup.find_all('url') if x['value'].find('.be') != -1]
#print(longUrls)
#print(shortUrls)
#itct = soup.annotations["itct"]
#newSoup=BeautifulSoup("<document><annotations itct=\""+itct+"\">"+"".join([str(x) for x in filteredSoup])+"</annotations></document>",'xml')
#print(newSoup.prettify())
for lId in filteredSoup:
#print (lId)
if not lId in m:
#Channel Lock
if channelLock:
#new dictionary for invalited links
if not lId in invld:
thisChannel=channelExtractor(getVideoUser(lId))
if channelUnavailable(thisChannel) or thisChannel!=channel:
invld[lId] = True
continue
else:
continue
m[lId] = False
q.append(lId)
if(hardLimitSet and len(m) >= hardLimit):
return 0
#print("added {} to queue".format(lId))
#else:
#print("duplicate entry detected")
except Exception as e:
print(e)
return 1
else:
return 0
def backUp(vID, retries=3):
try:
r = snapShotTaken(vID)
if 'closest' not in r.json()["archived_snapshots"]:
r2=snapShotPage(vID)
if r2.status_code != 200:
#Make a check to ensure the video isn't unavailable
if videoUnavailable(vID):
return 2
else:
return 1
r = annotationsBackedUp(vID)
if 'closest' not in r.json()["archived_snapshots"]:
r2=backUpAnnotations(vID)
if r2.status_code != 200:
if videoUnavailable(vID):
return 2
else:
return 1
except Exception as e:
if retries <= 0:
print(e)
return 1
else:
print("Unable to load retrying...")
time.sleep(5)
return backUp(vID, retries-1)
else:
return 0
def setHardLimit():
global hardLimit,hardLimitSet
print("Throughly scanning links can sometimes generate thousands of videos.")
print("To spare your computer we offer the option of setting a hard limit to how many videos its allowed to scan.")
print("Although this is largely dependent on what video you're scanning and on your internet speed")
print("We found that the average speed was about 10000 videos/hour on our devices.")
#print("Keep in mind that this is only the discovery process and that there's still time spent on .")
action=""
while True:
print("Please type a single number specifying the maximum number of videos to be scanned")
print("Or hit enter to scan everything available. (Do this only if you know what you're doing)")
action = input("")
action = action.rstrip().strip()
if action == '':
return 0
elif isASingleNumber(action):
hardLimitSet = True
hardLimit = getTheNumber(action)
if hardLimit==1:
print("Limited scan to 1 video.")
else:
print("Limited scan to {} videos.".format(str(hardLimit)))
return 0
def isASingleNumber(inp):
return ( len(re.findall('(?!\-|\.)[0-9]+',inp)) == 1) and ( int(re.findall('(?!\-|\.)[0-9]+',inp)[0]) > 0)
def getTheNumber(inp):
numberList = re.findall('(?!\-|\.)[0-9]+',inp)
return int(numberList[0])
def setChannelLock():
#Channel Lock
global channelLock
print("Would you like to only search for videos linked to same channel?")
print("This is a good idea if you only want to fetch unlisted videos from a video.")
#print("Keep in mind that this is only the discovery process and that nothing is backed up in this phase.")
action=""
while True:
print("Type y to confirm or enter to scan regardless:")
action = input("")
action = action.rstrip().strip()
if action == '':
channelLock=False
return 0
elif action == 'y':
channelLock=True
return 0
def activateChannelLock(vID):
#Attempt to get channel of vID
#print("attempting to get channel")
cID=getVideoUser(vID)
if cID=="":
if videoUnavailable(vID):
return 2
return 1
channel=channelExtractor(cID)
return 0
#cID
def setMode():
#Channel Lock
global mode1
print("Please choose the mode you'd like to use.")
print("Mode 1: Scan as you back up")
print("Mode 2: Scan first, then back up")
print("We recommend you use mode 1 since it doesn't waste any time making back-ups.")
print("Plus it's slightly faster.")
print("Mode 2's advantage is that it'll better help you track the progress.")
print("Consider using mode 2 if you know there won't be a lot of videos linked to from this video.")
action=""
while True:
action = input("Type 1 or 2:")
action = action.rstrip().strip()
if action == '1':
mode1=True
return 0
elif action == '2':
mode1=False
return 0
if __name__== "__main__":
main()