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.

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