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.

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