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.

1023 lines
33 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 sys
  18. import traceback
  19. import xml.etree.ElementTree
  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 self._tunnel_host:
  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.set_default_verify_paths()
  493. context.verify_mode = (ssl.CERT_NONE
  494. if opts_no_check_certificate
  495. else ssl.CERT_REQUIRED)
  496. return compat_urllib_request.HTTPSHandler(context=context)
  497. class ExtractorError(Exception):
  498. """Error during info extraction."""
  499. def __init__(self, msg, tb=None, expected=False, cause=None):
  500. """ tb, if given, is the original traceback (so that it can be printed out).
  501. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  502. """
  503. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  504. expected = True
  505. if not expected:
  506. 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.'
  507. super(ExtractorError, self).__init__(msg)
  508. self.traceback = tb
  509. self.exc_info = sys.exc_info() # preserve original exception
  510. self.cause = cause
  511. def format_traceback(self):
  512. if self.traceback is None:
  513. return None
  514. return u''.join(traceback.format_tb(self.traceback))
  515. class RegexNotFoundError(ExtractorError):
  516. """Error when a regex didn't match"""
  517. pass
  518. class DownloadError(Exception):
  519. """Download Error exception.
  520. This exception may be thrown by FileDownloader objects if they are not
  521. configured to continue on errors. They will contain the appropriate
  522. error message.
  523. """
  524. def __init__(self, msg, exc_info=None):
  525. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  526. super(DownloadError, self).__init__(msg)
  527. self.exc_info = exc_info
  528. class SameFileError(Exception):
  529. """Same File exception.
  530. This exception will be thrown by FileDownloader objects if they detect
  531. multiple files would have to be downloaded to the same file on disk.
  532. """
  533. pass
  534. class PostProcessingError(Exception):
  535. """Post Processing exception.
  536. This exception may be raised by PostProcessor's .run() method to
  537. indicate an error in the postprocessing task.
  538. """
  539. def __init__(self, msg):
  540. self.msg = msg
  541. class MaxDownloadsReached(Exception):
  542. """ --max-downloads limit has been reached. """
  543. pass
  544. class UnavailableVideoError(Exception):
  545. """Unavailable Format exception.
  546. This exception will be thrown when a video is requested
  547. in a format that is not available for that video.
  548. """
  549. pass
  550. class ContentTooShortError(Exception):
  551. """Content Too Short exception.
  552. This exception may be raised by FileDownloader objects when a file they
  553. download is too small for what the server announced first, indicating
  554. the connection was probably interrupted.
  555. """
  556. # Both in bytes
  557. downloaded = None
  558. expected = None
  559. def __init__(self, downloaded, expected):
  560. self.downloaded = downloaded
  561. self.expected = expected
  562. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  563. """Handler for HTTP requests and responses.
  564. This class, when installed with an OpenerDirector, automatically adds
  565. the standard headers to every HTTP request and handles gzipped and
  566. deflated responses from web servers. If compression is to be avoided in
  567. a particular request, the original request in the program code only has
  568. to include the HTTP header "Youtubedl-No-Compression", which will be
  569. removed before making the real request.
  570. Part of this code was copied from:
  571. http://techknack.net/python-urllib2-handlers/
  572. Andrew Rowls, the author of that code, agreed to release it to the
  573. public domain.
  574. """
  575. @staticmethod
  576. def deflate(data):
  577. try:
  578. return zlib.decompress(data, -zlib.MAX_WBITS)
  579. except zlib.error:
  580. return zlib.decompress(data)
  581. @staticmethod
  582. def addinfourl_wrapper(stream, headers, url, code):
  583. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  584. return compat_urllib_request.addinfourl(stream, headers, url, code)
  585. ret = compat_urllib_request.addinfourl(stream, headers, url)
  586. ret.code = code
  587. return ret
  588. def http_request(self, req):
  589. for h,v in std_headers.items():
  590. if h in req.headers:
  591. del req.headers[h]
  592. req.add_header(h, v)
  593. if 'Youtubedl-no-compression' in req.headers:
  594. if 'Accept-encoding' in req.headers:
  595. del req.headers['Accept-encoding']
  596. del req.headers['Youtubedl-no-compression']
  597. if 'Youtubedl-user-agent' in req.headers:
  598. if 'User-agent' in req.headers:
  599. del req.headers['User-agent']
  600. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  601. del req.headers['Youtubedl-user-agent']
  602. return req
  603. def http_response(self, req, resp):
  604. old_resp = resp
  605. # gzip
  606. if resp.headers.get('Content-encoding', '') == 'gzip':
  607. content = resp.read()
  608. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  609. try:
  610. uncompressed = io.BytesIO(gz.read())
  611. except IOError as original_ioerror:
  612. # There may be junk add the end of the file
  613. # See http://stackoverflow.com/q/4928560/35070 for details
  614. for i in range(1, 1024):
  615. try:
  616. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  617. uncompressed = io.BytesIO(gz.read())
  618. except IOError:
  619. continue
  620. break
  621. else:
  622. raise original_ioerror
  623. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  624. resp.msg = old_resp.msg
  625. # deflate
  626. if resp.headers.get('Content-encoding', '') == 'deflate':
  627. gz = io.BytesIO(self.deflate(resp.read()))
  628. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  629. resp.msg = old_resp.msg
  630. return resp
  631. https_request = http_request
  632. https_response = http_response
  633. def unified_strdate(date_str):
  634. """Return a string with the date in the format YYYYMMDD"""
  635. upload_date = None
  636. #Replace commas
  637. date_str = date_str.replace(',',' ')
  638. # %z (UTC offset) is only supported in python>=3.2
  639. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  640. format_expressions = [
  641. '%d %B %Y',
  642. '%B %d %Y',
  643. '%b %d %Y',
  644. '%Y-%m-%d',
  645. '%d/%m/%Y',
  646. '%Y/%m/%d %H:%M:%S',
  647. '%d.%m.%Y %H:%M',
  648. '%Y-%m-%dT%H:%M:%SZ',
  649. '%Y-%m-%dT%H:%M:%S.%fZ',
  650. '%Y-%m-%dT%H:%M:%S.%f0Z',
  651. '%Y-%m-%dT%H:%M:%S',
  652. ]
  653. for expression in format_expressions:
  654. try:
  655. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  656. except:
  657. pass
  658. return upload_date
  659. def determine_ext(url, default_ext=u'unknown_video'):
  660. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  661. if re.match(r'^[A-Za-z0-9]+$', guess):
  662. return guess
  663. else:
  664. return default_ext
  665. def subtitles_filename(filename, sub_lang, sub_format):
  666. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  667. def date_from_str(date_str):
  668. """
  669. Return a datetime object from a string in the format YYYYMMDD or
  670. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  671. today = datetime.date.today()
  672. if date_str == 'now'or date_str == 'today':
  673. return today
  674. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  675. if match is not None:
  676. sign = match.group('sign')
  677. time = int(match.group('time'))
  678. if sign == '-':
  679. time = -time
  680. unit = match.group('unit')
  681. #A bad aproximation?
  682. if unit == 'month':
  683. unit = 'day'
  684. time *= 30
  685. elif unit == 'year':
  686. unit = 'day'
  687. time *= 365
  688. unit += 's'
  689. delta = datetime.timedelta(**{unit: time})
  690. return today + delta
  691. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  692. class DateRange(object):
  693. """Represents a time interval between two dates"""
  694. def __init__(self, start=None, end=None):
  695. """start and end must be strings in the format accepted by date"""
  696. if start is not None:
  697. self.start = date_from_str(start)
  698. else:
  699. self.start = datetime.datetime.min.date()
  700. if end is not None:
  701. self.end = date_from_str(end)
  702. else:
  703. self.end = datetime.datetime.max.date()
  704. if self.start > self.end:
  705. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  706. @classmethod
  707. def day(cls, day):
  708. """Returns a range that only contains the given day"""
  709. return cls(day,day)
  710. def __contains__(self, date):
  711. """Check if the date is in the range"""
  712. if not isinstance(date, datetime.date):
  713. date = date_from_str(date)
  714. return self.start <= date <= self.end
  715. def __str__(self):
  716. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  717. def platform_name():
  718. """ Returns the platform name as a compat_str """
  719. res = platform.platform()
  720. if isinstance(res, bytes):
  721. res = res.decode(preferredencoding())
  722. assert isinstance(res, compat_str)
  723. return res
  724. def write_string(s, out=None):
  725. if out is None:
  726. out = sys.stderr
  727. assert type(s) == type(u'')
  728. if ('b' in getattr(out, 'mode', '') or
  729. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  730. s = s.encode(preferredencoding(), 'ignore')
  731. out.write(s)
  732. out.flush()
  733. def bytes_to_intlist(bs):
  734. if not bs:
  735. return []
  736. if isinstance(bs[0], int): # Python 3
  737. return list(bs)
  738. else:
  739. return [ord(c) for c in bs]
  740. def intlist_to_bytes(xs):
  741. if not xs:
  742. return b''
  743. if isinstance(chr(0), bytes): # Python 2
  744. return ''.join([chr(x) for x in xs])
  745. else:
  746. return bytes(xs)
  747. def get_cachedir(params={}):
  748. cache_root = os.environ.get('XDG_CACHE_HOME',
  749. os.path.expanduser('~/.cache'))
  750. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  751. # Cross-platform file locking
  752. if sys.platform == 'win32':
  753. import ctypes.wintypes
  754. import msvcrt
  755. class OVERLAPPED(ctypes.Structure):
  756. _fields_ = [
  757. ('Internal', ctypes.wintypes.LPVOID),
  758. ('InternalHigh', ctypes.wintypes.LPVOID),
  759. ('Offset', ctypes.wintypes.DWORD),
  760. ('OffsetHigh', ctypes.wintypes.DWORD),
  761. ('hEvent', ctypes.wintypes.HANDLE),
  762. ]
  763. kernel32 = ctypes.windll.kernel32
  764. LockFileEx = kernel32.LockFileEx
  765. LockFileEx.argtypes = [
  766. ctypes.wintypes.HANDLE, # hFile
  767. ctypes.wintypes.DWORD, # dwFlags
  768. ctypes.wintypes.DWORD, # dwReserved
  769. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  770. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  771. ctypes.POINTER(OVERLAPPED) # Overlapped
  772. ]
  773. LockFileEx.restype = ctypes.wintypes.BOOL
  774. UnlockFileEx = kernel32.UnlockFileEx
  775. UnlockFileEx.argtypes = [
  776. ctypes.wintypes.HANDLE, # hFile
  777. ctypes.wintypes.DWORD, # dwReserved
  778. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  779. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  780. ctypes.POINTER(OVERLAPPED) # Overlapped
  781. ]
  782. UnlockFileEx.restype = ctypes.wintypes.BOOL
  783. whole_low = 0xffffffff
  784. whole_high = 0x7fffffff
  785. def _lock_file(f, exclusive):
  786. overlapped = OVERLAPPED()
  787. overlapped.Offset = 0
  788. overlapped.OffsetHigh = 0
  789. overlapped.hEvent = 0
  790. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  791. handle = msvcrt.get_osfhandle(f.fileno())
  792. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  793. whole_low, whole_high, f._lock_file_overlapped_p):
  794. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  795. def _unlock_file(f):
  796. assert f._lock_file_overlapped_p
  797. handle = msvcrt.get_osfhandle(f.fileno())
  798. if not UnlockFileEx(handle, 0,
  799. whole_low, whole_high, f._lock_file_overlapped_p):
  800. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  801. else:
  802. import fcntl
  803. def _lock_file(f, exclusive):
  804. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  805. def _unlock_file(f):
  806. fcntl.lockf(f, fcntl.LOCK_UN)
  807. class locked_file(object):
  808. def __init__(self, filename, mode, encoding=None):
  809. assert mode in ['r', 'a', 'w']
  810. self.f = io.open(filename, mode, encoding=encoding)
  811. self.mode = mode
  812. def __enter__(self):
  813. exclusive = self.mode != 'r'
  814. try:
  815. _lock_file(self.f, exclusive)
  816. except IOError:
  817. self.f.close()
  818. raise
  819. return self
  820. def __exit__(self, etype, value, traceback):
  821. try:
  822. _unlock_file(self.f)
  823. finally:
  824. self.f.close()
  825. def __iter__(self):
  826. return iter(self.f)
  827. def write(self, *args):
  828. return self.f.write(*args)
  829. def read(self, *args):
  830. return self.f.read(*args)
  831. def shell_quote(args):
  832. quoted_args = []
  833. encoding = sys.getfilesystemencoding()
  834. if encoding is None:
  835. encoding = 'utf-8'
  836. for a in args:
  837. if isinstance(a, bytes):
  838. # We may get a filename encoded with 'encodeFilename'
  839. a = a.decode(encoding)
  840. quoted_args.append(pipes.quote(a))
  841. return u' '.join(quoted_args)
  842. def takewhile_inclusive(pred, seq):
  843. """ Like itertools.takewhile, but include the latest evaluated element
  844. (the first element so that Not pred(e)) """
  845. for e in seq:
  846. yield e
  847. if not pred(e):
  848. return
  849. def smuggle_url(url, data):
  850. """ Pass additional data in a URL for internal use. """
  851. sdata = compat_urllib_parse.urlencode(
  852. {u'__youtubedl_smuggle': json.dumps(data)})
  853. return url + u'#' + sdata
  854. def unsmuggle_url(smug_url):
  855. if not '#__youtubedl_smuggle' in smug_url:
  856. return smug_url, None
  857. url, _, sdata = smug_url.rpartition(u'#')
  858. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  859. data = json.loads(jsond)
  860. return url, data
  861. def format_bytes(bytes):
  862. if bytes is None:
  863. return u'N/A'
  864. if type(bytes) is str:
  865. bytes = float(bytes)
  866. if bytes == 0.0:
  867. exponent = 0
  868. else:
  869. exponent = int(math.log(bytes, 1024.0))
  870. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  871. converted = float(bytes) / float(1024 ** exponent)
  872. return u'%.2f%s' % (converted, suffix)