This repository has been archived by the owner on Jan 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackUpChannelAnnotations.py
417 lines (372 loc) · 11.7 KB
/
backUpChannelAnnotations.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
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 reportPlaylistProgress():
global t
print("{} videos have been read from the playlist...".format(len(p)))
t=threading.Timer(10.0, reportPlaylistProgress)
t.start()
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()
#Globals
m={}
q=deque()
p=[]
i=0
toGather=0
t = threading.Timer(10.0, reportProgress, [i,toGather])
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 snapShotOfPlaylist(ID):
return makeRequestWithoutParameter("http://web.archive.org/save/https://www.youtube.com/playlist?list={}".format(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 snapShotOfPlaylistTaken(ID):
return makeRequestWithoutParameter("http://archive.org/wayback/available?url=https://www.youtube.com/playlist?list={}".format(ID))
def main():
global i,toGather,p
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 the URL of a channel whose videos you'd like back up:\n")
if argument == "":
print("Program Terminated")
break
else:
channel = channelExtractor(argument)
#print(channel)
userPage=""
Break=False
while True:
r = requests.get("https://www.youtube.com/user/{}/videos".format(channel))
if r.status_code != 200:
print("An error occured while trying to load the 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
elif action == 'a':
break
userPage = r.text
break
if Break:
continue
userSoup = BeautifulSoup(userPage,"html.parser")
uP = userSoup.find("a", class_="play-all-icon-btn")
uPLink = "https://www.youtube.com{}".format(uP.get('href'))
print("getting upload playlist...")
lID = playlistIdExtractor(uPLink)
#print(lID)
#return
r=snapShotOfPlaylistTaken(lID)
if 'closest' in r.json()["archived_snapshots"]:
print('I have a hunch that this playlist has been scanned.')
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
#Go to the playlist page using teh id
reportPlaylistProgress()
err = analyzePlaylist(lID)
t.cancel()
if err==1:
continue
else:
print("Video Count in Playlist: {}".format(len(p)))
print("Optionally specify the interval of the videos to be scanned.")
start = 0
end = len(p)+1
while True:
print("Type the index of the video you want to start from and the index of the last one you'd like to include.")
print("Or simply press enter without typing anything to scan the full playlist...")
intervalInput = input()
if contains2Numbers(intervalInput):
start,end = get2Numbers(intervalInput)
if validInterval(start,end,len(p)):
end+=1
break
else:
print("Please specify a valid interval!")
elif intervalInput=="":
start = 0
end = len(p)+1
break
else:
print("Please type only two numbers representing indices in the playlist if you wish to specify an interval OR press enter to skip.")
#In the case of a playlist sweep ALSO take a snapshot of the playlist
playListSweep = False
if start == 0 and end == len(p)+1:
playListSweep = True
p = p[start:end]
#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
#gather videos linked to from this playlist
#print (p)
#continue
print("Gathering links... This might take a few moments...")
reportGathering()
err = gatherStartingFromPlaylistVids()
t.cancel()
if err == 1:
Break=True
break
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()
# #19 is problematic
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':
t.start()
continue
if action == 'i':
t.start()
i+=1
break
if action == 'a':
Break=True
playListSweep = False
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))
if playListSweep:
snapShotOfPlaylist(lID)
print("Took a snapshot of the playlist to let people know its been fully scanned.")
def gatherStartingFromPlaylistVids():
global m,q
m={}
q=deque()
for video in p:
q.append(video)
m[video] = False
while len(q) != 0:
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
q.append(head)
t.start()
continue
if action == 'a':
return 1
#q.pop()
#print (m)
return 0
def analyzePlaylist(pID):
try:
#First link is extracted as an html
target="https://www.youtube.com/playlist?list={}".format(pID)
while True:
r=requests.get(target)
if r.status_code != 200:
t.cancel()
print("An error occured while trying to read the playlist...")
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':
t.start()
continue
if action == 'a':
return 1
break
plt=r.text
imAtSoup = BeautifulSoup(plt,"html.parser")
#print("TRYING TO ADD NEW STUFF FROM imAtSoup HERE")
#print(str(imAtSoup.find_all("a")))
#print("did it work tho?")
for link in imAtSoup.find_all("a", class_="pl-video-title-link"):
p.append(idExtractor('https://www.youtube.com{}'.format(link.get('href'))))
nB = imAtSoup.find_all("button", class_="load-more-button")
if len(nB) == 0:
return 0
ajaxTarget=nB[0].get("data-uix-load-more-href")
target = "https://www.youtube.com{}".format(ajaxTarget)
while True:
#later playlist links are the internal html of a json
#and to be loaded links are stored in a seperate entry of said json
#print(target)
#print(plt.find('browse_ajax?ctoken='))
Break=False
while True:
r=requests.get(target)
if r.status_code != 200:
print("An error occured while trying to read the playlist...")
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':
return 1
break
plt=r.json()['content_html']
imAtSoup = BeautifulSoup(plt,"html.parser")
for link in imAtSoup.find_all("a", class_="pl-video-title-link"):
p.append(idExtractor('https://www.youtube.com{}'.format(link.get('href'))))
nextLink=r.json()['load_more_widget_html']
whereIsSoup = BeautifulSoup(nextLink,"html.parser")
#print(whereIsSoup.prettify())
nB = whereIsSoup.find_all("button", class_="load-more-button")
if len(nB) == 0:
return 0
ajaxTarget=nB[0].get("data-uix-load-more-href")
target = "https://www.youtube.com{}".format(ajaxTarget)
#return 0
#print(plt)
#return 1
except Exception as e:
print(e)
return 1
else:
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:
m[lId] = False
q.append(lId)
#print("added {} to queue".format(lId))
#else:
#print("duplicate entry detected")
except:
return 1
else:
return 0
def backUp(vID):
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:
print(e)
return 1
else:
return 0
#Interval functions
def contains2Numbers(inp):
return ( len(re.findall('(?!\-|\.)[0-9]+',inp)) == 2)
def get2Numbers(inp):
numberList = re.findall('(?!\-|\.)[0-9]+',inp)
return int(numberList[0]),int(numberList[1])
def validInterval(a,b,d):
if a <= 0:
return False
elif b > d:
return False
elif a > b:
return False
return True
if __name__== "__main__":
main()