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.

411 lines
11 KiB

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