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.

1395 lines
42 KiB

10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import gzip
  12. import itertools
  13. import io
  14. import json
  15. import locale
  16. import math
  17. import os
  18. import pipes
  19. import platform
  20. import re
  21. import ssl
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import traceback
  28. import xml.etree.ElementTree
  29. import zlib
  30. from .compat import (
  31. compat_chr,
  32. compat_getenv,
  33. compat_html_entities,
  34. compat_parse_qs,
  35. compat_str,
  36. compat_urllib_error,
  37. compat_urllib_parse,
  38. compat_urllib_parse_urlparse,
  39. compat_urllib_request,
  40. compat_urlparse,
  41. )
  42. # This is not clearly defined otherwise
  43. compiled_regex_type = type(re.compile(''))
  44. std_headers = {
  45. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  46. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  47. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  48. 'Accept-Encoding': 'gzip, deflate',
  49. 'Accept-Language': 'en-us,en;q=0.5',
  50. }
  51. def preferredencoding():
  52. """Get preferred encoding.
  53. Returns the best encoding scheme for the system, based on
  54. locale.getpreferredencoding() and some further tweaks.
  55. """
  56. try:
  57. pref = locale.getpreferredencoding()
  58. u'TEST'.encode(pref)
  59. except:
  60. pref = 'UTF-8'
  61. return pref
  62. def write_json_file(obj, fn):
  63. """ Encode obj as JSON and write it to fn, atomically """
  64. args = {
  65. 'suffix': '.tmp',
  66. 'prefix': os.path.basename(fn) + '.',
  67. 'dir': os.path.dirname(fn),
  68. 'delete': False,
  69. }
  70. # In Python 2.x, json.dump expects a bytestream.
  71. # In Python 3.x, it writes to a character stream
  72. if sys.version_info < (3, 0):
  73. args['mode'] = 'wb'
  74. else:
  75. args.update({
  76. 'mode': 'w',
  77. 'encoding': 'utf-8',
  78. })
  79. tf = tempfile.NamedTemporaryFile(**args)
  80. try:
  81. with tf:
  82. json.dump(obj, tf)
  83. os.rename(tf.name, fn)
  84. except:
  85. try:
  86. os.remove(tf.name)
  87. except OSError:
  88. pass
  89. raise
  90. if sys.version_info >= (2, 7):
  91. def find_xpath_attr(node, xpath, key, val):
  92. """ Find the xpath xpath[@key=val] """
  93. assert re.match(r'^[a-zA-Z-]+$', key)
  94. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  95. expr = xpath + u"[@%s='%s']" % (key, val)
  96. return node.find(expr)
  97. else:
  98. def find_xpath_attr(node, xpath, key, val):
  99. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  100. # .//node does not match if a node is a direct child of . !
  101. if isinstance(xpath, unicode):
  102. xpath = xpath.encode('ascii')
  103. for f in node.findall(xpath):
  104. if f.attrib.get(key) == val:
  105. return f
  106. return None
  107. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  108. # the namespace parameter
  109. def xpath_with_ns(path, ns_map):
  110. components = [c.split(':') for c in path.split('/')]
  111. replaced = []
  112. for c in components:
  113. if len(c) == 1:
  114. replaced.append(c[0])
  115. else:
  116. ns, tag = c
  117. replaced.append('{%s}%s' % (ns_map[ns], tag))
  118. return '/'.join(replaced)
  119. def xpath_text(node, xpath, name=None, fatal=False):
  120. if sys.version_info < (2, 7): # Crazy 2.6
  121. xpath = xpath.encode('ascii')
  122. n = node.find(xpath)
  123. if n is None:
  124. if fatal:
  125. name = xpath if name is None else name
  126. raise ExtractorError('Could not find XML element %s' % name)
  127. else:
  128. return None
  129. return n.text
  130. def get_element_by_id(id, html):
  131. """Return the content of the tag with the specified ID in the passed HTML document"""
  132. return get_element_by_attribute("id", id, html)
  133. def get_element_by_attribute(attribute, value, html):
  134. """Return the content of the tag with the specified attribute in the passed HTML document"""
  135. m = re.search(r'''(?xs)
  136. <([a-zA-Z0-9:._-]+)
  137. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  138. \s+%s=['"]?%s['"]?
  139. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  140. \s*>
  141. (?P<content>.*?)
  142. </\1>
  143. ''' % (re.escape(attribute), re.escape(value)), html)
  144. if not m:
  145. return None
  146. res = m.group('content')
  147. if res.startswith('"') or res.startswith("'"):
  148. res = res[1:-1]
  149. return unescapeHTML(res)
  150. def clean_html(html):
  151. """Clean an HTML snippet into a readable string"""
  152. # Newline vs <br />
  153. html = html.replace('\n', ' ')
  154. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  155. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  156. # Strip html tags
  157. html = re.sub('<.*?>', '', html)
  158. # Replace html entities
  159. html = unescapeHTML(html)
  160. return html.strip()
  161. def sanitize_open(filename, open_mode):
  162. """Try to open the given filename, and slightly tweak it if this fails.
  163. Attempts to open the given filename. If this fails, it tries to change
  164. the filename slightly, step by step, until it's either able to open it
  165. or it fails and raises a final exception, like the standard open()
  166. function.
  167. It returns the tuple (stream, definitive_file_name).
  168. """
  169. try:
  170. if filename == u'-':
  171. if sys.platform == 'win32':
  172. import msvcrt
  173. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  174. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  175. stream = open(encodeFilename(filename), open_mode)
  176. return (stream, filename)
  177. except (IOError, OSError) as err:
  178. if err.errno in (errno.EACCES,):
  179. raise
  180. # In case of error, try to remove win32 forbidden chars
  181. alt_filename = os.path.join(
  182. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  183. for path_part in os.path.split(filename)
  184. )
  185. if alt_filename == filename:
  186. raise
  187. else:
  188. # An exception here should be caught in the caller
  189. stream = open(encodeFilename(filename), open_mode)
  190. return (stream, alt_filename)
  191. def timeconvert(timestr):
  192. """Convert RFC 2822 defined time string into system timestamp"""
  193. timestamp = None
  194. timetuple = email.utils.parsedate_tz(timestr)
  195. if timetuple is not None:
  196. timestamp = email.utils.mktime_tz(timetuple)
  197. return timestamp
  198. def sanitize_filename(s, restricted=False, is_id=False):
  199. """Sanitizes a string so it could be used as part of a filename.
  200. If restricted is set, use a stricter subset of allowed characters.
  201. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  202. """
  203. def replace_insane(char):
  204. if char == '?' or ord(char) < 32 or ord(char) == 127:
  205. return ''
  206. elif char == '"':
  207. return '' if restricted else '\''
  208. elif char == ':':
  209. return '_-' if restricted else ' -'
  210. elif char in '\\/|*<>':
  211. return '_'
  212. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  213. return '_'
  214. if restricted and ord(char) > 127:
  215. return '_'
  216. return char
  217. result = u''.join(map(replace_insane, s))
  218. if not is_id:
  219. while '__' in result:
  220. result = result.replace('__', '_')
  221. result = result.strip('_')
  222. # Common case of "Foreign band name - English song title"
  223. if restricted and result.startswith('-_'):
  224. result = result[2:]
  225. if not result:
  226. result = '_'
  227. return result
  228. def orderedSet(iterable):
  229. """ Remove all duplicates from the input iterable """
  230. res = []
  231. for el in iterable:
  232. if el not in res:
  233. res.append(el)
  234. return res
  235. def _htmlentity_transform(entity):
  236. """Transforms an HTML entity to a character."""
  237. # Known non-numeric HTML entity
  238. if entity in compat_html_entities.name2codepoint:
  239. return compat_chr(compat_html_entities.name2codepoint[entity])
  240. mobj = re.match(r'#(x?[0-9]+)', entity)
  241. if mobj is not None:
  242. numstr = mobj.group(1)
  243. if numstr.startswith(u'x'):
  244. base = 16
  245. numstr = u'0%s' % numstr
  246. else:
  247. base = 10
  248. return compat_chr(int(numstr, base))
  249. # Unknown entity in name, return its literal representation
  250. return (u'&%s;' % entity)
  251. def unescapeHTML(s):
  252. if s is None:
  253. return None
  254. assert type(s) == compat_str
  255. return re.sub(
  256. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  257. def encodeFilename(s, for_subprocess=False):
  258. """
  259. @param s The name of the file
  260. """
  261. assert type(s) == compat_str
  262. # Python 3 has a Unicode API
  263. if sys.version_info >= (3, 0):
  264. return s
  265. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  266. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  267. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  268. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  269. if not for_subprocess:
  270. return s
  271. else:
  272. # For subprocess calls, encode with locale encoding
  273. # Refer to http://stackoverflow.com/a/9951851/35070
  274. encoding = preferredencoding()
  275. else:
  276. encoding = sys.getfilesystemencoding()
  277. if encoding is None:
  278. encoding = 'utf-8'
  279. return s.encode(encoding, 'ignore')
  280. def encodeArgument(s):
  281. if not isinstance(s, compat_str):
  282. # Legacy code that uses byte strings
  283. # Uncomment the following line after fixing all post processors
  284. #assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  285. s = s.decode('ascii')
  286. return encodeFilename(s, True)
  287. def decodeOption(optval):
  288. if optval is None:
  289. return optval
  290. if isinstance(optval, bytes):
  291. optval = optval.decode(preferredencoding())
  292. assert isinstance(optval, compat_str)
  293. return optval
  294. def formatSeconds(secs):
  295. if secs > 3600:
  296. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  297. elif secs > 60:
  298. return '%d:%02d' % (secs // 60, secs % 60)
  299. else:
  300. return '%d' % secs
  301. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  302. if sys.version_info < (3, 2):
  303. import httplib
  304. class HTTPSConnectionV3(httplib.HTTPSConnection):
  305. def __init__(self, *args, **kwargs):
  306. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  307. def connect(self):
  308. sock = socket.create_connection((self.host, self.port), self.timeout)
  309. if getattr(self, '_tunnel_host', False):
  310. self.sock = sock
  311. self._tunnel()
  312. try:
  313. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  314. except ssl.SSLError:
  315. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  316. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  317. def https_open(self, req):
  318. return self.do_open(HTTPSConnectionV3, req)
  319. return HTTPSHandlerV3(**kwargs)
  320. elif hasattr(ssl, 'create_default_context'): # Python >= 3.4
  321. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  322. context.options &= ~ssl.OP_NO_SSLv3 # Allow older, not-as-secure SSLv3
  323. if opts_no_check_certificate:
  324. context.verify_mode = ssl.CERT_NONE
  325. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  326. else: # Python < 3.4
  327. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  328. context.verify_mode = (ssl.CERT_NONE
  329. if opts_no_check_certificate
  330. else ssl.CERT_REQUIRED)
  331. context.set_default_verify_paths()
  332. try:
  333. context.load_default_certs()
  334. except AttributeError:
  335. pass # Python < 3.4
  336. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  337. class ExtractorError(Exception):
  338. """Error during info extraction."""
  339. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  340. """ tb, if given, is the original traceback (so that it can be printed out).
  341. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  342. """
  343. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  344. expected = True
  345. if video_id is not None:
  346. msg = video_id + ': ' + msg
  347. if cause:
  348. msg += u' (caused by %r)' % cause
  349. if not expected:
  350. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  351. super(ExtractorError, self).__init__(msg)
  352. self.traceback = tb
  353. self.exc_info = sys.exc_info() # preserve original exception
  354. self.cause = cause
  355. self.video_id = video_id
  356. def format_traceback(self):
  357. if self.traceback is None:
  358. return None
  359. return u''.join(traceback.format_tb(self.traceback))
  360. class RegexNotFoundError(ExtractorError):
  361. """Error when a regex didn't match"""
  362. pass
  363. class DownloadError(Exception):
  364. """Download Error exception.
  365. This exception may be thrown by FileDownloader objects if they are not
  366. configured to continue on errors. They will contain the appropriate
  367. error message.
  368. """
  369. def __init__(self, msg, exc_info=None):
  370. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  371. super(DownloadError, self).__init__(msg)
  372. self.exc_info = exc_info
  373. class SameFileError(Exception):
  374. """Same File exception.
  375. This exception will be thrown by FileDownloader objects if they detect
  376. multiple files would have to be downloaded to the same file on disk.
  377. """
  378. pass
  379. class PostProcessingError(Exception):
  380. """Post Processing exception.
  381. This exception may be raised by PostProcessor's .run() method to
  382. indicate an error in the postprocessing task.
  383. """
  384. def __init__(self, msg):
  385. self.msg = msg
  386. class MaxDownloadsReached(Exception):
  387. """ --max-downloads limit has been reached. """
  388. pass
  389. class UnavailableVideoError(Exception):
  390. """Unavailable Format exception.
  391. This exception will be thrown when a video is requested
  392. in a format that is not available for that video.
  393. """
  394. pass
  395. class ContentTooShortError(Exception):
  396. """Content Too Short exception.
  397. This exception may be raised by FileDownloader objects when a file they
  398. download is too small for what the server announced first, indicating
  399. the connection was probably interrupted.
  400. """
  401. # Both in bytes
  402. downloaded = None
  403. expected = None
  404. def __init__(self, downloaded, expected):
  405. self.downloaded = downloaded
  406. self.expected = expected
  407. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  408. """Handler for HTTP requests and responses.
  409. This class, when installed with an OpenerDirector, automatically adds
  410. the standard headers to every HTTP request and handles gzipped and
  411. deflated responses from web servers. If compression is to be avoided in
  412. a particular request, the original request in the program code only has
  413. to include the HTTP header "Youtubedl-No-Compression", which will be
  414. removed before making the real request.
  415. Part of this code was copied from:
  416. http://techknack.net/python-urllib2-handlers/
  417. Andrew Rowls, the author of that code, agreed to release it to the
  418. public domain.
  419. """
  420. @staticmethod
  421. def deflate(data):
  422. try:
  423. return zlib.decompress(data, -zlib.MAX_WBITS)
  424. except zlib.error:
  425. return zlib.decompress(data)
  426. @staticmethod
  427. def addinfourl_wrapper(stream, headers, url, code):
  428. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  429. return compat_urllib_request.addinfourl(stream, headers, url, code)
  430. ret = compat_urllib_request.addinfourl(stream, headers, url)
  431. ret.code = code
  432. return ret
  433. def http_request(self, req):
  434. for h, v in std_headers.items():
  435. if h not in req.headers:
  436. req.add_header(h, v)
  437. if 'Youtubedl-no-compression' in req.headers:
  438. if 'Accept-encoding' in req.headers:
  439. del req.headers['Accept-encoding']
  440. del req.headers['Youtubedl-no-compression']
  441. if 'Youtubedl-user-agent' in req.headers:
  442. if 'User-agent' in req.headers:
  443. del req.headers['User-agent']
  444. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  445. del req.headers['Youtubedl-user-agent']
  446. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  447. # Python 2.6 is brain-dead when it comes to fragments
  448. req._Request__original = req._Request__original.partition('#')[0]
  449. req._Request__r_type = req._Request__r_type.partition('#')[0]
  450. return req
  451. def http_response(self, req, resp):
  452. old_resp = resp
  453. # gzip
  454. if resp.headers.get('Content-encoding', '') == 'gzip':
  455. content = resp.read()
  456. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  457. try:
  458. uncompressed = io.BytesIO(gz.read())
  459. except IOError as original_ioerror:
  460. # There may be junk add the end of the file
  461. # See http://stackoverflow.com/q/4928560/35070 for details
  462. for i in range(1, 1024):
  463. try:
  464. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  465. uncompressed = io.BytesIO(gz.read())
  466. except IOError:
  467. continue
  468. break
  469. else:
  470. raise original_ioerror
  471. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  472. resp.msg = old_resp.msg
  473. # deflate
  474. if resp.headers.get('Content-encoding', '') == 'deflate':
  475. gz = io.BytesIO(self.deflate(resp.read()))
  476. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  477. resp.msg = old_resp.msg
  478. return resp
  479. https_request = http_request
  480. https_response = http_response
  481. def parse_iso8601(date_str, delimiter='T'):
  482. """ Return a UNIX timestamp from the given date """
  483. if date_str is None:
  484. return None
  485. m = re.search(
  486. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  487. date_str)
  488. if not m:
  489. timezone = datetime.timedelta()
  490. else:
  491. date_str = date_str[:-len(m.group(0))]
  492. if not m.group('sign'):
  493. timezone = datetime.timedelta()
  494. else:
  495. sign = 1 if m.group('sign') == '+' else -1
  496. timezone = datetime.timedelta(
  497. hours=sign * int(m.group('hours')),
  498. minutes=sign * int(m.group('minutes')))
  499. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  500. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  501. return calendar.timegm(dt.timetuple())
  502. def unified_strdate(date_str):
  503. """Return a string with the date in the format YYYYMMDD"""
  504. if date_str is None:
  505. return None
  506. upload_date = None
  507. #Replace commas
  508. date_str = date_str.replace(',', ' ')
  509. # %z (UTC offset) is only supported in python>=3.2
  510. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  511. format_expressions = [
  512. '%d %B %Y',
  513. '%d %b %Y',
  514. '%B %d %Y',
  515. '%b %d %Y',
  516. '%b %dst %Y %I:%M%p',
  517. '%b %dnd %Y %I:%M%p',
  518. '%b %dth %Y %I:%M%p',
  519. '%Y-%m-%d',
  520. '%Y/%m/%d',
  521. '%d.%m.%Y',
  522. '%d/%m/%Y',
  523. '%d/%m/%y',
  524. '%Y/%m/%d %H:%M:%S',
  525. '%d/%m/%Y %H:%M:%S',
  526. '%Y-%m-%d %H:%M:%S',
  527. '%Y-%m-%d %H:%M:%S.%f',
  528. '%d.%m.%Y %H:%M',
  529. '%d.%m.%Y %H.%M',
  530. '%Y-%m-%dT%H:%M:%SZ',
  531. '%Y-%m-%dT%H:%M:%S.%fZ',
  532. '%Y-%m-%dT%H:%M:%S.%f0Z',
  533. '%Y-%m-%dT%H:%M:%S',
  534. '%Y-%m-%dT%H:%M:%S.%f',
  535. '%Y-%m-%dT%H:%M',
  536. ]
  537. for expression in format_expressions:
  538. try:
  539. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  540. except ValueError:
  541. pass
  542. if upload_date is None:
  543. timetuple = email.utils.parsedate_tz(date_str)
  544. if timetuple:
  545. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  546. return upload_date
  547. def determine_ext(url, default_ext=u'unknown_video'):
  548. if url is None:
  549. return default_ext
  550. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  551. if re.match(r'^[A-Za-z0-9]+$', guess):
  552. return guess
  553. else:
  554. return default_ext
  555. def subtitles_filename(filename, sub_lang, sub_format):
  556. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  557. def date_from_str(date_str):
  558. """
  559. Return a datetime object from a string in the format YYYYMMDD or
  560. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  561. today = datetime.date.today()
  562. if date_str == 'now'or date_str == 'today':
  563. return today
  564. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  565. if match is not None:
  566. sign = match.group('sign')
  567. time = int(match.group('time'))
  568. if sign == '-':
  569. time = -time
  570. unit = match.group('unit')
  571. #A bad aproximation?
  572. if unit == 'month':
  573. unit = 'day'
  574. time *= 30
  575. elif unit == 'year':
  576. unit = 'day'
  577. time *= 365
  578. unit += 's'
  579. delta = datetime.timedelta(**{unit: time})
  580. return today + delta
  581. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  582. def hyphenate_date(date_str):
  583. """
  584. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  585. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  586. if match is not None:
  587. return '-'.join(match.groups())
  588. else:
  589. return date_str
  590. class DateRange(object):
  591. """Represents a time interval between two dates"""
  592. def __init__(self, start=None, end=None):
  593. """start and end must be strings in the format accepted by date"""
  594. if start is not None:
  595. self.start = date_from_str(start)
  596. else:
  597. self.start = datetime.datetime.min.date()
  598. if end is not None:
  599. self.end = date_from_str(end)
  600. else:
  601. self.end = datetime.datetime.max.date()
  602. if self.start > self.end:
  603. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  604. @classmethod
  605. def day(cls, day):
  606. """Returns a range that only contains the given day"""
  607. return cls(day,day)
  608. def __contains__(self, date):
  609. """Check if the date is in the range"""
  610. if not isinstance(date, datetime.date):
  611. date = date_from_str(date)
  612. return self.start <= date <= self.end
  613. def __str__(self):
  614. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  615. def platform_name():
  616. """ Returns the platform name as a compat_str """
  617. res = platform.platform()
  618. if isinstance(res, bytes):
  619. res = res.decode(preferredencoding())
  620. assert isinstance(res, compat_str)
  621. return res
  622. def _windows_write_string(s, out):
  623. """ Returns True if the string was written using special methods,
  624. False if it has yet to be written out."""
  625. # Adapted from http://stackoverflow.com/a/3259271/35070
  626. import ctypes
  627. import ctypes.wintypes
  628. WIN_OUTPUT_IDS = {
  629. 1: -11,
  630. 2: -12,
  631. }
  632. try:
  633. fileno = out.fileno()
  634. except AttributeError:
  635. # If the output stream doesn't have a fileno, it's virtual
  636. return False
  637. if fileno not in WIN_OUTPUT_IDS:
  638. return False
  639. GetStdHandle = ctypes.WINFUNCTYPE(
  640. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  641. ("GetStdHandle", ctypes.windll.kernel32))
  642. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  643. WriteConsoleW = ctypes.WINFUNCTYPE(
  644. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  645. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  646. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  647. written = ctypes.wintypes.DWORD(0)
  648. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  649. FILE_TYPE_CHAR = 0x0002
  650. FILE_TYPE_REMOTE = 0x8000
  651. GetConsoleMode = ctypes.WINFUNCTYPE(
  652. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  653. ctypes.POINTER(ctypes.wintypes.DWORD))(
  654. ("GetConsoleMode", ctypes.windll.kernel32))
  655. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  656. def not_a_console(handle):
  657. if handle == INVALID_HANDLE_VALUE or handle is None:
  658. return True
  659. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  660. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  661. if not_a_console(h):
  662. return False
  663. def next_nonbmp_pos(s):
  664. try:
  665. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  666. except StopIteration:
  667. return len(s)
  668. while s:
  669. count = min(next_nonbmp_pos(s), 1024)
  670. ret = WriteConsoleW(
  671. h, s, count if count else 2, ctypes.byref(written), None)
  672. if ret == 0:
  673. raise OSError('Failed to write string')
  674. if not count: # We just wrote a non-BMP character
  675. assert written.value == 2
  676. s = s[1:]
  677. else:
  678. assert written.value > 0
  679. s = s[written.value:]
  680. return True
  681. def write_string(s, out=None, encoding=None):
  682. if out is None:
  683. out = sys.stderr
  684. assert type(s) == compat_str
  685. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  686. if _windows_write_string(s, out):
  687. return
  688. if ('b' in getattr(out, 'mode', '') or
  689. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  690. byt = s.encode(encoding or preferredencoding(), 'ignore')
  691. out.write(byt)
  692. elif hasattr(out, 'buffer'):
  693. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  694. byt = s.encode(enc, 'ignore')
  695. out.buffer.write(byt)
  696. else:
  697. out.write(s)
  698. out.flush()
  699. def bytes_to_intlist(bs):
  700. if not bs:
  701. return []
  702. if isinstance(bs[0], int): # Python 3
  703. return list(bs)
  704. else:
  705. return [ord(c) for c in bs]
  706. def intlist_to_bytes(xs):
  707. if not xs:
  708. return b''
  709. return struct.pack('%dB' % len(xs), *xs)
  710. # Cross-platform file locking
  711. if sys.platform == 'win32':
  712. import ctypes.wintypes
  713. import msvcrt
  714. class OVERLAPPED(ctypes.Structure):
  715. _fields_ = [
  716. ('Internal', ctypes.wintypes.LPVOID),
  717. ('InternalHigh', ctypes.wintypes.LPVOID),
  718. ('Offset', ctypes.wintypes.DWORD),
  719. ('OffsetHigh', ctypes.wintypes.DWORD),
  720. ('hEvent', ctypes.wintypes.HANDLE),
  721. ]
  722. kernel32 = ctypes.windll.kernel32
  723. LockFileEx = kernel32.LockFileEx
  724. LockFileEx.argtypes = [
  725. ctypes.wintypes.HANDLE, # hFile
  726. ctypes.wintypes.DWORD, # dwFlags
  727. ctypes.wintypes.DWORD, # dwReserved
  728. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  729. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  730. ctypes.POINTER(OVERLAPPED) # Overlapped
  731. ]
  732. LockFileEx.restype = ctypes.wintypes.BOOL
  733. UnlockFileEx = kernel32.UnlockFileEx
  734. UnlockFileEx.argtypes = [
  735. ctypes.wintypes.HANDLE, # hFile
  736. ctypes.wintypes.DWORD, # dwReserved
  737. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  738. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  739. ctypes.POINTER(OVERLAPPED) # Overlapped
  740. ]
  741. UnlockFileEx.restype = ctypes.wintypes.BOOL
  742. whole_low = 0xffffffff
  743. whole_high = 0x7fffffff
  744. def _lock_file(f, exclusive):
  745. overlapped = OVERLAPPED()
  746. overlapped.Offset = 0
  747. overlapped.OffsetHigh = 0
  748. overlapped.hEvent = 0
  749. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  750. handle = msvcrt.get_osfhandle(f.fileno())
  751. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  752. whole_low, whole_high, f._lock_file_overlapped_p):
  753. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  754. def _unlock_file(f):
  755. assert f._lock_file_overlapped_p
  756. handle = msvcrt.get_osfhandle(f.fileno())
  757. if not UnlockFileEx(handle, 0,
  758. whole_low, whole_high, f._lock_file_overlapped_p):
  759. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  760. else:
  761. import fcntl
  762. def _lock_file(f, exclusive):
  763. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  764. def _unlock_file(f):
  765. fcntl.flock(f, fcntl.LOCK_UN)
  766. class locked_file(object):
  767. def __init__(self, filename, mode, encoding=None):
  768. assert mode in ['r', 'a', 'w']
  769. self.f = io.open(filename, mode, encoding=encoding)
  770. self.mode = mode
  771. def __enter__(self):
  772. exclusive = self.mode != 'r'
  773. try:
  774. _lock_file(self.f, exclusive)
  775. except IOError:
  776. self.f.close()
  777. raise
  778. return self
  779. def __exit__(self, etype, value, traceback):
  780. try:
  781. _unlock_file(self.f)
  782. finally:
  783. self.f.close()
  784. def __iter__(self):
  785. return iter(self.f)
  786. def write(self, *args):
  787. return self.f.write(*args)
  788. def read(self, *args):
  789. return self.f.read(*args)
  790. def get_filesystem_encoding():
  791. encoding = sys.getfilesystemencoding()
  792. return encoding if encoding is not None else 'utf-8'
  793. def shell_quote(args):
  794. quoted_args = []
  795. encoding = get_filesystem_encoding()
  796. for a in args:
  797. if isinstance(a, bytes):
  798. # We may get a filename encoded with 'encodeFilename'
  799. a = a.decode(encoding)
  800. quoted_args.append(pipes.quote(a))
  801. return u' '.join(quoted_args)
  802. def takewhile_inclusive(pred, seq):
  803. """ Like itertools.takewhile, but include the latest evaluated element
  804. (the first element so that Not pred(e)) """
  805. for e in seq:
  806. yield e
  807. if not pred(e):
  808. return
  809. def smuggle_url(url, data):
  810. """ Pass additional data in a URL for internal use. """
  811. sdata = compat_urllib_parse.urlencode(
  812. {u'__youtubedl_smuggle': json.dumps(data)})
  813. return url + u'#' + sdata
  814. def unsmuggle_url(smug_url, default=None):
  815. if not '#__youtubedl_smuggle' in smug_url:
  816. return smug_url, default
  817. url, _, sdata = smug_url.rpartition(u'#')
  818. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  819. data = json.loads(jsond)
  820. return url, data
  821. def format_bytes(bytes):
  822. if bytes is None:
  823. return u'N/A'
  824. if type(bytes) is str:
  825. bytes = float(bytes)
  826. if bytes == 0.0:
  827. exponent = 0
  828. else:
  829. exponent = int(math.log(bytes, 1024.0))
  830. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  831. converted = float(bytes) / float(1024 ** exponent)
  832. return u'%.2f%s' % (converted, suffix)
  833. def get_term_width():
  834. columns = compat_getenv('COLUMNS', None)
  835. if columns:
  836. return int(columns)
  837. try:
  838. sp = subprocess.Popen(
  839. ['stty', 'size'],
  840. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  841. out, err = sp.communicate()
  842. return int(out.split()[1])
  843. except:
  844. pass
  845. return None
  846. def month_by_name(name):
  847. """ Return the number of a month by (locale-independently) English name """
  848. ENGLISH_NAMES = [
  849. u'January', u'February', u'March', u'April', u'May', u'June',
  850. u'July', u'August', u'September', u'October', u'November', u'December']
  851. try:
  852. return ENGLISH_NAMES.index(name) + 1
  853. except ValueError:
  854. return None
  855. def fix_xml_ampersands(xml_str):
  856. """Replace all the '&' by '&amp;' in XML"""
  857. return re.sub(
  858. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  859. u'&amp;',
  860. xml_str)
  861. def setproctitle(title):
  862. assert isinstance(title, compat_str)
  863. try:
  864. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  865. except OSError:
  866. return
  867. title_bytes = title.encode('utf-8')
  868. buf = ctypes.create_string_buffer(len(title_bytes))
  869. buf.value = title_bytes
  870. try:
  871. libc.prctl(15, buf, 0, 0, 0)
  872. except AttributeError:
  873. return # Strange libc, just skip this
  874. def remove_start(s, start):
  875. if s.startswith(start):
  876. return s[len(start):]
  877. return s
  878. def remove_end(s, end):
  879. if s.endswith(end):
  880. return s[:-len(end)]
  881. return s
  882. def url_basename(url):
  883. path = compat_urlparse.urlparse(url).path
  884. return path.strip(u'/').split(u'/')[-1]
  885. class HEADRequest(compat_urllib_request.Request):
  886. def get_method(self):
  887. return "HEAD"
  888. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  889. if get_attr:
  890. if v is not None:
  891. v = getattr(v, get_attr, None)
  892. if v == '':
  893. v = None
  894. return default if v is None else (int(v) * invscale // scale)
  895. def str_or_none(v, default=None):
  896. return default if v is None else compat_str(v)
  897. def str_to_int(int_str):
  898. """ A more relaxed version of int_or_none """
  899. if int_str is None:
  900. return None
  901. int_str = re.sub(r'[,\.\+]', u'', int_str)
  902. return int(int_str)
  903. def float_or_none(v, scale=1, invscale=1, default=None):
  904. return default if v is None else (float(v) * invscale / scale)
  905. def parse_duration(s):
  906. if s is None:
  907. return None
  908. s = s.strip()
  909. m = re.match(
  910. r'(?i)(?:(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$', s)
  911. if not m:
  912. return None
  913. res = int(m.group('secs'))
  914. if m.group('mins'):
  915. res += int(m.group('mins')) * 60
  916. if m.group('hours'):
  917. res += int(m.group('hours')) * 60 * 60
  918. if m.group('ms'):
  919. res += float(m.group('ms'))
  920. return res
  921. def prepend_extension(filename, ext):
  922. name, real_ext = os.path.splitext(filename)
  923. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  924. def check_executable(exe, args=[]):
  925. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  926. args can be a list of arguments for a short output (like -version) """
  927. try:
  928. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  929. except OSError:
  930. return False
  931. return exe
  932. def get_exe_version(exe, args=['--version'],
  933. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  934. unrecognized=u'present'):
  935. """ Returns the version of the specified executable,
  936. or False if the executable is not present """
  937. try:
  938. out, err = subprocess.Popen(
  939. [exe] + args,
  940. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  941. except OSError:
  942. return False
  943. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  944. m = re.search(version_re, firstline)
  945. if m:
  946. return m.group(1)
  947. else:
  948. return unrecognized
  949. class PagedList(object):
  950. def __len__(self):
  951. # This is only useful for tests
  952. return len(self.getslice())
  953. class OnDemandPagedList(PagedList):
  954. def __init__(self, pagefunc, pagesize):
  955. self._pagefunc = pagefunc
  956. self._pagesize = pagesize
  957. def getslice(self, start=0, end=None):
  958. res = []
  959. for pagenum in itertools.count(start // self._pagesize):
  960. firstid = pagenum * self._pagesize
  961. nextfirstid = pagenum * self._pagesize + self._pagesize
  962. if start >= nextfirstid:
  963. continue
  964. page_results = list(self._pagefunc(pagenum))
  965. startv = (
  966. start % self._pagesize
  967. if firstid <= start < nextfirstid
  968. else 0)
  969. endv = (
  970. ((end - 1) % self._pagesize) + 1
  971. if (end is not None and firstid <= end <= nextfirstid)
  972. else None)
  973. if startv != 0 or endv is not None:
  974. page_results = page_results[startv:endv]
  975. res.extend(page_results)
  976. # A little optimization - if current page is not "full", ie. does
  977. # not contain page_size videos then we can assume that this page
  978. # is the last one - there are no more ids on further pages -
  979. # i.e. no need to query again.
  980. if len(page_results) + startv < self._pagesize:
  981. break
  982. # If we got the whole page, but the next page is not interesting,
  983. # break out early as well
  984. if end == nextfirstid:
  985. break
  986. return res
  987. class InAdvancePagedList(PagedList):
  988. def __init__(self, pagefunc, pagecount, pagesize):
  989. self._pagefunc = pagefunc
  990. self._pagecount = pagecount
  991. self._pagesize = pagesize
  992. def getslice(self, start=0, end=None):
  993. res = []
  994. start_page = start // self._pagesize
  995. end_page = (
  996. self._pagecount if end is None else (end // self._pagesize + 1))
  997. skip_elems = start - start_page * self._pagesize
  998. only_more = None if end is None else end - start
  999. for pagenum in range(start_page, end_page):
  1000. page = list(self._pagefunc(pagenum))
  1001. if skip_elems:
  1002. page = page[skip_elems:]
  1003. skip_elems = None
  1004. if only_more is not None:
  1005. if len(page) < only_more:
  1006. only_more -= len(page)
  1007. else:
  1008. page = page[:only_more]
  1009. res.extend(page)
  1010. break
  1011. res.extend(page)
  1012. return res
  1013. def uppercase_escape(s):
  1014. unicode_escape = codecs.getdecoder('unicode_escape')
  1015. return re.sub(
  1016. r'\\U[0-9a-fA-F]{8}',
  1017. lambda m: unicode_escape(m.group(0))[0],
  1018. s)
  1019. def escape_rfc3986(s):
  1020. """Escape non-ASCII characters as suggested by RFC 3986"""
  1021. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1022. s = s.encode('utf-8')
  1023. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1024. def escape_url(url):
  1025. """Escape URL as suggested by RFC 3986"""
  1026. url_parsed = compat_urllib_parse_urlparse(url)
  1027. return url_parsed._replace(
  1028. path=escape_rfc3986(url_parsed.path),
  1029. params=escape_rfc3986(url_parsed.params),
  1030. query=escape_rfc3986(url_parsed.query),
  1031. fragment=escape_rfc3986(url_parsed.fragment)
  1032. ).geturl()
  1033. try:
  1034. struct.pack(u'!I', 0)
  1035. except TypeError:
  1036. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1037. def struct_pack(spec, *args):
  1038. if isinstance(spec, compat_str):
  1039. spec = spec.encode('ascii')
  1040. return struct.pack(spec, *args)
  1041. def struct_unpack(spec, *args):
  1042. if isinstance(spec, compat_str):
  1043. spec = spec.encode('ascii')
  1044. return struct.unpack(spec, *args)
  1045. else:
  1046. struct_pack = struct.pack
  1047. struct_unpack = struct.unpack
  1048. def read_batch_urls(batch_fd):
  1049. def fixup(url):
  1050. if not isinstance(url, compat_str):
  1051. url = url.decode('utf-8', 'replace')
  1052. BOM_UTF8 = u'\xef\xbb\xbf'
  1053. if url.startswith(BOM_UTF8):
  1054. url = url[len(BOM_UTF8):]
  1055. url = url.strip()
  1056. if url.startswith(('#', ';', ']')):
  1057. return False
  1058. return url
  1059. with contextlib.closing(batch_fd) as fd:
  1060. return [url for url in map(fixup, fd) if url]
  1061. def urlencode_postdata(*args, **kargs):
  1062. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1063. try:
  1064. etree_iter = xml.etree.ElementTree.Element.iter
  1065. except AttributeError: # Python <=2.6
  1066. etree_iter = lambda n: n.findall('.//*')
  1067. def parse_xml(s):
  1068. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1069. def doctype(self, name, pubid, system):
  1070. pass # Ignore doctypes
  1071. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1072. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1073. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1074. # Fix up XML parser in Python 2.x
  1075. if sys.version_info < (3, 0):
  1076. for n in etree_iter(tree):
  1077. if n.text is not None:
  1078. if not isinstance(n.text, compat_str):
  1079. n.text = n.text.decode('utf-8')
  1080. return tree
  1081. US_RATINGS = {
  1082. 'G': 0,
  1083. 'PG': 10,
  1084. 'PG-13': 13,
  1085. 'R': 16,
  1086. 'NC': 18,
  1087. }
  1088. def parse_age_limit(s):
  1089. if s is None:
  1090. return None
  1091. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1092. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1093. def strip_jsonp(code):
  1094. return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
  1095. def js_to_json(code):
  1096. def fix_kv(m):
  1097. v = m.group(0)
  1098. if v in ('true', 'false', 'null'):
  1099. return v
  1100. if v.startswith('"'):
  1101. return v
  1102. if v.startswith("'"):
  1103. v = v[1:-1]
  1104. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1105. '\\\\': '\\\\',
  1106. "\\'": "'",
  1107. '"': '\\"',
  1108. }[m.group(0)], v)
  1109. return '"%s"' % v
  1110. res = re.sub(r'''(?x)
  1111. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1112. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1113. [a-zA-Z_][a-zA-Z_0-9]*
  1114. ''', fix_kv, code)
  1115. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1116. return res
  1117. def qualities(quality_ids):
  1118. """ Get a numeric quality value out of a list of possible values """
  1119. def q(qid):
  1120. try:
  1121. return quality_ids.index(qid)
  1122. except ValueError:
  1123. return -1
  1124. return q
  1125. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1126. def limit_length(s, length):
  1127. """ Add ellipses to overly long strings """
  1128. if s is None:
  1129. return None
  1130. ELLIPSES = '...'
  1131. if len(s) > length:
  1132. return s[:length - len(ELLIPSES)] + ELLIPSES
  1133. return s
  1134. def version_tuple(v):
  1135. return [int(e) for e in v.split('.')]
  1136. def is_outdated_version(version, limit, assume_new=True):
  1137. if not version:
  1138. return not assume_new
  1139. try:
  1140. return version_tuple(version) < version_tuple(limit)
  1141. except ValueError:
  1142. return not assume_new