You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1496 lines
46 KiB

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