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.

1281 lines
40 KiB

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