utils.py 83 KB

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