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.

1109 lines
35 KiB

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