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.

1143 lines
36 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, for_subprocess=False):
  441. """
  442. @param s The name of the file
  443. """
  444. assert type(s) == compat_str
  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. if not for_subprocess:
  453. return s
  454. else:
  455. # For subprocess calls, encode with locale encoding
  456. # Refer to http://stackoverflow.com/a/9951851/35070
  457. encoding = preferredencoding()
  458. else:
  459. encoding = sys.getfilesystemencoding()
  460. if encoding is None:
  461. encoding = 'utf-8'
  462. return s.encode(encoding, 'ignore')
  463. def decodeOption(optval):
  464. if optval is None:
  465. return optval
  466. if isinstance(optval, bytes):
  467. optval = optval.decode(preferredencoding())
  468. assert isinstance(optval, compat_str)
  469. return optval
  470. def formatSeconds(secs):
  471. if secs > 3600:
  472. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  473. elif secs > 60:
  474. return '%d:%02d' % (secs // 60, secs % 60)
  475. else:
  476. return '%d' % secs
  477. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  478. if sys.version_info < (3, 2):
  479. import httplib
  480. class HTTPSConnectionV3(httplib.HTTPSConnection):
  481. def __init__(self, *args, **kwargs):
  482. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  483. def connect(self):
  484. sock = socket.create_connection((self.host, self.port), self.timeout)
  485. if getattr(self, '_tunnel_host', False):
  486. self.sock = sock
  487. self._tunnel()
  488. try:
  489. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
  490. except ssl.SSLError:
  491. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  492. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  493. def https_open(self, req):
  494. return self.do_open(HTTPSConnectionV3, req)
  495. return HTTPSHandlerV3(**kwargs)
  496. else:
  497. context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
  498. context.verify_mode = (ssl.CERT_NONE
  499. if opts_no_check_certificate
  500. else ssl.CERT_REQUIRED)
  501. context.set_default_verify_paths()
  502. try:
  503. context.load_default_certs()
  504. except AttributeError:
  505. pass # Python < 3.4
  506. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  507. class ExtractorError(Exception):
  508. """Error during info extraction."""
  509. def __init__(self, msg, tb=None, expected=False, cause=None):
  510. """ tb, if given, is the original traceback (so that it can be printed out).
  511. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  512. """
  513. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  514. expected = True
  515. if not expected:
  516. 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.'
  517. super(ExtractorError, self).__init__(msg)
  518. self.traceback = tb
  519. self.exc_info = sys.exc_info() # preserve original exception
  520. self.cause = cause
  521. def format_traceback(self):
  522. if self.traceback is None:
  523. return None
  524. return u''.join(traceback.format_tb(self.traceback))
  525. class RegexNotFoundError(ExtractorError):
  526. """Error when a regex didn't match"""
  527. pass
  528. class DownloadError(Exception):
  529. """Download Error exception.
  530. This exception may be thrown by FileDownloader objects if they are not
  531. configured to continue on errors. They will contain the appropriate
  532. error message.
  533. """
  534. def __init__(self, msg, exc_info=None):
  535. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  536. super(DownloadError, self).__init__(msg)
  537. self.exc_info = exc_info
  538. class SameFileError(Exception):
  539. """Same File exception.
  540. This exception will be thrown by FileDownloader objects if they detect
  541. multiple files would have to be downloaded to the same file on disk.
  542. """
  543. pass
  544. class PostProcessingError(Exception):
  545. """Post Processing exception.
  546. This exception may be raised by PostProcessor's .run() method to
  547. indicate an error in the postprocessing task.
  548. """
  549. def __init__(self, msg):
  550. self.msg = msg
  551. class MaxDownloadsReached(Exception):
  552. """ --max-downloads limit has been reached. """
  553. pass
  554. class UnavailableVideoError(Exception):
  555. """Unavailable Format exception.
  556. This exception will be thrown when a video is requested
  557. in a format that is not available for that video.
  558. """
  559. pass
  560. class ContentTooShortError(Exception):
  561. """Content Too Short exception.
  562. This exception may be raised by FileDownloader objects when a file they
  563. download is too small for what the server announced first, indicating
  564. the connection was probably interrupted.
  565. """
  566. # Both in bytes
  567. downloaded = None
  568. expected = None
  569. def __init__(self, downloaded, expected):
  570. self.downloaded = downloaded
  571. self.expected = expected
  572. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  573. """Handler for HTTP requests and responses.
  574. This class, when installed with an OpenerDirector, automatically adds
  575. the standard headers to every HTTP request and handles gzipped and
  576. deflated responses from web servers. If compression is to be avoided in
  577. a particular request, the original request in the program code only has
  578. to include the HTTP header "Youtubedl-No-Compression", which will be
  579. removed before making the real request.
  580. Part of this code was copied from:
  581. http://techknack.net/python-urllib2-handlers/
  582. Andrew Rowls, the author of that code, agreed to release it to the
  583. public domain.
  584. """
  585. @staticmethod
  586. def deflate(data):
  587. try:
  588. return zlib.decompress(data, -zlib.MAX_WBITS)
  589. except zlib.error:
  590. return zlib.decompress(data)
  591. @staticmethod
  592. def addinfourl_wrapper(stream, headers, url, code):
  593. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  594. return compat_urllib_request.addinfourl(stream, headers, url, code)
  595. ret = compat_urllib_request.addinfourl(stream, headers, url)
  596. ret.code = code
  597. return ret
  598. def http_request(self, req):
  599. for h,v in std_headers.items():
  600. if h in req.headers:
  601. del req.headers[h]
  602. req.add_header(h, v)
  603. if 'Youtubedl-no-compression' in req.headers:
  604. if 'Accept-encoding' in req.headers:
  605. del req.headers['Accept-encoding']
  606. del req.headers['Youtubedl-no-compression']
  607. if 'Youtubedl-user-agent' in req.headers:
  608. if 'User-agent' in req.headers:
  609. del req.headers['User-agent']
  610. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  611. del req.headers['Youtubedl-user-agent']
  612. return req
  613. def http_response(self, req, resp):
  614. old_resp = resp
  615. # gzip
  616. if resp.headers.get('Content-encoding', '') == 'gzip':
  617. content = resp.read()
  618. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  619. try:
  620. uncompressed = io.BytesIO(gz.read())
  621. except IOError as original_ioerror:
  622. # There may be junk add the end of the file
  623. # See http://stackoverflow.com/q/4928560/35070 for details
  624. for i in range(1, 1024):
  625. try:
  626. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  627. uncompressed = io.BytesIO(gz.read())
  628. except IOError:
  629. continue
  630. break
  631. else:
  632. raise original_ioerror
  633. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  634. resp.msg = old_resp.msg
  635. # deflate
  636. if resp.headers.get('Content-encoding', '') == 'deflate':
  637. gz = io.BytesIO(self.deflate(resp.read()))
  638. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  639. resp.msg = old_resp.msg
  640. return resp
  641. https_request = http_request
  642. https_response = http_response
  643. def unified_strdate(date_str):
  644. """Return a string with the date in the format YYYYMMDD"""
  645. upload_date = None
  646. #Replace commas
  647. date_str = date_str.replace(',',' ')
  648. # %z (UTC offset) is only supported in python>=3.2
  649. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  650. format_expressions = [
  651. '%d %B %Y',
  652. '%B %d %Y',
  653. '%b %d %Y',
  654. '%Y-%m-%d',
  655. '%d/%m/%Y',
  656. '%Y/%m/%d %H:%M:%S',
  657. '%d.%m.%Y %H:%M',
  658. '%Y-%m-%dT%H:%M:%SZ',
  659. '%Y-%m-%dT%H:%M:%S.%fZ',
  660. '%Y-%m-%dT%H:%M:%S.%f0Z',
  661. '%Y-%m-%dT%H:%M:%S',
  662. ]
  663. for expression in format_expressions:
  664. try:
  665. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  666. except:
  667. pass
  668. if upload_date is None:
  669. timetuple = email.utils.parsedate_tz(date_str)
  670. if timetuple:
  671. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  672. return upload_date
  673. def determine_ext(url, default_ext=u'unknown_video'):
  674. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  675. if re.match(r'^[A-Za-z0-9]+$', guess):
  676. return guess
  677. else:
  678. return default_ext
  679. def subtitles_filename(filename, sub_lang, sub_format):
  680. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  681. def date_from_str(date_str):
  682. """
  683. Return a datetime object from a string in the format YYYYMMDD or
  684. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  685. today = datetime.date.today()
  686. if date_str == 'now'or date_str == 'today':
  687. return today
  688. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  689. if match is not None:
  690. sign = match.group('sign')
  691. time = int(match.group('time'))
  692. if sign == '-':
  693. time = -time
  694. unit = match.group('unit')
  695. #A bad aproximation?
  696. if unit == 'month':
  697. unit = 'day'
  698. time *= 30
  699. elif unit == 'year':
  700. unit = 'day'
  701. time *= 365
  702. unit += 's'
  703. delta = datetime.timedelta(**{unit: time})
  704. return today + delta
  705. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  706. class DateRange(object):
  707. """Represents a time interval between two dates"""
  708. def __init__(self, start=None, end=None):
  709. """start and end must be strings in the format accepted by date"""
  710. if start is not None:
  711. self.start = date_from_str(start)
  712. else:
  713. self.start = datetime.datetime.min.date()
  714. if end is not None:
  715. self.end = date_from_str(end)
  716. else:
  717. self.end = datetime.datetime.max.date()
  718. if self.start > self.end:
  719. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  720. @classmethod
  721. def day(cls, day):
  722. """Returns a range that only contains the given day"""
  723. return cls(day,day)
  724. def __contains__(self, date):
  725. """Check if the date is in the range"""
  726. if not isinstance(date, datetime.date):
  727. date = date_from_str(date)
  728. return self.start <= date <= self.end
  729. def __str__(self):
  730. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  731. def platform_name():
  732. """ Returns the platform name as a compat_str """
  733. res = platform.platform()
  734. if isinstance(res, bytes):
  735. res = res.decode(preferredencoding())
  736. assert isinstance(res, compat_str)
  737. return res
  738. def write_string(s, out=None):
  739. if out is None:
  740. out = sys.stderr
  741. assert type(s) == compat_str
  742. if ('b' in getattr(out, 'mode', '') or
  743. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  744. s = s.encode(preferredencoding(), 'ignore')
  745. try:
  746. out.write(s)
  747. except UnicodeEncodeError:
  748. # In Windows shells, this can fail even when the codec is just charmap!?
  749. # See https://wiki.python.org/moin/PrintFails#Issue
  750. if sys.platform == 'win32' and hasattr(out, 'encoding'):
  751. s = s.encode(out.encoding, 'ignore').decode(out.encoding)
  752. out.write(s)
  753. else:
  754. raise
  755. out.flush()
  756. def bytes_to_intlist(bs):
  757. if not bs:
  758. return []
  759. if isinstance(bs[0], int): # Python 3
  760. return list(bs)
  761. else:
  762. return [ord(c) for c in bs]
  763. def intlist_to_bytes(xs):
  764. if not xs:
  765. return b''
  766. if isinstance(chr(0), bytes): # Python 2
  767. return ''.join([chr(x) for x in xs])
  768. else:
  769. return bytes(xs)
  770. def get_cachedir(params={}):
  771. cache_root = os.environ.get('XDG_CACHE_HOME',
  772. os.path.expanduser('~/.cache'))
  773. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  774. # Cross-platform file locking
  775. if sys.platform == 'win32':
  776. import ctypes.wintypes
  777. import msvcrt
  778. class OVERLAPPED(ctypes.Structure):
  779. _fields_ = [
  780. ('Internal', ctypes.wintypes.LPVOID),
  781. ('InternalHigh', ctypes.wintypes.LPVOID),
  782. ('Offset', ctypes.wintypes.DWORD),
  783. ('OffsetHigh', ctypes.wintypes.DWORD),
  784. ('hEvent', ctypes.wintypes.HANDLE),
  785. ]
  786. kernel32 = ctypes.windll.kernel32
  787. LockFileEx = kernel32.LockFileEx
  788. LockFileEx.argtypes = [
  789. ctypes.wintypes.HANDLE, # hFile
  790. ctypes.wintypes.DWORD, # dwFlags
  791. ctypes.wintypes.DWORD, # dwReserved
  792. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  793. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  794. ctypes.POINTER(OVERLAPPED) # Overlapped
  795. ]
  796. LockFileEx.restype = ctypes.wintypes.BOOL
  797. UnlockFileEx = kernel32.UnlockFileEx
  798. UnlockFileEx.argtypes = [
  799. ctypes.wintypes.HANDLE, # hFile
  800. ctypes.wintypes.DWORD, # dwReserved
  801. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  802. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  803. ctypes.POINTER(OVERLAPPED) # Overlapped
  804. ]
  805. UnlockFileEx.restype = ctypes.wintypes.BOOL
  806. whole_low = 0xffffffff
  807. whole_high = 0x7fffffff
  808. def _lock_file(f, exclusive):
  809. overlapped = OVERLAPPED()
  810. overlapped.Offset = 0
  811. overlapped.OffsetHigh = 0
  812. overlapped.hEvent = 0
  813. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  814. handle = msvcrt.get_osfhandle(f.fileno())
  815. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  816. whole_low, whole_high, f._lock_file_overlapped_p):
  817. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  818. def _unlock_file(f):
  819. assert f._lock_file_overlapped_p
  820. handle = msvcrt.get_osfhandle(f.fileno())
  821. if not UnlockFileEx(handle, 0,
  822. whole_low, whole_high, f._lock_file_overlapped_p):
  823. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  824. else:
  825. import fcntl
  826. def _lock_file(f, exclusive):
  827. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  828. def _unlock_file(f):
  829. fcntl.lockf(f, fcntl.LOCK_UN)
  830. class locked_file(object):
  831. def __init__(self, filename, mode, encoding=None):
  832. assert mode in ['r', 'a', 'w']
  833. self.f = io.open(filename, mode, encoding=encoding)
  834. self.mode = mode
  835. def __enter__(self):
  836. exclusive = self.mode != 'r'
  837. try:
  838. _lock_file(self.f, exclusive)
  839. except IOError:
  840. self.f.close()
  841. raise
  842. return self
  843. def __exit__(self, etype, value, traceback):
  844. try:
  845. _unlock_file(self.f)
  846. finally:
  847. self.f.close()
  848. def __iter__(self):
  849. return iter(self.f)
  850. def write(self, *args):
  851. return self.f.write(*args)
  852. def read(self, *args):
  853. return self.f.read(*args)
  854. def shell_quote(args):
  855. quoted_args = []
  856. encoding = sys.getfilesystemencoding()
  857. if encoding is None:
  858. encoding = 'utf-8'
  859. for a in args:
  860. if isinstance(a, bytes):
  861. # We may get a filename encoded with 'encodeFilename'
  862. a = a.decode(encoding)
  863. quoted_args.append(pipes.quote(a))
  864. return u' '.join(quoted_args)
  865. def takewhile_inclusive(pred, seq):
  866. """ Like itertools.takewhile, but include the latest evaluated element
  867. (the first element so that Not pred(e)) """
  868. for e in seq:
  869. yield e
  870. if not pred(e):
  871. return
  872. def smuggle_url(url, data):
  873. """ Pass additional data in a URL for internal use. """
  874. sdata = compat_urllib_parse.urlencode(
  875. {u'__youtubedl_smuggle': json.dumps(data)})
  876. return url + u'#' + sdata
  877. def unsmuggle_url(smug_url):
  878. if not '#__youtubedl_smuggle' in smug_url:
  879. return smug_url, None
  880. url, _, sdata = smug_url.rpartition(u'#')
  881. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  882. data = json.loads(jsond)
  883. return url, data
  884. def format_bytes(bytes):
  885. if bytes is None:
  886. return u'N/A'
  887. if type(bytes) is str:
  888. bytes = float(bytes)
  889. if bytes == 0.0:
  890. exponent = 0
  891. else:
  892. exponent = int(math.log(bytes, 1024.0))
  893. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  894. converted = float(bytes) / float(1024 ** exponent)
  895. return u'%.2f%s' % (converted, suffix)
  896. def str_to_int(int_str):
  897. int_str = re.sub(r'[,\.]', u'', int_str)
  898. return int(int_str)
  899. def get_term_width():
  900. columns = os.environ.get('COLUMNS', None)
  901. if columns:
  902. return int(columns)
  903. try:
  904. sp = subprocess.Popen(
  905. ['stty', 'size'],
  906. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  907. out, err = sp.communicate()
  908. return int(out.split()[1])
  909. except:
  910. pass
  911. return None
  912. def month_by_name(name):
  913. """ Return the number of a month by (locale-independently) English name """
  914. ENGLISH_NAMES = [
  915. u'January', u'February', u'March', u'April', u'May', u'June',
  916. u'July', u'August', u'September', u'October', u'November', u'December']
  917. try:
  918. return ENGLISH_NAMES.index(name) + 1
  919. except ValueError:
  920. return None
  921. def fix_xml_all_ampersand(xml_str):
  922. """Replace all the '&' by '&amp;' in XML"""
  923. return xml_str.replace(u'&', u'&amp;')
  924. def setproctitle(title):
  925. assert isinstance(title, compat_str)
  926. try:
  927. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  928. except OSError:
  929. return
  930. title = title
  931. buf = ctypes.create_string_buffer(len(title) + 1)
  932. buf.value = title.encode('utf-8')
  933. try:
  934. libc.prctl(15, ctypes.byref(buf), 0, 0, 0)
  935. except AttributeError:
  936. return # Strange libc, just skip this
  937. def remove_start(s, start):
  938. if s.startswith(start):
  939. return s[len(start):]
  940. return s
  941. def url_basename(url):
  942. path = compat_urlparse.urlparse(url).path
  943. return path.strip(u'/').split(u'/')[-1]
  944. class HEADRequest(compat_urllib_request.Request):
  945. def get_method(self):
  946. return "HEAD"
  947. def int_or_none(v):
  948. return v if v is None else int(v)
  949. def parse_duration(s):
  950. if s is None:
  951. return None
  952. m = re.match(
  953. r'(?:(?:(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)$', s)
  954. if not m:
  955. return None
  956. res = int(m.group('secs'))
  957. if m.group('mins'):
  958. res += int(m.group('mins')) * 60
  959. if m.group('hours'):
  960. res += int(m.group('hours')) * 60 * 60
  961. return res
  962. def prepend_extension(filename, ext):
  963. name, real_ext = os.path.splitext(filename)
  964. return u'{0}.{1}{2}'.format(name, ext, real_ext)