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.

1646 lines
51 KiB

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