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.

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