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.

1079 lines
34 KiB

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