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.

368 lines
10 KiB

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