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.

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