utils.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import gzip
  12. import itertools
  13. import io
  14. import json
  15. import locale
  16. import math
  17. import os
  18. import pipes
  19. import platform
  20. import re
  21. import ssl
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import traceback
  28. import xml.etree.ElementTree
  29. import zlib
  30. from .compat import (
  31. compat_chr,
  32. compat_getenv,
  33. compat_html_entities,
  34. compat_html_parser,
  35. compat_parse_qs,
  36. compat_str,
  37. compat_urllib_error,
  38. compat_urllib_parse,
  39. compat_urllib_parse_urlparse,
  40. compat_urllib_request,
  41. compat_urlparse,
  42. )
  43. # This is not clearly defined otherwise
  44. compiled_regex_type = type(re.compile(''))
  45. std_headers = {
  46. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  47. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  48. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  49. 'Accept-Encoding': 'gzip, deflate',
  50. 'Accept-Language': 'en-us,en;q=0.5',
  51. }
  52. def preferredencoding():
  53. """Get preferred encoding.
  54. Returns the best encoding scheme for the system, based on
  55. locale.getpreferredencoding() and some further tweaks.
  56. """
  57. try:
  58. pref = locale.getpreferredencoding()
  59. u'TEST'.encode(pref)
  60. except:
  61. pref = 'UTF-8'
  62. return pref
  63. def write_json_file(obj, fn):
  64. """ Encode obj as JSON and write it to fn, atomically """
  65. args = {
  66. 'suffix': '.tmp',
  67. 'prefix': os.path.basename(fn) + '.',
  68. 'dir': os.path.dirname(fn),
  69. 'delete': False,
  70. }
  71. # In Python 2.x, json.dump expects a bytestream.
  72. # In Python 3.x, it writes to a character stream
  73. if sys.version_info < (3, 0):
  74. args['mode'] = 'wb'
  75. else:
  76. args.update({
  77. 'mode': 'w',
  78. 'encoding': 'utf-8',
  79. })
  80. tf = tempfile.NamedTemporaryFile(**args)
  81. try:
  82. with tf:
  83. json.dump(obj, tf)
  84. os.rename(tf.name, fn)
  85. except:
  86. try:
  87. os.remove(tf.name)
  88. except OSError:
  89. pass
  90. raise
  91. if sys.version_info >= (2, 7):
  92. def find_xpath_attr(node, xpath, key, val):
  93. """ Find the xpath xpath[@key=val] """
  94. assert re.match(r'^[a-zA-Z-]+$', key)
  95. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  96. expr = xpath + u"[@%s='%s']" % (key, val)
  97. return node.find(expr)
  98. else:
  99. def find_xpath_attr(node, xpath, key, val):
  100. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  101. # .//node does not match if a node is a direct child of . !
  102. if isinstance(xpath, unicode):
  103. xpath = xpath.encode('ascii')
  104. for f in node.findall(xpath):
  105. if f.attrib.get(key) == val:
  106. return f
  107. return None
  108. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  109. # the namespace parameter
  110. def xpath_with_ns(path, ns_map):
  111. components = [c.split(':') for c in path.split('/')]
  112. replaced = []
  113. for c in components:
  114. if len(c) == 1:
  115. replaced.append(c[0])
  116. else:
  117. ns, tag = c
  118. replaced.append('{%s}%s' % (ns_map[ns], tag))
  119. return '/'.join(replaced)
  120. def xpath_text(node, xpath, name=None, fatal=False):
  121. if sys.version_info < (2, 7): # Crazy 2.6
  122. xpath = xpath.encode('ascii')
  123. n = node.find(xpath)
  124. if n is None:
  125. if fatal:
  126. name = xpath if name is None else name
  127. raise ExtractorError('Could not find XML element %s' % name)
  128. else:
  129. return None
  130. return n.text
  131. if sys.version_info < (2, 7):
  132. compat_html_parser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  133. class BaseHTMLParser(compat_html_parser.HTMLParser):
  134. def __init(self):
  135. compat_html_parser.HTMLParser.__init__(self)
  136. self.html = None
  137. def loads(self, html):
  138. self.html = html
  139. self.feed(html)
  140. self.close()
  141. class AttrParser(BaseHTMLParser):
  142. """Modified HTMLParser that isolates a tag with the specified attribute"""
  143. def __init__(self, attribute, value):
  144. self.attribute = attribute
  145. self.value = value
  146. self.result = None
  147. self.started = False
  148. self.depth = {}
  149. self.watch_startpos = False
  150. self.error_count = 0
  151. BaseHTMLParser.__init__(self)
  152. def error(self, message):
  153. if self.error_count > 10 or self.started:
  154. raise compat_html_parser.HTMLParseError(message, self.getpos())
  155. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  156. self.error_count += 1
  157. self.goahead(1)
  158. def handle_starttag(self, tag, attrs):
  159. attrs = dict(attrs)
  160. if self.started:
  161. self.find_startpos(None)
  162. if self.attribute in attrs and attrs[self.attribute] == self.value:
  163. self.result = [tag]
  164. self.started = True
  165. self.watch_startpos = True
  166. if self.started:
  167. if not tag in self.depth: self.depth[tag] = 0
  168. self.depth[tag] += 1
  169. def handle_endtag(self, tag):
  170. if self.started:
  171. if tag in self.depth: self.depth[tag] -= 1
  172. if self.depth[self.result[0]] == 0:
  173. self.started = False
  174. self.result.append(self.getpos())
  175. def find_startpos(self, x):
  176. """Needed to put the start position of the result (self.result[1])
  177. after the opening tag with the requested id"""
  178. if self.watch_startpos:
  179. self.watch_startpos = False
  180. self.result.append(self.getpos())
  181. handle_entityref = handle_charref = handle_data = handle_comment = \
  182. handle_decl = handle_pi = unknown_decl = find_startpos
  183. def get_result(self):
  184. if self.result is None:
  185. return None
  186. if len(self.result) != 3:
  187. return None
  188. lines = self.html.split('\n')
  189. lines = lines[self.result[1][0]-1:self.result[2][0]]
  190. lines[0] = lines[0][self.result[1][1]:]
  191. if len(lines) == 1:
  192. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  193. lines[-1] = lines[-1][:self.result[2][1]]
  194. return '\n'.join(lines).strip()
  195. # Hack for https://github.com/rg3/youtube-dl/issues/662
  196. if sys.version_info < (2, 7, 3):
  197. AttrParser.parse_endtag = (lambda self, i:
  198. i + len("</scr'+'ipt>")
  199. if self.rawdata[i:].startswith("</scr'+'ipt>")
  200. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  201. def get_element_by_id(id, html):
  202. """Return the content of the tag with the specified ID in the passed HTML document"""
  203. return get_element_by_attribute("id", id, html)
  204. def get_element_by_attribute(attribute, value, html):
  205. """Return the content of the tag with the specified attribute in the passed HTML document"""
  206. parser = AttrParser(attribute, value)
  207. try:
  208. parser.loads(html)
  209. except compat_html_parser.HTMLParseError:
  210. pass
  211. return parser.get_result()
  212. class MetaParser(BaseHTMLParser):
  213. """
  214. Modified HTMLParser that isolates a meta tag with the specified name
  215. attribute.
  216. """
  217. def __init__(self, name):
  218. BaseHTMLParser.__init__(self)
  219. self.name = name
  220. self.content = None
  221. self.result = None
  222. def handle_starttag(self, tag, attrs):
  223. if tag != 'meta':
  224. return
  225. attrs = dict(attrs)
  226. if attrs.get('name') == self.name:
  227. self.result = attrs.get('content')
  228. def get_result(self):
  229. return self.result
  230. def clean_html(html):
  231. """Clean an HTML snippet into a readable string"""
  232. # Newline vs <br />
  233. html = html.replace('\n', ' ')
  234. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  235. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  236. # Strip html tags
  237. html = re.sub('<.*?>', '', html)
  238. # Replace html entities
  239. html = unescapeHTML(html)
  240. return html.strip()
  241. def sanitize_open(filename, open_mode):
  242. """Try to open the given filename, and slightly tweak it if this fails.
  243. Attempts to open the given filename. If this fails, it tries to change
  244. the filename slightly, step by step, until it's either able to open it
  245. or it fails and raises a final exception, like the standard open()
  246. function.
  247. It returns the tuple (stream, definitive_file_name).
  248. """
  249. try:
  250. if filename == u'-':
  251. if sys.platform == 'win32':
  252. import msvcrt
  253. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  254. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  255. stream = open(encodeFilename(filename), open_mode)
  256. return (stream, filename)
  257. except (IOError, OSError) as err:
  258. if err.errno in (errno.EACCES,):
  259. raise
  260. # In case of error, try to remove win32 forbidden chars
  261. alt_filename = os.path.join(
  262. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  263. for path_part in os.path.split(filename)
  264. )
  265. if alt_filename == filename:
  266. raise
  267. else:
  268. # An exception here should be caught in the caller
  269. stream = open(encodeFilename(filename), open_mode)
  270. return (stream, alt_filename)
  271. def timeconvert(timestr):
  272. """Convert RFC 2822 defined time string into system timestamp"""
  273. timestamp = None
  274. timetuple = email.utils.parsedate_tz(timestr)
  275. if timetuple is not None:
  276. timestamp = email.utils.mktime_tz(timetuple)
  277. return timestamp
  278. def sanitize_filename(s, restricted=False, is_id=False):
  279. """Sanitizes a string so it could be used as part of a filename.
  280. If restricted is set, use a stricter subset of allowed characters.
  281. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  282. """
  283. def replace_insane(char):
  284. if char == '?' or ord(char) < 32 or ord(char) == 127:
  285. return ''
  286. elif char == '"':
  287. return '' if restricted else '\''
  288. elif char == ':':
  289. return '_-' if restricted else ' -'
  290. elif char in '\\/|*<>':
  291. return '_'
  292. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  293. return '_'
  294. if restricted and ord(char) > 127:
  295. return '_'
  296. return char
  297. result = u''.join(map(replace_insane, s))
  298. if not is_id:
  299. while '__' in result:
  300. result = result.replace('__', '_')
  301. result = result.strip('_')
  302. # Common case of "Foreign band name - English song title"
  303. if restricted and result.startswith('-_'):
  304. result = result[2:]
  305. if not result:
  306. result = '_'
  307. return result
  308. def orderedSet(iterable):
  309. """ Remove all duplicates from the input iterable """
  310. res = []
  311. for el in iterable:
  312. if el not in res:
  313. res.append(el)
  314. return res
  315. def _htmlentity_transform(entity):
  316. """Transforms an HTML entity to a character."""
  317. # Known non-numeric HTML entity
  318. if entity in compat_html_entities.name2codepoint:
  319. return compat_chr(compat_html_entities.name2codepoint[entity])
  320. mobj = re.match(r'#(x?[0-9]+)', entity)
  321. if mobj is not None:
  322. numstr = mobj.group(1)
  323. if numstr.startswith(u'x'):
  324. base = 16
  325. numstr = u'0%s' % numstr
  326. else:
  327. base = 10
  328. return compat_chr(int(numstr, base))
  329. # Unknown entity in name, return its literal representation
  330. return (u'&%s;' % entity)
  331. def unescapeHTML(s):
  332. if s is None:
  333. return None
  334. assert type(s) == compat_str
  335. return re.sub(
  336. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  337. def encodeFilename(s, for_subprocess=False):
  338. """
  339. @param s The name of the file
  340. """
  341. assert type(s) == compat_str
  342. # Python 3 has a Unicode API
  343. if sys.version_info >= (3, 0):
  344. return s
  345. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  346. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  347. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  348. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  349. if not for_subprocess:
  350. return s
  351. else:
  352. # For subprocess calls, encode with locale encoding
  353. # Refer to http://stackoverflow.com/a/9951851/35070
  354. encoding = preferredencoding()
  355. else:
  356. encoding = sys.getfilesystemencoding()
  357. if encoding is None:
  358. encoding = 'utf-8'
  359. return s.encode(encoding, 'ignore')
  360. def encodeArgument(s):
  361. if not isinstance(s, compat_str):
  362. # Legacy code that uses byte strings
  363. # Uncomment the following line after fixing all post processors
  364. #assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  365. s = s.decode('ascii')
  366. return encodeFilename(s, True)
  367. def decodeOption(optval):
  368. if optval is None:
  369. return optval
  370. if isinstance(optval, bytes):
  371. optval = optval.decode(preferredencoding())
  372. assert isinstance(optval, compat_str)
  373. return optval
  374. def formatSeconds(secs):
  375. if secs > 3600:
  376. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  377. elif secs > 60:
  378. return '%d:%02d' % (secs // 60, secs % 60)
  379. else:
  380. return '%d' % secs
  381. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  382. if sys.version_info < (3, 2):
  383. import httplib
  384. class HTTPSConnectionV3(httplib.HTTPSConnection):
  385. def __init__(self, *args, **kwargs):
  386. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  387. def connect(self):
  388. sock = socket.create_connection((self.host, self.port), self.timeout)
  389. if getattr(self, '_tunnel_host', False):
  390. self.sock = sock
  391. self._tunnel()
  392. try:
  393. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  394. except ssl.SSLError:
  395. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  396. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  397. def https_open(self, req):
  398. return self.do_open(HTTPSConnectionV3, req)
  399. return HTTPSHandlerV3(**kwargs)
  400. elif hasattr(ssl, 'create_default_context'): # Python >= 3.4
  401. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  402. context.options &= ~ssl.OP_NO_SSLv3 # Allow older, not-as-secure SSLv3
  403. if opts_no_check_certificate:
  404. context.verify_mode = ssl.CERT_NONE
  405. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  406. else: # Python < 3.4
  407. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  408. context.verify_mode = (ssl.CERT_NONE
  409. if opts_no_check_certificate
  410. else ssl.CERT_REQUIRED)
  411. context.set_default_verify_paths()
  412. try:
  413. context.load_default_certs()
  414. except AttributeError:
  415. pass # Python < 3.4
  416. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  417. class ExtractorError(Exception):
  418. """Error during info extraction."""
  419. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  420. """ tb, if given, is the original traceback (so that it can be printed out).
  421. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  422. """
  423. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  424. expected = True
  425. if video_id is not None:
  426. msg = video_id + ': ' + msg
  427. if cause:
  428. msg += u' (caused by %r)' % cause
  429. if not expected:
  430. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  431. super(ExtractorError, self).__init__(msg)
  432. self.traceback = tb
  433. self.exc_info = sys.exc_info() # preserve original exception
  434. self.cause = cause
  435. self.video_id = video_id
  436. def format_traceback(self):
  437. if self.traceback is None:
  438. return None
  439. return u''.join(traceback.format_tb(self.traceback))
  440. class RegexNotFoundError(ExtractorError):
  441. """Error when a regex didn't match"""
  442. pass
  443. class DownloadError(Exception):
  444. """Download Error exception.
  445. This exception may be thrown by FileDownloader objects if they are not
  446. configured to continue on errors. They will contain the appropriate
  447. error message.
  448. """
  449. def __init__(self, msg, exc_info=None):
  450. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  451. super(DownloadError, self).__init__(msg)
  452. self.exc_info = exc_info
  453. class SameFileError(Exception):
  454. """Same File exception.
  455. This exception will be thrown by FileDownloader objects if they detect
  456. multiple files would have to be downloaded to the same file on disk.
  457. """
  458. pass
  459. class PostProcessingError(Exception):
  460. """Post Processing exception.
  461. This exception may be raised by PostProcessor's .run() method to
  462. indicate an error in the postprocessing task.
  463. """
  464. def __init__(self, msg):
  465. self.msg = msg
  466. class MaxDownloadsReached(Exception):
  467. """ --max-downloads limit has been reached. """
  468. pass
  469. class UnavailableVideoError(Exception):
  470. """Unavailable Format exception.
  471. This exception will be thrown when a video is requested
  472. in a format that is not available for that video.
  473. """
  474. pass
  475. class ContentTooShortError(Exception):
  476. """Content Too Short exception.
  477. This exception may be raised by FileDownloader objects when a file they
  478. download is too small for what the server announced first, indicating
  479. the connection was probably interrupted.
  480. """
  481. # Both in bytes
  482. downloaded = None
  483. expected = None
  484. def __init__(self, downloaded, expected):
  485. self.downloaded = downloaded
  486. self.expected = expected
  487. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  488. """Handler for HTTP requests and responses.
  489. This class, when installed with an OpenerDirector, automatically adds
  490. the standard headers to every HTTP request and handles gzipped and
  491. deflated responses from web servers. If compression is to be avoided in
  492. a particular request, the original request in the program code only has
  493. to include the HTTP header "Youtubedl-No-Compression", which will be
  494. removed before making the real request.
  495. Part of this code was copied from:
  496. http://techknack.net/python-urllib2-handlers/
  497. Andrew Rowls, the author of that code, agreed to release it to the
  498. public domain.
  499. """
  500. @staticmethod
  501. def deflate(data):
  502. try:
  503. return zlib.decompress(data, -zlib.MAX_WBITS)
  504. except zlib.error:
  505. return zlib.decompress(data)
  506. @staticmethod
  507. def addinfourl_wrapper(stream, headers, url, code):
  508. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  509. return compat_urllib_request.addinfourl(stream, headers, url, code)
  510. ret = compat_urllib_request.addinfourl(stream, headers, url)
  511. ret.code = code
  512. return ret
  513. def http_request(self, req):
  514. for h, v in std_headers.items():
  515. if h not in req.headers:
  516. req.add_header(h, v)
  517. if 'Youtubedl-no-compression' in req.headers:
  518. if 'Accept-encoding' in req.headers:
  519. del req.headers['Accept-encoding']
  520. del req.headers['Youtubedl-no-compression']
  521. if 'Youtubedl-user-agent' in req.headers:
  522. if 'User-agent' in req.headers:
  523. del req.headers['User-agent']
  524. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  525. del req.headers['Youtubedl-user-agent']
  526. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  527. # Python 2.6 is brain-dead when it comes to fragments
  528. req._Request__original = req._Request__original.partition('#')[0]
  529. req._Request__r_type = req._Request__r_type.partition('#')[0]
  530. return req
  531. def http_response(self, req, resp):
  532. old_resp = resp
  533. # gzip
  534. if resp.headers.get('Content-encoding', '') == 'gzip':
  535. content = resp.read()
  536. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  537. try:
  538. uncompressed = io.BytesIO(gz.read())
  539. except IOError as original_ioerror:
  540. # There may be junk add the end of the file
  541. # See http://stackoverflow.com/q/4928560/35070 for details
  542. for i in range(1, 1024):
  543. try:
  544. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  545. uncompressed = io.BytesIO(gz.read())
  546. except IOError:
  547. continue
  548. break
  549. else:
  550. raise original_ioerror
  551. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  552. resp.msg = old_resp.msg
  553. # deflate
  554. if resp.headers.get('Content-encoding', '') == 'deflate':
  555. gz = io.BytesIO(self.deflate(resp.read()))
  556. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  557. resp.msg = old_resp.msg
  558. return resp
  559. https_request = http_request
  560. https_response = http_response
  561. def parse_iso8601(date_str, delimiter='T'):
  562. """ Return a UNIX timestamp from the given date """
  563. if date_str is None:
  564. return None
  565. m = re.search(
  566. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  567. date_str)
  568. if not m:
  569. timezone = datetime.timedelta()
  570. else:
  571. date_str = date_str[:-len(m.group(0))]
  572. if not m.group('sign'):
  573. timezone = datetime.timedelta()
  574. else:
  575. sign = 1 if m.group('sign') == '+' else -1
  576. timezone = datetime.timedelta(
  577. hours=sign * int(m.group('hours')),
  578. minutes=sign * int(m.group('minutes')))
  579. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  580. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  581. return calendar.timegm(dt.timetuple())
  582. def unified_strdate(date_str):
  583. """Return a string with the date in the format YYYYMMDD"""
  584. if date_str is None:
  585. return None
  586. upload_date = None
  587. #Replace commas
  588. date_str = date_str.replace(',', ' ')
  589. # %z (UTC offset) is only supported in python>=3.2
  590. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  591. format_expressions = [
  592. '%d %B %Y',
  593. '%d %b %Y',
  594. '%B %d %Y',
  595. '%b %d %Y',
  596. '%b %dst %Y %I:%M%p',
  597. '%b %dnd %Y %I:%M%p',
  598. '%b %dth %Y %I:%M%p',
  599. '%Y-%m-%d',
  600. '%Y/%m/%d',
  601. '%d.%m.%Y',
  602. '%d/%m/%Y',
  603. '%d/%m/%y',
  604. '%Y/%m/%d %H:%M:%S',
  605. '%d/%m/%Y %H:%M:%S',
  606. '%Y-%m-%d %H:%M:%S',
  607. '%Y-%m-%d %H:%M:%S.%f',
  608. '%d.%m.%Y %H:%M',
  609. '%d.%m.%Y %H.%M',
  610. '%Y-%m-%dT%H:%M:%SZ',
  611. '%Y-%m-%dT%H:%M:%S.%fZ',
  612. '%Y-%m-%dT%H:%M:%S.%f0Z',
  613. '%Y-%m-%dT%H:%M:%S',
  614. '%Y-%m-%dT%H:%M:%S.%f',
  615. '%Y-%m-%dT%H:%M',
  616. ]
  617. for expression in format_expressions:
  618. try:
  619. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  620. except ValueError:
  621. pass
  622. if upload_date is None:
  623. timetuple = email.utils.parsedate_tz(date_str)
  624. if timetuple:
  625. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  626. return upload_date
  627. def determine_ext(url, default_ext=u'unknown_video'):
  628. if url is None:
  629. return default_ext
  630. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  631. if re.match(r'^[A-Za-z0-9]+$', guess):
  632. return guess
  633. else:
  634. return default_ext
  635. def subtitles_filename(filename, sub_lang, sub_format):
  636. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  637. def date_from_str(date_str):
  638. """
  639. Return a datetime object from a string in the format YYYYMMDD or
  640. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  641. today = datetime.date.today()
  642. if date_str == 'now'or date_str == 'today':
  643. return today
  644. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  645. if match is not None:
  646. sign = match.group('sign')
  647. time = int(match.group('time'))
  648. if sign == '-':
  649. time = -time
  650. unit = match.group('unit')
  651. #A bad aproximation?
  652. if unit == 'month':
  653. unit = 'day'
  654. time *= 30
  655. elif unit == 'year':
  656. unit = 'day'
  657. time *= 365
  658. unit += 's'
  659. delta = datetime.timedelta(**{unit: time})
  660. return today + delta
  661. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  662. def hyphenate_date(date_str):
  663. """
  664. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  665. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  666. if match is not None:
  667. return '-'.join(match.groups())
  668. else:
  669. return date_str
  670. class DateRange(object):
  671. """Represents a time interval between two dates"""
  672. def __init__(self, start=None, end=None):
  673. """start and end must be strings in the format accepted by date"""
  674. if start is not None:
  675. self.start = date_from_str(start)
  676. else:
  677. self.start = datetime.datetime.min.date()
  678. if end is not None:
  679. self.end = date_from_str(end)
  680. else:
  681. self.end = datetime.datetime.max.date()
  682. if self.start > self.end:
  683. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  684. @classmethod
  685. def day(cls, day):
  686. """Returns a range that only contains the given day"""
  687. return cls(day,day)
  688. def __contains__(self, date):
  689. """Check if the date is in the range"""
  690. if not isinstance(date, datetime.date):
  691. date = date_from_str(date)
  692. return self.start <= date <= self.end
  693. def __str__(self):
  694. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  695. def platform_name():
  696. """ Returns the platform name as a compat_str """
  697. res = platform.platform()
  698. if isinstance(res, bytes):
  699. res = res.decode(preferredencoding())
  700. assert isinstance(res, compat_str)
  701. return res
  702. def _windows_write_string(s, out):
  703. """ Returns True if the string was written using special methods,
  704. False if it has yet to be written out."""
  705. # Adapted from http://stackoverflow.com/a/3259271/35070
  706. import ctypes
  707. import ctypes.wintypes
  708. WIN_OUTPUT_IDS = {
  709. 1: -11,
  710. 2: -12,
  711. }
  712. try:
  713. fileno = out.fileno()
  714. except AttributeError:
  715. # If the output stream doesn't have a fileno, it's virtual
  716. return False
  717. if fileno not in WIN_OUTPUT_IDS:
  718. return False
  719. GetStdHandle = ctypes.WINFUNCTYPE(
  720. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  721. ("GetStdHandle", ctypes.windll.kernel32))
  722. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  723. WriteConsoleW = ctypes.WINFUNCTYPE(
  724. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  725. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  726. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  727. written = ctypes.wintypes.DWORD(0)
  728. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  729. FILE_TYPE_CHAR = 0x0002
  730. FILE_TYPE_REMOTE = 0x8000
  731. GetConsoleMode = ctypes.WINFUNCTYPE(
  732. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  733. ctypes.POINTER(ctypes.wintypes.DWORD))(
  734. ("GetConsoleMode", ctypes.windll.kernel32))
  735. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  736. def not_a_console(handle):
  737. if handle == INVALID_HANDLE_VALUE or handle is None:
  738. return True
  739. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  740. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  741. if not_a_console(h):
  742. return False
  743. def next_nonbmp_pos(s):
  744. try:
  745. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  746. except StopIteration:
  747. return len(s)
  748. while s:
  749. count = min(next_nonbmp_pos(s), 1024)
  750. ret = WriteConsoleW(
  751. h, s, count if count else 2, ctypes.byref(written), None)
  752. if ret == 0:
  753. raise OSError('Failed to write string')
  754. if not count: # We just wrote a non-BMP character
  755. assert written.value == 2
  756. s = s[1:]
  757. else:
  758. assert written.value > 0
  759. s = s[written.value:]
  760. return True
  761. def write_string(s, out=None, encoding=None):
  762. if out is None:
  763. out = sys.stderr
  764. assert type(s) == compat_str
  765. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  766. if _windows_write_string(s, out):
  767. return
  768. if ('b' in getattr(out, 'mode', '') or
  769. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  770. byt = s.encode(encoding or preferredencoding(), 'ignore')
  771. out.write(byt)
  772. elif hasattr(out, 'buffer'):
  773. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  774. byt = s.encode(enc, 'ignore')
  775. out.buffer.write(byt)
  776. else:
  777. out.write(s)
  778. out.flush()
  779. def bytes_to_intlist(bs):
  780. if not bs:
  781. return []
  782. if isinstance(bs[0], int): # Python 3
  783. return list(bs)
  784. else:
  785. return [ord(c) for c in bs]
  786. def intlist_to_bytes(xs):
  787. if not xs:
  788. return b''
  789. if isinstance(chr(0), bytes): # Python 2
  790. return ''.join([chr(x) for x in xs])
  791. else:
  792. return bytes(xs)
  793. # Cross-platform file locking
  794. if sys.platform == 'win32':
  795. import ctypes.wintypes
  796. import msvcrt
  797. class OVERLAPPED(ctypes.Structure):
  798. _fields_ = [
  799. ('Internal', ctypes.wintypes.LPVOID),
  800. ('InternalHigh', ctypes.wintypes.LPVOID),
  801. ('Offset', ctypes.wintypes.DWORD),
  802. ('OffsetHigh', ctypes.wintypes.DWORD),
  803. ('hEvent', ctypes.wintypes.HANDLE),
  804. ]
  805. kernel32 = ctypes.windll.kernel32
  806. LockFileEx = kernel32.LockFileEx
  807. LockFileEx.argtypes = [
  808. ctypes.wintypes.HANDLE, # hFile
  809. ctypes.wintypes.DWORD, # dwFlags
  810. ctypes.wintypes.DWORD, # dwReserved
  811. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  812. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  813. ctypes.POINTER(OVERLAPPED) # Overlapped
  814. ]
  815. LockFileEx.restype = ctypes.wintypes.BOOL
  816. UnlockFileEx = kernel32.UnlockFileEx
  817. UnlockFileEx.argtypes = [
  818. ctypes.wintypes.HANDLE, # hFile
  819. ctypes.wintypes.DWORD, # dwReserved
  820. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  821. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  822. ctypes.POINTER(OVERLAPPED) # Overlapped
  823. ]
  824. UnlockFileEx.restype = ctypes.wintypes.BOOL
  825. whole_low = 0xffffffff
  826. whole_high = 0x7fffffff
  827. def _lock_file(f, exclusive):
  828. overlapped = OVERLAPPED()
  829. overlapped.Offset = 0
  830. overlapped.OffsetHigh = 0
  831. overlapped.hEvent = 0
  832. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  833. handle = msvcrt.get_osfhandle(f.fileno())
  834. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  835. whole_low, whole_high, f._lock_file_overlapped_p):
  836. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  837. def _unlock_file(f):
  838. assert f._lock_file_overlapped_p
  839. handle = msvcrt.get_osfhandle(f.fileno())
  840. if not UnlockFileEx(handle, 0,
  841. whole_low, whole_high, f._lock_file_overlapped_p):
  842. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  843. else:
  844. import fcntl
  845. def _lock_file(f, exclusive):
  846. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  847. def _unlock_file(f):
  848. fcntl.flock(f, fcntl.LOCK_UN)
  849. class locked_file(object):
  850. def __init__(self, filename, mode, encoding=None):
  851. assert mode in ['r', 'a', 'w']
  852. self.f = io.open(filename, mode, encoding=encoding)
  853. self.mode = mode
  854. def __enter__(self):
  855. exclusive = self.mode != 'r'
  856. try:
  857. _lock_file(self.f, exclusive)
  858. except IOError:
  859. self.f.close()
  860. raise
  861. return self
  862. def __exit__(self, etype, value, traceback):
  863. try:
  864. _unlock_file(self.f)
  865. finally:
  866. self.f.close()
  867. def __iter__(self):
  868. return iter(self.f)
  869. def write(self, *args):
  870. return self.f.write(*args)
  871. def read(self, *args):
  872. return self.f.read(*args)
  873. def get_filesystem_encoding():
  874. encoding = sys.getfilesystemencoding()
  875. return encoding if encoding is not None else 'utf-8'
  876. def shell_quote(args):
  877. quoted_args = []
  878. encoding = get_filesystem_encoding()
  879. for a in args:
  880. if isinstance(a, bytes):
  881. # We may get a filename encoded with 'encodeFilename'
  882. a = a.decode(encoding)
  883. quoted_args.append(pipes.quote(a))
  884. return u' '.join(quoted_args)
  885. def takewhile_inclusive(pred, seq):
  886. """ Like itertools.takewhile, but include the latest evaluated element
  887. (the first element so that Not pred(e)) """
  888. for e in seq:
  889. yield e
  890. if not pred(e):
  891. return
  892. def smuggle_url(url, data):
  893. """ Pass additional data in a URL for internal use. """
  894. sdata = compat_urllib_parse.urlencode(
  895. {u'__youtubedl_smuggle': json.dumps(data)})
  896. return url + u'#' + sdata
  897. def unsmuggle_url(smug_url, default=None):
  898. if not '#__youtubedl_smuggle' in smug_url:
  899. return smug_url, default
  900. url, _, sdata = smug_url.rpartition(u'#')
  901. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  902. data = json.loads(jsond)
  903. return url, data
  904. def format_bytes(bytes):
  905. if bytes is None:
  906. return u'N/A'
  907. if type(bytes) is str:
  908. bytes = float(bytes)
  909. if bytes == 0.0:
  910. exponent = 0
  911. else:
  912. exponent = int(math.log(bytes, 1024.0))
  913. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  914. converted = float(bytes) / float(1024 ** exponent)
  915. return u'%.2f%s' % (converted, suffix)
  916. def get_term_width():
  917. columns = compat_getenv('COLUMNS', None)
  918. if columns:
  919. return int(columns)
  920. try:
  921. sp = subprocess.Popen(
  922. ['stty', 'size'],
  923. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  924. out, err = sp.communicate()
  925. return int(out.split()[1])
  926. except:
  927. pass
  928. return None
  929. def month_by_name(name):
  930. """ Return the number of a month by (locale-independently) English name """
  931. ENGLISH_NAMES = [
  932. u'January', u'February', u'March', u'April', u'May', u'June',
  933. u'July', u'August', u'September', u'October', u'November', u'December']
  934. try:
  935. return ENGLISH_NAMES.index(name) + 1
  936. except ValueError:
  937. return None
  938. def fix_xml_ampersands(xml_str):
  939. """Replace all the '&' by '&amp;' in XML"""
  940. return re.sub(
  941. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  942. u'&amp;',
  943. xml_str)
  944. def setproctitle(title):
  945. assert isinstance(title, compat_str)
  946. try:
  947. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  948. except OSError:
  949. return
  950. title_bytes = title.encode('utf-8')
  951. buf = ctypes.create_string_buffer(len(title_bytes))
  952. buf.value = title_bytes
  953. try:
  954. libc.prctl(15, buf, 0, 0, 0)
  955. except AttributeError:
  956. return # Strange libc, just skip this
  957. def remove_start(s, start):
  958. if s.startswith(start):
  959. return s[len(start):]
  960. return s
  961. def remove_end(s, end):
  962. if s.endswith(end):
  963. return s[:-len(end)]
  964. return s
  965. def url_basename(url):
  966. path = compat_urlparse.urlparse(url).path
  967. return path.strip(u'/').split(u'/')[-1]
  968. class HEADRequest(compat_urllib_request.Request):
  969. def get_method(self):
  970. return "HEAD"
  971. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  972. if get_attr:
  973. if v is not None:
  974. v = getattr(v, get_attr, None)
  975. if v == '':
  976. v = None
  977. return default if v is None else (int(v) * invscale // scale)
  978. def str_or_none(v, default=None):
  979. return default if v is None else compat_str(v)
  980. def str_to_int(int_str):
  981. """ A more relaxed version of int_or_none """
  982. if int_str is None:
  983. return None
  984. int_str = re.sub(r'[,\.\+]', u'', int_str)
  985. return int(int_str)
  986. def float_or_none(v, scale=1, invscale=1, default=None):
  987. return default if v is None else (float(v) * invscale / scale)
  988. def parse_duration(s):
  989. if s is None:
  990. return None
  991. s = s.strip()
  992. m = re.match(
  993. r'(?i)(?:(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$', s)
  994. if not m:
  995. return None
  996. res = int(m.group('secs'))
  997. if m.group('mins'):
  998. res += int(m.group('mins')) * 60
  999. if m.group('hours'):
  1000. res += int(m.group('hours')) * 60 * 60
  1001. if m.group('ms'):
  1002. res += float(m.group('ms'))
  1003. return res
  1004. def prepend_extension(filename, ext):
  1005. name, real_ext = os.path.splitext(filename)
  1006. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  1007. def check_executable(exe, args=[]):
  1008. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1009. args can be a list of arguments for a short output (like -version) """
  1010. try:
  1011. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1012. except OSError:
  1013. return False
  1014. return exe
  1015. def get_exe_version(exe, args=['--version'],
  1016. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  1017. unrecognized=u'present'):
  1018. """ Returns the version of the specified executable,
  1019. or False if the executable is not present """
  1020. try:
  1021. out, err = subprocess.Popen(
  1022. [exe] + args,
  1023. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1024. except OSError:
  1025. return False
  1026. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  1027. m = re.search(version_re, firstline)
  1028. if m:
  1029. return m.group(1)
  1030. else:
  1031. return unrecognized
  1032. class PagedList(object):
  1033. def __len__(self):
  1034. # This is only useful for tests
  1035. return len(self.getslice())
  1036. class OnDemandPagedList(PagedList):
  1037. def __init__(self, pagefunc, pagesize):
  1038. self._pagefunc = pagefunc
  1039. self._pagesize = pagesize
  1040. def getslice(self, start=0, end=None):
  1041. res = []
  1042. for pagenum in itertools.count(start // self._pagesize):
  1043. firstid = pagenum * self._pagesize
  1044. nextfirstid = pagenum * self._pagesize + self._pagesize
  1045. if start >= nextfirstid:
  1046. continue
  1047. page_results = list(self._pagefunc(pagenum))
  1048. startv = (
  1049. start % self._pagesize
  1050. if firstid <= start < nextfirstid
  1051. else 0)
  1052. endv = (
  1053. ((end - 1) % self._pagesize) + 1
  1054. if (end is not None and firstid <= end <= nextfirstid)
  1055. else None)
  1056. if startv != 0 or endv is not None:
  1057. page_results = page_results[startv:endv]
  1058. res.extend(page_results)
  1059. # A little optimization - if current page is not "full", ie. does
  1060. # not contain page_size videos then we can assume that this page
  1061. # is the last one - there are no more ids on further pages -
  1062. # i.e. no need to query again.
  1063. if len(page_results) + startv < self._pagesize:
  1064. break
  1065. # If we got the whole page, but the next page is not interesting,
  1066. # break out early as well
  1067. if end == nextfirstid:
  1068. break
  1069. return res
  1070. class InAdvancePagedList(PagedList):
  1071. def __init__(self, pagefunc, pagecount, pagesize):
  1072. self._pagefunc = pagefunc
  1073. self._pagecount = pagecount
  1074. self._pagesize = pagesize
  1075. def getslice(self, start=0, end=None):
  1076. res = []
  1077. start_page = start // self._pagesize
  1078. end_page = (
  1079. self._pagecount if end is None else (end // self._pagesize + 1))
  1080. skip_elems = start - start_page * self._pagesize
  1081. only_more = None if end is None else end - start
  1082. for pagenum in range(start_page, end_page):
  1083. page = list(self._pagefunc(pagenum))
  1084. if skip_elems:
  1085. page = page[skip_elems:]
  1086. skip_elems = None
  1087. if only_more is not None:
  1088. if len(page) < only_more:
  1089. only_more -= len(page)
  1090. else:
  1091. page = page[:only_more]
  1092. res.extend(page)
  1093. break
  1094. res.extend(page)
  1095. return res
  1096. def uppercase_escape(s):
  1097. unicode_escape = codecs.getdecoder('unicode_escape')
  1098. return re.sub(
  1099. r'\\U[0-9a-fA-F]{8}',
  1100. lambda m: unicode_escape(m.group(0))[0],
  1101. s)
  1102. def escape_rfc3986(s):
  1103. """Escape non-ASCII characters as suggested by RFC 3986"""
  1104. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1105. s = s.encode('utf-8')
  1106. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1107. def escape_url(url):
  1108. """Escape URL as suggested by RFC 3986"""
  1109. url_parsed = compat_urllib_parse_urlparse(url)
  1110. return url_parsed._replace(
  1111. path=escape_rfc3986(url_parsed.path),
  1112. params=escape_rfc3986(url_parsed.params),
  1113. query=escape_rfc3986(url_parsed.query),
  1114. fragment=escape_rfc3986(url_parsed.fragment)
  1115. ).geturl()
  1116. try:
  1117. struct.pack(u'!I', 0)
  1118. except TypeError:
  1119. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1120. def struct_pack(spec, *args):
  1121. if isinstance(spec, compat_str):
  1122. spec = spec.encode('ascii')
  1123. return struct.pack(spec, *args)
  1124. def struct_unpack(spec, *args):
  1125. if isinstance(spec, compat_str):
  1126. spec = spec.encode('ascii')
  1127. return struct.unpack(spec, *args)
  1128. else:
  1129. struct_pack = struct.pack
  1130. struct_unpack = struct.unpack
  1131. def read_batch_urls(batch_fd):
  1132. def fixup(url):
  1133. if not isinstance(url, compat_str):
  1134. url = url.decode('utf-8', 'replace')
  1135. BOM_UTF8 = u'\xef\xbb\xbf'
  1136. if url.startswith(BOM_UTF8):
  1137. url = url[len(BOM_UTF8):]
  1138. url = url.strip()
  1139. if url.startswith(('#', ';', ']')):
  1140. return False
  1141. return url
  1142. with contextlib.closing(batch_fd) as fd:
  1143. return [url for url in map(fixup, fd) if url]
  1144. def urlencode_postdata(*args, **kargs):
  1145. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1146. try:
  1147. etree_iter = xml.etree.ElementTree.Element.iter
  1148. except AttributeError: # Python <=2.6
  1149. etree_iter = lambda n: n.findall('.//*')
  1150. def parse_xml(s):
  1151. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1152. def doctype(self, name, pubid, system):
  1153. pass # Ignore doctypes
  1154. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1155. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1156. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1157. # Fix up XML parser in Python 2.x
  1158. if sys.version_info < (3, 0):
  1159. for n in etree_iter(tree):
  1160. if n.text is not None:
  1161. if not isinstance(n.text, compat_str):
  1162. n.text = n.text.decode('utf-8')
  1163. return tree
  1164. US_RATINGS = {
  1165. 'G': 0,
  1166. 'PG': 10,
  1167. 'PG-13': 13,
  1168. 'R': 16,
  1169. 'NC': 18,
  1170. }
  1171. def parse_age_limit(s):
  1172. if s is None:
  1173. return None
  1174. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1175. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1176. def strip_jsonp(code):
  1177. return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
  1178. def js_to_json(code):
  1179. def fix_kv(m):
  1180. v = m.group(0)
  1181. if v in ('true', 'false', 'null'):
  1182. return v
  1183. if v.startswith('"'):
  1184. return v
  1185. if v.startswith("'"):
  1186. v = v[1:-1]
  1187. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1188. '\\\\': '\\\\',
  1189. "\\'": "'",
  1190. '"': '\\"',
  1191. }[m.group(0)], v)
  1192. return '"%s"' % v
  1193. res = re.sub(r'''(?x)
  1194. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1195. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1196. [a-zA-Z_][a-zA-Z_0-9]*
  1197. ''', fix_kv, code)
  1198. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1199. return res
  1200. def qualities(quality_ids):
  1201. """ Get a numeric quality value out of a list of possible values """
  1202. def q(qid):
  1203. try:
  1204. return quality_ids.index(qid)
  1205. except ValueError:
  1206. return -1
  1207. return q
  1208. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1209. def limit_length(s, length):
  1210. """ Add ellipses to overly long strings """
  1211. if s is None:
  1212. return None
  1213. ELLIPSES = '...'
  1214. if len(s) > length:
  1215. return s[:length - len(ELLIPSES)] + ELLIPSES
  1216. return s
  1217. def version_tuple(v):
  1218. return [int(e) for e in v.split('.')]
  1219. def is_outdated_version(version, limit, assume_new=True):
  1220. if not version:
  1221. return not assume_new
  1222. try:
  1223. return version_tuple(version) < version_tuple(limit)
  1224. except ValueError:
  1225. return not assume_new