-
Notifications
You must be signed in to change notification settings - Fork 21
/
dagr.py
486 lines (437 loc) · 20.8 KB
/
dagr.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# deviantArt Gallery Ripper v0.43
# http://lovecastle.org/dagr/
# Copying and distribution of this file, with or without
# modification, is permitted.
# This file is offered as-is, without any warranty.
import random, re, os, sys, hashlib, getopt, urllib2, urllib, cookielib
from urllib2 import Request, urlopen, URLError, HTTPError
MAX = 1000000 #max deviations
VERSION="0.43"
NAME = os.path.basename(__file__)
USERAGENTS = (
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)',
'Opera/9.99 (Windows NT 5.1; U; pl) Presto/9.9.9',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-US) AppleWebKit/530.5 (KHTML, like Gecko) Chrome/ Safari/530.5',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/6.0',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)'
)
DOOVERWRITE = False
def daLogin(username,password,proxy=None):
jar = cookielib.CookieJar()
handler = urllib2.HTTPCookieProcessor(jar)
opener = urllib2.build_opener(handler)
if proxy:
proxy_handler = urllib2.ProxyHandler({'http': proxy})
opener.add_handler(proxy_handler)
urllib2.install_opener(opener)
opener.addheaders = [('Referer', 'http://www.deviantart.com/')]
opener.addheaders = [('User-Agent', random.choice(USERAGENTS))]
data = ""
try:
f = opener.open('https://www.deviantart.com/users/login', "ref=http%3A%2F%2Fwww.deviantart.com%2F&username="+username+"&password="+password+"&remember_me=1")
data = f.read()
f.close()
except HTTPError, e:
print "HTTP Error:",e.code
sys.exit()
except URLError, e:
print "URL Error:",e.reason
sys.exit()
if re.search("<title>deviantART\ +:\ +Wrong Password!</title>",data):
print "Wrong password or username. Attempting to download anyway."
elif re.search("<title>deviantART:\ +where\ +ART\ +meets\ +application!</title>",data):
print "Logged in!"
else:
print "Login unsuccessful. Attempting to download anyway."
return jar
def get(url, cookiejar=None, proxy=None):
if cookiejar:
handler = urllib2.HTTPCookieProcessor(cookiejar)
opener = urllib2.build_opener(handler)
else:
opener = urllib2.build_opener()
if proxy:
proxy_handler = urllib2.ProxyHandler({'http': proxy})
opener.add_handler(proxy_handler)
urllib2.install_opener(opener)
opener.addheaders = [('User-Agent', random.choice(USERAGENTS))]
try:
f = opener.open(url)
return str(f.read())
except HTTPError, e:
print "HTTP Error:",e.code , url
except URLError, e:
print "URL Error:",e.reason , url
def download(url,file_name,cookiejar=None,proxy=None):
if (DOOVERWRITE == False) and (os.path.exists(file_name)):
print file_name+" exists - skipping"
return
if cookiejar:
handler = urllib2.HTTPCookieProcessor(cookiejar)
opener = urllib2.build_opener(handler)
else:
opener = urllib2.build_opener()
if proxy:
proxy_handler = urllib2.ProxyHandler({'http': proxy})
opener.add_handler(proxy_handler)
urllib2.install_opener(opener)
opener.addheaders = [('User-Agent', random.choice(USERAGENTS))]
try:
f = opener.open(url)
# Open our local file for writing
local_file = open(file_name, "wb")
#Write to our local file
local_file.write(f.read())
local_file.close()
except HTTPError, e:
print "HTTP Error:",e.code , url
except URLError, e:
print "URL Error:",e.reason , url
except IOError, e:
print e
sys.exit()
def findLink(link,html):
if re.search("id=\"download-button\"",html,re.IGNORECASE|re.DOTALL):
filelink = re.search("id=\"download-button\".*\".*\"",html,re.IGNORECASE|re.DOTALL).group(0)
filelink = filelink.split("\"")[3]
filename = filelink.split("/")[-1]
elif re.search("collect_rid=\"\d*:\d*\" src=\"",html,re.IGNORECASE):
k = re.search("data-gmiclass=\"ResViewSizer_fullimg\".*src=\"([^\"]*)\".*class=\"fullview smshadow\">",html,re.DOTALL | re.IGNORECASE)
if k:
filelink = k.group(1)
else:
filelink = re.search("src=\"([^\"]*)",re.search("data-gmiclass=\"ResViewSizer_fullimg\".*",html,re.DOTALL | re.IGNORECASE).group(0),re.DOTALL | re.IGNORECASE).group(1)
if re.search("_by_[A-Za-z0-9-_]+-\w+\.\w+",filelink,re.IGNORECASE) or re.search("_by_[A-Za-z0-9-_]+\.\w+",filelink,re.IGNORECASE):
filename = filelink.split("/")[-1]
elif filelink:
filext = re.search("\.\w+$",filelink).group(0)
filename = re.sub("-[0-9]+$","",link.split("/")[-1])+"_by_"+re.search("^http://([A-Za-z0-9-_]+)\.",link).group(1)+filext
return (filename,filelink)
def deviantGet(mode,deviant,verbose,reverse,cookiejar=None,proxy=None,testOnly=False):
print "Ripping "+deviant+"'s "+mode+"..."
pat = "http://[a-zA-Z0-9_-]*\.deviantart\.com/art/[a-zA-Z0-9_-]*"
modeArg = '_'
if mode.find(':') != -1:
mode = mode.split(':',1)
modeArg = mode[1]
mode = mode[0]
#DEPTH 1
pages = []
for i in range(0,MAX/24,24):
html = ""
try:
if mode == "favs":
html = get("http://" + deviant.lower() + ".deviantart.com/favourites/?catpath=/&offset=" + str(i), cookiejar, proxy)
elif mode == "scraps":
html = get("http://" + deviant.lower() + ".deviantart.com/gallery/?catpath=scraps&offset=" + str(i), cookiejar, proxy)
elif mode == "gallery":
html = get("http://" + deviant.lower() + ".deviantart.com/gallery/?catpath=/&offset=" + str(i), cookiejar, proxy)
elif mode == "album":
html = get("http://" + deviant.lower() + ".deviantart.com/gallery/" + modeArg + "?offset=" + str(i), cookiejar, proxy)
elif mode == "query":
print "http://" + deviant.lower() + ".deviantart.com/gallery/?q="+modeArg+"&offset=" + str(i)
html = get("http://" + deviant.lower() + ".deviantart.com/gallery/?q="+modeArg+"&offset=" + str(i), cookiejar, proxy)
else:
continue
except HTTPError, e:
print "HTTP Error:",e.code , url
continue
except URLError, e:
print "URL Error:",e.reason , url
continue
except Exception, e:
print e
continue
prelim = re.findall(pat, html, re.IGNORECASE|re.DOTALL)
c = len(prelim)
for match in prelim:
if match in pages:
c -= 1
else:
pages.append(match)
done = re.findall("(This section has no deviations yet!|This collection has no items yet!)", html, re.IGNORECASE|re.S)
if len(done) >= 1 or c <= 0:
break
print deviant+"'s",mode,"page",str((i/24)+1),"crawled..."
if not reverse:
pages.reverse()
if len(pages) == 0:
print deviant+"'s "+mode+" had no deviations."
return 0
else:
try:
os.makedirs(deviant+"/"+mode)
if (mode == "query") or (mode == "album"):
os.makedirs(deviant+"/"+mode+"/"+modeArg)
except Exception, e:
print str(e)
print "Total deviations in "+deviant+"'s gallery found:",len(pages)
##DEPTH 2
counter2 = 0
for link in pages:
html = get(link,cookiejar,proxy)
counter2 += 1
if verbose:
print "Downloading",counter2,"of",len(pages),"( "+link+" )"
filename = ""
filelink = ""
try:
filename,filelink = findLink(link,html)
except:
print "Download error. Possible mature deviation? (",link,")"
continue
if testOnly == False:
if (mode == "query") or (mode=="album"):
download(filelink,deviant+"/"+mode+"/"+modeArg+"/"+filename,proxy)
else:
download(filelink,deviant+"/"+mode+"/"+filename,proxy)
else:
print filelink
print deviant+"'s gallery successfully ripped."
def groupGet(mode,deviant,verbose,reverse,cookiejar=None,proxy=None,testOnly=False):
if mode == "favs":
strmode = "favby"
strmode2 = "favourites"
strmode3 = "favs gallery"
elif mode == "gallery":
strmode = "gallery"
strmode2 = "gallery"
strmode3 = "gallery"
else:
print "?"
sys.exit()
print "Ripping "+deviant+"'s",strmode2+"..."
folders = []
insideFolder = False
#are we inside a gallery folder?
html = get('http://'+deviant+'.deviantart.com/'+strmode2+'/',cookiejar,proxy)
if re.search(strmode2+"/\?set=.+&offset=",html,re.IGNORECASE|re.S):
insideFolder = True
folders = re.findall(strmode+":.+ label=\"[^\"]*\"", html, re.IGNORECASE)
#no repeats
folders = list(set(folders))
i = 0
while not insideFolder:
html = get('http://'+deviant+'.deviantart.com/'+strmode2+'/?offset='+str(i),cookiejar,proxy)
k = re.findall(strmode+":"+deviant+"/\d+\"\ +label=\"[^\"]*\"", html, re.IGNORECASE)
if k == []:
break
flag = False
for match in k:
if match in folders:
flag = True
else:
folders+=k
if verbose:
print "Gallery page",(i/10)+1,"crawled..."
if flag:
break
i += 10
#no repeats
folders = list(set(folders))
if len(folders) == 0:
print deviant+"'s",strmode3,"is empty."
return 0
else:
print "Total folders in "+deviant+"'s",strmode3,"found:",len(folders)
if reverse:
folders.reverse()
pat = "http:\\/\\/[a-zA-Z0-9_-]*\.deviantart\.com\\/art\\/[a-zA-Z0-9_-]*"
pages = []
for folder in folders:
try:
folderid = re.search("[0-9]+",folder,re.IGNORECASE).group(0)
label = re.search("label=\"([^\"]*)",folder,re.IGNORECASE).group(1)
except:
continue
for i in range(0,MAX/24,24):
html = ""
try:
html = get("http://" + deviant.lower() + ".deviantart.com/" + strmode2 + "/?set=" + folderid + "&offset=" + str(i - 24), cookiejar, proxy)
except (URLError,HTTPError):
print Exception
continue
prelim = re.findall(pat, html, re.IGNORECASE)
if not prelim:
break
for x in prelim:
p = str(re.sub(r'\\/','/',x))
if p not in pages:
pages.append(p)
if verbose:
print "Page",(i/24)+1,"in folder",label,"crawled..."
if not reverse:
pages.reverse()
try:
if mode == "favs":
os.makedirs(deviant+"/favs/"+label)
elif mode == "gallery":
os.makedirs(deviant+"/"+label)
except Exception, err:
print err
counter = 0
for link in pages:
html = get(link,cookiejar,proxy)
counter += 1
if verbose:
print "Downloading",counter,"of",len(pages),"( "+link+" )"
filename = ""
filelink = ""
try:
filename,filelink = findLink(link,html)
except:
print "Download error. Possible mature deviation? (",link,")"
continue
if testOnly==False:
if mode == "favs":
download(filelink,deviant+"/favs/"+label+"/"+filename,proxy)
elif mode == "gallery":
download(filelink,deviant+"/"+label+"/"+filename,proxy)
else:
print filelink
print deviant+"'s",strmode3,"successfully ripped."
def printHelp():
print NAME+" v"+VERSION+" - deviantArt gallery ripper"
print "Usage: "+NAME+" [-u username] [-p password] [-hfgsv] [deviant]..."
print "Example: "+NAME+" -u user -p 1234 -gsfv derp123 blah55"
print "For help use the -h flag, ie. dagr.py -h"
def printHelpDetailed():
printHelp()
print "Argument list:"
print "-u, --username=USERNAME"
print " your username (account must have \"Show Deviations with Mature Content\" enabled to download mature deviations)"
print "-p, --password=PASSWORD"
print " your password (account must have \"Show Deviations with Mature Content\" enabled to download mature deviations)"
print "-g, --gallery"
print " downloads entire gallery of selected deviants"
print "-s, --scraps"
print " downloads entire scraps gallery of selected deviants"
print "-f, --favs"
print " downloads all favourites of selected deviants"
print "-a, --album=#####"
print " downloads specified album"
print "-q, --query"
print " downloads artwork matching specified query string"
print "-t, --test"
print " skips the actual download, just prints urls"
print "-h, --help"
print " prints usage message and exits (this text)"
print "-r, --reverse"
print " download oldest deviations first"
print "-o, --overwrite"
print " redownloads a file even if it already exists"
print "-x, --proxy=PROXY:PORT"
print " enables proxy mode (very unreliable)"
print "-v, --verbose"
print " outputs detailed information on downloads"
if __name__ == "__main__":
if len(sys.argv) <= 1:
printHelp()
sys.exit()
#defaults
username = ""
password = ""
proxy = None
gallery = False
verbose = False
reverse = False
scraps = False
favs = False
testOnly = False
album = False
albumId = -1
query = False
queryS = ""
try:
options, deviants = getopt.gnu_getopt(sys.argv[1:], 'u:p:x:a:q:vfgshrto', ['username=', 'password=', 'proxy=','album=', 'query=', 'verbose', 'favs', 'gallery', 'scraps', 'help', 'reverse', 'test', 'overwrite'])
except getopt.GetoptError, err:
print "Error:",str(err)
sys.exit()
for opt, arg in options:
if opt in ('-h', '--help'):
printHelpDetailed()
sys.exit()
elif opt in ('-u', '--username'):
username = arg
elif opt in ('-p', '--password'):
password = arg
elif opt in ('-x', '--proxy'):
proxy = arg
elif opt in ('-s', '--scraps'):
scraps = True
elif opt in ('-g', '--gallery'):
gallery = True
elif opt in ('-r', '--reverse'):
reverse = True
elif opt in ('-f', '--favs'):
favs = True
elif opt in ('-v', '--verbose'):
verbose = True
elif opt in ('-a', '--album'):
album = True
albumId = arg.strip()
elif opt in ('-q', '--query'):
query = True
queryS = arg.strip().strip('"')
elif opt in ('-t', '--test'):
testOnly = True
elif opt in ('-o', '--overwrite'):
DOOVERWRITE = True
print NAME+" v"+VERSION+" - deviantArt gallery ripper"
if deviants == []:
print "No deviants entered. Quitting."
sys.exit()
if not gallery and not scraps and not favs and not album and not query:
print "Nothing to do. Quitting."
sys.exit()
cookiejar = None
if username and password:
print "Attempting to log in to deviantArt..."
cookiejar = daLogin(username,password,proxy)
else:
print "Mature deviations will not be available for download without logging in!"
for deviant in deviants:
group = False
try:
deviant = re.search(r'<title>.[A-Za-z0-9-]*', get("http://"+deviant+".deviantart.com",cookiejar,proxy),re.IGNORECASE).group(0)[7:]
if re.match("#", deviant):
group = True
deviant = re.sub('[^a-zA-Z0-9_-]+', '', deviant)
except:
print "Deviant",deviant,"not found or deactivated!"
continue
if group:
print "Current group:",deviant
else:
print "Current deviant:",deviant
try:
os.makedirs(deviant)
except Exception, err:
print err
args = (deviant,verbose,reverse,cookiejar,proxy,testOnly)
if group:
if scraps:
print "Groups have no scraps gallery..."
if gallery:
groupGet("gallery",*args)
if favs:
groupGet("favs",*args)
else:
print "Option not supported in groups"
else:
if gallery:
deviantGet("gallery",*args)
if scraps:
deviantGet("scraps",*args)
if favs:
deviantGet("favs",*args)
if album:
deviatGet("album:"+albumId,*args)
if query:
deviantGet("query:"+queryS,*args)
print "Job complete."