Repository navigation
Expand file tree
/
Copy pathSimpleHoster.py
More file actions
758 lines (549 loc) · 25 KB
/
Copy pathSimpleHoster.py
File metadata and controls
758 lines (549 loc) · 25 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
# -*- coding: utf-8 -*-
import datetime
import mimetypes
import os
import re
import time
import urllib
import urlparse
from pyload.Datatype.File import statusMap as _statusMap
from pyload.network.CookieJar import CookieJar
from pyload.network.HTTPRequest import BadHeader
from pyload.network.RequestFactory import getURL
from pyload.plugin.Hoster import Hoster
from pyload.plugin.Plugin import Fail, Retry
from pyload.utils import fixup, fs_encode, parseFileSize
#@TODO: Adapt and move to PyFile in 0.4.10
statusMap = dict((v, k) for k, v in _statusMap.iteritems())
#@TODO: Remove in 0.4.10 and redirect to self.error instead
def _error(self, reason, type):
if not reason and not type:
type = "unknown"
msg = _("%s error") % type.strip().capitalize() if type else _("Error")
msg += (": %s" % reason.strip()) if reason else ""
msg += _(" | Plugin may be out of date")
raise Fail(msg)
#@TODO: Remove in 0.4.10
def _wait(self, seconds, reconnect):
if seconds:
self.setWait(int(seconds) + 1)
if reconnect is not None:
self.wantReconnect = reconnect
super(SimpleHoster, self).wait()
def replace_patterns(string, ruleslist):
for r in ruleslist:
rf, rt = r
string = re.sub(rf, rt, string)
return string
def set_cookies(cj, cookies):
for cookie in cookies:
if isinstance(cookie, tuple) and len(cookie) == 3:
domain, name, value = cookie
cj.setCookie(domain, name, value)
def parseHtmlTagAttrValue(attr_name, tag):
m = re.search(r"%s\s*=\s*([\"']?)((?<=\")[^\"]+|(?<=')[^']+|[^>\s\"'][^>\s]*)\1" % attr_name, tag, re.I)
return m.group(2) if m else None
def parseHtmlForm(attr_str, html, input_names={}):
for form in re.finditer(r"(?P<TAG><form[^>]*%s[^>]*>)(?P<CONTENT>.*?)</?(form|body|html)[^>]*>" % attr_str,
html, re.S | re.I):
inputs = {}
action = parseHtmlTagAttrValue("action", form.group('TAG'))
for inputtag in re.finditer(r'(<(input|textarea)[^>]*>)([^<]*(?=</\2)|)', form.group('CONTENT'), re.S | re.I):
name = parseHtmlTagAttrValue("name", inputtag.group(1))
if name:
value = parseHtmlTagAttrValue("value", inputtag.group(1))
if not value:
inputs[name] = inputtag.group(3) or ''
else:
inputs[name] = value
if input_names:
# check input attributes
for key, val in input_names.iteritems():
if key in inputs:
if isinstance(val, basestring) and inputs[key] == val:
continue
elif isinstance(val, tuple) and inputs[key] in val:
continue
elif hasattr(val, "search") and re.match(val, inputs[key]):
continue
break #: attibute value does not match
else:
break #: attibute name does not match
else:
return action, inputs #: passed attribute check
else:
# no attribute check
return action, inputs
return {}, None #: no matching form found
#: Deprecated
def parseFileInfo(plugin, url="", html=""):
if hasattr(plugin, "getInfo"):
info = plugin.getInfo(url, html)
res = info['name'], info['size'], info['status'], info['url']
else:
url = urllib.unquote(url)
url_p = urlparse.urlparse(url)
res = ((url_p.path.split('/')[-1]
or url_p.query.split('=', 1)[::-1][0].split('&', 1)[0]
or url_p.netloc.split('.', 1)[0]),
0,
3 if url else 8,
url)
return res
#@TODO: Remove in 0.4.10
#@NOTE: Every plugin must have own parseInfos classmethod to work with 0.4.10
# def create_getInfo(plugin):
# def generator(list):
# for x in list:
# yield x
# if hasattr(plugin, "parseInfos"):
# fn = lambda urls: generator((info['name'], info['size'], info['status'], info['url']) for info in plugin.parseInfos(urls))
# else:
# fn = lambda urls: generator(parseFileInfo(url) for url in urls)
# return fn
def timestamp():
return int(time.time() * 1000)
#@TODO: Move to hoster class in 0.4.10
def getFileURL(self, url, follow_location=None):
link = ""
redirect = 1
if type(follow_location) is int:
redirect = max(follow_location, 1)
else:
redirect = 10
for i in xrange(redirect):
try:
self.logDebug("Redirect #%d to: %s" % (i, url))
header = self.load(url, just_header=True, decode=True)
except Exception: #: Bad bad bad...
req = pyreq.getHTTPRequest()
res = req.load(url, just_header=True, decode=True)
req.close()
header = {"code": req.code}
for line in res.splitlines():
line = line.strip()
if not line or ":" not in line:
continue
key, none, value = line.partition(":")
key = key.lower().strip()
value = value.strip()
if key in header:
if type(header[key]) == list:
header[key].append(value)
else:
header[key] = [header[key], value]
else:
header[key] = value
if 'content-disposition' in header:
link = url
elif 'location' in header and header['location'].strip():
location = header['location']
if not urlparse.urlparse(location).scheme:
url_p = urlparse.urlparse(url)
baseurl = "%s://%s" % (url_p.scheme, url_p.netloc)
location = urlparse.urljoin(baseurl, location)
if 'code' in header and header['code'] == 302:
link = location
if follow_location:
url = location
continue
else:
extension = os.path.splitext(urlparse.urlparse(url).path.split('/')[-1])[-1]
if 'content-type' in header and header['content-type'].strip():
mimetype = header['content-type'].split(';')[0].strip()
elif extension:
mimetype = mimetypes.guess_type(extension, False)[0] or "application/octet-stream"
else:
mimetype = ""
if mimetype and (link or 'html' not in mimetype):
link = url
else:
link = ""
break
else:
try:
self.logError(_("Too many redirects"))
except Exception:
pass
return link
def secondsToMidnight(gmt=0):
now = datetime.datetime.utcnow() + datetime.timedelta(hours=gmt)
if now.hour is 0 and now.minute < 10:
midnight = now
else:
midnight = now + datetime.timedelta(days=1)
td = midnight.replace(hour=0, minute=10, second=0, microsecond=0) - now
if hasattr(td, 'total_seconds'):
res = td.total_seconds()
else: #: work-around for python 2.5 and 2.6 missing datetime.timedelta.total_seconds
res = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6
return int(res)
class SimpleHoster(Hoster):
__name = "SimpleHoster"
__type = "hoster"
__version = "1.42"
__pattern = r'^unmatchable$'
__config = [("use_premium", "bool", "Use premium account if available" , True),
("fallback" , "bool", "Fallback to free download if premium fails", True)]
__description = """Simple hoster plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "vuolter@gmail.com")]
"""
Info patterns should be defined by each hoster:
INFO_PATTERN: (optional) Name and Size of the file
example: INFO_PATTERN = r'(?P<N>file_name) (?P<S>file_size) (?P<U>size_unit)'
or
NAME_PATTERN: (optional) Name that will be set for the file
example: NAME_PATTERN = r'(?P<N>file_name)'
SIZE_PATTERN: (optional) Size that will be checked for the file
example: SIZE_PATTERN = r'(?P<S>file_size) (?P<U>size_unit)'
HASHSUM_PATTERN: (optional) Hash code and type of the file
example: HASHSUM_PATTERN = r'(?P<H>hash_code) (?P<T>MD5)'
OFFLINE_PATTERN: (optional) Check if the page is unreachable
example: OFFLINE_PATTERN = r'File (deleted|not found)'
TEMP_OFFLINE_PATTERN: (optional) Check if the page is temporarily unreachable
example: TEMP_OFFLINE_PATTERN = r'Server (maintenance|maintainance)'
Error handling patterns are all optional:
WAIT_PATTERN: (optional) Detect waiting time
example: WAIT_PATTERN = r''
PREMIUM_ONLY_PATTERN: (optional) Check if the file can be downloaded only with a premium account
example: PREMIUM_ONLY_PATTERN = r'Premium account required'
ERROR_PATTERN: (optional) Detect any error preventing download
example: ERROR_PATTERN = r''
Instead overriding handle_free and handle_premium methods you can define the following patterns for direct download:
LINK_FREE_PATTERN: (optional) group(1) should be the direct link for free download
example: LINK_FREE_PATTERN = r'<div class="link"><a href="(.+?)"'
LINK_PREMIUM_PATTERN: (optional) group(1) should be the direct link for premium download
example: LINK_PREMIUM_PATTERN = r'<div class="link"><a href="(.+?)"'
"""
NAME_REPLACEMENTS = [("&#?\w+;", fixup)]
SIZE_REPLACEMENTS = []
URL_REPLACEMENTS = []
TEXT_ENCODING = False #: Set to True or encoding name if encoding value in http header is not correct
COOKIES = True #: or False or list of tuples [(domain, name, value)]
CHECK_TRAFFIC = False #: Set to True to force checking traffic left for premium account
DIRECT_LINK = None #: Set to True to looking for direct link (as defined in handle_direct method), set to None to do it if self.account is True else False
MULTI_HOSTER = False #: Set to True to leech other hoster link (as defined in handle_multi method)
LOGIN_ACCOUNT = False #: Set to True to require account login
DISPOSITION = True #: Set to True to use any content-disposition value in http header as file name
directLink = getFileURL #@TODO: Remove in 0.4.10
@classmethod
def parseInfos(cls, urls): #@TODO: Built-in in 0.4.10 core (remove from plugins)
for url in urls:
url = replace_patterns(url, cls.URL_REPLACEMENTS)
yield cls.getInfo(url)
@classmethod
def apiInfo(cls, url="", get={}, post={}):
url = urllib.unquote(url)
url_p = urlparse.urlparse(url)
return {'name': (url_p.path.split('/')[-1]
or url_p.query.split('=', 1)[::-1][0].split('&', 1)[0]
or url_p.netloc.split('.', 1)[0]),
'size': 0,
'status': 3 if url else 8,
'url': url}
@classmethod
def getInfo(cls, url="", html=""):
info = cls.apiInfo(url)
online = info['status'] == 2
try:
info['pattern'] = re.match(cls.__pattern, url).groupdict() #: pattern groups will be saved here
except Exception:
info['pattern'] = {}
if not html and not online:
if not url:
info['error'] = "missing url"
info['status'] = 1
elif info['status'] is 3 and not getFileURL(None, url):
try:
html = getURL(url, cookies=cls.COOKIES, decode=not cls.TEXT_ENCODING)
if isinstance(cls.TEXT_ENCODING, basestring):
html = unicode(html, cls.TEXT_ENCODING)
except BadHeader, e:
info['error'] = "%d: %s" % (e.code, e.content)
if e.code is 404:
info['status'] = 1
elif e.code is 503:
info['status'] = 6
if html:
if hasattr(cls, "OFFLINE_PATTERN") and re.search(cls.OFFLINE_PATTERN, html):
info['status'] = 1
elif hasattr(cls, "TEMP_OFFLINE_PATTERN") and re.search(cls.TEMP_OFFLINE_PATTERN, html):
info['status'] = 6
else:
for pattern in ("INFO_PATTERN", "NAME_PATTERN", "SIZE_PATTERN", "HASHSUM_PATTERN"):
try:
attr = getattr(cls, pattern)
pdict = re.search(attr, html).groupdict()
if all(True for k in pdict if k not in info['pattern']):
info['pattern'].update(pdict)
except AttributeError:
continue
else:
online = True
if online:
info['status'] = 2
if 'N' in info['pattern']:
info['name'] = replace_patterns(urllib.unquote(info['pattern']['N'].strip()),
cls.NAME_REPLACEMENTS)
if 'S' in info['pattern']:
size = replace_patterns(info['pattern']['S'] + info['pattern']['U'] if 'U' in info['pattern'] else info['pattern']['S'],
cls.SIZE_REPLACEMENTS)
info['size'] = parseFileSize(size)
elif isinstance(info['size'], basestring):
unit = info['units'] if 'units' in info else None
info['size'] = parseFileSize(info['size'], unit)
if 'H' in info['pattern']:
hashtype = info['pattern']['T'] if 'T' in info['pattern'] else "hash"
info[hashtype] = info['pattern']['H']
if not info['pattern']:
info.pop('pattern', None)
return info
def setup(self):
self.resumeDownload = self.multiDL = self.premium
def prepare(self):
self.pyfile.error = "" #@TODO: Remove in 0.4.10
self.info = {}
self.html = ""
self.link = "" #@TODO: Move to hoster class in 0.4.10
self.directDL = False #@TODO: Move to hoster class in 0.4.10
self.multihost = False #@TODO: Move to hoster class in 0.4.10
if not self.getConfig('use_premium', True):
self.retryFree()
if self.LOGIN_ACCOUNT and not self.account:
self.fail(_("Required account not found"))
self.req.setOption("timeout", 120)
if isinstance(self.COOKIES, list):
set_cookies(self.req.cj, self.COOKIES)
if (self.MULTI_HOSTER
and (self.__pattern != self.core.pluginManager.hosterPlugins[self.getClassName()]['pattern']
or re.match(self.__pattern, self.pyfile.url) is None)):
self.multihost = True
return
if self.DIRECT_LINK is None:
self.directDL = bool(self.account)
else:
self.directDL = self.DIRECT_LINK
self.pyfile.url = replace_patterns(self.pyfile.url, self.URL_REPLACEMENTS)
def preload(self):
self.html = self.load(self.pyfile.url, cookies=bool(self.COOKIES), decode=not self.TEXT_ENCODING)
if isinstance(self.TEXT_ENCODING, basestring):
self.html = unicode(self.html, self.TEXT_ENCODING)
def process(self, pyfile):
try:
self.prepare()
self.checkInfo()
if self.directDL:
self.logDebug("Looking for direct download link...")
self.handle_direct(pyfile)
if self.multihost and not self.link and not self.lastDownload:
self.logDebug("Looking for leeched download link...")
self.handle_multi(pyfile)
if not self.link and not self.lastDownload:
self.MULTI_HOSTER = False
self.retry(1, reason="Multi hoster fails")
if not self.link and not self.lastDownload:
self.preload()
self.checkInfo()
if self.premium and (not self.CHECK_TRAFFIC or self.checkTrafficLeft()):
self.logDebug("Handled as premium download")
self.handle_premium(pyfile)
elif not self.LOGIN_ACCOUNT or (not self.CHECK_TRAFFIC or self.checkTrafficLeft()):
self.logDebug("Handled as free download")
self.handle_free(pyfile)
self.downloadLink(self.link, self.DISPOSITION)
self.checkFile()
except Fail, e: #@TODO: Move to PluginThread in 0.4.10
if self.getConfig('fallback', True) and self.premium:
self.logWarning(_("Premium download failed"), e)
self.retryFree()
else:
raise Fail(e)
def downloadLink(self, link, disposition=True):
if link and isinstance(link, basestring):
self.correctCaptcha()
if not urlparse.urlparse(link).scheme:
url_p = urlparse.urlparse(self.pyfile.url)
baseurl = "%s://%s" % (url_p.scheme, url_p.netloc)
link = urlparse.urljoin(baseurl, link)
self.download(link, ref=False, disposition=disposition)
def checkFile(self, rules={}):
if self.cTask and not self.lastDownload:
self.invalidCaptcha()
self.retry(10, reason=_("Wrong captcha"))
elif not self.lastDownload or not os.path.exists(fs_encode(self.lastDownload)):
self.lastDownload = ""
self.error(self.pyfile.error or _("No file downloaded"))
else:
errmsg = self.checkDownload({'Empty file': re.compile(r'\A\s*\Z'),
'Html error': re.compile(r'\A(?:\s*<.+>)?((?:[\w\s]*(?:[Ee]rror|ERROR)\s*\:?)?\s*\d{3})(?:\Z|\s+)')})
if not errmsg:
for r, p in [('Html file', re.compile(r'\A\s*<!DOCTYPE html')),
('Request error', re.compile(r'([Aa]n error occured while processing your request)'))]:
if r not in rules:
rules[r] = p
for r, a in [('Error', "ERROR_PATTERN"),
('Premium only', "PREMIUM_ONLY_PATTERN"),
('Wait error', "WAIT_PATTERN")]:
if r not in rules and hasattr(self, a):
rules[r] = getattr(self, a)
errmsg = self.checkDownload(rules)
if not errmsg:
return
errmsg = errmsg.strip().capitalize()
try:
errmsg += " | " + self.lastCheck.group(1).strip()
except Exception:
pass
self.logWarning("Check result: " + errmsg, "Waiting 1 minute and retry")
self.retry(3, 60, errmsg)
def checkErrors(self):
if not self.html:
self.logWarning(_("No html code to check"))
return
if hasattr(self, 'PREMIUM_ONLY_PATTERN') and not self.premium and re.search(self.PREMIUM_ONLY_PATTERN, self.html):
self.fail(_("Link require a premium account to be handled"))
elif hasattr(self, 'ERROR_PATTERN'):
m = re.search(self.ERROR_PATTERN, self.html)
if m:
try:
errmsg = m.group(1).strip()
except Exception:
errmsg = m.group(0).strip()
self.info['error'] = errmsg
if "hour" in errmsg:
self.wait(1 * 60 * 60, True)
elif re.search("da(il)?y|today", errmsg):
self.wait(secondsToMidnight(gmt=2), True)
elif "minute" in errmsg:
self.wait(1 * 60)
else:
self.error(errmsg)
elif hasattr(self, 'WAIT_PATTERN'):
m = re.search(self.WAIT_PATTERN, self.html)
if m:
try:
waitmsg = m.group(1).strip()
except Exception:
waitmsg = m.group(0).strip()
wait_time = sum(int(v) * {"hr": 3600, "hour": 3600, "min": 60, "sec": 1, "": 1}[u.lower()] for v, u in
re.findall(r'(\d+)\s*(hr|hour|min|sec|)', waitmsg, re.I))
self.wait(wait_time, wait_time > 300)
self.info.pop('error', None)
def checkStatus(self, getinfo=True):
if not self.info or getinfo:
self.logDebug("Update file info...")
self.logDebug("Previous file info: %s" % self.info)
self.info.update(self.getInfo(self.pyfile.url, self.html))
self.logDebug("Current file info: %s" % self.info)
try:
status = self.info['status']
if status is 1:
self.offline()
elif status is 6:
self.tempOffline()
elif status is 8:
self.fail(self.info['error'] if 'error' in self.info else "Failed")
finally:
self.logDebug("File status: %s" % statusMap[status])
def checkNameSize(self, getinfo=True):
if not self.info or getinfo:
self.logDebug("Update file info...")
self.logDebug("Previous file info: %s" % self.info)
self.info.update(self.getInfo(self.pyfile.url, self.html))
self.logDebug("Current file info: %s" % self.info)
try:
url = self.info['url'].strip()
name = self.info['name'].strip()
if name and name != url:
self.pyfile.name = name
except Exception:
pass
try:
size = self.info['size']
if size > 0:
self.pyfile.size = size
except Exception:
pass
self.logDebug("File name: %s" % self.pyfile.name,
"File size: %s byte" % self.pyfile.size if self.pyfile.size > 0 else "File size: Unknown")
def checkInfo(self):
self.checkNameSize()
if self.html:
self.checkErrors()
self.checkNameSize()
self.checkStatus(getinfo=False)
#: Deprecated
def getFileInfo(self):
self.info = {}
self.checkInfo()
return self.info
def handle_direct(self, pyfile):
link = self.directLink(pyfile.url, self.resumeDownload)
if link:
self.logInfo(_("Direct download link detected"))
self.link = link
else:
self.logDebug("Direct download link not found")
def handle_multi(self, pyfile): #: Multi-hoster handler
pass
def handle_free(self, pyfile):
if not hasattr(self, 'LINK_FREE_PATTERN'):
self.logError(_("Free download not implemented"))
m = re.search(self.LINK_FREE_PATTERN, self.html)
if m is None:
self.error(_("Free download link not found"))
else:
self.link = m.group(1)
def handle_premium(self, pyfile):
if not hasattr(self, 'LINK_PREMIUM_PATTERN'):
self.logError(_("Premium download not implemented"))
self.logDebug("Handled as free download")
self.handle_free(pyfile)
m = re.search(self.LINK_PREMIUM_PATTERN, self.html)
if m is None:
self.error(_("Premium download link not found"))
else:
self.link = m.group(1)
def longWait(self, wait_time=None, max_tries=3):
if wait_time and isinstance(wait_time, (int, long, float)):
time_str = "%dh %dm" % divmod(wait_time / 60, 60)
else:
wait_time = 900
time_str = _("(unknown time)")
max_tries = 100
self.logInfo(_("Download limit reached, reconnect or wait %s") % time_str)
self.wait(wait_time, True)
self.retry(max_tries=max_tries, reason=_("Download limit reached"))
def parseHtmlForm(self, attr_str="", input_names={}):
return parseHtmlForm(attr_str, self.html, input_names)
def checkTrafficLeft(self):
if not self.account:
return True
traffic = self.account.getAccountInfo(self.user, True)['trafficleft']
if traffic is None:
return False
elif traffic == -1:
return True
else:
size = self.pyfile.size
self.logInfo(_("Filesize: %i KiB, Traffic left for user %s: %i KiB") % (size / 1024, self.user, traffic / 1024))
return size <= traffic
def getConfig(self, option, default=''): #@TODO: Remove in 0.4.10
"""getConfig with default value - sublass may not implements all config options"""
try:
return self.getConf(option)
except KeyError:
return default
def retryFree(self):
if not self.premium:
return
self.premium = False
self.account = None
self.req = self.core.requestFactory.getRequest(self.getClassName())
self.retries = -1
raise Retry(_("Fallback to free download"))
def wait(self, seconds=0, reconnect=None):
return _wait(self, seconds, reconnect)
def error(self, reason="", type="parse"):
return _error(self, reason, type)