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.

1059 lines
34 KiB

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