utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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. def htmlentity_transform(matchobj):
  205. """Transforms an HTML entity to a character.
  206. This function receives a match object and is intended to be used with
  207. the re.sub() function.
  208. """
  209. entity = matchobj.group(1)
  210. # Known non-numeric HTML entity
  211. if entity in compat_html_entities.name2codepoint:
  212. return compat_chr(compat_html_entities.name2codepoint[entity])
  213. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  214. if mobj is not None:
  215. numstr = mobj.group(1)
  216. if numstr.startswith(u'x'):
  217. base = 16
  218. numstr = u'0%s' % numstr
  219. else:
  220. base = 10
  221. return compat_chr(int(numstr, base))
  222. # Unknown entity in name, return its literal representation
  223. return (u'&%s;' % entity)
  224. 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
  225. class BaseHTMLParser(compat_html_parser.HTMLParser):
  226. def __init(self):
  227. compat_html_parser.HTMLParser.__init__(self)
  228. self.html = None
  229. def loads(self, html):
  230. self.html = html
  231. self.feed(html)
  232. self.close()
  233. class AttrParser(BaseHTMLParser):
  234. """Modified HTMLParser that isolates a tag with the specified attribute"""
  235. def __init__(self, attribute, value):
  236. self.attribute = attribute
  237. self.value = value
  238. self.result = None
  239. self.started = False
  240. self.depth = {}
  241. self.watch_startpos = False
  242. self.error_count = 0
  243. BaseHTMLParser.__init__(self)
  244. def error(self, message):
  245. if self.error_count > 10 or self.started:
  246. raise compat_html_parser.HTMLParseError(message, self.getpos())
  247. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  248. self.error_count += 1
  249. self.goahead(1)
  250. def handle_starttag(self, tag, attrs):
  251. attrs = dict(attrs)
  252. if self.started:
  253. self.find_startpos(None)
  254. if self.attribute in attrs and attrs[self.attribute] == self.value:
  255. self.result = [tag]
  256. self.started = True
  257. self.watch_startpos = True
  258. if self.started:
  259. if not tag in self.depth: self.depth[tag] = 0
  260. self.depth[tag] += 1
  261. def handle_endtag(self, tag):
  262. if self.started:
  263. if tag in self.depth: self.depth[tag] -= 1
  264. if self.depth[self.result[0]] == 0:
  265. self.started = False
  266. self.result.append(self.getpos())
  267. def find_startpos(self, x):
  268. """Needed to put the start position of the result (self.result[1])
  269. after the opening tag with the requested id"""
  270. if self.watch_startpos:
  271. self.watch_startpos = False
  272. self.result.append(self.getpos())
  273. handle_entityref = handle_charref = handle_data = handle_comment = \
  274. handle_decl = handle_pi = unknown_decl = find_startpos
  275. def get_result(self):
  276. if self.result is None:
  277. return None
  278. if len(self.result) != 3:
  279. return None
  280. lines = self.html.split('\n')
  281. lines = lines[self.result[1][0]-1:self.result[2][0]]
  282. lines[0] = lines[0][self.result[1][1]:]
  283. if len(lines) == 1:
  284. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  285. lines[-1] = lines[-1][:self.result[2][1]]
  286. return '\n'.join(lines).strip()
  287. # Hack for https://github.com/rg3/youtube-dl/issues/662
  288. if sys.version_info < (2, 7, 3):
  289. AttrParser.parse_endtag = (lambda self, i:
  290. i + len("</scr'+'ipt>")
  291. if self.rawdata[i:].startswith("</scr'+'ipt>")
  292. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  293. def get_element_by_id(id, html):
  294. """Return the content of the tag with the specified ID in the passed HTML document"""
  295. return get_element_by_attribute("id", id, html)
  296. def get_element_by_attribute(attribute, value, html):
  297. """Return the content of the tag with the specified attribute in the passed HTML document"""
  298. parser = AttrParser(attribute, value)
  299. try:
  300. parser.loads(html)
  301. except compat_html_parser.HTMLParseError:
  302. pass
  303. return parser.get_result()
  304. class MetaParser(BaseHTMLParser):
  305. """
  306. Modified HTMLParser that isolates a meta tag with the specified name
  307. attribute.
  308. """
  309. def __init__(self, name):
  310. BaseHTMLParser.__init__(self)
  311. self.name = name
  312. self.content = None
  313. self.result = None
  314. def handle_starttag(self, tag, attrs):
  315. if tag != 'meta':
  316. return
  317. attrs = dict(attrs)
  318. if attrs.get('name') == self.name:
  319. self.result = attrs.get('content')
  320. def get_result(self):
  321. return self.result
  322. def get_meta_content(name, html):
  323. """
  324. Return the content attribute from the meta tag with the given name attribute.
  325. """
  326. parser = MetaParser(name)
  327. try:
  328. parser.loads(html)
  329. except compat_html_parser.HTMLParseError:
  330. pass
  331. return parser.get_result()
  332. def clean_html(html):
  333. """Clean an HTML snippet into a readable string"""
  334. # Newline vs <br />
  335. html = html.replace('\n', ' ')
  336. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  337. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  338. # Strip html tags
  339. html = re.sub('<.*?>', '', html)
  340. # Replace html entities
  341. html = unescapeHTML(html)
  342. return html.strip()
  343. def sanitize_open(filename, open_mode):
  344. """Try to open the given filename, and slightly tweak it if this fails.
  345. Attempts to open the given filename. If this fails, it tries to change
  346. the filename slightly, step by step, until it's either able to open it
  347. or it fails and raises a final exception, like the standard open()
  348. function.
  349. It returns the tuple (stream, definitive_file_name).
  350. """
  351. try:
  352. if filename == u'-':
  353. if sys.platform == 'win32':
  354. import msvcrt
  355. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  356. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  357. stream = open(encodeFilename(filename), open_mode)
  358. return (stream, filename)
  359. except (IOError, OSError) as err:
  360. if err.errno in (errno.EACCES,):
  361. raise
  362. # In case of error, try to remove win32 forbidden chars
  363. alt_filename = os.path.join(
  364. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  365. for path_part in os.path.split(filename)
  366. )
  367. if alt_filename == filename:
  368. raise
  369. else:
  370. # An exception here should be caught in the caller
  371. stream = open(encodeFilename(filename), open_mode)
  372. return (stream, alt_filename)
  373. def timeconvert(timestr):
  374. """Convert RFC 2822 defined time string into system timestamp"""
  375. timestamp = None
  376. timetuple = email.utils.parsedate_tz(timestr)
  377. if timetuple is not None:
  378. timestamp = email.utils.mktime_tz(timetuple)
  379. return timestamp
  380. def sanitize_filename(s, restricted=False, is_id=False):
  381. """Sanitizes a string so it could be used as part of a filename.
  382. If restricted is set, use a stricter subset of allowed characters.
  383. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  384. """
  385. def replace_insane(char):
  386. if char == '?' or ord(char) < 32 or ord(char) == 127:
  387. return ''
  388. elif char == '"':
  389. return '' if restricted else '\''
  390. elif char == ':':
  391. return '_-' if restricted else ' -'
  392. elif char in '\\/|*<>':
  393. return '_'
  394. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  395. return '_'
  396. if restricted and ord(char) > 127:
  397. return '_'
  398. return char
  399. result = u''.join(map(replace_insane, s))
  400. if not is_id:
  401. while '__' in result:
  402. result = result.replace('__', '_')
  403. result = result.strip('_')
  404. # Common case of "Foreign band name - English song title"
  405. if restricted and result.startswith('-_'):
  406. result = result[2:]
  407. if not result:
  408. result = '_'
  409. return result
  410. def orderedSet(iterable):
  411. """ Remove all duplicates from the input iterable """
  412. res = []
  413. for el in iterable:
  414. if el not in res:
  415. res.append(el)
  416. return res
  417. def unescapeHTML(s):
  418. """
  419. @param s a string
  420. """
  421. assert type(s) == type(u'')
  422. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  423. return result
  424. def encodeFilename(s):
  425. """
  426. @param s The name of the file
  427. """
  428. assert type(s) == type(u'')
  429. # Python 3 has a Unicode API
  430. if sys.version_info >= (3, 0):
  431. return s
  432. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  433. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  434. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  435. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  436. return s
  437. else:
  438. encoding = sys.getfilesystemencoding()
  439. if encoding is None:
  440. encoding = 'utf-8'
  441. return s.encode(encoding, 'ignore')
  442. def decodeOption(optval):
  443. if optval is None:
  444. return optval
  445. if isinstance(optval, bytes):
  446. optval = optval.decode(preferredencoding())
  447. assert isinstance(optval, compat_str)
  448. return optval
  449. def formatSeconds(secs):
  450. if secs > 3600:
  451. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  452. elif secs > 60:
  453. return '%d:%02d' % (secs // 60, secs % 60)
  454. else:
  455. return '%d' % secs
  456. def make_HTTPS_handler(opts):
  457. if sys.version_info < (3,2):
  458. # Python's 2.x handler is very simplistic
  459. return compat_urllib_request.HTTPSHandler()
  460. else:
  461. import ssl
  462. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  463. context.set_default_verify_paths()
  464. context.verify_mode = (ssl.CERT_NONE
  465. if opts.no_check_certificate
  466. else ssl.CERT_REQUIRED)
  467. return compat_urllib_request.HTTPSHandler(context=context)
  468. class ExtractorError(Exception):
  469. """Error during info extraction."""
  470. def __init__(self, msg, tb=None, expected=False, cause=None):
  471. """ tb, if given, is the original traceback (so that it can be printed out).
  472. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  473. """
  474. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  475. expected = True
  476. if not expected:
  477. 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.'
  478. super(ExtractorError, self).__init__(msg)
  479. self.traceback = tb
  480. self.exc_info = sys.exc_info() # preserve original exception
  481. self.cause = cause
  482. def format_traceback(self):
  483. if self.traceback is None:
  484. return None
  485. return u''.join(traceback.format_tb(self.traceback))
  486. class DownloadError(Exception):
  487. """Download Error exception.
  488. This exception may be thrown by FileDownloader objects if they are not
  489. configured to continue on errors. They will contain the appropriate
  490. error message.
  491. """
  492. def __init__(self, msg, exc_info=None):
  493. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  494. super(DownloadError, self).__init__(msg)
  495. self.exc_info = exc_info
  496. class SameFileError(Exception):
  497. """Same File exception.
  498. This exception will be thrown by FileDownloader objects if they detect
  499. multiple files would have to be downloaded to the same file on disk.
  500. """
  501. pass
  502. class PostProcessingError(Exception):
  503. """Post Processing exception.
  504. This exception may be raised by PostProcessor's .run() method to
  505. indicate an error in the postprocessing task.
  506. """
  507. def __init__(self, msg):
  508. self.msg = msg
  509. class MaxDownloadsReached(Exception):
  510. """ --max-downloads limit has been reached. """
  511. pass
  512. class UnavailableVideoError(Exception):
  513. """Unavailable Format exception.
  514. This exception will be thrown when a video is requested
  515. in a format that is not available for that video.
  516. """
  517. pass
  518. class ContentTooShortError(Exception):
  519. """Content Too Short exception.
  520. This exception may be raised by FileDownloader objects when a file they
  521. download is too small for what the server announced first, indicating
  522. the connection was probably interrupted.
  523. """
  524. # Both in bytes
  525. downloaded = None
  526. expected = None
  527. def __init__(self, downloaded, expected):
  528. self.downloaded = downloaded
  529. self.expected = expected
  530. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  531. """Handler for HTTP requests and responses.
  532. This class, when installed with an OpenerDirector, automatically adds
  533. the standard headers to every HTTP request and handles gzipped and
  534. deflated responses from web servers. If compression is to be avoided in
  535. a particular request, the original request in the program code only has
  536. to include the HTTP header "Youtubedl-No-Compression", which will be
  537. removed before making the real request.
  538. Part of this code was copied from:
  539. http://techknack.net/python-urllib2-handlers/
  540. Andrew Rowls, the author of that code, agreed to release it to the
  541. public domain.
  542. """
  543. @staticmethod
  544. def deflate(data):
  545. try:
  546. return zlib.decompress(data, -zlib.MAX_WBITS)
  547. except zlib.error:
  548. return zlib.decompress(data)
  549. @staticmethod
  550. def addinfourl_wrapper(stream, headers, url, code):
  551. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  552. return compat_urllib_request.addinfourl(stream, headers, url, code)
  553. ret = compat_urllib_request.addinfourl(stream, headers, url)
  554. ret.code = code
  555. return ret
  556. def http_request(self, req):
  557. for h,v in std_headers.items():
  558. if h in req.headers:
  559. del req.headers[h]
  560. req.add_header(h, v)
  561. if 'Youtubedl-no-compression' in req.headers:
  562. if 'Accept-encoding' in req.headers:
  563. del req.headers['Accept-encoding']
  564. del req.headers['Youtubedl-no-compression']
  565. if 'Youtubedl-user-agent' in req.headers:
  566. if 'User-agent' in req.headers:
  567. del req.headers['User-agent']
  568. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  569. del req.headers['Youtubedl-user-agent']
  570. return req
  571. def http_response(self, req, resp):
  572. old_resp = resp
  573. # gzip
  574. if resp.headers.get('Content-encoding', '') == 'gzip':
  575. content = resp.read()
  576. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  577. try:
  578. uncompressed = io.BytesIO(gz.read())
  579. except IOError as original_ioerror:
  580. # There may be junk add the end of the file
  581. # See http://stackoverflow.com/q/4928560/35070 for details
  582. for i in range(1, 1024):
  583. try:
  584. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  585. uncompressed = io.BytesIO(gz.read())
  586. except IOError:
  587. continue
  588. break
  589. else:
  590. raise original_ioerror
  591. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  592. resp.msg = old_resp.msg
  593. # deflate
  594. if resp.headers.get('Content-encoding', '') == 'deflate':
  595. gz = io.BytesIO(self.deflate(resp.read()))
  596. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  597. resp.msg = old_resp.msg
  598. return resp
  599. https_request = http_request
  600. https_response = http_response
  601. def unified_strdate(date_str):
  602. """Return a string with the date in the format YYYYMMDD"""
  603. upload_date = None
  604. #Replace commas
  605. date_str = date_str.replace(',',' ')
  606. # %z (UTC offset) is only supported in python>=3.2
  607. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  608. format_expressions = [
  609. '%d %B %Y',
  610. '%B %d %Y',
  611. '%b %d %Y',
  612. '%Y-%m-%d',
  613. '%d/%m/%Y',
  614. '%Y/%m/%d %H:%M:%S',
  615. '%d.%m.%Y %H:%M',
  616. '%Y-%m-%dT%H:%M:%SZ',
  617. '%Y-%m-%dT%H:%M:%S',
  618. ]
  619. for expression in format_expressions:
  620. try:
  621. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  622. except:
  623. pass
  624. return upload_date
  625. def determine_ext(url, default_ext=u'unknown_video'):
  626. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  627. if re.match(r'^[A-Za-z0-9]+$', guess):
  628. return guess
  629. else:
  630. return default_ext
  631. def subtitles_filename(filename, sub_lang, sub_format):
  632. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  633. def date_from_str(date_str):
  634. """
  635. Return a datetime object from a string in the format YYYYMMDD or
  636. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  637. today = datetime.date.today()
  638. if date_str == 'now'or date_str == 'today':
  639. return today
  640. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  641. if match is not None:
  642. sign = match.group('sign')
  643. time = int(match.group('time'))
  644. if sign == '-':
  645. time = -time
  646. unit = match.group('unit')
  647. #A bad aproximation?
  648. if unit == 'month':
  649. unit = 'day'
  650. time *= 30
  651. elif unit == 'year':
  652. unit = 'day'
  653. time *= 365
  654. unit += 's'
  655. delta = datetime.timedelta(**{unit: time})
  656. return today + delta
  657. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  658. class DateRange(object):
  659. """Represents a time interval between two dates"""
  660. def __init__(self, start=None, end=None):
  661. """start and end must be strings in the format accepted by date"""
  662. if start is not None:
  663. self.start = date_from_str(start)
  664. else:
  665. self.start = datetime.datetime.min.date()
  666. if end is not None:
  667. self.end = date_from_str(end)
  668. else:
  669. self.end = datetime.datetime.max.date()
  670. if self.start > self.end:
  671. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  672. @classmethod
  673. def day(cls, day):
  674. """Returns a range that only contains the given day"""
  675. return cls(day,day)
  676. def __contains__(self, date):
  677. """Check if the date is in the range"""
  678. if not isinstance(date, datetime.date):
  679. date = date_from_str(date)
  680. return self.start <= date <= self.end
  681. def __str__(self):
  682. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  683. def platform_name():
  684. """ Returns the platform name as a compat_str """
  685. res = platform.platform()
  686. if isinstance(res, bytes):
  687. res = res.decode(preferredencoding())
  688. assert isinstance(res, compat_str)
  689. return res
  690. def write_string(s, out=None):
  691. if out is None:
  692. out = sys.stderr
  693. assert type(s) == type(u'')
  694. if ('b' in getattr(out, 'mode', '') or
  695. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  696. s = s.encode(preferredencoding(), 'ignore')
  697. out.write(s)
  698. out.flush()
  699. def bytes_to_intlist(bs):
  700. if not bs:
  701. return []
  702. if isinstance(bs[0], int): # Python 3
  703. return list(bs)
  704. else:
  705. return [ord(c) for c in bs]
  706. def intlist_to_bytes(xs):
  707. if not xs:
  708. return b''
  709. if isinstance(chr(0), bytes): # Python 2
  710. return ''.join([chr(x) for x in xs])
  711. else:
  712. return bytes(xs)
  713. def get_cachedir(params={}):
  714. cache_root = os.environ.get('XDG_CACHE_HOME',
  715. os.path.expanduser('~/.cache'))
  716. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  717. # Cross-platform file locking
  718. if sys.platform == 'win32':
  719. import ctypes.wintypes
  720. import msvcrt
  721. class OVERLAPPED(ctypes.Structure):
  722. _fields_ = [
  723. ('Internal', ctypes.wintypes.LPVOID),
  724. ('InternalHigh', ctypes.wintypes.LPVOID),
  725. ('Offset', ctypes.wintypes.DWORD),
  726. ('OffsetHigh', ctypes.wintypes.DWORD),
  727. ('hEvent', ctypes.wintypes.HANDLE),
  728. ]
  729. kernel32 = ctypes.windll.kernel32
  730. LockFileEx = kernel32.LockFileEx
  731. LockFileEx.argtypes = [
  732. ctypes.wintypes.HANDLE, # hFile
  733. ctypes.wintypes.DWORD, # dwFlags
  734. ctypes.wintypes.DWORD, # dwReserved
  735. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  736. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  737. ctypes.POINTER(OVERLAPPED) # Overlapped
  738. ]
  739. LockFileEx.restype = ctypes.wintypes.BOOL
  740. UnlockFileEx = kernel32.UnlockFileEx
  741. UnlockFileEx.argtypes = [
  742. ctypes.wintypes.HANDLE, # hFile
  743. ctypes.wintypes.DWORD, # dwReserved
  744. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  745. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  746. ctypes.POINTER(OVERLAPPED) # Overlapped
  747. ]
  748. UnlockFileEx.restype = ctypes.wintypes.BOOL
  749. whole_low = 0xffffffff
  750. whole_high = 0x7fffffff
  751. def _lock_file(f, exclusive):
  752. overlapped = OVERLAPPED()
  753. overlapped.Offset = 0
  754. overlapped.OffsetHigh = 0
  755. overlapped.hEvent = 0
  756. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  757. handle = msvcrt.get_osfhandle(f.fileno())
  758. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  759. whole_low, whole_high, f._lock_file_overlapped_p):
  760. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  761. def _unlock_file(f):
  762. assert f._lock_file_overlapped_p
  763. handle = msvcrt.get_osfhandle(f.fileno())
  764. if not UnlockFileEx(handle, 0,
  765. whole_low, whole_high, f._lock_file_overlapped_p):
  766. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  767. else:
  768. import fcntl
  769. def _lock_file(f, exclusive):
  770. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  771. def _unlock_file(f):
  772. fcntl.lockf(f, fcntl.LOCK_UN)
  773. class locked_file(object):
  774. def __init__(self, filename, mode, encoding=None):
  775. assert mode in ['r', 'a', 'w']
  776. self.f = io.open(filename, mode, encoding=encoding)
  777. self.mode = mode
  778. def __enter__(self):
  779. exclusive = self.mode != 'r'
  780. try:
  781. _lock_file(self.f, exclusive)
  782. except IOError:
  783. self.f.close()
  784. raise
  785. return self
  786. def __exit__(self, etype, value, traceback):
  787. try:
  788. _unlock_file(self.f)
  789. finally:
  790. self.f.close()
  791. def __iter__(self):
  792. return iter(self.f)
  793. def write(self, *args):
  794. return self.f.write(*args)
  795. def read(self, *args):
  796. return self.f.read(*args)
  797. def shell_quote(args):
  798. return ' '.join(map(pipes.quote, args))