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.

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