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.

1398 lines
43 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. if isinstance(chr(0), bytes): # Python 2
  710. return ''.join([chr(x) for x in xs])
  711. else:
  712. return bytes(xs)
  713. # Cross-platform file locking
  714. if sys.platform == 'win32':
  715. import ctypes.wintypes
  716. import msvcrt
  717. class OVERLAPPED(ctypes.Structure):
  718. _fields_ = [
  719. ('Internal', ctypes.wintypes.LPVOID),
  720. ('InternalHigh', ctypes.wintypes.LPVOID),
  721. ('Offset', ctypes.wintypes.DWORD),
  722. ('OffsetHigh', ctypes.wintypes.DWORD),
  723. ('hEvent', ctypes.wintypes.HANDLE),
  724. ]
  725. kernel32 = ctypes.windll.kernel32
  726. LockFileEx = kernel32.LockFileEx
  727. LockFileEx.argtypes = [
  728. ctypes.wintypes.HANDLE, # hFile
  729. ctypes.wintypes.DWORD, # dwFlags
  730. ctypes.wintypes.DWORD, # dwReserved
  731. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  732. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  733. ctypes.POINTER(OVERLAPPED) # Overlapped
  734. ]
  735. LockFileEx.restype = ctypes.wintypes.BOOL
  736. UnlockFileEx = kernel32.UnlockFileEx
  737. UnlockFileEx.argtypes = [
  738. ctypes.wintypes.HANDLE, # hFile
  739. ctypes.wintypes.DWORD, # dwReserved
  740. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  741. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  742. ctypes.POINTER(OVERLAPPED) # Overlapped
  743. ]
  744. UnlockFileEx.restype = ctypes.wintypes.BOOL
  745. whole_low = 0xffffffff
  746. whole_high = 0x7fffffff
  747. def _lock_file(f, exclusive):
  748. overlapped = OVERLAPPED()
  749. overlapped.Offset = 0
  750. overlapped.OffsetHigh = 0
  751. overlapped.hEvent = 0
  752. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  753. handle = msvcrt.get_osfhandle(f.fileno())
  754. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  755. whole_low, whole_high, f._lock_file_overlapped_p):
  756. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  757. def _unlock_file(f):
  758. assert f._lock_file_overlapped_p
  759. handle = msvcrt.get_osfhandle(f.fileno())
  760. if not UnlockFileEx(handle, 0,
  761. whole_low, whole_high, f._lock_file_overlapped_p):
  762. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  763. else:
  764. import fcntl
  765. def _lock_file(f, exclusive):
  766. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  767. def _unlock_file(f):
  768. fcntl.flock(f, fcntl.LOCK_UN)
  769. class locked_file(object):
  770. def __init__(self, filename, mode, encoding=None):
  771. assert mode in ['r', 'a', 'w']
  772. self.f = io.open(filename, mode, encoding=encoding)
  773. self.mode = mode
  774. def __enter__(self):
  775. exclusive = self.mode != 'r'
  776. try:
  777. _lock_file(self.f, exclusive)
  778. except IOError:
  779. self.f.close()
  780. raise
  781. return self
  782. def __exit__(self, etype, value, traceback):
  783. try:
  784. _unlock_file(self.f)
  785. finally:
  786. self.f.close()
  787. def __iter__(self):
  788. return iter(self.f)
  789. def write(self, *args):
  790. return self.f.write(*args)
  791. def read(self, *args):
  792. return self.f.read(*args)
  793. def get_filesystem_encoding():
  794. encoding = sys.getfilesystemencoding()
  795. return encoding if encoding is not None else 'utf-8'
  796. def shell_quote(args):
  797. quoted_args = []
  798. encoding = get_filesystem_encoding()
  799. for a in args:
  800. if isinstance(a, bytes):
  801. # We may get a filename encoded with 'encodeFilename'
  802. a = a.decode(encoding)
  803. quoted_args.append(pipes.quote(a))
  804. return u' '.join(quoted_args)
  805. def takewhile_inclusive(pred, seq):
  806. """ Like itertools.takewhile, but include the latest evaluated element
  807. (the first element so that Not pred(e)) """
  808. for e in seq:
  809. yield e
  810. if not pred(e):
  811. return
  812. def smuggle_url(url, data):
  813. """ Pass additional data in a URL for internal use. """
  814. sdata = compat_urllib_parse.urlencode(
  815. {u'__youtubedl_smuggle': json.dumps(data)})
  816. return url + u'#' + sdata
  817. def unsmuggle_url(smug_url, default=None):
  818. if not '#__youtubedl_smuggle' in smug_url:
  819. return smug_url, default
  820. url, _, sdata = smug_url.rpartition(u'#')
  821. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  822. data = json.loads(jsond)
  823. return url, data
  824. def format_bytes(bytes):
  825. if bytes is None:
  826. return u'N/A'
  827. if type(bytes) is str:
  828. bytes = float(bytes)
  829. if bytes == 0.0:
  830. exponent = 0
  831. else:
  832. exponent = int(math.log(bytes, 1024.0))
  833. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  834. converted = float(bytes) / float(1024 ** exponent)
  835. return u'%.2f%s' % (converted, suffix)
  836. def get_term_width():
  837. columns = compat_getenv('COLUMNS', None)
  838. if columns:
  839. return int(columns)
  840. try:
  841. sp = subprocess.Popen(
  842. ['stty', 'size'],
  843. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  844. out, err = sp.communicate()
  845. return int(out.split()[1])
  846. except:
  847. pass
  848. return None
  849. def month_by_name(name):
  850. """ Return the number of a month by (locale-independently) English name """
  851. ENGLISH_NAMES = [
  852. u'January', u'February', u'March', u'April', u'May', u'June',
  853. u'July', u'August', u'September', u'October', u'November', u'December']
  854. try:
  855. return ENGLISH_NAMES.index(name) + 1
  856. except ValueError:
  857. return None
  858. def fix_xml_ampersands(xml_str):
  859. """Replace all the '&' by '&amp;' in XML"""
  860. return re.sub(
  861. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  862. u'&amp;',
  863. xml_str)
  864. def setproctitle(title):
  865. assert isinstance(title, compat_str)
  866. try:
  867. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  868. except OSError:
  869. return
  870. title_bytes = title.encode('utf-8')
  871. buf = ctypes.create_string_buffer(len(title_bytes))
  872. buf.value = title_bytes
  873. try:
  874. libc.prctl(15, buf, 0, 0, 0)
  875. except AttributeError:
  876. return # Strange libc, just skip this
  877. def remove_start(s, start):
  878. if s.startswith(start):
  879. return s[len(start):]
  880. return s
  881. def remove_end(s, end):
  882. if s.endswith(end):
  883. return s[:-len(end)]
  884. return s
  885. def url_basename(url):
  886. path = compat_urlparse.urlparse(url).path
  887. return path.strip(u'/').split(u'/')[-1]
  888. class HEADRequest(compat_urllib_request.Request):
  889. def get_method(self):
  890. return "HEAD"
  891. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  892. if get_attr:
  893. if v is not None:
  894. v = getattr(v, get_attr, None)
  895. if v == '':
  896. v = None
  897. return default if v is None else (int(v) * invscale // scale)
  898. def str_or_none(v, default=None):
  899. return default if v is None else compat_str(v)
  900. def str_to_int(int_str):
  901. """ A more relaxed version of int_or_none """
  902. if int_str is None:
  903. return None
  904. int_str = re.sub(r'[,\.\+]', u'', int_str)
  905. return int(int_str)
  906. def float_or_none(v, scale=1, invscale=1, default=None):
  907. return default if v is None else (float(v) * invscale / scale)
  908. def parse_duration(s):
  909. if s is None:
  910. return None
  911. s = s.strip()
  912. m = re.match(
  913. 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)
  914. if not m:
  915. return None
  916. res = int(m.group('secs'))
  917. if m.group('mins'):
  918. res += int(m.group('mins')) * 60
  919. if m.group('hours'):
  920. res += int(m.group('hours')) * 60 * 60
  921. if m.group('ms'):
  922. res += float(m.group('ms'))
  923. return res
  924. def prepend_extension(filename, ext):
  925. name, real_ext = os.path.splitext(filename)
  926. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  927. def check_executable(exe, args=[]):
  928. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  929. args can be a list of arguments for a short output (like -version) """
  930. try:
  931. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  932. except OSError:
  933. return False
  934. return exe
  935. def get_exe_version(exe, args=['--version'],
  936. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  937. unrecognized=u'present'):
  938. """ Returns the version of the specified executable,
  939. or False if the executable is not present """
  940. try:
  941. out, err = subprocess.Popen(
  942. [exe] + args,
  943. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  944. except OSError:
  945. return False
  946. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  947. m = re.search(version_re, firstline)
  948. if m:
  949. return m.group(1)
  950. else:
  951. return unrecognized
  952. class PagedList(object):
  953. def __len__(self):
  954. # This is only useful for tests
  955. return len(self.getslice())
  956. class OnDemandPagedList(PagedList):
  957. def __init__(self, pagefunc, pagesize):
  958. self._pagefunc = pagefunc
  959. self._pagesize = pagesize
  960. def getslice(self, start=0, end=None):
  961. res = []
  962. for pagenum in itertools.count(start // self._pagesize):
  963. firstid = pagenum * self._pagesize
  964. nextfirstid = pagenum * self._pagesize + self._pagesize
  965. if start >= nextfirstid:
  966. continue
  967. page_results = list(self._pagefunc(pagenum))
  968. startv = (
  969. start % self._pagesize
  970. if firstid <= start < nextfirstid
  971. else 0)
  972. endv = (
  973. ((end - 1) % self._pagesize) + 1
  974. if (end is not None and firstid <= end <= nextfirstid)
  975. else None)
  976. if startv != 0 or endv is not None:
  977. page_results = page_results[startv:endv]
  978. res.extend(page_results)
  979. # A little optimization - if current page is not "full", ie. does
  980. # not contain page_size videos then we can assume that this page
  981. # is the last one - there are no more ids on further pages -
  982. # i.e. no need to query again.
  983. if len(page_results) + startv < self._pagesize:
  984. break
  985. # If we got the whole page, but the next page is not interesting,
  986. # break out early as well
  987. if end == nextfirstid:
  988. break
  989. return res
  990. class InAdvancePagedList(PagedList):
  991. def __init__(self, pagefunc, pagecount, pagesize):
  992. self._pagefunc = pagefunc
  993. self._pagecount = pagecount
  994. self._pagesize = pagesize
  995. def getslice(self, start=0, end=None):
  996. res = []
  997. start_page = start // self._pagesize
  998. end_page = (
  999. self._pagecount if end is None else (end // self._pagesize + 1))
  1000. skip_elems = start - start_page * self._pagesize
  1001. only_more = None if end is None else end - start
  1002. for pagenum in range(start_page, end_page):
  1003. page = list(self._pagefunc(pagenum))
  1004. if skip_elems:
  1005. page = page[skip_elems:]
  1006. skip_elems = None
  1007. if only_more is not None:
  1008. if len(page) < only_more:
  1009. only_more -= len(page)
  1010. else:
  1011. page = page[:only_more]
  1012. res.extend(page)
  1013. break
  1014. res.extend(page)
  1015. return res
  1016. def uppercase_escape(s):
  1017. unicode_escape = codecs.getdecoder('unicode_escape')
  1018. return re.sub(
  1019. r'\\U[0-9a-fA-F]{8}',
  1020. lambda m: unicode_escape(m.group(0))[0],
  1021. s)
  1022. def escape_rfc3986(s):
  1023. """Escape non-ASCII characters as suggested by RFC 3986"""
  1024. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1025. s = s.encode('utf-8')
  1026. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1027. def escape_url(url):
  1028. """Escape URL as suggested by RFC 3986"""
  1029. url_parsed = compat_urllib_parse_urlparse(url)
  1030. return url_parsed._replace(
  1031. path=escape_rfc3986(url_parsed.path),
  1032. params=escape_rfc3986(url_parsed.params),
  1033. query=escape_rfc3986(url_parsed.query),
  1034. fragment=escape_rfc3986(url_parsed.fragment)
  1035. ).geturl()
  1036. try:
  1037. struct.pack(u'!I', 0)
  1038. except TypeError:
  1039. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1040. def struct_pack(spec, *args):
  1041. if isinstance(spec, compat_str):
  1042. spec = spec.encode('ascii')
  1043. return struct.pack(spec, *args)
  1044. def struct_unpack(spec, *args):
  1045. if isinstance(spec, compat_str):
  1046. spec = spec.encode('ascii')
  1047. return struct.unpack(spec, *args)
  1048. else:
  1049. struct_pack = struct.pack
  1050. struct_unpack = struct.unpack
  1051. def read_batch_urls(batch_fd):
  1052. def fixup(url):
  1053. if not isinstance(url, compat_str):
  1054. url = url.decode('utf-8', 'replace')
  1055. BOM_UTF8 = u'\xef\xbb\xbf'
  1056. if url.startswith(BOM_UTF8):
  1057. url = url[len(BOM_UTF8):]
  1058. url = url.strip()
  1059. if url.startswith(('#', ';', ']')):
  1060. return False
  1061. return url
  1062. with contextlib.closing(batch_fd) as fd:
  1063. return [url for url in map(fixup, fd) if url]
  1064. def urlencode_postdata(*args, **kargs):
  1065. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1066. try:
  1067. etree_iter = xml.etree.ElementTree.Element.iter
  1068. except AttributeError: # Python <=2.6
  1069. etree_iter = lambda n: n.findall('.//*')
  1070. def parse_xml(s):
  1071. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1072. def doctype(self, name, pubid, system):
  1073. pass # Ignore doctypes
  1074. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1075. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1076. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1077. # Fix up XML parser in Python 2.x
  1078. if sys.version_info < (3, 0):
  1079. for n in etree_iter(tree):
  1080. if n.text is not None:
  1081. if not isinstance(n.text, compat_str):
  1082. n.text = n.text.decode('utf-8')
  1083. return tree
  1084. US_RATINGS = {
  1085. 'G': 0,
  1086. 'PG': 10,
  1087. 'PG-13': 13,
  1088. 'R': 16,
  1089. 'NC': 18,
  1090. }
  1091. def parse_age_limit(s):
  1092. if s is None:
  1093. return None
  1094. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1095. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1096. def strip_jsonp(code):
  1097. return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
  1098. def js_to_json(code):
  1099. def fix_kv(m):
  1100. v = m.group(0)
  1101. if v in ('true', 'false', 'null'):
  1102. return v
  1103. if v.startswith('"'):
  1104. return v
  1105. if v.startswith("'"):
  1106. v = v[1:-1]
  1107. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1108. '\\\\': '\\\\',
  1109. "\\'": "'",
  1110. '"': '\\"',
  1111. }[m.group(0)], v)
  1112. return '"%s"' % v
  1113. res = re.sub(r'''(?x)
  1114. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1115. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1116. [a-zA-Z_][a-zA-Z_0-9]*
  1117. ''', fix_kv, code)
  1118. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1119. return res
  1120. def qualities(quality_ids):
  1121. """ Get a numeric quality value out of a list of possible values """
  1122. def q(qid):
  1123. try:
  1124. return quality_ids.index(qid)
  1125. except ValueError:
  1126. return -1
  1127. return q
  1128. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1129. def limit_length(s, length):
  1130. """ Add ellipses to overly long strings """
  1131. if s is None:
  1132. return None
  1133. ELLIPSES = '...'
  1134. if len(s) > length:
  1135. return s[:length - len(ELLIPSES)] + ELLIPSES
  1136. return s
  1137. def version_tuple(v):
  1138. return [int(e) for e in v.split('.')]
  1139. def is_outdated_version(version, limit, assume_new=True):
  1140. if not version:
  1141. return not assume_new
  1142. try:
  1143. return version_tuple(version) < version_tuple(limit)
  1144. except ValueError:
  1145. return not assume_new