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.

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