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.

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