utils.py 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import itertools
  16. import io
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import ssl
  26. import socket
  27. import struct
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_http_client,
  40. compat_kwargs,
  41. compat_parse_qs,
  42. compat_socket_create_connection,
  43. compat_str,
  44. compat_urllib_error,
  45. compat_urllib_parse,
  46. compat_urllib_parse_urlparse,
  47. compat_urllib_request,
  48. compat_urlparse,
  49. shlex_quote,
  50. )
  51. # This is not clearly defined otherwise
  52. compiled_regex_type = type(re.compile(''))
  53. std_headers = {
  54. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/44.0 (Chrome)',
  55. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  56. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  57. 'Accept-Encoding': 'gzip, deflate',
  58. 'Accept-Language': 'en-us,en;q=0.5',
  59. }
  60. NO_DEFAULT = object()
  61. ENGLISH_MONTH_NAMES = [
  62. 'January', 'February', 'March', 'April', 'May', 'June',
  63. 'July', 'August', 'September', 'October', 'November', 'December']
  64. KNOWN_EXTENSIONS = (
  65. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  66. 'flv', 'f4v', 'f4a', 'f4b',
  67. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  68. 'mkv', 'mka', 'mk3d',
  69. 'avi', 'divx',
  70. 'mov',
  71. 'asf', 'wmv', 'wma',
  72. '3gp', '3g2',
  73. 'mp3',
  74. 'flac',
  75. 'ape',
  76. 'wav',
  77. 'f4f', 'f4m', 'm3u8', 'smil')
  78. def preferredencoding():
  79. """Get preferred encoding.
  80. Returns the best encoding scheme for the system, based on
  81. locale.getpreferredencoding() and some further tweaks.
  82. """
  83. try:
  84. pref = locale.getpreferredencoding()
  85. 'TEST'.encode(pref)
  86. except Exception:
  87. pref = 'UTF-8'
  88. return pref
  89. def write_json_file(obj, fn):
  90. """ Encode obj as JSON and write it to fn, atomically if possible """
  91. fn = encodeFilename(fn)
  92. if sys.version_info < (3, 0) and sys.platform != 'win32':
  93. encoding = get_filesystem_encoding()
  94. # os.path.basename returns a bytes object, but NamedTemporaryFile
  95. # will fail if the filename contains non ascii characters unless we
  96. # use a unicode object
  97. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  98. # the same for os.path.dirname
  99. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  100. else:
  101. path_basename = os.path.basename
  102. path_dirname = os.path.dirname
  103. args = {
  104. 'suffix': '.tmp',
  105. 'prefix': path_basename(fn) + '.',
  106. 'dir': path_dirname(fn),
  107. 'delete': False,
  108. }
  109. # In Python 2.x, json.dump expects a bytestream.
  110. # In Python 3.x, it writes to a character stream
  111. if sys.version_info < (3, 0):
  112. args['mode'] = 'wb'
  113. else:
  114. args.update({
  115. 'mode': 'w',
  116. 'encoding': 'utf-8',
  117. })
  118. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  119. try:
  120. with tf:
  121. json.dump(obj, tf)
  122. if sys.platform == 'win32':
  123. # Need to remove existing file on Windows, else os.rename raises
  124. # WindowsError or FileExistsError.
  125. try:
  126. os.unlink(fn)
  127. except OSError:
  128. pass
  129. os.rename(tf.name, fn)
  130. except Exception:
  131. try:
  132. os.remove(tf.name)
  133. except OSError:
  134. pass
  135. raise
  136. if sys.version_info >= (2, 7):
  137. def find_xpath_attr(node, xpath, key, val=None):
  138. """ Find the xpath xpath[@key=val] """
  139. assert re.match(r'^[a-zA-Z_-]+$', key)
  140. if val:
  141. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  142. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  143. return node.find(expr)
  144. else:
  145. def find_xpath_attr(node, xpath, key, val=None):
  146. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  147. # .//node does not match if a node is a direct child of . !
  148. if isinstance(xpath, compat_str):
  149. xpath = xpath.encode('ascii')
  150. for f in node.findall(xpath):
  151. if key not in f.attrib:
  152. continue
  153. if val is None or f.attrib.get(key) == val:
  154. return f
  155. return None
  156. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  157. # the namespace parameter
  158. def xpath_with_ns(path, ns_map):
  159. components = [c.split(':') for c in path.split('/')]
  160. replaced = []
  161. for c in components:
  162. if len(c) == 1:
  163. replaced.append(c[0])
  164. else:
  165. ns, tag = c
  166. replaced.append('{%s}%s' % (ns_map[ns], tag))
  167. return '/'.join(replaced)
  168. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  169. def _find_xpath(xpath):
  170. if sys.version_info < (2, 7): # Crazy 2.6
  171. xpath = xpath.encode('ascii')
  172. return node.find(xpath)
  173. if isinstance(xpath, (str, compat_str)):
  174. n = _find_xpath(xpath)
  175. else:
  176. for xp in xpath:
  177. n = _find_xpath(xp)
  178. if n is not None:
  179. break
  180. if n is None:
  181. if default is not NO_DEFAULT:
  182. return default
  183. elif fatal:
  184. name = xpath if name is None else name
  185. raise ExtractorError('Could not find XML element %s' % name)
  186. else:
  187. return None
  188. return n
  189. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  190. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  191. if n is None or n == default:
  192. return n
  193. if n.text is None:
  194. if default is not NO_DEFAULT:
  195. return default
  196. elif fatal:
  197. name = xpath if name is None else name
  198. raise ExtractorError('Could not find XML element\'s text %s' % name)
  199. else:
  200. return None
  201. return n.text
  202. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  203. n = find_xpath_attr(node, xpath, key)
  204. if n is None:
  205. if default is not NO_DEFAULT:
  206. return default
  207. elif fatal:
  208. name = '%s[@%s]' % (xpath, key) if name is None else name
  209. raise ExtractorError('Could not find XML attribute %s' % name)
  210. else:
  211. return None
  212. return n.attrib[key]
  213. def get_element_by_id(id, html):
  214. """Return the content of the tag with the specified ID in the passed HTML document"""
  215. return get_element_by_attribute('id', id, html)
  216. def get_element_by_attribute(attribute, value, html):
  217. """Return the content of the tag with the specified attribute in the passed HTML document"""
  218. m = re.search(r'''(?xs)
  219. <([a-zA-Z0-9:._-]+)
  220. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  221. \s+%s=['"]?%s['"]?
  222. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  223. \s*>
  224. (?P<content>.*?)
  225. </\1>
  226. ''' % (re.escape(attribute), re.escape(value)), html)
  227. if not m:
  228. return None
  229. res = m.group('content')
  230. if res.startswith('"') or res.startswith("'"):
  231. res = res[1:-1]
  232. return unescapeHTML(res)
  233. def clean_html(html):
  234. """Clean an HTML snippet into a readable string"""
  235. if html is None: # Convenience for sanitizing descriptions etc.
  236. return html
  237. # Newline vs <br />
  238. html = html.replace('\n', ' ')
  239. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  240. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  241. # Strip html tags
  242. html = re.sub('<.*?>', '', html)
  243. # Replace html entities
  244. html = unescapeHTML(html)
  245. return html.strip()
  246. def sanitize_open(filename, open_mode):
  247. """Try to open the given filename, and slightly tweak it if this fails.
  248. Attempts to open the given filename. If this fails, it tries to change
  249. the filename slightly, step by step, until it's either able to open it
  250. or it fails and raises a final exception, like the standard open()
  251. function.
  252. It returns the tuple (stream, definitive_file_name).
  253. """
  254. try:
  255. if filename == '-':
  256. if sys.platform == 'win32':
  257. import msvcrt
  258. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  259. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  260. stream = open(encodeFilename(filename), open_mode)
  261. return (stream, filename)
  262. except (IOError, OSError) as err:
  263. if err.errno in (errno.EACCES,):
  264. raise
  265. # In case of error, try to remove win32 forbidden chars
  266. alt_filename = sanitize_path(filename)
  267. if alt_filename == filename:
  268. raise
  269. else:
  270. # An exception here should be caught in the caller
  271. stream = open(encodeFilename(alt_filename), open_mode)
  272. return (stream, alt_filename)
  273. def timeconvert(timestr):
  274. """Convert RFC 2822 defined time string into system timestamp"""
  275. timestamp = None
  276. timetuple = email.utils.parsedate_tz(timestr)
  277. if timetuple is not None:
  278. timestamp = email.utils.mktime_tz(timetuple)
  279. return timestamp
  280. def sanitize_filename(s, restricted=False, is_id=False):
  281. """Sanitizes a string so it could be used as part of a filename.
  282. If restricted is set, use a stricter subset of allowed characters.
  283. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  284. """
  285. def replace_insane(char):
  286. if char == '?' or ord(char) < 32 or ord(char) == 127:
  287. return ''
  288. elif char == '"':
  289. return '' if restricted else '\''
  290. elif char == ':':
  291. return '_-' if restricted else ' -'
  292. elif char in '\\/|*<>':
  293. return '_'
  294. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  295. return '_'
  296. if restricted and ord(char) > 127:
  297. return '_'
  298. return char
  299. # Handle timestamps
  300. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  301. result = ''.join(map(replace_insane, s))
  302. if not is_id:
  303. while '__' in result:
  304. result = result.replace('__', '_')
  305. result = result.strip('_')
  306. # Common case of "Foreign band name - English song title"
  307. if restricted and result.startswith('-_'):
  308. result = result[2:]
  309. if result.startswith('-'):
  310. result = '_' + result[len('-'):]
  311. result = result.lstrip('.')
  312. if not result:
  313. result = '_'
  314. return result
  315. def sanitize_path(s):
  316. """Sanitizes and normalizes path on Windows"""
  317. if sys.platform != 'win32':
  318. return s
  319. drive_or_unc, _ = os.path.splitdrive(s)
  320. if sys.version_info < (2, 7) and not drive_or_unc:
  321. drive_or_unc, _ = os.path.splitunc(s)
  322. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  323. if drive_or_unc:
  324. norm_path.pop(0)
  325. sanitized_path = [
  326. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  327. for path_part in norm_path]
  328. if drive_or_unc:
  329. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  330. return os.path.join(*sanitized_path)
  331. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  332. # unwanted failures due to missing protocol
  333. def sanitized_Request(url, *args, **kwargs):
  334. return compat_urllib_request.Request(
  335. 'http:%s' % url if url.startswith('//') else url, *args, **kwargs)
  336. def orderedSet(iterable):
  337. """ Remove all duplicates from the input iterable """
  338. res = []
  339. for el in iterable:
  340. if el not in res:
  341. res.append(el)
  342. return res
  343. def _htmlentity_transform(entity):
  344. """Transforms an HTML entity to a character."""
  345. # Known non-numeric HTML entity
  346. if entity in compat_html_entities.name2codepoint:
  347. return compat_chr(compat_html_entities.name2codepoint[entity])
  348. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  349. if mobj is not None:
  350. numstr = mobj.group(1)
  351. if numstr.startswith('x'):
  352. base = 16
  353. numstr = '0%s' % numstr
  354. else:
  355. base = 10
  356. # See https://github.com/rg3/youtube-dl/issues/7518
  357. try:
  358. return compat_chr(int(numstr, base))
  359. except ValueError:
  360. pass
  361. # Unknown entity in name, return its literal representation
  362. return '&%s;' % entity
  363. def unescapeHTML(s):
  364. if s is None:
  365. return None
  366. assert type(s) == compat_str
  367. return re.sub(
  368. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  369. def get_subprocess_encoding():
  370. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  371. # For subprocess calls, encode with locale encoding
  372. # Refer to http://stackoverflow.com/a/9951851/35070
  373. encoding = preferredencoding()
  374. else:
  375. encoding = sys.getfilesystemencoding()
  376. if encoding is None:
  377. encoding = 'utf-8'
  378. return encoding
  379. def encodeFilename(s, for_subprocess=False):
  380. """
  381. @param s The name of the file
  382. """
  383. assert type(s) == compat_str
  384. # Python 3 has a Unicode API
  385. if sys.version_info >= (3, 0):
  386. return s
  387. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  388. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  389. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  390. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  391. return s
  392. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  393. if sys.platform.startswith('java'):
  394. return s
  395. return s.encode(get_subprocess_encoding(), 'ignore')
  396. def decodeFilename(b, for_subprocess=False):
  397. if sys.version_info >= (3, 0):
  398. return b
  399. if not isinstance(b, bytes):
  400. return b
  401. return b.decode(get_subprocess_encoding(), 'ignore')
  402. def encodeArgument(s):
  403. if not isinstance(s, compat_str):
  404. # Legacy code that uses byte strings
  405. # Uncomment the following line after fixing all post processors
  406. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  407. s = s.decode('ascii')
  408. return encodeFilename(s, True)
  409. def decodeArgument(b):
  410. return decodeFilename(b, True)
  411. def decodeOption(optval):
  412. if optval is None:
  413. return optval
  414. if isinstance(optval, bytes):
  415. optval = optval.decode(preferredencoding())
  416. assert isinstance(optval, compat_str)
  417. return optval
  418. def formatSeconds(secs):
  419. if secs > 3600:
  420. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  421. elif secs > 60:
  422. return '%d:%02d' % (secs // 60, secs % 60)
  423. else:
  424. return '%d' % secs
  425. def make_HTTPS_handler(params, **kwargs):
  426. opts_no_check_certificate = params.get('nocheckcertificate', False)
  427. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  428. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  429. if opts_no_check_certificate:
  430. context.check_hostname = False
  431. context.verify_mode = ssl.CERT_NONE
  432. try:
  433. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  434. except TypeError:
  435. # Python 2.7.8
  436. # (create_default_context present but HTTPSHandler has no context=)
  437. pass
  438. if sys.version_info < (3, 2):
  439. return YoutubeDLHTTPSHandler(params, **kwargs)
  440. else: # Python < 3.4
  441. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  442. context.verify_mode = (ssl.CERT_NONE
  443. if opts_no_check_certificate
  444. else ssl.CERT_REQUIRED)
  445. context.set_default_verify_paths()
  446. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  447. def bug_reports_message():
  448. if ytdl_is_updateable():
  449. update_cmd = 'type youtube-dl -U to update'
  450. else:
  451. update_cmd = 'see https://yt-dl.org/update on how to update'
  452. msg = '; please report this issue on https://yt-dl.org/bug .'
  453. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  454. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  455. return msg
  456. class ExtractorError(Exception):
  457. """Error during info extraction."""
  458. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  459. """ tb, if given, is the original traceback (so that it can be printed out).
  460. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  461. """
  462. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  463. expected = True
  464. if video_id is not None:
  465. msg = video_id + ': ' + msg
  466. if cause:
  467. msg += ' (caused by %r)' % cause
  468. if not expected:
  469. msg += bug_reports_message()
  470. super(ExtractorError, self).__init__(msg)
  471. self.traceback = tb
  472. self.exc_info = sys.exc_info() # preserve original exception
  473. self.cause = cause
  474. self.video_id = video_id
  475. def format_traceback(self):
  476. if self.traceback is None:
  477. return None
  478. return ''.join(traceback.format_tb(self.traceback))
  479. class UnsupportedError(ExtractorError):
  480. def __init__(self, url):
  481. super(UnsupportedError, self).__init__(
  482. 'Unsupported URL: %s' % url, expected=True)
  483. self.url = url
  484. class RegexNotFoundError(ExtractorError):
  485. """Error when a regex didn't match"""
  486. pass
  487. class DownloadError(Exception):
  488. """Download Error exception.
  489. This exception may be thrown by FileDownloader objects if they are not
  490. configured to continue on errors. They will contain the appropriate
  491. error message.
  492. """
  493. def __init__(self, msg, exc_info=None):
  494. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  495. super(DownloadError, self).__init__(msg)
  496. self.exc_info = exc_info
  497. class SameFileError(Exception):
  498. """Same File exception.
  499. This exception will be thrown by FileDownloader objects if they detect
  500. multiple files would have to be downloaded to the same file on disk.
  501. """
  502. pass
  503. class PostProcessingError(Exception):
  504. """Post Processing exception.
  505. This exception may be raised by PostProcessor's .run() method to
  506. indicate an error in the postprocessing task.
  507. """
  508. def __init__(self, msg):
  509. self.msg = msg
  510. class MaxDownloadsReached(Exception):
  511. """ --max-downloads limit has been reached. """
  512. pass
  513. class UnavailableVideoError(Exception):
  514. """Unavailable Format exception.
  515. This exception will be thrown when a video is requested
  516. in a format that is not available for that video.
  517. """
  518. pass
  519. class ContentTooShortError(Exception):
  520. """Content Too Short exception.
  521. This exception may be raised by FileDownloader objects when a file they
  522. download is too small for what the server announced first, indicating
  523. the connection was probably interrupted.
  524. """
  525. def __init__(self, downloaded, expected):
  526. # Both in bytes
  527. self.downloaded = downloaded
  528. self.expected = expected
  529. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  530. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  531. # expected HTTP responses to meet HTTP/1.0 or later (see also
  532. # https://github.com/rg3/youtube-dl/issues/6727)
  533. if sys.version_info < (3, 0):
  534. kwargs[b'strict'] = True
  535. hc = http_class(*args, **kwargs)
  536. source_address = ydl_handler._params.get('source_address')
  537. if source_address is not None:
  538. sa = (source_address, 0)
  539. if hasattr(hc, 'source_address'): # Python 2.7+
  540. hc.source_address = sa
  541. else: # Python 2.6
  542. def _hc_connect(self, *args, **kwargs):
  543. sock = compat_socket_create_connection(
  544. (self.host, self.port), self.timeout, sa)
  545. if is_https:
  546. self.sock = ssl.wrap_socket(
  547. sock, self.key_file, self.cert_file,
  548. ssl_version=ssl.PROTOCOL_TLSv1)
  549. else:
  550. self.sock = sock
  551. hc.connect = functools.partial(_hc_connect, hc)
  552. return hc
  553. def handle_youtubedl_headers(headers):
  554. filtered_headers = headers
  555. if 'Youtubedl-no-compression' in filtered_headers:
  556. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  557. del filtered_headers['Youtubedl-no-compression']
  558. return filtered_headers
  559. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  560. """Handler for HTTP requests and responses.
  561. This class, when installed with an OpenerDirector, automatically adds
  562. the standard headers to every HTTP request and handles gzipped and
  563. deflated responses from web servers. If compression is to be avoided in
  564. a particular request, the original request in the program code only has
  565. to include the HTTP header "Youtubedl-no-compression", which will be
  566. removed before making the real request.
  567. Part of this code was copied from:
  568. http://techknack.net/python-urllib2-handlers/
  569. Andrew Rowls, the author of that code, agreed to release it to the
  570. public domain.
  571. """
  572. def __init__(self, params, *args, **kwargs):
  573. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  574. self._params = params
  575. def http_open(self, req):
  576. return self.do_open(functools.partial(
  577. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  578. req)
  579. @staticmethod
  580. def deflate(data):
  581. try:
  582. return zlib.decompress(data, -zlib.MAX_WBITS)
  583. except zlib.error:
  584. return zlib.decompress(data)
  585. @staticmethod
  586. def addinfourl_wrapper(stream, headers, url, code):
  587. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  588. return compat_urllib_request.addinfourl(stream, headers, url, code)
  589. ret = compat_urllib_request.addinfourl(stream, headers, url)
  590. ret.code = code
  591. return ret
  592. def http_request(self, req):
  593. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  594. # always respected by websites, some tend to give out URLs with non percent-encoded
  595. # non-ASCII characters (see telemb.py, ard.py [#3412])
  596. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  597. # To work around aforementioned issue we will replace request's original URL with
  598. # percent-encoded one
  599. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  600. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  601. url = req.get_full_url()
  602. url_escaped = escape_url(url)
  603. # Substitute URL if any change after escaping
  604. if url != url_escaped:
  605. req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
  606. new_req = req_type(
  607. url_escaped, data=req.data, headers=req.headers,
  608. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  609. new_req.timeout = req.timeout
  610. req = new_req
  611. for h, v in std_headers.items():
  612. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  613. # The dict keys are capitalized because of this bug by urllib
  614. if h.capitalize() not in req.headers:
  615. req.add_header(h, v)
  616. req.headers = handle_youtubedl_headers(req.headers)
  617. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  618. # Python 2.6 is brain-dead when it comes to fragments
  619. req._Request__original = req._Request__original.partition('#')[0]
  620. req._Request__r_type = req._Request__r_type.partition('#')[0]
  621. return req
  622. def http_response(self, req, resp):
  623. old_resp = resp
  624. # gzip
  625. if resp.headers.get('Content-encoding', '') == 'gzip':
  626. content = resp.read()
  627. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  628. try:
  629. uncompressed = io.BytesIO(gz.read())
  630. except IOError as original_ioerror:
  631. # There may be junk add the end of the file
  632. # See http://stackoverflow.com/q/4928560/35070 for details
  633. for i in range(1, 1024):
  634. try:
  635. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  636. uncompressed = io.BytesIO(gz.read())
  637. except IOError:
  638. continue
  639. break
  640. else:
  641. raise original_ioerror
  642. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  643. resp.msg = old_resp.msg
  644. del resp.headers['Content-encoding']
  645. # deflate
  646. if resp.headers.get('Content-encoding', '') == 'deflate':
  647. gz = io.BytesIO(self.deflate(resp.read()))
  648. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  649. resp.msg = old_resp.msg
  650. del resp.headers['Content-encoding']
  651. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  652. # https://github.com/rg3/youtube-dl/issues/6457).
  653. if 300 <= resp.code < 400:
  654. location = resp.headers.get('Location')
  655. if location:
  656. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  657. if sys.version_info >= (3, 0):
  658. location = location.encode('iso-8859-1').decode('utf-8')
  659. location_escaped = escape_url(location)
  660. if location != location_escaped:
  661. del resp.headers['Location']
  662. resp.headers['Location'] = location_escaped
  663. return resp
  664. https_request = http_request
  665. https_response = http_response
  666. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  667. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  668. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  669. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  670. self._params = params
  671. def https_open(self, req):
  672. kwargs = {}
  673. if hasattr(self, '_context'): # python > 2.6
  674. kwargs['context'] = self._context
  675. if hasattr(self, '_check_hostname'): # python 3.x
  676. kwargs['check_hostname'] = self._check_hostname
  677. return self.do_open(functools.partial(
  678. _create_http_connection, self, self._https_conn_class, True),
  679. req, **kwargs)
  680. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  681. def __init__(self, cookiejar=None):
  682. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  683. def http_response(self, request, response):
  684. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  685. # characters in Set-Cookie HTTP header of last response (see
  686. # https://github.com/rg3/youtube-dl/issues/6769).
  687. # In order to at least prevent crashing we will percent encode Set-Cookie
  688. # header before HTTPCookieProcessor starts processing it.
  689. # if sys.version_info < (3, 0) and response.headers:
  690. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  691. # set_cookie = response.headers.get(set_cookie_header)
  692. # if set_cookie:
  693. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  694. # if set_cookie != set_cookie_escaped:
  695. # del response.headers[set_cookie_header]
  696. # response.headers[set_cookie_header] = set_cookie_escaped
  697. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  698. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  699. https_response = http_response
  700. def parse_iso8601(date_str, delimiter='T', timezone=None):
  701. """ Return a UNIX timestamp from the given date """
  702. if date_str is None:
  703. return None
  704. date_str = re.sub(r'\.[0-9]+', '', date_str)
  705. if timezone is None:
  706. m = re.search(
  707. r'(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  708. date_str)
  709. if not m:
  710. timezone = datetime.timedelta()
  711. else:
  712. date_str = date_str[:-len(m.group(0))]
  713. if not m.group('sign'):
  714. timezone = datetime.timedelta()
  715. else:
  716. sign = 1 if m.group('sign') == '+' else -1
  717. timezone = datetime.timedelta(
  718. hours=sign * int(m.group('hours')),
  719. minutes=sign * int(m.group('minutes')))
  720. try:
  721. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  722. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  723. return calendar.timegm(dt.timetuple())
  724. except ValueError:
  725. pass
  726. def unified_strdate(date_str, day_first=True):
  727. """Return a string with the date in the format YYYYMMDD"""
  728. if date_str is None:
  729. return None
  730. upload_date = None
  731. # Replace commas
  732. date_str = date_str.replace(',', ' ')
  733. # %z (UTC offset) is only supported in python>=3.2
  734. if not re.match(r'^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$', date_str):
  735. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  736. # Remove AM/PM + timezone
  737. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  738. format_expressions = [
  739. '%d %B %Y',
  740. '%d %b %Y',
  741. '%B %d %Y',
  742. '%b %d %Y',
  743. '%b %dst %Y %I:%M%p',
  744. '%b %dnd %Y %I:%M%p',
  745. '%b %dth %Y %I:%M%p',
  746. '%Y %m %d',
  747. '%Y-%m-%d',
  748. '%Y/%m/%d',
  749. '%Y/%m/%d %H:%M:%S',
  750. '%Y-%m-%d %H:%M:%S',
  751. '%Y-%m-%d %H:%M:%S.%f',
  752. '%d.%m.%Y %H:%M',
  753. '%d.%m.%Y %H.%M',
  754. '%Y-%m-%dT%H:%M:%SZ',
  755. '%Y-%m-%dT%H:%M:%S.%fZ',
  756. '%Y-%m-%dT%H:%M:%S.%f0Z',
  757. '%Y-%m-%dT%H:%M:%S',
  758. '%Y-%m-%dT%H:%M:%S.%f',
  759. '%Y-%m-%dT%H:%M',
  760. ]
  761. if day_first:
  762. format_expressions.extend([
  763. '%d-%m-%Y',
  764. '%d.%m.%Y',
  765. '%d/%m/%Y',
  766. '%d/%m/%y',
  767. '%d/%m/%Y %H:%M:%S',
  768. ])
  769. else:
  770. format_expressions.extend([
  771. '%m-%d-%Y',
  772. '%m.%d.%Y',
  773. '%m/%d/%Y',
  774. '%m/%d/%y',
  775. '%m/%d/%Y %H:%M:%S',
  776. ])
  777. for expression in format_expressions:
  778. try:
  779. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  780. except ValueError:
  781. pass
  782. if upload_date is None:
  783. timetuple = email.utils.parsedate_tz(date_str)
  784. if timetuple:
  785. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  786. if upload_date is not None:
  787. return compat_str(upload_date)
  788. def determine_ext(url, default_ext='unknown_video'):
  789. if url is None:
  790. return default_ext
  791. guess = url.partition('?')[0].rpartition('.')[2]
  792. if re.match(r'^[A-Za-z0-9]+$', guess):
  793. return guess
  794. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  795. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  796. return guess.rstrip('/')
  797. else:
  798. return default_ext
  799. def subtitles_filename(filename, sub_lang, sub_format):
  800. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  801. def date_from_str(date_str):
  802. """
  803. Return a datetime object from a string in the format YYYYMMDD or
  804. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  805. today = datetime.date.today()
  806. if date_str in ('now', 'today'):
  807. return today
  808. if date_str == 'yesterday':
  809. return today - datetime.timedelta(days=1)
  810. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  811. if match is not None:
  812. sign = match.group('sign')
  813. time = int(match.group('time'))
  814. if sign == '-':
  815. time = -time
  816. unit = match.group('unit')
  817. # A bad approximation?
  818. if unit == 'month':
  819. unit = 'day'
  820. time *= 30
  821. elif unit == 'year':
  822. unit = 'day'
  823. time *= 365
  824. unit += 's'
  825. delta = datetime.timedelta(**{unit: time})
  826. return today + delta
  827. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  828. def hyphenate_date(date_str):
  829. """
  830. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  831. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  832. if match is not None:
  833. return '-'.join(match.groups())
  834. else:
  835. return date_str
  836. class DateRange(object):
  837. """Represents a time interval between two dates"""
  838. def __init__(self, start=None, end=None):
  839. """start and end must be strings in the format accepted by date"""
  840. if start is not None:
  841. self.start = date_from_str(start)
  842. else:
  843. self.start = datetime.datetime.min.date()
  844. if end is not None:
  845. self.end = date_from_str(end)
  846. else:
  847. self.end = datetime.datetime.max.date()
  848. if self.start > self.end:
  849. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  850. @classmethod
  851. def day(cls, day):
  852. """Returns a range that only contains the given day"""
  853. return cls(day, day)
  854. def __contains__(self, date):
  855. """Check if the date is in the range"""
  856. if not isinstance(date, datetime.date):
  857. date = date_from_str(date)
  858. return self.start <= date <= self.end
  859. def __str__(self):
  860. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  861. def platform_name():
  862. """ Returns the platform name as a compat_str """
  863. res = platform.platform()
  864. if isinstance(res, bytes):
  865. res = res.decode(preferredencoding())
  866. assert isinstance(res, compat_str)
  867. return res
  868. def _windows_write_string(s, out):
  869. """ Returns True if the string was written using special methods,
  870. False if it has yet to be written out."""
  871. # Adapted from http://stackoverflow.com/a/3259271/35070
  872. import ctypes
  873. import ctypes.wintypes
  874. WIN_OUTPUT_IDS = {
  875. 1: -11,
  876. 2: -12,
  877. }
  878. try:
  879. fileno = out.fileno()
  880. except AttributeError:
  881. # If the output stream doesn't have a fileno, it's virtual
  882. return False
  883. except io.UnsupportedOperation:
  884. # Some strange Windows pseudo files?
  885. return False
  886. if fileno not in WIN_OUTPUT_IDS:
  887. return False
  888. GetStdHandle = ctypes.WINFUNCTYPE(
  889. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  890. (b'GetStdHandle', ctypes.windll.kernel32))
  891. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  892. WriteConsoleW = ctypes.WINFUNCTYPE(
  893. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  894. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  895. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  896. written = ctypes.wintypes.DWORD(0)
  897. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  898. FILE_TYPE_CHAR = 0x0002
  899. FILE_TYPE_REMOTE = 0x8000
  900. GetConsoleMode = ctypes.WINFUNCTYPE(
  901. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  902. ctypes.POINTER(ctypes.wintypes.DWORD))(
  903. (b'GetConsoleMode', ctypes.windll.kernel32))
  904. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  905. def not_a_console(handle):
  906. if handle == INVALID_HANDLE_VALUE or handle is None:
  907. return True
  908. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  909. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  910. if not_a_console(h):
  911. return False
  912. def next_nonbmp_pos(s):
  913. try:
  914. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  915. except StopIteration:
  916. return len(s)
  917. while s:
  918. count = min(next_nonbmp_pos(s), 1024)
  919. ret = WriteConsoleW(
  920. h, s, count if count else 2, ctypes.byref(written), None)
  921. if ret == 0:
  922. raise OSError('Failed to write string')
  923. if not count: # We just wrote a non-BMP character
  924. assert written.value == 2
  925. s = s[1:]
  926. else:
  927. assert written.value > 0
  928. s = s[written.value:]
  929. return True
  930. def write_string(s, out=None, encoding=None):
  931. if out is None:
  932. out = sys.stderr
  933. assert type(s) == compat_str
  934. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  935. if _windows_write_string(s, out):
  936. return
  937. if ('b' in getattr(out, 'mode', '') or
  938. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  939. byt = s.encode(encoding or preferredencoding(), 'ignore')
  940. out.write(byt)
  941. elif hasattr(out, 'buffer'):
  942. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  943. byt = s.encode(enc, 'ignore')
  944. out.buffer.write(byt)
  945. else:
  946. out.write(s)
  947. out.flush()
  948. def bytes_to_intlist(bs):
  949. if not bs:
  950. return []
  951. if isinstance(bs[0], int): # Python 3
  952. return list(bs)
  953. else:
  954. return [ord(c) for c in bs]
  955. def intlist_to_bytes(xs):
  956. if not xs:
  957. return b''
  958. return struct_pack('%dB' % len(xs), *xs)
  959. # Cross-platform file locking
  960. if sys.platform == 'win32':
  961. import ctypes.wintypes
  962. import msvcrt
  963. class OVERLAPPED(ctypes.Structure):
  964. _fields_ = [
  965. ('Internal', ctypes.wintypes.LPVOID),
  966. ('InternalHigh', ctypes.wintypes.LPVOID),
  967. ('Offset', ctypes.wintypes.DWORD),
  968. ('OffsetHigh', ctypes.wintypes.DWORD),
  969. ('hEvent', ctypes.wintypes.HANDLE),
  970. ]
  971. kernel32 = ctypes.windll.kernel32
  972. LockFileEx = kernel32.LockFileEx
  973. LockFileEx.argtypes = [
  974. ctypes.wintypes.HANDLE, # hFile
  975. ctypes.wintypes.DWORD, # dwFlags
  976. ctypes.wintypes.DWORD, # dwReserved
  977. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  978. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  979. ctypes.POINTER(OVERLAPPED) # Overlapped
  980. ]
  981. LockFileEx.restype = ctypes.wintypes.BOOL
  982. UnlockFileEx = kernel32.UnlockFileEx
  983. UnlockFileEx.argtypes = [
  984. ctypes.wintypes.HANDLE, # hFile
  985. ctypes.wintypes.DWORD, # dwReserved
  986. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  987. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  988. ctypes.POINTER(OVERLAPPED) # Overlapped
  989. ]
  990. UnlockFileEx.restype = ctypes.wintypes.BOOL
  991. whole_low = 0xffffffff
  992. whole_high = 0x7fffffff
  993. def _lock_file(f, exclusive):
  994. overlapped = OVERLAPPED()
  995. overlapped.Offset = 0
  996. overlapped.OffsetHigh = 0
  997. overlapped.hEvent = 0
  998. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  999. handle = msvcrt.get_osfhandle(f.fileno())
  1000. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1001. whole_low, whole_high, f._lock_file_overlapped_p):
  1002. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1003. def _unlock_file(f):
  1004. assert f._lock_file_overlapped_p
  1005. handle = msvcrt.get_osfhandle(f.fileno())
  1006. if not UnlockFileEx(handle, 0,
  1007. whole_low, whole_high, f._lock_file_overlapped_p):
  1008. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1009. else:
  1010. # Some platforms, such as Jython, is missing fcntl
  1011. try:
  1012. import fcntl
  1013. def _lock_file(f, exclusive):
  1014. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1015. def _unlock_file(f):
  1016. fcntl.flock(f, fcntl.LOCK_UN)
  1017. except ImportError:
  1018. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1019. def _lock_file(f, exclusive):
  1020. raise IOError(UNSUPPORTED_MSG)
  1021. def _unlock_file(f):
  1022. raise IOError(UNSUPPORTED_MSG)
  1023. class locked_file(object):
  1024. def __init__(self, filename, mode, encoding=None):
  1025. assert mode in ['r', 'a', 'w']
  1026. self.f = io.open(filename, mode, encoding=encoding)
  1027. self.mode = mode
  1028. def __enter__(self):
  1029. exclusive = self.mode != 'r'
  1030. try:
  1031. _lock_file(self.f, exclusive)
  1032. except IOError:
  1033. self.f.close()
  1034. raise
  1035. return self
  1036. def __exit__(self, etype, value, traceback):
  1037. try:
  1038. _unlock_file(self.f)
  1039. finally:
  1040. self.f.close()
  1041. def __iter__(self):
  1042. return iter(self.f)
  1043. def write(self, *args):
  1044. return self.f.write(*args)
  1045. def read(self, *args):
  1046. return self.f.read(*args)
  1047. def get_filesystem_encoding():
  1048. encoding = sys.getfilesystemencoding()
  1049. return encoding if encoding is not None else 'utf-8'
  1050. def shell_quote(args):
  1051. quoted_args = []
  1052. encoding = get_filesystem_encoding()
  1053. for a in args:
  1054. if isinstance(a, bytes):
  1055. # We may get a filename encoded with 'encodeFilename'
  1056. a = a.decode(encoding)
  1057. quoted_args.append(pipes.quote(a))
  1058. return ' '.join(quoted_args)
  1059. def smuggle_url(url, data):
  1060. """ Pass additional data in a URL for internal use. """
  1061. sdata = compat_urllib_parse.urlencode(
  1062. {'__youtubedl_smuggle': json.dumps(data)})
  1063. return url + '#' + sdata
  1064. def unsmuggle_url(smug_url, default=None):
  1065. if '#__youtubedl_smuggle' not in smug_url:
  1066. return smug_url, default
  1067. url, _, sdata = smug_url.rpartition('#')
  1068. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1069. data = json.loads(jsond)
  1070. return url, data
  1071. def format_bytes(bytes):
  1072. if bytes is None:
  1073. return 'N/A'
  1074. if type(bytes) is str:
  1075. bytes = float(bytes)
  1076. if bytes == 0.0:
  1077. exponent = 0
  1078. else:
  1079. exponent = int(math.log(bytes, 1024.0))
  1080. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1081. converted = float(bytes) / float(1024 ** exponent)
  1082. return '%.2f%s' % (converted, suffix)
  1083. def parse_filesize(s):
  1084. if s is None:
  1085. return None
  1086. # The lower-case forms are of course incorrect and unofficial,
  1087. # but we support those too
  1088. _UNIT_TABLE = {
  1089. 'B': 1,
  1090. 'b': 1,
  1091. 'KiB': 1024,
  1092. 'KB': 1000,
  1093. 'kB': 1024,
  1094. 'Kb': 1000,
  1095. 'MiB': 1024 ** 2,
  1096. 'MB': 1000 ** 2,
  1097. 'mB': 1024 ** 2,
  1098. 'Mb': 1000 ** 2,
  1099. 'GiB': 1024 ** 3,
  1100. 'GB': 1000 ** 3,
  1101. 'gB': 1024 ** 3,
  1102. 'Gb': 1000 ** 3,
  1103. 'TiB': 1024 ** 4,
  1104. 'TB': 1000 ** 4,
  1105. 'tB': 1024 ** 4,
  1106. 'Tb': 1000 ** 4,
  1107. 'PiB': 1024 ** 5,
  1108. 'PB': 1000 ** 5,
  1109. 'pB': 1024 ** 5,
  1110. 'Pb': 1000 ** 5,
  1111. 'EiB': 1024 ** 6,
  1112. 'EB': 1000 ** 6,
  1113. 'eB': 1024 ** 6,
  1114. 'Eb': 1000 ** 6,
  1115. 'ZiB': 1024 ** 7,
  1116. 'ZB': 1000 ** 7,
  1117. 'zB': 1024 ** 7,
  1118. 'Zb': 1000 ** 7,
  1119. 'YiB': 1024 ** 8,
  1120. 'YB': 1000 ** 8,
  1121. 'yB': 1024 ** 8,
  1122. 'Yb': 1000 ** 8,
  1123. }
  1124. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  1125. m = re.match(
  1126. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  1127. if not m:
  1128. return None
  1129. num_str = m.group('num').replace(',', '.')
  1130. mult = _UNIT_TABLE[m.group('unit')]
  1131. return int(float(num_str) * mult)
  1132. def month_by_name(name):
  1133. """ Return the number of a month by (locale-independently) English name """
  1134. try:
  1135. return ENGLISH_MONTH_NAMES.index(name) + 1
  1136. except ValueError:
  1137. return None
  1138. def month_by_abbreviation(abbrev):
  1139. """ Return the number of a month by (locale-independently) English
  1140. abbreviations """
  1141. try:
  1142. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1143. except ValueError:
  1144. return None
  1145. def fix_xml_ampersands(xml_str):
  1146. """Replace all the '&' by '&amp;' in XML"""
  1147. return re.sub(
  1148. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1149. '&amp;',
  1150. xml_str)
  1151. def setproctitle(title):
  1152. assert isinstance(title, compat_str)
  1153. # ctypes in Jython is not complete
  1154. # http://bugs.jython.org/issue2148
  1155. if sys.platform.startswith('java'):
  1156. return
  1157. try:
  1158. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1159. except OSError:
  1160. return
  1161. title_bytes = title.encode('utf-8')
  1162. buf = ctypes.create_string_buffer(len(title_bytes))
  1163. buf.value = title_bytes
  1164. try:
  1165. libc.prctl(15, buf, 0, 0, 0)
  1166. except AttributeError:
  1167. return # Strange libc, just skip this
  1168. def remove_start(s, start):
  1169. if s.startswith(start):
  1170. return s[len(start):]
  1171. return s
  1172. def remove_end(s, end):
  1173. if s.endswith(end):
  1174. return s[:-len(end)]
  1175. return s
  1176. def remove_quotes(s):
  1177. if s is None or len(s) < 2:
  1178. return s
  1179. for quote in ('"', "'", ):
  1180. if s[0] == quote and s[-1] == quote:
  1181. return s[1:-1]
  1182. return s
  1183. def url_basename(url):
  1184. path = compat_urlparse.urlparse(url).path
  1185. return path.strip('/').split('/')[-1]
  1186. class HEADRequest(compat_urllib_request.Request):
  1187. def get_method(self):
  1188. return 'HEAD'
  1189. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1190. if get_attr:
  1191. if v is not None:
  1192. v = getattr(v, get_attr, None)
  1193. if v == '':
  1194. v = None
  1195. if v is None:
  1196. return default
  1197. try:
  1198. return int(v) * invscale // scale
  1199. except ValueError:
  1200. return default
  1201. def str_or_none(v, default=None):
  1202. return default if v is None else compat_str(v)
  1203. def str_to_int(int_str):
  1204. """ A more relaxed version of int_or_none """
  1205. if int_str is None:
  1206. return None
  1207. int_str = re.sub(r'[,\.\+]', '', int_str)
  1208. return int(int_str)
  1209. def float_or_none(v, scale=1, invscale=1, default=None):
  1210. if v is None:
  1211. return default
  1212. try:
  1213. return float(v) * invscale / scale
  1214. except ValueError:
  1215. return default
  1216. def parse_duration(s):
  1217. if not isinstance(s, compat_basestring):
  1218. return None
  1219. s = s.strip()
  1220. m = re.match(
  1221. r'''(?ix)(?:P?T)?
  1222. (?:
  1223. (?P<only_mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*|
  1224. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1225. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?\.?|minutes?)\s*|
  1226. (?:
  1227. (?:
  1228. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1229. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1230. )?
  1231. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1232. )?
  1233. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1234. )$''', s)
  1235. if not m:
  1236. return None
  1237. res = 0
  1238. if m.group('only_mins'):
  1239. return float_or_none(m.group('only_mins'), invscale=60)
  1240. if m.group('only_hours'):
  1241. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1242. if m.group('secs'):
  1243. res += int(m.group('secs'))
  1244. if m.group('mins_reversed'):
  1245. res += int(m.group('mins_reversed')) * 60
  1246. if m.group('mins'):
  1247. res += int(m.group('mins')) * 60
  1248. if m.group('hours'):
  1249. res += int(m.group('hours')) * 60 * 60
  1250. if m.group('hours_reversed'):
  1251. res += int(m.group('hours_reversed')) * 60 * 60
  1252. if m.group('days'):
  1253. res += int(m.group('days')) * 24 * 60 * 60
  1254. if m.group('ms'):
  1255. res += float(m.group('ms'))
  1256. return res
  1257. def prepend_extension(filename, ext, expected_real_ext=None):
  1258. name, real_ext = os.path.splitext(filename)
  1259. return (
  1260. '{0}.{1}{2}'.format(name, ext, real_ext)
  1261. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1262. else '{0}.{1}'.format(filename, ext))
  1263. def replace_extension(filename, ext, expected_real_ext=None):
  1264. name, real_ext = os.path.splitext(filename)
  1265. return '{0}.{1}'.format(
  1266. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1267. ext)
  1268. def check_executable(exe, args=[]):
  1269. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1270. args can be a list of arguments for a short output (like -version) """
  1271. try:
  1272. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1273. except OSError:
  1274. return False
  1275. return exe
  1276. def get_exe_version(exe, args=['--version'],
  1277. version_re=None, unrecognized='present'):
  1278. """ Returns the version of the specified executable,
  1279. or False if the executable is not present """
  1280. try:
  1281. out, _ = subprocess.Popen(
  1282. [encodeArgument(exe)] + args,
  1283. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1284. except OSError:
  1285. return False
  1286. if isinstance(out, bytes): # Python 2.x
  1287. out = out.decode('ascii', 'ignore')
  1288. return detect_exe_version(out, version_re, unrecognized)
  1289. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1290. assert isinstance(output, compat_str)
  1291. if version_re is None:
  1292. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1293. m = re.search(version_re, output)
  1294. if m:
  1295. return m.group(1)
  1296. else:
  1297. return unrecognized
  1298. class PagedList(object):
  1299. def __len__(self):
  1300. # This is only useful for tests
  1301. return len(self.getslice())
  1302. class OnDemandPagedList(PagedList):
  1303. def __init__(self, pagefunc, pagesize):
  1304. self._pagefunc = pagefunc
  1305. self._pagesize = pagesize
  1306. def getslice(self, start=0, end=None):
  1307. res = []
  1308. for pagenum in itertools.count(start // self._pagesize):
  1309. firstid = pagenum * self._pagesize
  1310. nextfirstid = pagenum * self._pagesize + self._pagesize
  1311. if start >= nextfirstid:
  1312. continue
  1313. page_results = list(self._pagefunc(pagenum))
  1314. startv = (
  1315. start % self._pagesize
  1316. if firstid <= start < nextfirstid
  1317. else 0)
  1318. endv = (
  1319. ((end - 1) % self._pagesize) + 1
  1320. if (end is not None and firstid <= end <= nextfirstid)
  1321. else None)
  1322. if startv != 0 or endv is not None:
  1323. page_results = page_results[startv:endv]
  1324. res.extend(page_results)
  1325. # A little optimization - if current page is not "full", ie. does
  1326. # not contain page_size videos then we can assume that this page
  1327. # is the last one - there are no more ids on further pages -
  1328. # i.e. no need to query again.
  1329. if len(page_results) + startv < self._pagesize:
  1330. break
  1331. # If we got the whole page, but the next page is not interesting,
  1332. # break out early as well
  1333. if end == nextfirstid:
  1334. break
  1335. return res
  1336. class InAdvancePagedList(PagedList):
  1337. def __init__(self, pagefunc, pagecount, pagesize):
  1338. self._pagefunc = pagefunc
  1339. self._pagecount = pagecount
  1340. self._pagesize = pagesize
  1341. def getslice(self, start=0, end=None):
  1342. res = []
  1343. start_page = start // self._pagesize
  1344. end_page = (
  1345. self._pagecount if end is None else (end // self._pagesize + 1))
  1346. skip_elems = start - start_page * self._pagesize
  1347. only_more = None if end is None else end - start
  1348. for pagenum in range(start_page, end_page):
  1349. page = list(self._pagefunc(pagenum))
  1350. if skip_elems:
  1351. page = page[skip_elems:]
  1352. skip_elems = None
  1353. if only_more is not None:
  1354. if len(page) < only_more:
  1355. only_more -= len(page)
  1356. else:
  1357. page = page[:only_more]
  1358. res.extend(page)
  1359. break
  1360. res.extend(page)
  1361. return res
  1362. def uppercase_escape(s):
  1363. unicode_escape = codecs.getdecoder('unicode_escape')
  1364. return re.sub(
  1365. r'\\U[0-9a-fA-F]{8}',
  1366. lambda m: unicode_escape(m.group(0))[0],
  1367. s)
  1368. def lowercase_escape(s):
  1369. unicode_escape = codecs.getdecoder('unicode_escape')
  1370. return re.sub(
  1371. r'\\u[0-9a-fA-F]{4}',
  1372. lambda m: unicode_escape(m.group(0))[0],
  1373. s)
  1374. def escape_rfc3986(s):
  1375. """Escape non-ASCII characters as suggested by RFC 3986"""
  1376. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1377. s = s.encode('utf-8')
  1378. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1379. def escape_url(url):
  1380. """Escape URL as suggested by RFC 3986"""
  1381. url_parsed = compat_urllib_parse_urlparse(url)
  1382. return url_parsed._replace(
  1383. path=escape_rfc3986(url_parsed.path),
  1384. params=escape_rfc3986(url_parsed.params),
  1385. query=escape_rfc3986(url_parsed.query),
  1386. fragment=escape_rfc3986(url_parsed.fragment)
  1387. ).geturl()
  1388. try:
  1389. struct.pack('!I', 0)
  1390. except TypeError:
  1391. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1392. def struct_pack(spec, *args):
  1393. if isinstance(spec, compat_str):
  1394. spec = spec.encode('ascii')
  1395. return struct.pack(spec, *args)
  1396. def struct_unpack(spec, *args):
  1397. if isinstance(spec, compat_str):
  1398. spec = spec.encode('ascii')
  1399. return struct.unpack(spec, *args)
  1400. else:
  1401. struct_pack = struct.pack
  1402. struct_unpack = struct.unpack
  1403. def read_batch_urls(batch_fd):
  1404. def fixup(url):
  1405. if not isinstance(url, compat_str):
  1406. url = url.decode('utf-8', 'replace')
  1407. BOM_UTF8 = '\xef\xbb\xbf'
  1408. if url.startswith(BOM_UTF8):
  1409. url = url[len(BOM_UTF8):]
  1410. url = url.strip()
  1411. if url.startswith(('#', ';', ']')):
  1412. return False
  1413. return url
  1414. with contextlib.closing(batch_fd) as fd:
  1415. return [url for url in map(fixup, fd) if url]
  1416. def urlencode_postdata(*args, **kargs):
  1417. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1418. def encode_dict(d, encoding='utf-8'):
  1419. def encode(v):
  1420. return v.encode(encoding) if isinstance(v, compat_basestring) else v
  1421. return dict((encode(k), encode(v)) for k, v in d.items())
  1422. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1423. if isinstance(key_or_keys, (list, tuple)):
  1424. for key in key_or_keys:
  1425. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1426. continue
  1427. return d[key]
  1428. return default
  1429. return d.get(key_or_keys, default)
  1430. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1431. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1432. US_RATINGS = {
  1433. 'G': 0,
  1434. 'PG': 10,
  1435. 'PG-13': 13,
  1436. 'R': 16,
  1437. 'NC': 18,
  1438. }
  1439. def parse_age_limit(s):
  1440. if s is None:
  1441. return None
  1442. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1443. return int(m.group('age')) if m else US_RATINGS.get(s)
  1444. def strip_jsonp(code):
  1445. return re.sub(
  1446. r'(?s)^[a-zA-Z0-9_.]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1447. def js_to_json(code):
  1448. def fix_kv(m):
  1449. v = m.group(0)
  1450. if v in ('true', 'false', 'null'):
  1451. return v
  1452. if v.startswith('"'):
  1453. v = re.sub(r"\\'", "'", v[1:-1])
  1454. elif v.startswith("'"):
  1455. v = v[1:-1]
  1456. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1457. '\\\\': '\\\\',
  1458. "\\'": "'",
  1459. '"': '\\"',
  1460. }[m.group(0)], v)
  1461. return '"%s"' % v
  1462. res = re.sub(r'''(?x)
  1463. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1464. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1465. [a-zA-Z_][.a-zA-Z_0-9]*
  1466. ''', fix_kv, code)
  1467. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1468. return res
  1469. def qualities(quality_ids):
  1470. """ Get a numeric quality value out of a list of possible values """
  1471. def q(qid):
  1472. try:
  1473. return quality_ids.index(qid)
  1474. except ValueError:
  1475. return -1
  1476. return q
  1477. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1478. def limit_length(s, length):
  1479. """ Add ellipses to overly long strings """
  1480. if s is None:
  1481. return None
  1482. ELLIPSES = '...'
  1483. if len(s) > length:
  1484. return s[:length - len(ELLIPSES)] + ELLIPSES
  1485. return s
  1486. def version_tuple(v):
  1487. return tuple(int(e) for e in re.split(r'[-.]', v))
  1488. def is_outdated_version(version, limit, assume_new=True):
  1489. if not version:
  1490. return not assume_new
  1491. try:
  1492. return version_tuple(version) < version_tuple(limit)
  1493. except ValueError:
  1494. return not assume_new
  1495. def ytdl_is_updateable():
  1496. """ Returns if youtube-dl can be updated with -U """
  1497. from zipimport import zipimporter
  1498. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1499. def args_to_str(args):
  1500. # Get a short string representation for a subprocess command
  1501. return ' '.join(shlex_quote(a) for a in args)
  1502. def error_to_compat_str(err):
  1503. err_str = str(err)
  1504. # On python 2 error byte string must be decoded with proper
  1505. # encoding rather than ascii
  1506. if sys.version_info[0] < 3:
  1507. err_str = err_str.decode(preferredencoding())
  1508. return err_str
  1509. def mimetype2ext(mt):
  1510. ext = {
  1511. 'audio/mp4': 'm4a',
  1512. }.get(mt)
  1513. if ext is not None:
  1514. return ext
  1515. _, _, res = mt.rpartition('/')
  1516. return {
  1517. '3gpp': '3gp',
  1518. 'ttml+xml': 'ttml',
  1519. 'x-flv': 'flv',
  1520. 'x-mp4-fragmented': 'mp4',
  1521. 'x-ms-wmv': 'wmv',
  1522. }.get(res, res)
  1523. def urlhandle_detect_ext(url_handle):
  1524. try:
  1525. url_handle.headers
  1526. getheader = lambda h: url_handle.headers[h]
  1527. except AttributeError: # Python < 3
  1528. getheader = url_handle.info().getheader
  1529. cd = getheader('Content-Disposition')
  1530. if cd:
  1531. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1532. if m:
  1533. e = determine_ext(m.group('filename'), default_ext=None)
  1534. if e:
  1535. return e
  1536. return mimetype2ext(getheader('Content-Type'))
  1537. def encode_data_uri(data, mime_type):
  1538. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1539. def age_restricted(content_limit, age_limit):
  1540. """ Returns True iff the content should be blocked """
  1541. if age_limit is None: # No limit set
  1542. return False
  1543. if content_limit is None:
  1544. return False # Content available for everyone
  1545. return age_limit < content_limit
  1546. def is_html(first_bytes):
  1547. """ Detect whether a file contains HTML by examining its first bytes. """
  1548. BOMS = [
  1549. (b'\xef\xbb\xbf', 'utf-8'),
  1550. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1551. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1552. (b'\xff\xfe', 'utf-16-le'),
  1553. (b'\xfe\xff', 'utf-16-be'),
  1554. ]
  1555. for bom, enc in BOMS:
  1556. if first_bytes.startswith(bom):
  1557. s = first_bytes[len(bom):].decode(enc, 'replace')
  1558. break
  1559. else:
  1560. s = first_bytes.decode('utf-8', 'replace')
  1561. return re.match(r'^\s*<', s)
  1562. def determine_protocol(info_dict):
  1563. protocol = info_dict.get('protocol')
  1564. if protocol is not None:
  1565. return protocol
  1566. url = info_dict['url']
  1567. if url.startswith('rtmp'):
  1568. return 'rtmp'
  1569. elif url.startswith('mms'):
  1570. return 'mms'
  1571. elif url.startswith('rtsp'):
  1572. return 'rtsp'
  1573. ext = determine_ext(url)
  1574. if ext == 'm3u8':
  1575. return 'm3u8'
  1576. elif ext == 'f4m':
  1577. return 'f4m'
  1578. return compat_urllib_parse_urlparse(url).scheme
  1579. def render_table(header_row, data):
  1580. """ Render a list of rows, each as a list of values """
  1581. table = [header_row] + data
  1582. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1583. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1584. return '\n'.join(format_str % tuple(row) for row in table)
  1585. def _match_one(filter_part, dct):
  1586. COMPARISON_OPERATORS = {
  1587. '<': operator.lt,
  1588. '<=': operator.le,
  1589. '>': operator.gt,
  1590. '>=': operator.ge,
  1591. '=': operator.eq,
  1592. '!=': operator.ne,
  1593. }
  1594. operator_rex = re.compile(r'''(?x)\s*
  1595. (?P<key>[a-z_]+)
  1596. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1597. (?:
  1598. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1599. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1600. )
  1601. \s*$
  1602. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1603. m = operator_rex.search(filter_part)
  1604. if m:
  1605. op = COMPARISON_OPERATORS[m.group('op')]
  1606. if m.group('strval') is not None:
  1607. if m.group('op') not in ('=', '!='):
  1608. raise ValueError(
  1609. 'Operator %s does not support string values!' % m.group('op'))
  1610. comparison_value = m.group('strval')
  1611. else:
  1612. try:
  1613. comparison_value = int(m.group('intval'))
  1614. except ValueError:
  1615. comparison_value = parse_filesize(m.group('intval'))
  1616. if comparison_value is None:
  1617. comparison_value = parse_filesize(m.group('intval') + 'B')
  1618. if comparison_value is None:
  1619. raise ValueError(
  1620. 'Invalid integer value %r in filter part %r' % (
  1621. m.group('intval'), filter_part))
  1622. actual_value = dct.get(m.group('key'))
  1623. if actual_value is None:
  1624. return m.group('none_inclusive')
  1625. return op(actual_value, comparison_value)
  1626. UNARY_OPERATORS = {
  1627. '': lambda v: v is not None,
  1628. '!': lambda v: v is None,
  1629. }
  1630. operator_rex = re.compile(r'''(?x)\s*
  1631. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1632. \s*$
  1633. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1634. m = operator_rex.search(filter_part)
  1635. if m:
  1636. op = UNARY_OPERATORS[m.group('op')]
  1637. actual_value = dct.get(m.group('key'))
  1638. return op(actual_value)
  1639. raise ValueError('Invalid filter part %r' % filter_part)
  1640. def match_str(filter_str, dct):
  1641. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1642. return all(
  1643. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1644. def match_filter_func(filter_str):
  1645. def _match_func(info_dict):
  1646. if match_str(filter_str, info_dict):
  1647. return None
  1648. else:
  1649. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1650. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1651. return _match_func
  1652. def parse_dfxp_time_expr(time_expr):
  1653. if not time_expr:
  1654. return
  1655. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1656. if mobj:
  1657. return float(mobj.group('time_offset'))
  1658. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1659. if mobj:
  1660. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1661. def srt_subtitles_timecode(seconds):
  1662. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1663. def dfxp2srt(dfxp_data):
  1664. _x = functools.partial(xpath_with_ns, ns_map={
  1665. 'ttml': 'http://www.w3.org/ns/ttml',
  1666. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1667. })
  1668. class TTMLPElementParser(object):
  1669. out = ''
  1670. def start(self, tag, attrib):
  1671. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1672. self.out += '\n'
  1673. def end(self, tag):
  1674. pass
  1675. def data(self, data):
  1676. self.out += data
  1677. def close(self):
  1678. return self.out.strip()
  1679. def parse_node(node):
  1680. target = TTMLPElementParser()
  1681. parser = xml.etree.ElementTree.XMLParser(target=target)
  1682. parser.feed(xml.etree.ElementTree.tostring(node))
  1683. return parser.close()
  1684. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1685. out = []
  1686. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall('.//p')
  1687. if not paras:
  1688. raise ValueError('Invalid dfxp/TTML subtitle')
  1689. for para, index in zip(paras, itertools.count(1)):
  1690. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1691. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1692. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1693. if begin_time is None:
  1694. continue
  1695. if not end_time:
  1696. if not dur:
  1697. continue
  1698. end_time = begin_time + dur
  1699. out.append('%d\n%s --> %s\n%s\n\n' % (
  1700. index,
  1701. srt_subtitles_timecode(begin_time),
  1702. srt_subtitles_timecode(end_time),
  1703. parse_node(para)))
  1704. return ''.join(out)
  1705. def cli_option(params, command_option, param):
  1706. param = params.get(param)
  1707. return [command_option, param] if param is not None else []
  1708. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1709. param = params.get(param)
  1710. assert isinstance(param, bool)
  1711. if separator:
  1712. return [command_option + separator + (true_value if param else false_value)]
  1713. return [command_option, true_value if param else false_value]
  1714. def cli_valueless_option(params, command_option, param, expected_value=True):
  1715. param = params.get(param)
  1716. return [command_option] if param == expected_value else []
  1717. def cli_configuration_args(params, param, default=[]):
  1718. ex_args = params.get(param)
  1719. if ex_args is None:
  1720. return default
  1721. assert isinstance(ex_args, list)
  1722. return ex_args
  1723. class ISO639Utils(object):
  1724. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1725. _lang_map = {
  1726. 'aa': 'aar',
  1727. 'ab': 'abk',
  1728. 'ae': 'ave',
  1729. 'af': 'afr',
  1730. 'ak': 'aka',
  1731. 'am': 'amh',
  1732. 'an': 'arg',
  1733. 'ar': 'ara',
  1734. 'as': 'asm',
  1735. 'av': 'ava',
  1736. 'ay': 'aym',
  1737. 'az': 'aze',
  1738. 'ba': 'bak',
  1739. 'be': 'bel',
  1740. 'bg': 'bul',
  1741. 'bh': 'bih',
  1742. 'bi': 'bis',
  1743. 'bm': 'bam',
  1744. 'bn': 'ben',
  1745. 'bo': 'bod',
  1746. 'br': 'bre',
  1747. 'bs': 'bos',
  1748. 'ca': 'cat',
  1749. 'ce': 'che',
  1750. 'ch': 'cha',
  1751. 'co': 'cos',
  1752. 'cr': 'cre',
  1753. 'cs': 'ces',
  1754. 'cu': 'chu',
  1755. 'cv': 'chv',
  1756. 'cy': 'cym',
  1757. 'da': 'dan',
  1758. 'de': 'deu',
  1759. 'dv': 'div',
  1760. 'dz': 'dzo',
  1761. 'ee': 'ewe',
  1762. 'el': 'ell',
  1763. 'en': 'eng',
  1764. 'eo': 'epo',
  1765. 'es': 'spa',
  1766. 'et': 'est',
  1767. 'eu': 'eus',
  1768. 'fa': 'fas',
  1769. 'ff': 'ful',
  1770. 'fi': 'fin',
  1771. 'fj': 'fij',
  1772. 'fo': 'fao',
  1773. 'fr': 'fra',
  1774. 'fy': 'fry',
  1775. 'ga': 'gle',
  1776. 'gd': 'gla',
  1777. 'gl': 'glg',
  1778. 'gn': 'grn',
  1779. 'gu': 'guj',
  1780. 'gv': 'glv',
  1781. 'ha': 'hau',
  1782. 'he': 'heb',
  1783. 'hi': 'hin',
  1784. 'ho': 'hmo',
  1785. 'hr': 'hrv',
  1786. 'ht': 'hat',
  1787. 'hu': 'hun',
  1788. 'hy': 'hye',
  1789. 'hz': 'her',
  1790. 'ia': 'ina',
  1791. 'id': 'ind',
  1792. 'ie': 'ile',
  1793. 'ig': 'ibo',
  1794. 'ii': 'iii',
  1795. 'ik': 'ipk',
  1796. 'io': 'ido',
  1797. 'is': 'isl',
  1798. 'it': 'ita',
  1799. 'iu': 'iku',
  1800. 'ja': 'jpn',
  1801. 'jv': 'jav',
  1802. 'ka': 'kat',
  1803. 'kg': 'kon',
  1804. 'ki': 'kik',
  1805. 'kj': 'kua',
  1806. 'kk': 'kaz',
  1807. 'kl': 'kal',
  1808. 'km': 'khm',
  1809. 'kn': 'kan',
  1810. 'ko': 'kor',
  1811. 'kr': 'kau',
  1812. 'ks': 'kas',
  1813. 'ku': 'kur',
  1814. 'kv': 'kom',
  1815. 'kw': 'cor',
  1816. 'ky': 'kir',
  1817. 'la': 'lat',
  1818. 'lb': 'ltz',
  1819. 'lg': 'lug',
  1820. 'li': 'lim',
  1821. 'ln': 'lin',
  1822. 'lo': 'lao',
  1823. 'lt': 'lit',
  1824. 'lu': 'lub',
  1825. 'lv': 'lav',
  1826. 'mg': 'mlg',
  1827. 'mh': 'mah',
  1828. 'mi': 'mri',
  1829. 'mk': 'mkd',
  1830. 'ml': 'mal',
  1831. 'mn': 'mon',
  1832. 'mr': 'mar',
  1833. 'ms': 'msa',
  1834. 'mt': 'mlt',
  1835. 'my': 'mya',
  1836. 'na': 'nau',
  1837. 'nb': 'nob',
  1838. 'nd': 'nde',
  1839. 'ne': 'nep',
  1840. 'ng': 'ndo',
  1841. 'nl': 'nld',
  1842. 'nn': 'nno',
  1843. 'no': 'nor',
  1844. 'nr': 'nbl',
  1845. 'nv': 'nav',
  1846. 'ny': 'nya',
  1847. 'oc': 'oci',
  1848. 'oj': 'oji',
  1849. 'om': 'orm',
  1850. 'or': 'ori',
  1851. 'os': 'oss',
  1852. 'pa': 'pan',
  1853. 'pi': 'pli',
  1854. 'pl': 'pol',
  1855. 'ps': 'pus',
  1856. 'pt': 'por',
  1857. 'qu': 'que',
  1858. 'rm': 'roh',
  1859. 'rn': 'run',
  1860. 'ro': 'ron',
  1861. 'ru': 'rus',
  1862. 'rw': 'kin',
  1863. 'sa': 'san',
  1864. 'sc': 'srd',
  1865. 'sd': 'snd',
  1866. 'se': 'sme',
  1867. 'sg': 'sag',
  1868. 'si': 'sin',
  1869. 'sk': 'slk',
  1870. 'sl': 'slv',
  1871. 'sm': 'smo',
  1872. 'sn': 'sna',
  1873. 'so': 'som',
  1874. 'sq': 'sqi',
  1875. 'sr': 'srp',
  1876. 'ss': 'ssw',
  1877. 'st': 'sot',
  1878. 'su': 'sun',
  1879. 'sv': 'swe',
  1880. 'sw': 'swa',
  1881. 'ta': 'tam',
  1882. 'te': 'tel',
  1883. 'tg': 'tgk',
  1884. 'th': 'tha',
  1885. 'ti': 'tir',
  1886. 'tk': 'tuk',
  1887. 'tl': 'tgl',
  1888. 'tn': 'tsn',
  1889. 'to': 'ton',
  1890. 'tr': 'tur',
  1891. 'ts': 'tso',
  1892. 'tt': 'tat',
  1893. 'tw': 'twi',
  1894. 'ty': 'tah',
  1895. 'ug': 'uig',
  1896. 'uk': 'ukr',
  1897. 'ur': 'urd',
  1898. 'uz': 'uzb',
  1899. 've': 'ven',
  1900. 'vi': 'vie',
  1901. 'vo': 'vol',
  1902. 'wa': 'wln',
  1903. 'wo': 'wol',
  1904. 'xh': 'xho',
  1905. 'yi': 'yid',
  1906. 'yo': 'yor',
  1907. 'za': 'zha',
  1908. 'zh': 'zho',
  1909. 'zu': 'zul',
  1910. }
  1911. @classmethod
  1912. def short2long(cls, code):
  1913. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1914. return cls._lang_map.get(code[:2])
  1915. @classmethod
  1916. def long2short(cls, code):
  1917. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1918. for short_name, long_name in cls._lang_map.items():
  1919. if long_name == code:
  1920. return short_name
  1921. class ISO3166Utils(object):
  1922. # From http://data.okfn.org/data/core/country-list
  1923. _country_map = {
  1924. 'AF': 'Afghanistan',
  1925. 'AX': 'Åland Islands',
  1926. 'AL': 'Albania',
  1927. 'DZ': 'Algeria',
  1928. 'AS': 'American Samoa',
  1929. 'AD': 'Andorra',
  1930. 'AO': 'Angola',
  1931. 'AI': 'Anguilla',
  1932. 'AQ': 'Antarctica',
  1933. 'AG': 'Antigua and Barbuda',
  1934. 'AR': 'Argentina',
  1935. 'AM': 'Armenia',
  1936. 'AW': 'Aruba',
  1937. 'AU': 'Australia',
  1938. 'AT': 'Austria',
  1939. 'AZ': 'Azerbaijan',
  1940. 'BS': 'Bahamas',
  1941. 'BH': 'Bahrain',
  1942. 'BD': 'Bangladesh',
  1943. 'BB': 'Barbados',
  1944. 'BY': 'Belarus',
  1945. 'BE': 'Belgium',
  1946. 'BZ': 'Belize',
  1947. 'BJ': 'Benin',
  1948. 'BM': 'Bermuda',
  1949. 'BT': 'Bhutan',
  1950. 'BO': 'Bolivia, Plurinational State of',
  1951. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  1952. 'BA': 'Bosnia and Herzegovina',
  1953. 'BW': 'Botswana',
  1954. 'BV': 'Bouvet Island',
  1955. 'BR': 'Brazil',
  1956. 'IO': 'British Indian Ocean Territory',
  1957. 'BN': 'Brunei Darussalam',
  1958. 'BG': 'Bulgaria',
  1959. 'BF': 'Burkina Faso',
  1960. 'BI': 'Burundi',
  1961. 'KH': 'Cambodia',
  1962. 'CM': 'Cameroon',
  1963. 'CA': 'Canada',
  1964. 'CV': 'Cape Verde',
  1965. 'KY': 'Cayman Islands',
  1966. 'CF': 'Central African Republic',
  1967. 'TD': 'Chad',
  1968. 'CL': 'Chile',
  1969. 'CN': 'China',
  1970. 'CX': 'Christmas Island',
  1971. 'CC': 'Cocos (Keeling) Islands',
  1972. 'CO': 'Colombia',
  1973. 'KM': 'Comoros',
  1974. 'CG': 'Congo',
  1975. 'CD': 'Congo, the Democratic Republic of the',
  1976. 'CK': 'Cook Islands',
  1977. 'CR': 'Costa Rica',
  1978. 'CI': 'Côte d\'Ivoire',
  1979. 'HR': 'Croatia',
  1980. 'CU': 'Cuba',
  1981. 'CW': 'Curaçao',
  1982. 'CY': 'Cyprus',
  1983. 'CZ': 'Czech Republic',
  1984. 'DK': 'Denmark',
  1985. 'DJ': 'Djibouti',
  1986. 'DM': 'Dominica',
  1987. 'DO': 'Dominican Republic',
  1988. 'EC': 'Ecuador',
  1989. 'EG': 'Egypt',
  1990. 'SV': 'El Salvador',
  1991. 'GQ': 'Equatorial Guinea',
  1992. 'ER': 'Eritrea',
  1993. 'EE': 'Estonia',
  1994. 'ET': 'Ethiopia',
  1995. 'FK': 'Falkland Islands (Malvinas)',
  1996. 'FO': 'Faroe Islands',
  1997. 'FJ': 'Fiji',
  1998. 'FI': 'Finland',
  1999. 'FR': 'France',
  2000. 'GF': 'French Guiana',
  2001. 'PF': 'French Polynesia',
  2002. 'TF': 'French Southern Territories',
  2003. 'GA': 'Gabon',
  2004. 'GM': 'Gambia',
  2005. 'GE': 'Georgia',
  2006. 'DE': 'Germany',
  2007. 'GH': 'Ghana',
  2008. 'GI': 'Gibraltar',
  2009. 'GR': 'Greece',
  2010. 'GL': 'Greenland',
  2011. 'GD': 'Grenada',
  2012. 'GP': 'Guadeloupe',
  2013. 'GU': 'Guam',
  2014. 'GT': 'Guatemala',
  2015. 'GG': 'Guernsey',
  2016. 'GN': 'Guinea',
  2017. 'GW': 'Guinea-Bissau',
  2018. 'GY': 'Guyana',
  2019. 'HT': 'Haiti',
  2020. 'HM': 'Heard Island and McDonald Islands',
  2021. 'VA': 'Holy See (Vatican City State)',
  2022. 'HN': 'Honduras',
  2023. 'HK': 'Hong Kong',
  2024. 'HU': 'Hungary',
  2025. 'IS': 'Iceland',
  2026. 'IN': 'India',
  2027. 'ID': 'Indonesia',
  2028. 'IR': 'Iran, Islamic Republic of',
  2029. 'IQ': 'Iraq',
  2030. 'IE': 'Ireland',
  2031. 'IM': 'Isle of Man',
  2032. 'IL': 'Israel',
  2033. 'IT': 'Italy',
  2034. 'JM': 'Jamaica',
  2035. 'JP': 'Japan',
  2036. 'JE': 'Jersey',
  2037. 'JO': 'Jordan',
  2038. 'KZ': 'Kazakhstan',
  2039. 'KE': 'Kenya',
  2040. 'KI': 'Kiribati',
  2041. 'KP': 'Korea, Democratic People\'s Republic of',
  2042. 'KR': 'Korea, Republic of',
  2043. 'KW': 'Kuwait',
  2044. 'KG': 'Kyrgyzstan',
  2045. 'LA': 'Lao People\'s Democratic Republic',
  2046. 'LV': 'Latvia',
  2047. 'LB': 'Lebanon',
  2048. 'LS': 'Lesotho',
  2049. 'LR': 'Liberia',
  2050. 'LY': 'Libya',
  2051. 'LI': 'Liechtenstein',
  2052. 'LT': 'Lithuania',
  2053. 'LU': 'Luxembourg',
  2054. 'MO': 'Macao',
  2055. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2056. 'MG': 'Madagascar',
  2057. 'MW': 'Malawi',
  2058. 'MY': 'Malaysia',
  2059. 'MV': 'Maldives',
  2060. 'ML': 'Mali',
  2061. 'MT': 'Malta',
  2062. 'MH': 'Marshall Islands',
  2063. 'MQ': 'Martinique',
  2064. 'MR': 'Mauritania',
  2065. 'MU': 'Mauritius',
  2066. 'YT': 'Mayotte',
  2067. 'MX': 'Mexico',
  2068. 'FM': 'Micronesia, Federated States of',
  2069. 'MD': 'Moldova, Republic of',
  2070. 'MC': 'Monaco',
  2071. 'MN': 'Mongolia',
  2072. 'ME': 'Montenegro',
  2073. 'MS': 'Montserrat',
  2074. 'MA': 'Morocco',
  2075. 'MZ': 'Mozambique',
  2076. 'MM': 'Myanmar',
  2077. 'NA': 'Namibia',
  2078. 'NR': 'Nauru',
  2079. 'NP': 'Nepal',
  2080. 'NL': 'Netherlands',
  2081. 'NC': 'New Caledonia',
  2082. 'NZ': 'New Zealand',
  2083. 'NI': 'Nicaragua',
  2084. 'NE': 'Niger',
  2085. 'NG': 'Nigeria',
  2086. 'NU': 'Niue',
  2087. 'NF': 'Norfolk Island',
  2088. 'MP': 'Northern Mariana Islands',
  2089. 'NO': 'Norway',
  2090. 'OM': 'Oman',
  2091. 'PK': 'Pakistan',
  2092. 'PW': 'Palau',
  2093. 'PS': 'Palestine, State of',
  2094. 'PA': 'Panama',
  2095. 'PG': 'Papua New Guinea',
  2096. 'PY': 'Paraguay',
  2097. 'PE': 'Peru',
  2098. 'PH': 'Philippines',
  2099. 'PN': 'Pitcairn',
  2100. 'PL': 'Poland',
  2101. 'PT': 'Portugal',
  2102. 'PR': 'Puerto Rico',
  2103. 'QA': 'Qatar',
  2104. 'RE': 'Réunion',
  2105. 'RO': 'Romania',
  2106. 'RU': 'Russian Federation',
  2107. 'RW': 'Rwanda',
  2108. 'BL': 'Saint Barthélemy',
  2109. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2110. 'KN': 'Saint Kitts and Nevis',
  2111. 'LC': 'Saint Lucia',
  2112. 'MF': 'Saint Martin (French part)',
  2113. 'PM': 'Saint Pierre and Miquelon',
  2114. 'VC': 'Saint Vincent and the Grenadines',
  2115. 'WS': 'Samoa',
  2116. 'SM': 'San Marino',
  2117. 'ST': 'Sao Tome and Principe',
  2118. 'SA': 'Saudi Arabia',
  2119. 'SN': 'Senegal',
  2120. 'RS': 'Serbia',
  2121. 'SC': 'Seychelles',
  2122. 'SL': 'Sierra Leone',
  2123. 'SG': 'Singapore',
  2124. 'SX': 'Sint Maarten (Dutch part)',
  2125. 'SK': 'Slovakia',
  2126. 'SI': 'Slovenia',
  2127. 'SB': 'Solomon Islands',
  2128. 'SO': 'Somalia',
  2129. 'ZA': 'South Africa',
  2130. 'GS': 'South Georgia and the South Sandwich Islands',
  2131. 'SS': 'South Sudan',
  2132. 'ES': 'Spain',
  2133. 'LK': 'Sri Lanka',
  2134. 'SD': 'Sudan',
  2135. 'SR': 'Suriname',
  2136. 'SJ': 'Svalbard and Jan Mayen',
  2137. 'SZ': 'Swaziland',
  2138. 'SE': 'Sweden',
  2139. 'CH': 'Switzerland',
  2140. 'SY': 'Syrian Arab Republic',
  2141. 'TW': 'Taiwan, Province of China',
  2142. 'TJ': 'Tajikistan',
  2143. 'TZ': 'Tanzania, United Republic of',
  2144. 'TH': 'Thailand',
  2145. 'TL': 'Timor-Leste',
  2146. 'TG': 'Togo',
  2147. 'TK': 'Tokelau',
  2148. 'TO': 'Tonga',
  2149. 'TT': 'Trinidad and Tobago',
  2150. 'TN': 'Tunisia',
  2151. 'TR': 'Turkey',
  2152. 'TM': 'Turkmenistan',
  2153. 'TC': 'Turks and Caicos Islands',
  2154. 'TV': 'Tuvalu',
  2155. 'UG': 'Uganda',
  2156. 'UA': 'Ukraine',
  2157. 'AE': 'United Arab Emirates',
  2158. 'GB': 'United Kingdom',
  2159. 'US': 'United States',
  2160. 'UM': 'United States Minor Outlying Islands',
  2161. 'UY': 'Uruguay',
  2162. 'UZ': 'Uzbekistan',
  2163. 'VU': 'Vanuatu',
  2164. 'VE': 'Venezuela, Bolivarian Republic of',
  2165. 'VN': 'Viet Nam',
  2166. 'VG': 'Virgin Islands, British',
  2167. 'VI': 'Virgin Islands, U.S.',
  2168. 'WF': 'Wallis and Futuna',
  2169. 'EH': 'Western Sahara',
  2170. 'YE': 'Yemen',
  2171. 'ZM': 'Zambia',
  2172. 'ZW': 'Zimbabwe',
  2173. }
  2174. @classmethod
  2175. def short2full(cls, code):
  2176. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2177. return cls._country_map.get(code.upper())
  2178. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2179. def __init__(self, proxies=None):
  2180. # Set default handlers
  2181. for type in ('http', 'https'):
  2182. setattr(self, '%s_open' % type,
  2183. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2184. meth(r, proxy, type))
  2185. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2186. def proxy_open(self, req, proxy, type):
  2187. req_proxy = req.headers.get('Ytdl-request-proxy')
  2188. if req_proxy is not None:
  2189. proxy = req_proxy
  2190. del req.headers['Ytdl-request-proxy']
  2191. if proxy == '__noproxy__':
  2192. return None # No Proxy
  2193. return compat_urllib_request.ProxyHandler.proxy_open(
  2194. self, req, proxy, type)
  2195. def ohdave_rsa_encrypt(data, exponent, modulus):
  2196. '''
  2197. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2198. Input:
  2199. data: data to encrypt, bytes-like object
  2200. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2201. Output: hex string of encrypted data
  2202. Limitation: supports one block encryption only
  2203. '''
  2204. payload = int(binascii.hexlify(data[::-1]), 16)
  2205. encrypted = pow(payload, exponent, modulus)
  2206. return '%x' % encrypted