utils.py 10 KB

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