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.

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