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.

928 lines
30 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import email.utils
  5. import errno
  6. import gzip
  7. import io
  8. import json
  9. import locale
  10. import os
  11. import platform
  12. import re
  13. import socket
  14. import sys
  15. import traceback
  16. import zlib
  17. try:
  18. import urllib.request as compat_urllib_request
  19. except ImportError: # Python 2
  20. import urllib2 as compat_urllib_request
  21. try:
  22. import urllib.error as compat_urllib_error
  23. except ImportError: # Python 2
  24. import urllib2 as compat_urllib_error
  25. try:
  26. import urllib.parse as compat_urllib_parse
  27. except ImportError: # Python 2
  28. import urllib as compat_urllib_parse
  29. try:
  30. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  31. except ImportError: # Python 2
  32. from urlparse import urlparse as compat_urllib_parse_urlparse
  33. try:
  34. import urllib.parse as compat_urlparse
  35. except ImportError: # Python 2
  36. import urlparse as compat_urlparse
  37. try:
  38. import http.cookiejar as compat_cookiejar
  39. except ImportError: # Python 2
  40. import cookielib as compat_cookiejar
  41. try:
  42. import html.entities as compat_html_entities
  43. except ImportError: # Python 2
  44. import htmlentitydefs as compat_html_entities
  45. try:
  46. import html.parser as compat_html_parser
  47. except ImportError: # Python 2
  48. import HTMLParser as compat_html_parser
  49. try:
  50. import http.client as compat_http_client
  51. except ImportError: # Python 2
  52. import httplib as compat_http_client
  53. try:
  54. from urllib.error import HTTPError as compat_HTTPError
  55. except ImportError: # Python 2
  56. from urllib2 import HTTPError as compat_HTTPError
  57. try:
  58. from urllib.request import urlretrieve as compat_urlretrieve
  59. except ImportError: # Python 2
  60. from urllib import urlretrieve as compat_urlretrieve
  61. try:
  62. from subprocess import DEVNULL
  63. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  64. except ImportError:
  65. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  66. try:
  67. from urllib.parse import parse_qs as compat_parse_qs
  68. except ImportError: # Python 2
  69. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  70. # Python 2's version is apparently totally broken
  71. def _unquote(string, encoding='utf-8', errors='replace'):
  72. if string == '':
  73. return string
  74. res = string.split('%')
  75. if len(res) == 1:
  76. return string
  77. if encoding is None:
  78. encoding = 'utf-8'
  79. if errors is None:
  80. errors = 'replace'
  81. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  82. pct_sequence = b''
  83. string = res[0]
  84. for item in res[1:]:
  85. try:
  86. if not item:
  87. raise ValueError
  88. pct_sequence += item[:2].decode('hex')
  89. rest = item[2:]
  90. if not rest:
  91. # This segment was just a single percent-encoded character.
  92. # May be part of a sequence of code units, so delay decoding.
  93. # (Stored in pct_sequence).
  94. continue
  95. except ValueError:
  96. rest = '%' + item
  97. # Encountered non-percent-encoded characters. Flush the current
  98. # pct_sequence.
  99. string += pct_sequence.decode(encoding, errors) + rest
  100. pct_sequence = b''
  101. if pct_sequence:
  102. # Flush the final pct_sequence
  103. string += pct_sequence.decode(encoding, errors)
  104. return string
  105. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  106. encoding='utf-8', errors='replace'):
  107. qs, _coerce_result = qs, unicode
  108. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  109. r = []
  110. for name_value in pairs:
  111. if not name_value and not strict_parsing:
  112. continue
  113. nv = name_value.split('=', 1)
  114. if len(nv) != 2:
  115. if strict_parsing:
  116. raise ValueError("bad query field: %r" % (name_value,))
  117. # Handle case of a control-name with no equal sign
  118. if keep_blank_values:
  119. nv.append('')
  120. else:
  121. continue
  122. if len(nv[1]) or keep_blank_values:
  123. name = nv[0].replace('+', ' ')
  124. name = _unquote(name, encoding=encoding, errors=errors)
  125. name = _coerce_result(name)
  126. value = nv[1].replace('+', ' ')
  127. value = _unquote(value, encoding=encoding, errors=errors)
  128. value = _coerce_result(value)
  129. r.append((name, value))
  130. return r
  131. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  132. encoding='utf-8', errors='replace'):
  133. parsed_result = {}
  134. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  135. encoding=encoding, errors=errors)
  136. for name, value in pairs:
  137. if name in parsed_result:
  138. parsed_result[name].append(value)
  139. else:
  140. parsed_result[name] = [value]
  141. return parsed_result
  142. try:
  143. compat_str = unicode # Python 2
  144. except NameError:
  145. compat_str = str
  146. try:
  147. compat_chr = unichr # Python 2
  148. except NameError:
  149. compat_chr = chr
  150. def compat_ord(c):
  151. if type(c) is int: return c
  152. else: return ord(c)
  153. # This is not clearly defined otherwise
  154. compiled_regex_type = type(re.compile(''))
  155. std_headers = {
  156. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  157. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  158. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  159. 'Accept-Encoding': 'gzip, deflate',
  160. 'Accept-Language': 'en-us,en;q=0.5',
  161. }
  162. def preferredencoding():
  163. """Get preferred encoding.
  164. Returns the best encoding scheme for the system, based on
  165. locale.getpreferredencoding() and some further tweaks.
  166. """
  167. try:
  168. pref = locale.getpreferredencoding()
  169. u'TEST'.encode(pref)
  170. except:
  171. pref = 'UTF-8'
  172. return pref
  173. if sys.version_info < (3,0):
  174. def compat_print(s):
  175. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  176. else:
  177. def compat_print(s):
  178. assert type(s) == type(u'')
  179. print(s)
  180. # In Python 2.x, json.dump expects a bytestream.
  181. # In Python 3.x, it writes to a character stream
  182. if sys.version_info < (3,0):
  183. def write_json_file(obj, fn):
  184. with open(fn, 'wb') as f:
  185. json.dump(obj, f)
  186. else:
  187. def write_json_file(obj, fn):
  188. with open(fn, 'w', encoding='utf-8') as f:
  189. json.dump(obj, f)
  190. if sys.version_info >= (2,7):
  191. def find_xpath_attr(node, xpath, key, val):
  192. """ Find the xpath xpath[@key=val] """
  193. assert re.match(r'^[a-zA-Z]+$', key)
  194. assert re.match(r'^[a-zA-Z0-9@\s]*$', val)
  195. expr = xpath + u"[@%s='%s']" % (key, val)
  196. return node.find(expr)
  197. else:
  198. def find_xpath_attr(node, xpath, key, val):
  199. for f in node.findall(xpath):
  200. if f.attrib.get(key) == val:
  201. return f
  202. return None
  203. def htmlentity_transform(matchobj):
  204. """Transforms an HTML entity to a character.
  205. This function receives a match object and is intended to be used with
  206. the re.sub() function.
  207. """
  208. entity = matchobj.group(1)
  209. # Known non-numeric HTML entity
  210. if entity in compat_html_entities.name2codepoint:
  211. return compat_chr(compat_html_entities.name2codepoint[entity])
  212. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  213. if mobj is not None:
  214. numstr = mobj.group(1)
  215. if numstr.startswith(u'x'):
  216. base = 16
  217. numstr = u'0%s' % numstr
  218. else:
  219. base = 10
  220. return compat_chr(int(numstr, base))
  221. # Unknown entity in name, return its literal representation
  222. return (u'&%s;' % entity)
  223. 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
  224. class BaseHTMLParser(compat_html_parser.HTMLParser):
  225. def __init(self):
  226. compat_html_parser.HTMLParser.__init__(self)
  227. self.html = None
  228. def loads(self, html):
  229. self.html = html
  230. self.feed(html)
  231. self.close()
  232. class AttrParser(BaseHTMLParser):
  233. """Modified HTMLParser that isolates a tag with the specified attribute"""
  234. def __init__(self, attribute, value):
  235. self.attribute = attribute
  236. self.value = value
  237. self.result = None
  238. self.started = False
  239. self.depth = {}
  240. self.watch_startpos = False
  241. self.error_count = 0
  242. BaseHTMLParser.__init__(self)
  243. def error(self, message):
  244. if self.error_count > 10 or self.started:
  245. raise compat_html_parser.HTMLParseError(message, self.getpos())
  246. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  247. self.error_count += 1
  248. self.goahead(1)
  249. def handle_starttag(self, tag, attrs):
  250. attrs = dict(attrs)
  251. if self.started:
  252. self.find_startpos(None)
  253. if self.attribute in attrs and attrs[self.attribute] == self.value:
  254. self.result = [tag]
  255. self.started = True
  256. self.watch_startpos = True
  257. if self.started:
  258. if not tag in self.depth: self.depth[tag] = 0
  259. self.depth[tag] += 1
  260. def handle_endtag(self, tag):
  261. if self.started:
  262. if tag in self.depth: self.depth[tag] -= 1
  263. if self.depth[self.result[0]] == 0:
  264. self.started = False
  265. self.result.append(self.getpos())
  266. def find_startpos(self, x):
  267. """Needed to put the start position of the result (self.result[1])
  268. after the opening tag with the requested id"""
  269. if self.watch_startpos:
  270. self.watch_startpos = False
  271. self.result.append(self.getpos())
  272. handle_entityref = handle_charref = handle_data = handle_comment = \
  273. handle_decl = handle_pi = unknown_decl = find_startpos
  274. def get_result(self):
  275. if self.result is None:
  276. return None
  277. if len(self.result) != 3:
  278. return None
  279. lines = self.html.split('\n')
  280. lines = lines[self.result[1][0]-1:self.result[2][0]]
  281. lines[0] = lines[0][self.result[1][1]:]
  282. if len(lines) == 1:
  283. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  284. lines[-1] = lines[-1][:self.result[2][1]]
  285. return '\n'.join(lines).strip()
  286. # Hack for https://github.com/rg3/youtube-dl/issues/662
  287. if sys.version_info < (2, 7, 3):
  288. AttrParser.parse_endtag = (lambda self, i:
  289. i + len("</scr'+'ipt>")
  290. if self.rawdata[i:].startswith("</scr'+'ipt>")
  291. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  292. def get_element_by_id(id, html):
  293. """Return the content of the tag with the specified ID in the passed HTML document"""
  294. return get_element_by_attribute("id", id, html)
  295. def get_element_by_attribute(attribute, value, html):
  296. """Return the content of the tag with the specified attribute in the passed HTML document"""
  297. parser = AttrParser(attribute, value)
  298. try:
  299. parser.loads(html)
  300. except compat_html_parser.HTMLParseError:
  301. pass
  302. return parser.get_result()
  303. class MetaParser(BaseHTMLParser):
  304. """
  305. Modified HTMLParser that isolates a meta tag with the specified name
  306. attribute.
  307. """
  308. def __init__(self, name):
  309. BaseHTMLParser.__init__(self)
  310. self.name = name
  311. self.content = None
  312. self.result = None
  313. def handle_starttag(self, tag, attrs):
  314. if tag != 'meta':
  315. return
  316. attrs = dict(attrs)
  317. if attrs.get('name') == self.name:
  318. self.result = attrs.get('content')
  319. def get_result(self):
  320. return self.result
  321. def get_meta_content(name, html):
  322. """
  323. Return the content attribute from the meta tag with the given name attribute.
  324. """
  325. parser = MetaParser(name)
  326. try:
  327. parser.loads(html)
  328. except compat_html_parser.HTMLParseError:
  329. pass
  330. return parser.get_result()
  331. def clean_html(html):
  332. """Clean an HTML snippet into a readable string"""
  333. # Newline vs <br />
  334. html = html.replace('\n', ' ')
  335. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  336. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  337. # Strip html tags
  338. html = re.sub('<.*?>', '', html)
  339. # Replace html entities
  340. html = unescapeHTML(html)
  341. return html.strip()
  342. def sanitize_open(filename, open_mode):
  343. """Try to open the given filename, and slightly tweak it if this fails.
  344. Attempts to open the given filename. If this fails, it tries to change
  345. the filename slightly, step by step, until it's either able to open it
  346. or it fails and raises a final exception, like the standard open()
  347. function.
  348. It returns the tuple (stream, definitive_file_name).
  349. """
  350. try:
  351. if filename == u'-':
  352. if sys.platform == 'win32':
  353. import msvcrt
  354. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  355. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  356. stream = open(encodeFilename(filename), open_mode)
  357. return (stream, filename)
  358. except (IOError, OSError) as err:
  359. if err.errno in (errno.EACCES,):
  360. raise
  361. # In case of error, try to remove win32 forbidden chars
  362. alt_filename = os.path.join(
  363. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  364. for path_part in os.path.split(filename)
  365. )
  366. if alt_filename == filename:
  367. raise
  368. else:
  369. # An exception here should be caught in the caller
  370. stream = open(encodeFilename(filename), open_mode)
  371. return (stream, alt_filename)
  372. def timeconvert(timestr):
  373. """Convert RFC 2822 defined time string into system timestamp"""
  374. timestamp = None
  375. timetuple = email.utils.parsedate_tz(timestr)
  376. if timetuple is not None:
  377. timestamp = email.utils.mktime_tz(timetuple)
  378. return timestamp
  379. def sanitize_filename(s, restricted=False, is_id=False):
  380. """Sanitizes a string so it could be used as part of a filename.
  381. If restricted is set, use a stricter subset of allowed characters.
  382. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  383. """
  384. def replace_insane(char):
  385. if char == '?' or ord(char) < 32 or ord(char) == 127:
  386. return ''
  387. elif char == '"':
  388. return '' if restricted else '\''
  389. elif char == ':':
  390. return '_-' if restricted else ' -'
  391. elif char in '\\/|*<>':
  392. return '_'
  393. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  394. return '_'
  395. if restricted and ord(char) > 127:
  396. return '_'
  397. return char
  398. result = u''.join(map(replace_insane, s))
  399. if not is_id:
  400. while '__' in result:
  401. result = result.replace('__', '_')
  402. result = result.strip('_')
  403. # Common case of "Foreign band name - English song title"
  404. if restricted and result.startswith('-_'):
  405. result = result[2:]
  406. if not result:
  407. result = '_'
  408. return result
  409. def orderedSet(iterable):
  410. """ Remove all duplicates from the input iterable """
  411. res = []
  412. for el in iterable:
  413. if el not in res:
  414. res.append(el)
  415. return res
  416. def unescapeHTML(s):
  417. """
  418. @param s a string
  419. """
  420. assert type(s) == type(u'')
  421. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  422. return result
  423. def encodeFilename(s):
  424. """
  425. @param s The name of the file
  426. """
  427. assert type(s) == type(u'')
  428. # Python 3 has a Unicode API
  429. if sys.version_info >= (3, 0):
  430. return s
  431. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  432. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  433. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  434. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  435. return s
  436. else:
  437. encoding = sys.getfilesystemencoding()
  438. if encoding is None:
  439. encoding = 'utf-8'
  440. return s.encode(encoding, 'ignore')
  441. def decodeOption(optval):
  442. if optval is None:
  443. return optval
  444. if isinstance(optval, bytes):
  445. optval = optval.decode(preferredencoding())
  446. assert isinstance(optval, compat_str)
  447. return optval
  448. def formatSeconds(secs):
  449. if secs > 3600:
  450. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  451. elif secs > 60:
  452. return '%d:%02d' % (secs // 60, secs % 60)
  453. else:
  454. return '%d' % secs
  455. def make_HTTPS_handler(opts):
  456. if sys.version_info < (3,2):
  457. # Python's 2.x handler is very simplistic
  458. return compat_urllib_request.HTTPSHandler()
  459. else:
  460. import ssl
  461. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  462. context.set_default_verify_paths()
  463. context.verify_mode = (ssl.CERT_NONE
  464. if opts.no_check_certificate
  465. else ssl.CERT_REQUIRED)
  466. return compat_urllib_request.HTTPSHandler(context=context)
  467. class ExtractorError(Exception):
  468. """Error during info extraction."""
  469. def __init__(self, msg, tb=None, expected=False, cause=None):
  470. """ tb, if given, is the original traceback (so that it can be printed out).
  471. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  472. """
  473. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  474. expected = True
  475. if not expected:
  476. 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.'
  477. super(ExtractorError, self).__init__(msg)
  478. self.traceback = tb
  479. self.exc_info = sys.exc_info() # preserve original exception
  480. self.cause = cause
  481. def format_traceback(self):
  482. if self.traceback is None:
  483. return None
  484. return u''.join(traceback.format_tb(self.traceback))
  485. class DownloadError(Exception):
  486. """Download Error exception.
  487. This exception may be thrown by FileDownloader objects if they are not
  488. configured to continue on errors. They will contain the appropriate
  489. error message.
  490. """
  491. def __init__(self, msg, exc_info=None):
  492. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  493. super(DownloadError, self).__init__(msg)
  494. self.exc_info = exc_info
  495. class SameFileError(Exception):
  496. """Same File exception.
  497. This exception will be thrown by FileDownloader objects if they detect
  498. multiple files would have to be downloaded to the same file on disk.
  499. """
  500. pass
  501. class PostProcessingError(Exception):
  502. """Post Processing exception.
  503. This exception may be raised by PostProcessor's .run() method to
  504. indicate an error in the postprocessing task.
  505. """
  506. def __init__(self, msg):
  507. self.msg = msg
  508. class MaxDownloadsReached(Exception):
  509. """ --max-downloads limit has been reached. """
  510. pass
  511. class UnavailableVideoError(Exception):
  512. """Unavailable Format exception.
  513. This exception will be thrown when a video is requested
  514. in a format that is not available for that video.
  515. """
  516. pass
  517. class ContentTooShortError(Exception):
  518. """Content Too Short exception.
  519. This exception may be raised by FileDownloader objects when a file they
  520. download is too small for what the server announced first, indicating
  521. the connection was probably interrupted.
  522. """
  523. # Both in bytes
  524. downloaded = None
  525. expected = None
  526. def __init__(self, downloaded, expected):
  527. self.downloaded = downloaded
  528. self.expected = expected
  529. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  530. """Handler for HTTP requests and responses.
  531. This class, when installed with an OpenerDirector, automatically adds
  532. the standard headers to every HTTP request and handles gzipped and
  533. deflated responses from web servers. If compression is to be avoided in
  534. a particular request, the original request in the program code only has
  535. to include the HTTP header "Youtubedl-No-Compression", which will be
  536. removed before making the real request.
  537. Part of this code was copied from:
  538. http://techknack.net/python-urllib2-handlers/
  539. Andrew Rowls, the author of that code, agreed to release it to the
  540. public domain.
  541. """
  542. @staticmethod
  543. def deflate(data):
  544. try:
  545. return zlib.decompress(data, -zlib.MAX_WBITS)
  546. except zlib.error:
  547. return zlib.decompress(data)
  548. @staticmethod
  549. def addinfourl_wrapper(stream, headers, url, code):
  550. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  551. return compat_urllib_request.addinfourl(stream, headers, url, code)
  552. ret = compat_urllib_request.addinfourl(stream, headers, url)
  553. ret.code = code
  554. return ret
  555. def http_request(self, req):
  556. for h,v in std_headers.items():
  557. if h in req.headers:
  558. del req.headers[h]
  559. req.add_header(h, v)
  560. if 'Youtubedl-no-compression' in req.headers:
  561. if 'Accept-encoding' in req.headers:
  562. del req.headers['Accept-encoding']
  563. del req.headers['Youtubedl-no-compression']
  564. if 'Youtubedl-user-agent' in req.headers:
  565. if 'User-agent' in req.headers:
  566. del req.headers['User-agent']
  567. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  568. del req.headers['Youtubedl-user-agent']
  569. return req
  570. def http_response(self, req, resp):
  571. old_resp = resp
  572. # gzip
  573. if resp.headers.get('Content-encoding', '') == 'gzip':
  574. content = resp.read()
  575. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  576. try:
  577. uncompressed = io.BytesIO(gz.read())
  578. except IOError as original_ioerror:
  579. # There may be junk add the end of the file
  580. # See http://stackoverflow.com/q/4928560/35070 for details
  581. for i in range(1, 1024):
  582. try:
  583. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  584. uncompressed = io.BytesIO(gz.read())
  585. except IOError:
  586. continue
  587. break
  588. else:
  589. raise original_ioerror
  590. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  591. resp.msg = old_resp.msg
  592. # deflate
  593. if resp.headers.get('Content-encoding', '') == 'deflate':
  594. gz = io.BytesIO(self.deflate(resp.read()))
  595. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  596. resp.msg = old_resp.msg
  597. return resp
  598. https_request = http_request
  599. https_response = http_response
  600. def unified_strdate(date_str):
  601. """Return a string with the date in the format YYYYMMDD"""
  602. upload_date = None
  603. #Replace commas
  604. date_str = date_str.replace(',',' ')
  605. # %z (UTC offset) is only supported in python>=3.2
  606. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  607. format_expressions = [
  608. '%d %B %Y',
  609. '%B %d %Y',
  610. '%b %d %Y',
  611. '%Y-%m-%d',
  612. '%d/%m/%Y',
  613. '%Y/%m/%d %H:%M:%S',
  614. '%d.%m.%Y %H:%M',
  615. '%Y-%m-%dT%H:%M:%SZ',
  616. ]
  617. for expression in format_expressions:
  618. try:
  619. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  620. except:
  621. pass
  622. return upload_date
  623. def determine_ext(url, default_ext=u'unknown_video'):
  624. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  625. if re.match(r'^[A-Za-z0-9]+$', guess):
  626. return guess
  627. else:
  628. return default_ext
  629. def subtitles_filename(filename, sub_lang, sub_format):
  630. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  631. def date_from_str(date_str):
  632. """
  633. Return a datetime object from a string in the format YYYYMMDD or
  634. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  635. today = datetime.date.today()
  636. if date_str == 'now'or date_str == 'today':
  637. return today
  638. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  639. if match is not None:
  640. sign = match.group('sign')
  641. time = int(match.group('time'))
  642. if sign == '-':
  643. time = -time
  644. unit = match.group('unit')
  645. #A bad aproximation?
  646. if unit == 'month':
  647. unit = 'day'
  648. time *= 30
  649. elif unit == 'year':
  650. unit = 'day'
  651. time *= 365
  652. unit += 's'
  653. delta = datetime.timedelta(**{unit: time})
  654. return today + delta
  655. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  656. class DateRange(object):
  657. """Represents a time interval between two dates"""
  658. def __init__(self, start=None, end=None):
  659. """start and end must be strings in the format accepted by date"""
  660. if start is not None:
  661. self.start = date_from_str(start)
  662. else:
  663. self.start = datetime.datetime.min.date()
  664. if end is not None:
  665. self.end = date_from_str(end)
  666. else:
  667. self.end = datetime.datetime.max.date()
  668. if self.start > self.end:
  669. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  670. @classmethod
  671. def day(cls, day):
  672. """Returns a range that only contains the given day"""
  673. return cls(day,day)
  674. def __contains__(self, date):
  675. """Check if the date is in the range"""
  676. if not isinstance(date, datetime.date):
  677. date = date_from_str(date)
  678. return self.start <= date <= self.end
  679. def __str__(self):
  680. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  681. def platform_name():
  682. """ Returns the platform name as a compat_str """
  683. res = platform.platform()
  684. if isinstance(res, bytes):
  685. res = res.decode(preferredencoding())
  686. assert isinstance(res, compat_str)
  687. return res
  688. def write_string(s, out=None):
  689. if out is None:
  690. out = sys.stderr
  691. assert type(s) == type(u'')
  692. if ('b' in getattr(out, 'mode', '') or
  693. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  694. s = s.encode(preferredencoding(), 'ignore')
  695. out.write(s)
  696. out.flush()
  697. def bytes_to_intlist(bs):
  698. if not bs:
  699. return []
  700. if isinstance(bs[0], int): # Python 3
  701. return list(bs)
  702. else:
  703. return [ord(c) for c in bs]
  704. def intlist_to_bytes(xs):
  705. if not xs:
  706. return b''
  707. if isinstance(chr(0), bytes): # Python 2
  708. return ''.join([chr(x) for x in xs])
  709. else:
  710. return bytes(xs)
  711. def get_cachedir(params={}):
  712. cache_root = os.environ.get('XDG_CACHE_HOME',
  713. os.path.expanduser('~/.cache'))
  714. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  715. # Cross-platform file locking
  716. if sys.platform == 'win32':
  717. import ctypes.wintypes
  718. import msvcrt
  719. class OVERLAPPED(ctypes.Structure):
  720. _fields_ = [
  721. ('Internal', ctypes.wintypes.LPVOID),
  722. ('InternalHigh', ctypes.wintypes.LPVOID),
  723. ('Offset', ctypes.wintypes.DWORD),
  724. ('OffsetHigh', ctypes.wintypes.DWORD),
  725. ('hEvent', ctypes.wintypes.HANDLE),
  726. ]
  727. kernel32 = ctypes.windll.kernel32
  728. LockFileEx = kernel32.LockFileEx
  729. LockFileEx.argtypes = [
  730. ctypes.wintypes.HANDLE, # hFile
  731. ctypes.wintypes.DWORD, # dwFlags
  732. ctypes.wintypes.DWORD, # dwReserved
  733. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  734. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  735. ctypes.POINTER(OVERLAPPED) # Overlapped
  736. ]
  737. LockFileEx.restype = ctypes.wintypes.BOOL
  738. UnlockFileEx = kernel32.UnlockFileEx
  739. UnlockFileEx.argtypes = [
  740. ctypes.wintypes.HANDLE, # hFile
  741. ctypes.wintypes.DWORD, # dwReserved
  742. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  743. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  744. ctypes.POINTER(OVERLAPPED) # Overlapped
  745. ]
  746. UnlockFileEx.restype = ctypes.wintypes.BOOL
  747. whole_low = 0xffffffff
  748. whole_high = 0x7fffffff
  749. def _lock_file(f, exclusive):
  750. overlapped = OVERLAPPED()
  751. overlapped.Offset = 0
  752. overlapped.OffsetHigh = 0
  753. overlapped.hEvent = 0
  754. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  755. handle = msvcrt.get_osfhandle(f.fileno())
  756. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  757. whole_low, whole_high, f._lock_file_overlapped_p):
  758. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  759. def _unlock_file(f):
  760. assert f._lock_file_overlapped_p
  761. handle = msvcrt.get_osfhandle(f.fileno())
  762. if not UnlockFileEx(handle, 0,
  763. whole_low, whole_high, f._lock_file_overlapped_p):
  764. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  765. else:
  766. import fcntl
  767. def _lock_file(f, exclusive):
  768. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  769. def _unlock_file(f):
  770. fcntl.lockf(f, fcntl.LOCK_UN)
  771. class locked_file(object):
  772. def __init__(self, filename, mode, encoding=None):
  773. assert mode in ['r', 'a', 'w']
  774. self.f = io.open(filename, mode, encoding=encoding)
  775. self.mode = mode
  776. def __enter__(self):
  777. exclusive = self.mode != 'r'
  778. try:
  779. _lock_file(self.f, exclusive)
  780. except IOError:
  781. self.f.close()
  782. raise
  783. return self
  784. def __exit__(self, etype, value, traceback):
  785. try:
  786. _unlock_file(self.f)
  787. finally:
  788. self.f.close()
  789. def __iter__(self):
  790. return iter(self.f)
  791. def write(self, *args):
  792. return self.f.write(*args)
  793. def read(self, *args):
  794. return self.f.read(*args)