utils.py 11 KB

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