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.

517 lines
16 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import gzip
  4. import io
  5. import locale
  6. import os
  7. import re
  8. import sys
  9. import zlib
  10. import email.utils
  11. import json
  12. try:
  13. import urllib.request as compat_urllib_request
  14. except ImportError: # Python 2
  15. import urllib2 as compat_urllib_request
  16. try:
  17. import urllib.error as compat_urllib_error
  18. except ImportError: # Python 2
  19. import urllib2 as compat_urllib_error
  20. try:
  21. import urllib.parse as compat_urllib_parse
  22. except ImportError: # Python 2
  23. import urllib as compat_urllib_parse
  24. try:
  25. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  26. except ImportError: # Python 2
  27. from urlparse import urlparse as compat_urllib_parse_urlparse
  28. try:
  29. import http.cookiejar as compat_cookiejar
  30. except ImportError: # Python 2
  31. import cookielib as compat_cookiejar
  32. try:
  33. import html.entities as compat_html_entities
  34. except ImportError: # Python 2
  35. import htmlentitydefs as compat_html_entities
  36. try:
  37. import html.parser as compat_html_parser
  38. except ImportError: # Python 2
  39. import HTMLParser as compat_html_parser
  40. try:
  41. import http.client as compat_http_client
  42. except ImportError: # Python 2
  43. import httplib as compat_http_client
  44. try:
  45. from subprocess import DEVNULL
  46. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  47. except ImportError:
  48. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  49. try:
  50. from urllib.parse import parse_qs as compat_parse_qs
  51. except ImportError: # Python 2
  52. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  53. # Python 2's version is apparently totally broken
  54. def _unquote(string, encoding='utf-8', errors='replace'):
  55. if string == '':
  56. return string
  57. res = string.split('%')
  58. if len(res) == 1:
  59. return string
  60. if encoding is None:
  61. encoding = 'utf-8'
  62. if errors is None:
  63. errors = 'replace'
  64. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  65. pct_sequence = b''
  66. string = res[0]
  67. for item in res[1:]:
  68. try:
  69. if not item:
  70. raise ValueError
  71. pct_sequence += item[:2].decode('hex')
  72. rest = item[2:]
  73. if not rest:
  74. # This segment was just a single percent-encoded character.
  75. # May be part of a sequence of code units, so delay decoding.
  76. # (Stored in pct_sequence).
  77. continue
  78. except ValueError:
  79. rest = '%' + item
  80. # Encountered non-percent-encoded characters. Flush the current
  81. # pct_sequence.
  82. string += pct_sequence.decode(encoding, errors) + rest
  83. pct_sequence = b''
  84. if pct_sequence:
  85. # Flush the final pct_sequence
  86. string += pct_sequence.decode(encoding, errors)
  87. return string
  88. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  89. encoding='utf-8', errors='replace'):
  90. qs, _coerce_result = qs, unicode
  91. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  92. r = []
  93. for name_value in pairs:
  94. if not name_value and not strict_parsing:
  95. continue
  96. nv = name_value.split('=', 1)
  97. if len(nv) != 2:
  98. if strict_parsing:
  99. raise ValueError("bad query field: %r" % (name_value,))
  100. # Handle case of a control-name with no equal sign
  101. if keep_blank_values:
  102. nv.append('')
  103. else:
  104. continue
  105. if len(nv[1]) or keep_blank_values:
  106. name = nv[0].replace('+', ' ')
  107. name = _unquote(name, encoding=encoding, errors=errors)
  108. name = _coerce_result(name)
  109. value = nv[1].replace('+', ' ')
  110. value = _unquote(value, encoding=encoding, errors=errors)
  111. value = _coerce_result(value)
  112. r.append((name, value))
  113. return r
  114. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  115. encoding='utf-8', errors='replace'):
  116. parsed_result = {}
  117. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  118. encoding=encoding, errors=errors)
  119. for name, value in pairs:
  120. if name in parsed_result:
  121. parsed_result[name].append(value)
  122. else:
  123. parsed_result[name] = [value]
  124. return parsed_result
  125. try:
  126. compat_str = unicode # Python 2
  127. except NameError:
  128. compat_str = str
  129. try:
  130. compat_chr = unichr # Python 2
  131. except NameError:
  132. compat_chr = chr
  133. std_headers = {
  134. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  135. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  136. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  137. 'Accept-Encoding': 'gzip, deflate',
  138. 'Accept-Language': 'en-us,en;q=0.5',
  139. }
  140. def preferredencoding():
  141. """Get preferred encoding.
  142. Returns the best encoding scheme for the system, based on
  143. locale.getpreferredencoding() and some further tweaks.
  144. """
  145. try:
  146. pref = locale.getpreferredencoding()
  147. u'TEST'.encode(pref)
  148. except:
  149. pref = 'UTF-8'
  150. return pref
  151. if sys.version_info < (3,0):
  152. def compat_print(s):
  153. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  154. else:
  155. def compat_print(s):
  156. assert type(s) == type(u'')
  157. print(s)
  158. def htmlentity_transform(matchobj):
  159. """Transforms an HTML entity to a character.
  160. This function receives a match object and is intended to be used with
  161. the re.sub() function.
  162. """
  163. entity = matchobj.group(1)
  164. # Known non-numeric HTML entity
  165. if entity in compat_html_entities.name2codepoint:
  166. return compat_chr(compat_html_entities.name2codepoint[entity])
  167. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  168. if mobj is not None:
  169. numstr = mobj.group(1)
  170. if numstr.startswith(u'x'):
  171. base = 16
  172. numstr = u'0%s' % numstr
  173. else:
  174. base = 10
  175. return compat_chr(int(numstr, base))
  176. # Unknown entity in name, return its literal representation
  177. return (u'&%s;' % entity)
  178. 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
  179. class IDParser(compat_html_parser.HTMLParser):
  180. """Modified HTMLParser that isolates a tag with the specified id"""
  181. def __init__(self, id):
  182. self.id = id
  183. self.result = None
  184. self.started = False
  185. self.depth = {}
  186. self.html = None
  187. self.watch_startpos = False
  188. self.error_count = 0
  189. compat_html_parser.HTMLParser.__init__(self)
  190. def error(self, message):
  191. if self.error_count > 10 or self.started:
  192. raise compat_html_parser.HTMLParseError(message, self.getpos())
  193. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  194. self.error_count += 1
  195. self.goahead(1)
  196. def loads(self, html):
  197. self.html = html
  198. self.feed(html)
  199. self.close()
  200. def handle_starttag(self, tag, attrs):
  201. attrs = dict(attrs)
  202. if self.started:
  203. self.find_startpos(None)
  204. if 'id' in attrs and attrs['id'] == self.id:
  205. self.result = [tag]
  206. self.started = True
  207. self.watch_startpos = True
  208. if self.started:
  209. if not tag in self.depth: self.depth[tag] = 0
  210. self.depth[tag] += 1
  211. def handle_endtag(self, tag):
  212. if self.started:
  213. if tag in self.depth: self.depth[tag] -= 1
  214. if self.depth[self.result[0]] == 0:
  215. self.started = False
  216. self.result.append(self.getpos())
  217. def find_startpos(self, x):
  218. """Needed to put the start position of the result (self.result[1])
  219. after the opening tag with the requested id"""
  220. if self.watch_startpos:
  221. self.watch_startpos = False
  222. self.result.append(self.getpos())
  223. handle_entityref = handle_charref = handle_data = handle_comment = \
  224. handle_decl = handle_pi = unknown_decl = find_startpos
  225. def get_result(self):
  226. if self.result is None:
  227. return None
  228. if len(self.result) != 3:
  229. return None
  230. lines = self.html.split('\n')
  231. lines = lines[self.result[1][0]-1:self.result[2][0]]
  232. lines[0] = lines[0][self.result[1][1]:]
  233. if len(lines) == 1:
  234. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  235. lines[-1] = lines[-1][:self.result[2][1]]
  236. return '\n'.join(lines).strip()
  237. def get_element_by_id(id, html):
  238. """Return the content of the tag with the specified id in the passed HTML document"""
  239. parser = IDParser(id)
  240. try:
  241. parser.loads(html)
  242. except compat_html_parser.HTMLParseError:
  243. pass
  244. return parser.get_result()
  245. def clean_html(html):
  246. """Clean an HTML snippet into a readable string"""
  247. # Newline vs <br />
  248. html = html.replace('\n', ' ')
  249. html = re.sub('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  250. # Strip html tags
  251. html = re.sub('<.*?>', '', html)
  252. # Replace html entities
  253. html = unescapeHTML(html)
  254. return html
  255. def sanitize_open(filename, open_mode):
  256. """Try to open the given filename, and slightly tweak it if this fails.
  257. Attempts to open the given filename. If this fails, it tries to change
  258. the filename slightly, step by step, until it's either able to open it
  259. or it fails and raises a final exception, like the standard open()
  260. function.
  261. It returns the tuple (stream, definitive_file_name).
  262. """
  263. try:
  264. if filename == u'-':
  265. if sys.platform == 'win32':
  266. import msvcrt
  267. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  268. return (sys.stdout, filename)
  269. stream = open(encodeFilename(filename), open_mode)
  270. return (stream, filename)
  271. except (IOError, OSError) as err:
  272. # In case of error, try to remove win32 forbidden chars
  273. filename = re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', filename)
  274. # An exception here should be caught in the caller
  275. stream = open(encodeFilename(filename), open_mode)
  276. return (stream, filename)
  277. def timeconvert(timestr):
  278. """Convert RFC 2822 defined time string into system timestamp"""
  279. timestamp = None
  280. timetuple = email.utils.parsedate_tz(timestr)
  281. if timetuple is not None:
  282. timestamp = email.utils.mktime_tz(timetuple)
  283. return timestamp
  284. def sanitize_filename(s, restricted=False, is_id=False):
  285. """Sanitizes a string so it could be used as part of a filename.
  286. If restricted is set, use a stricter subset of allowed characters.
  287. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  288. """
  289. def replace_insane(char):
  290. if char == '?' or ord(char) < 32 or ord(char) == 127:
  291. return ''
  292. elif char == '"':
  293. return '' if restricted else '\''
  294. elif char == ':':
  295. return '_-' if restricted else ' -'
  296. elif char in '\\/|*<>':
  297. return '_'
  298. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  299. return '_'
  300. if restricted and ord(char) > 127:
  301. return '_'
  302. return char
  303. result = u''.join(map(replace_insane, s))
  304. if not is_id:
  305. while '__' in result:
  306. result = result.replace('__', '_')
  307. result = result.strip('_')
  308. # Common case of "Foreign band name - English song title"
  309. if restricted and result.startswith('-_'):
  310. result = result[2:]
  311. if not result:
  312. result = '_'
  313. return result
  314. def orderedSet(iterable):
  315. """ Remove all duplicates from the input iterable """
  316. res = []
  317. for el in iterable:
  318. if el not in res:
  319. res.append(el)
  320. return res
  321. def unescapeHTML(s):
  322. """
  323. @param s a string
  324. """
  325. assert type(s) == type(u'')
  326. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  327. return result
  328. def encodeFilename(s):
  329. """
  330. @param s The name of the file
  331. """
  332. assert type(s) == type(u'')
  333. # Python 3 has a Unicode API
  334. if sys.version_info >= (3, 0):
  335. return s
  336. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  337. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  338. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  339. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  340. return s
  341. else:
  342. return s.encode(sys.getfilesystemencoding(), 'ignore')
  343. class DownloadError(Exception):
  344. """Download Error exception.
  345. This exception may be thrown by FileDownloader objects if they are not
  346. configured to continue on errors. They will contain the appropriate
  347. error message.
  348. """
  349. pass
  350. class SameFileError(Exception):
  351. """Same File exception.
  352. This exception will be thrown by FileDownloader objects if they detect
  353. multiple files would have to be downloaded to the same file on disk.
  354. """
  355. pass
  356. class PostProcessingError(Exception):
  357. """Post Processing exception.
  358. This exception may be raised by PostProcessor's .run() method to
  359. indicate an error in the postprocessing task.
  360. """
  361. pass
  362. class MaxDownloadsReached(Exception):
  363. """ --max-downloads limit has been reached. """
  364. pass
  365. class UnavailableVideoError(Exception):
  366. """Unavailable Format exception.
  367. This exception will be thrown when a video is requested
  368. in a format that is not available for that video.
  369. """
  370. pass
  371. class ContentTooShortError(Exception):
  372. """Content Too Short exception.
  373. This exception may be raised by FileDownloader objects when a file they
  374. download is too small for what the server announced first, indicating
  375. the connection was probably interrupted.
  376. """
  377. # Both in bytes
  378. downloaded = None
  379. expected = None
  380. def __init__(self, downloaded, expected):
  381. self.downloaded = downloaded
  382. self.expected = expected
  383. class Trouble(Exception):
  384. """Trouble helper exception
  385. This is an exception to be handled with
  386. FileDownloader.trouble
  387. """
  388. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  389. """Handler for HTTP requests and responses.
  390. This class, when installed with an OpenerDirector, automatically adds
  391. the standard headers to every HTTP request and handles gzipped and
  392. deflated responses from web servers. If compression is to be avoided in
  393. a particular request, the original request in the program code only has
  394. to include the HTTP header "Youtubedl-No-Compression", which will be
  395. removed before making the real request.
  396. Part of this code was copied from:
  397. http://techknack.net/python-urllib2-handlers/
  398. Andrew Rowls, the author of that code, agreed to release it to the
  399. public domain.
  400. """
  401. @staticmethod
  402. def deflate(data):
  403. try:
  404. return zlib.decompress(data, -zlib.MAX_WBITS)
  405. except zlib.error:
  406. return zlib.decompress(data)
  407. @staticmethod
  408. def addinfourl_wrapper(stream, headers, url, code):
  409. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  410. return compat_urllib_request.addinfourl(stream, headers, url, code)
  411. ret = compat_urllib_request.addinfourl(stream, headers, url)
  412. ret.code = code
  413. return ret
  414. def http_request(self, req):
  415. for h in std_headers:
  416. if h in req.headers:
  417. del req.headers[h]
  418. req.add_header(h, std_headers[h])
  419. if 'Youtubedl-no-compression' in req.headers:
  420. if 'Accept-encoding' in req.headers:
  421. del req.headers['Accept-encoding']
  422. del req.headers['Youtubedl-no-compression']
  423. return req
  424. def http_response(self, req, resp):
  425. old_resp = resp
  426. # gzip
  427. if resp.headers.get('Content-encoding', '') == 'gzip':
  428. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  429. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  430. resp.msg = old_resp.msg
  431. # deflate
  432. if resp.headers.get('Content-encoding', '') == 'deflate':
  433. gz = io.BytesIO(self.deflate(resp.read()))
  434. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  435. resp.msg = old_resp.msg
  436. return resp
  437. https_request = http_request
  438. https_response = http_response