You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5614 lines
160 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  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 email.header
  13. import errno
  14. import functools
  15. import gzip
  16. import io
  17. import itertools
  18. import json
  19. import locale
  20. import math
  21. import operator
  22. import os
  23. import platform
  24. import random
  25. import re
  26. import socket
  27. import ssl
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_HTMLParseError,
  36. compat_HTMLParser,
  37. compat_basestring,
  38. compat_chr,
  39. compat_cookiejar,
  40. compat_ctypes_WINFUNCTYPE,
  41. compat_etree_fromstring,
  42. compat_expanduser,
  43. compat_html_entities,
  44. compat_html_entities_html5,
  45. compat_http_client,
  46. compat_integer_types,
  47. compat_kwargs,
  48. compat_os_name,
  49. compat_parse_qs,
  50. compat_shlex_quote,
  51. compat_str,
  52. compat_struct_pack,
  53. compat_struct_unpack,
  54. compat_urllib_error,
  55. compat_urllib_parse,
  56. compat_urllib_parse_urlencode,
  57. compat_urllib_parse_urlparse,
  58. compat_urllib_parse_unquote_plus,
  59. compat_urllib_request,
  60. compat_urlparse,
  61. compat_xpath,
  62. )
  63. from .socks import (
  64. ProxyType,
  65. sockssocket,
  66. )
  67. def register_socks_protocols():
  68. # "Register" SOCKS protocols
  69. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  70. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  71. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  72. if scheme not in compat_urlparse.uses_netloc:
  73. compat_urlparse.uses_netloc.append(scheme)
  74. # This is not clearly defined otherwise
  75. compiled_regex_type = type(re.compile(''))
  76. def random_user_agent():
  77. _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
  78. _CHROME_VERSIONS = (
  79. '74.0.3729.129',
  80. '76.0.3780.3',
  81. '76.0.3780.2',
  82. '74.0.3729.128',
  83. '76.0.3780.1',
  84. '76.0.3780.0',
  85. '75.0.3770.15',
  86. '74.0.3729.127',
  87. '74.0.3729.126',
  88. '76.0.3779.1',
  89. '76.0.3779.0',
  90. '75.0.3770.14',
  91. '74.0.3729.125',
  92. '76.0.3778.1',
  93. '76.0.3778.0',
  94. '75.0.3770.13',
  95. '74.0.3729.124',
  96. '74.0.3729.123',
  97. '73.0.3683.121',
  98. '76.0.3777.1',
  99. '76.0.3777.0',
  100. '75.0.3770.12',
  101. '74.0.3729.122',
  102. '76.0.3776.4',
  103. '75.0.3770.11',
  104. '74.0.3729.121',
  105. '76.0.3776.3',
  106. '76.0.3776.2',
  107. '73.0.3683.120',
  108. '74.0.3729.120',
  109. '74.0.3729.119',
  110. '74.0.3729.118',
  111. '76.0.3776.1',
  112. '76.0.3776.0',
  113. '76.0.3775.5',
  114. '75.0.3770.10',
  115. '74.0.3729.117',
  116. '76.0.3775.4',
  117. '76.0.3775.3',
  118. '74.0.3729.116',
  119. '75.0.3770.9',
  120. '76.0.3775.2',
  121. '76.0.3775.1',
  122. '76.0.3775.0',
  123. '75.0.3770.8',
  124. '74.0.3729.115',
  125. '74.0.3729.114',
  126. '76.0.3774.1',
  127. '76.0.3774.0',
  128. '75.0.3770.7',
  129. '74.0.3729.113',
  130. '74.0.3729.112',
  131. '74.0.3729.111',
  132. '76.0.3773.1',
  133. '76.0.3773.0',
  134. '75.0.3770.6',
  135. '74.0.3729.110',
  136. '74.0.3729.109',
  137. '76.0.3772.1',
  138. '76.0.3772.0',
  139. '75.0.3770.5',
  140. '74.0.3729.108',
  141. '74.0.3729.107',
  142. '76.0.3771.1',
  143. '76.0.3771.0',
  144. '75.0.3770.4',
  145. '74.0.3729.106',
  146. '74.0.3729.105',
  147. '75.0.3770.3',
  148. '74.0.3729.104',
  149. '74.0.3729.103',
  150. '74.0.3729.102',
  151. '75.0.3770.2',
  152. '74.0.3729.101',
  153. '75.0.3770.1',
  154. '75.0.3770.0',
  155. '74.0.3729.100',
  156. '75.0.3769.5',
  157. '75.0.3769.4',
  158. '74.0.3729.99',
  159. '75.0.3769.3',
  160. '75.0.3769.2',
  161. '75.0.3768.6',
  162. '74.0.3729.98',
  163. '75.0.3769.1',
  164. '75.0.3769.0',
  165. '74.0.3729.97',
  166. '73.0.3683.119',
  167. '73.0.3683.118',
  168. '74.0.3729.96',
  169. '75.0.3768.5',
  170. '75.0.3768.4',
  171. '75.0.3768.3',
  172. '75.0.3768.2',
  173. '74.0.3729.95',
  174. '74.0.3729.94',
  175. '75.0.3768.1',
  176. '75.0.3768.0',
  177. '74.0.3729.93',
  178. '74.0.3729.92',
  179. '73.0.3683.117',
  180. '74.0.3729.91',
  181. '75.0.3766.3',
  182. '74.0.3729.90',
  183. '75.0.3767.2',
  184. '75.0.3767.1',
  185. '75.0.3767.0',
  186. '74.0.3729.89',
  187. '73.0.3683.116',
  188. '75.0.3766.2',
  189. '74.0.3729.88',
  190. '75.0.3766.1',
  191. '75.0.3766.0',
  192. '74.0.3729.87',
  193. '73.0.3683.115',
  194. '74.0.3729.86',
  195. '75.0.3765.1',
  196. '75.0.3765.0',
  197. '74.0.3729.85',
  198. '73.0.3683.114',
  199. '74.0.3729.84',
  200. '75.0.3764.1',
  201. '75.0.3764.0',
  202. '74.0.3729.83',
  203. '73.0.3683.113',
  204. '75.0.3763.2',
  205. '75.0.3761.4',
  206. '74.0.3729.82',
  207. '75.0.3763.1',
  208. '75.0.3763.0',
  209. '74.0.3729.81',
  210. '73.0.3683.112',
  211. '75.0.3762.1',
  212. '75.0.3762.0',
  213. '74.0.3729.80',
  214. '75.0.3761.3',
  215. '74.0.3729.79',
  216. '73.0.3683.111',
  217. '75.0.3761.2',
  218. '74.0.3729.78',
  219. '74.0.3729.77',
  220. '75.0.3761.1',
  221. '75.0.3761.0',
  222. '73.0.3683.110',
  223. '74.0.3729.76',
  224. '74.0.3729.75',
  225. '75.0.3760.0',
  226. '74.0.3729.74',
  227. '75.0.3759.8',
  228. '75.0.3759.7',
  229. '75.0.3759.6',
  230. '74.0.3729.73',
  231. '75.0.3759.5',
  232. '74.0.3729.72',
  233. '73.0.3683.109',
  234. '75.0.3759.4',
  235. '75.0.3759.3',
  236. '74.0.3729.71',
  237. '75.0.3759.2',
  238. '74.0.3729.70',
  239. '73.0.3683.108',
  240. '74.0.3729.69',
  241. '75.0.3759.1',
  242. '75.0.3759.0',
  243. '74.0.3729.68',
  244. '73.0.3683.107',
  245. '74.0.3729.67',
  246. '75.0.3758.1',
  247. '75.0.3758.0',
  248. '74.0.3729.66',
  249. '73.0.3683.106',
  250. '74.0.3729.65',
  251. '75.0.3757.1',
  252. '75.0.3757.0',
  253. '74.0.3729.64',
  254. '73.0.3683.105',
  255. '74.0.3729.63',
  256. '75.0.3756.1',
  257. '75.0.3756.0',
  258. '74.0.3729.62',
  259. '73.0.3683.104',
  260. '75.0.3755.3',
  261. '75.0.3755.2',
  262. '73.0.3683.103',
  263. '75.0.3755.1',
  264. '75.0.3755.0',
  265. '74.0.3729.61',
  266. '73.0.3683.102',
  267. '74.0.3729.60',
  268. '75.0.3754.2',
  269. '74.0.3729.59',
  270. '75.0.3753.4',
  271. '74.0.3729.58',
  272. '75.0.3754.1',
  273. '75.0.3754.0',
  274. '74.0.3729.57',
  275. '73.0.3683.101',
  276. '75.0.3753.3',
  277. '75.0.3752.2',
  278. '75.0.3753.2',
  279. '74.0.3729.56',
  280. '75.0.3753.1',
  281. '75.0.3753.0',
  282. '74.0.3729.55',
  283. '73.0.3683.100',
  284. '74.0.3729.54',
  285. '75.0.3752.1',
  286. '75.0.3752.0',
  287. '74.0.3729.53',
  288. '73.0.3683.99',
  289. '74.0.3729.52',
  290. '75.0.3751.1',
  291. '75.0.3751.0',
  292. '74.0.3729.51',
  293. '73.0.3683.98',
  294. '74.0.3729.50',
  295. '75.0.3750.0',
  296. '74.0.3729.49',
  297. '74.0.3729.48',
  298. '74.0.3729.47',
  299. '75.0.3749.3',
  300. '74.0.3729.46',
  301. '73.0.3683.97',
  302. '75.0.3749.2',
  303. '74.0.3729.45',
  304. '75.0.3749.1',
  305. '75.0.3749.0',
  306. '74.0.3729.44',
  307. '73.0.3683.96',
  308. '74.0.3729.43',
  309. '74.0.3729.42',
  310. '75.0.3748.1',
  311. '75.0.3748.0',
  312. '74.0.3729.41',
  313. '75.0.3747.1',
  314. '73.0.3683.95',
  315. '75.0.3746.4',
  316. '74.0.3729.40',
  317. '74.0.3729.39',
  318. '75.0.3747.0',
  319. '75.0.3746.3',
  320. '75.0.3746.2',
  321. '74.0.3729.38',
  322. '75.0.3746.1',
  323. '75.0.3746.0',
  324. '74.0.3729.37',
  325. '73.0.3683.94',
  326. '75.0.3745.5',
  327. '75.0.3745.4',
  328. '75.0.3745.3',
  329. '75.0.3745.2',
  330. '74.0.3729.36',
  331. '75.0.3745.1',
  332. '75.0.3745.0',
  333. '75.0.3744.2',
  334. '74.0.3729.35',
  335. '73.0.3683.93',
  336. '74.0.3729.34',
  337. '75.0.3744.1',
  338. '75.0.3744.0',
  339. '74.0.3729.33',
  340. '73.0.3683.92',
  341. '74.0.3729.32',
  342. '74.0.3729.31',
  343. '73.0.3683.91',
  344. '75.0.3741.2',
  345. '75.0.3740.5',
  346. '74.0.3729.30',
  347. '75.0.3741.1',
  348. '75.0.3741.0',
  349. '74.0.3729.29',
  350. '75.0.3740.4',
  351. '73.0.3683.90',
  352. '74.0.3729.28',
  353. '75.0.3740.3',
  354. '73.0.3683.89',
  355. '75.0.3740.2',
  356. '74.0.3729.27',
  357. '75.0.3740.1',
  358. '75.0.3740.0',
  359. '74.0.3729.26',
  360. '73.0.3683.88',
  361. '73.0.3683.87',
  362. '74.0.3729.25',
  363. '75.0.3739.1',
  364. '75.0.3739.0',
  365. '73.0.3683.86',
  366. '74.0.3729.24',
  367. '73.0.3683.85',
  368. '75.0.3738.4',
  369. '75.0.3738.3',
  370. '75.0.3738.2',
  371. '75.0.3738.1',
  372. '75.0.3738.0',
  373. '74.0.3729.23',
  374. '73.0.3683.84',
  375. '74.0.3729.22',
  376. '74.0.3729.21',
  377. '75.0.3737.1',
  378. '75.0.3737.0',
  379. '74.0.3729.20',
  380. '73.0.3683.83',
  381. '74.0.3729.19',
  382. '75.0.3736.1',
  383. '75.0.3736.0',
  384. '74.0.3729.18',
  385. '73.0.3683.82',
  386. '74.0.3729.17',
  387. '75.0.3735.1',
  388. '75.0.3735.0',
  389. '74.0.3729.16',
  390. '73.0.3683.81',
  391. '75.0.3734.1',
  392. '75.0.3734.0',
  393. '74.0.3729.15',
  394. '73.0.3683.80',
  395. '74.0.3729.14',
  396. '75.0.3733.1',
  397. '75.0.3733.0',
  398. '75.0.3732.1',
  399. '74.0.3729.13',
  400. '74.0.3729.12',
  401. '73.0.3683.79',
  402. '74.0.3729.11',
  403. '75.0.3732.0',
  404. '74.0.3729.10',
  405. '73.0.3683.78',
  406. '74.0.3729.9',
  407. '74.0.3729.8',
  408. '74.0.3729.7',
  409. '75.0.3731.3',
  410. '75.0.3731.2',
  411. '75.0.3731.0',
  412. '74.0.3729.6',
  413. '73.0.3683.77',
  414. '73.0.3683.76',
  415. '75.0.3730.5',
  416. '75.0.3730.4',
  417. '73.0.3683.75',
  418. '74.0.3729.5',
  419. '73.0.3683.74',
  420. '75.0.3730.3',
  421. '75.0.3730.2',
  422. '74.0.3729.4',
  423. '73.0.3683.73',
  424. '73.0.3683.72',
  425. '75.0.3730.1',
  426. '75.0.3730.0',
  427. '74.0.3729.3',
  428. '73.0.3683.71',
  429. '74.0.3729.2',
  430. '73.0.3683.70',
  431. '74.0.3729.1',
  432. '74.0.3729.0',
  433. '74.0.3726.4',
  434. '73.0.3683.69',
  435. '74.0.3726.3',
  436. '74.0.3728.0',
  437. '74.0.3726.2',
  438. '73.0.3683.68',
  439. '74.0.3726.1',
  440. '74.0.3726.0',
  441. '74.0.3725.4',
  442. '73.0.3683.67',
  443. '73.0.3683.66',
  444. '74.0.3725.3',
  445. '74.0.3725.2',
  446. '74.0.3725.1',
  447. '74.0.3724.8',
  448. '74.0.3725.0',
  449. '73.0.3683.65',
  450. '74.0.3724.7',
  451. '74.0.3724.6',
  452. '74.0.3724.5',
  453. '74.0.3724.4',
  454. '74.0.3724.3',
  455. '74.0.3724.2',
  456. '74.0.3724.1',
  457. '74.0.3724.0',
  458. '73.0.3683.64',
  459. '74.0.3723.1',
  460. '74.0.3723.0',
  461. '73.0.3683.63',
  462. '74.0.3722.1',
  463. '74.0.3722.0',
  464. '73.0.3683.62',
  465. '74.0.3718.9',
  466. '74.0.3702.3',
  467. '74.0.3721.3',
  468. '74.0.3721.2',
  469. '74.0.3721.1',
  470. '74.0.3721.0',
  471. '74.0.3720.6',
  472. '73.0.3683.61',
  473. '72.0.3626.122',
  474. '73.0.3683.60',
  475. '74.0.3720.5',
  476. '72.0.3626.121',
  477. '74.0.3718.8',
  478. '74.0.3720.4',
  479. '74.0.3720.3',
  480. '74.0.3718.7',
  481. '74.0.3720.2',
  482. '74.0.3720.1',
  483. '74.0.3720.0',
  484. '74.0.3718.6',
  485. '74.0.3719.5',
  486. '73.0.3683.59',
  487. '74.0.3718.5',
  488. '74.0.3718.4',
  489. '74.0.3719.4',
  490. '74.0.3719.3',
  491. '74.0.3719.2',
  492. '74.0.3719.1',
  493. '73.0.3683.58',
  494. '74.0.3719.0',
  495. '73.0.3683.57',
  496. '73.0.3683.56',
  497. '74.0.3718.3',
  498. '73.0.3683.55',
  499. '74.0.3718.2',
  500. '74.0.3718.1',
  501. '74.0.3718.0',
  502. '73.0.3683.54',
  503. '74.0.3717.2',
  504. '73.0.3683.53',
  505. '74.0.3717.1',
  506. '74.0.3717.0',
  507. '73.0.3683.52',
  508. '74.0.3716.1',
  509. '74.0.3716.0',
  510. '73.0.3683.51',
  511. '74.0.3715.1',
  512. '74.0.3715.0',
  513. '73.0.3683.50',
  514. '74.0.3711.2',
  515. '74.0.3714.2',
  516. '74.0.3713.3',
  517. '74.0.3714.1',
  518. '74.0.3714.0',
  519. '73.0.3683.49',
  520. '74.0.3713.1',
  521. '74.0.3713.0',
  522. '72.0.3626.120',
  523. '73.0.3683.48',
  524. '74.0.3712.2',
  525. '74.0.3712.1',
  526. '74.0.3712.0',
  527. '73.0.3683.47',
  528. '72.0.3626.119',
  529. '73.0.3683.46',
  530. '74.0.3710.2',
  531. '72.0.3626.118',
  532. '74.0.3711.1',
  533. '74.0.3711.0',
  534. '73.0.3683.45',
  535. '72.0.3626.117',
  536. '74.0.3710.1',
  537. '74.0.3710.0',
  538. '73.0.3683.44',
  539. '72.0.3626.116',
  540. '74.0.3709.1',
  541. '74.0.3709.0',
  542. '74.0.3704.9',
  543. '73.0.3683.43',
  544. '72.0.3626.115',
  545. '74.0.3704.8',
  546. '74.0.3704.7',
  547. '74.0.3708.0',
  548. '74.0.3706.7',
  549. '74.0.3704.6',
  550. '73.0.3683.42',
  551. '72.0.3626.114',
  552. '74.0.3706.6',
  553. '72.0.3626.113',
  554. '74.0.3704.5',
  555. '74.0.3706.5',
  556. '74.0.3706.4',
  557. '74.0.3706.3',
  558. '74.0.3706.2',
  559. '74.0.3706.1',
  560. '74.0.3706.0',
  561. '73.0.3683.41',
  562. '72.0.3626.112',
  563. '74.0.3705.1',
  564. '74.0.3705.0',
  565. '73.0.3683.40',
  566. '72.0.3626.111',
  567. '73.0.3683.39',
  568. '74.0.3704.4',
  569. '73.0.3683.38',
  570. '74.0.3704.3',
  571. '74.0.3704.2',
  572. '74.0.3704.1',
  573. '74.0.3704.0',
  574. '73.0.3683.37',
  575. '72.0.3626.110',
  576. '72.0.3626.109',
  577. '74.0.3703.3',
  578. '74.0.3703.2',
  579. '73.0.3683.36',
  580. '74.0.3703.1',
  581. '74.0.3703.0',
  582. '73.0.3683.35',
  583. '72.0.3626.108',
  584. '74.0.3702.2',
  585. '74.0.3699.3',
  586. '74.0.3702.1',
  587. '74.0.3702.0',
  588. '73.0.3683.34',
  589. '72.0.3626.107',
  590. '73.0.3683.33',
  591. '74.0.3701.1',
  592. '74.0.3701.0',
  593. '73.0.3683.32',
  594. '73.0.3683.31',
  595. '72.0.3626.105',
  596. '74.0.3700.1',
  597. '74.0.3700.0',
  598. '73.0.3683.29',
  599. '72.0.3626.103',
  600. '74.0.3699.2',
  601. '74.0.3699.1',
  602. '74.0.3699.0',
  603. '73.0.3683.28',
  604. '72.0.3626.102',
  605. '73.0.3683.27',
  606. '73.0.3683.26',
  607. '74.0.3698.0',
  608. '74.0.3696.2',
  609. '72.0.3626.101',
  610. '73.0.3683.25',
  611. '74.0.3696.1',
  612. '74.0.3696.0',
  613. '74.0.3694.8',
  614. '72.0.3626.100',
  615. '74.0.3694.7',
  616. '74.0.3694.6',
  617. '74.0.3694.5',
  618. '74.0.3694.4',
  619. '72.0.3626.99',
  620. '72.0.3626.98',
  621. '74.0.3694.3',
  622. '73.0.3683.24',
  623. '72.0.3626.97',
  624. '72.0.3626.96',
  625. '72.0.3626.95',
  626. '73.0.3683.23',
  627. '72.0.3626.94',
  628. '73.0.3683.22',
  629. '73.0.3683.21',
  630. '72.0.3626.93',
  631. '74.0.3694.2',
  632. '72.0.3626.92',
  633. '74.0.3694.1',
  634. '74.0.3694.0',
  635. '74.0.3693.6',
  636. '73.0.3683.20',
  637. '72.0.3626.91',
  638. '74.0.3693.5',
  639. '74.0.3693.4',
  640. '74.0.3693.3',
  641. '74.0.3693.2',
  642. '73.0.3683.19',
  643. '74.0.3693.1',
  644. '74.0.3693.0',
  645. '73.0.3683.18',
  646. '72.0.3626.90',
  647. '74.0.3692.1',
  648. '74.0.3692.0',
  649. '73.0.3683.17',
  650. '72.0.3626.89',
  651. '74.0.3687.3',
  652. '74.0.3691.1',
  653. '74.0.3691.0',
  654. '73.0.3683.16',
  655. '72.0.3626.88',
  656. '72.0.3626.87',
  657. '73.0.3683.15',
  658. '74.0.3690.1',
  659. '74.0.3690.0',
  660. '73.0.3683.14',
  661. '72.0.3626.86',
  662. '73.0.3683.13',
  663. '73.0.3683.12',
  664. '74.0.3689.1',
  665. '74.0.3689.0',
  666. '73.0.3683.11',
  667. '72.0.3626.85',
  668. '73.0.3683.10',
  669. '72.0.3626.84',
  670. '73.0.3683.9',
  671. '74.0.3688.1',
  672. '74.0.3688.0',
  673. '73.0.3683.8',
  674. '72.0.3626.83',
  675. '74.0.3687.2',
  676. '74.0.3687.1',
  677. '74.0.3687.0',
  678. '73.0.3683.7',
  679. '72.0.3626.82',
  680. '74.0.3686.4',
  681. '72.0.3626.81',
  682. '74.0.3686.3',
  683. '74.0.3686.2',
  684. '74.0.3686.1',
  685. '74.0.3686.0',
  686. '73.0.3683.6',
  687. '72.0.3626.80',
  688. '74.0.3685.1',
  689. '74.0.3685.0',
  690. '73.0.3683.5',
  691. '72.0.3626.79',
  692. '74.0.3684.1',
  693. '74.0.3684.0',
  694. '73.0.3683.4',
  695. '72.0.3626.78',
  696. '72.0.3626.77',
  697. '73.0.3683.3',
  698. '73.0.3683.2',
  699. '72.0.3626.76',
  700. '73.0.3683.1',
  701. '73.0.3683.0',
  702. '72.0.3626.75',
  703. '71.0.3578.141',
  704. '73.0.3682.1',
  705. '73.0.3682.0',
  706. '72.0.3626.74',
  707. '71.0.3578.140',
  708. '73.0.3681.4',
  709. '73.0.3681.3',
  710. '73.0.3681.2',
  711. '73.0.3681.1',
  712. '73.0.3681.0',
  713. '72.0.3626.73',
  714. '71.0.3578.139',
  715. '72.0.3626.72',
  716. '72.0.3626.71',
  717. '73.0.3680.1',
  718. '73.0.3680.0',
  719. '72.0.3626.70',
  720. '71.0.3578.138',
  721. '73.0.3678.2',
  722. '73.0.3679.1',
  723. '73.0.3679.0',
  724. '72.0.3626.69',
  725. '71.0.3578.137',
  726. '73.0.3678.1',
  727. '73.0.3678.0',
  728. '71.0.3578.136',
  729. '73.0.3677.1',
  730. '73.0.3677.0',
  731. '72.0.3626.68',
  732. '72.0.3626.67',
  733. '71.0.3578.135',
  734. '73.0.3676.1',
  735. '73.0.3676.0',
  736. '73.0.3674.2',
  737. '72.0.3626.66',
  738. '71.0.3578.134',
  739. '73.0.3674.1',
  740. '73.0.3674.0',
  741. '72.0.3626.65',
  742. '71.0.3578.133',
  743. '73.0.3673.2',
  744. '73.0.3673.1',
  745. '73.0.3673.0',
  746. '72.0.3626.64',
  747. '71.0.3578.132',
  748. '72.0.3626.63',
  749. '72.0.3626.62',
  750. '72.0.3626.61',
  751. '72.0.3626.60',
  752. '73.0.3672.1',
  753. '73.0.3672.0',
  754. '72.0.3626.59',
  755. '71.0.3578.131',
  756. '73.0.3671.3',
  757. '73.0.3671.2',
  758. '73.0.3671.1',
  759. '73.0.3671.0',
  760. '72.0.3626.58',
  761. '71.0.3578.130',
  762. '73.0.3670.1',
  763. '73.0.3670.0',
  764. '72.0.3626.57',
  765. '71.0.3578.129',
  766. '73.0.3669.1',
  767. '73.0.3669.0',
  768. '72.0.3626.56',
  769. '71.0.3578.128',
  770. '73.0.3668.2',
  771. '73.0.3668.1',
  772. '73.0.3668.0',
  773. '72.0.3626.55',
  774. '71.0.3578.127',
  775. '73.0.3667.2',
  776. '73.0.3667.1',
  777. '73.0.3667.0',
  778. '72.0.3626.54',
  779. '71.0.3578.126',
  780. '73.0.3666.1',
  781. '73.0.3666.0',
  782. '72.0.3626.53',
  783. '71.0.3578.125',
  784. '73.0.3665.4',
  785. '73.0.3665.3',
  786. '72.0.3626.52',
  787. '73.0.3665.2',
  788. '73.0.3664.4',
  789. '73.0.3665.1',
  790. '73.0.3665.0',
  791. '72.0.3626.51',
  792. '71.0.3578.124',
  793. '72.0.3626.50',
  794. '73.0.3664.3',
  795. '73.0.3664.2',
  796. '73.0.3664.1',
  797. '73.0.3664.0',
  798. '73.0.3663.2',
  799. '72.0.3626.49',
  800. '71.0.3578.123',
  801. '73.0.3663.1',
  802. '73.0.3663.0',
  803. '72.0.3626.48',
  804. '71.0.3578.122',
  805. '73.0.3662.1',
  806. '73.0.3662.0',
  807. '72.0.3626.47',
  808. '71.0.3578.121',
  809. '73.0.3661.1',
  810. '72.0.3626.46',
  811. '73.0.3661.0',
  812. '72.0.3626.45',
  813. '71.0.3578.120',
  814. '73.0.3660.2',
  815. '73.0.3660.1',
  816. '73.0.3660.0',
  817. '72.0.3626.44',
  818. '71.0.3578.119',
  819. '73.0.3659.1',
  820. '73.0.3659.0',
  821. '72.0.3626.43',
  822. '71.0.3578.118',
  823. '73.0.3658.1',
  824. '73.0.3658.0',
  825. '72.0.3626.42',
  826. '71.0.3578.117',
  827. '73.0.3657.1',
  828. '73.0.3657.0',
  829. '72.0.3626.41',
  830. '71.0.3578.116',
  831. '73.0.3656.1',
  832. '73.0.3656.0',
  833. '72.0.3626.40',
  834. '71.0.3578.115',
  835. '73.0.3655.1',
  836. '73.0.3655.0',
  837. '72.0.3626.39',
  838. '71.0.3578.114',
  839. '73.0.3654.1',
  840. '73.0.3654.0',
  841. '72.0.3626.38',
  842. '71.0.3578.113',
  843. '73.0.3653.1',
  844. '73.0.3653.0',
  845. '72.0.3626.37',
  846. '71.0.3578.112',
  847. '73.0.3652.1',
  848. '73.0.3652.0',
  849. '72.0.3626.36',
  850. '71.0.3578.111',
  851. '73.0.3651.1',
  852. '73.0.3651.0',
  853. '72.0.3626.35',
  854. '71.0.3578.110',
  855. '73.0.3650.1',
  856. '73.0.3650.0',
  857. '72.0.3626.34',
  858. '71.0.3578.109',
  859. '73.0.3649.1',
  860. '73.0.3649.0',
  861. '72.0.3626.33',
  862. '71.0.3578.108',
  863. '73.0.3648.2',
  864. '73.0.3648.1',
  865. '73.0.3648.0',
  866. '72.0.3626.32',
  867. '71.0.3578.107',
  868. '73.0.3647.2',
  869. '73.0.3647.1',
  870. '73.0.3647.0',
  871. '72.0.3626.31',
  872. '71.0.3578.106',
  873. '73.0.3635.3',
  874. '73.0.3646.2',
  875. '73.0.3646.1',
  876. '73.0.3646.0',
  877. '72.0.3626.30',
  878. '71.0.3578.105',
  879. '72.0.3626.29',
  880. '73.0.3645.2',
  881. '73.0.3645.1',
  882. '73.0.3645.0',
  883. '72.0.3626.28',
  884. '71.0.3578.104',
  885. '72.0.3626.27',
  886. '72.0.3626.26',
  887. '72.0.3626.25',
  888. '72.0.3626.24',
  889. '73.0.3644.0',
  890. '73.0.3643.2',
  891. '72.0.3626.23',
  892. '71.0.3578.103',
  893. '73.0.3643.1',
  894. '73.0.3643.0',
  895. '72.0.3626.22',
  896. '71.0.3578.102',
  897. '73.0.3642.1',
  898. '73.0.3642.0',
  899. '72.0.3626.21',
  900. '71.0.3578.101',
  901. '73.0.3641.1',
  902. '73.0.3641.0',
  903. '72.0.3626.20',
  904. '71.0.3578.100',
  905. '72.0.3626.19',
  906. '73.0.3640.1',
  907. '73.0.3640.0',
  908. '72.0.3626.18',
  909. '73.0.3639.1',
  910. '71.0.3578.99',
  911. '73.0.3639.0',
  912. '72.0.3626.17',
  913. '73.0.3638.2',
  914. '72.0.3626.16',
  915. '73.0.3638.1',
  916. '73.0.3638.0',
  917. '72.0.3626.15',
  918. '71.0.3578.98',
  919. '73.0.3635.2',
  920. '71.0.3578.97',
  921. '73.0.3637.1',
  922. '73.0.3637.0',
  923. '72.0.3626.14',
  924. '71.0.3578.96',
  925. '71.0.3578.95',
  926. '72.0.3626.13',
  927. '71.0.3578.94',
  928. '73.0.3636.2',
  929. '71.0.3578.93',
  930. '73.0.3636.1',
  931. '73.0.3636.0',
  932. '72.0.3626.12',
  933. '71.0.3578.92',
  934. '73.0.3635.1',
  935. '73.0.3635.0',
  936. '72.0.3626.11',
  937. '71.0.3578.91',
  938. '73.0.3634.2',
  939. '73.0.3634.1',
  940. '73.0.3634.0',
  941. '72.0.3626.10',
  942. '71.0.3578.90',
  943. '71.0.3578.89',
  944. '73.0.3633.2',
  945. '73.0.3633.1',
  946. '73.0.3633.0',
  947. '72.0.3610.4',
  948. '72.0.3626.9',
  949. '71.0.3578.88',
  950. '73.0.3632.5',
  951. '73.0.3632.4',
  952. '73.0.3632.3',
  953. '73.0.3632.2',
  954. '73.0.3632.1',
  955. '73.0.3632.0',
  956. '72.0.3626.8',
  957. '71.0.3578.87',
  958. '73.0.3631.2',
  959. '73.0.3631.1',
  960. '73.0.3631.0',
  961. '72.0.3626.7',
  962. '71.0.3578.86',
  963. '72.0.3626.6',
  964. '73.0.3630.1',
  965. '73.0.3630.0',
  966. '72.0.3626.5',
  967. '71.0.3578.85',
  968. '72.0.3626.4',
  969. '73.0.3628.3',
  970. '73.0.3628.2',
  971. '73.0.3629.1',
  972. '73.0.3629.0',
  973. '72.0.3626.3',
  974. '71.0.3578.84',
  975. '73.0.3628.1',
  976. '73.0.3628.0',
  977. '71.0.3578.83',
  978. '73.0.3627.1',
  979. '73.0.3627.0',
  980. '72.0.3626.2',
  981. '71.0.3578.82',
  982. '71.0.3578.81',
  983. '71.0.3578.80',
  984. '72.0.3626.1',
  985. '72.0.3626.0',
  986. '71.0.3578.79',
  987. '70.0.3538.124',
  988. '71.0.3578.78',
  989. '72.0.3623.4',
  990. '72.0.3625.2',
  991. '72.0.3625.1',
  992. '72.0.3625.0',
  993. '71.0.3578.77',
  994. '70.0.3538.123',
  995. '72.0.3624.4',
  996. '72.0.3624.3',
  997. '72.0.3624.2',
  998. '71.0.3578.76',
  999. '72.0.3624.1',
  1000. '72.0.3624.0',
  1001. '72.0.3623.3',
  1002. '71.0.3578.75',
  1003. '70.0.3538.122',
  1004. '71.0.3578.74',
  1005. '72.0.3623.2',
  1006. '72.0.3610.3',
  1007. '72.0.3623.1',
  1008. '72.0.3623.0',
  1009. '72.0.3622.3',
  1010. '72.0.3622.2',
  1011. '71.0.3578.73',
  1012. '70.0.3538.121',
  1013. '72.0.3622.1',
  1014. '72.0.3622.0',
  1015. '71.0.3578.72',
  1016. '70.0.3538.120',
  1017. '72.0.3621.1',
  1018. '72.0.3621.0',
  1019. '71.0.3578.71',
  1020. '70.0.3538.119',
  1021. '72.0.3620.1',
  1022. '72.0.3620.0',
  1023. '71.0.3578.70',
  1024. '70.0.3538.118',
  1025. '71.0.3578.69',
  1026. '72.0.3619.1',
  1027. '72.0.3619.0',
  1028. '71.0.3578.68',
  1029. '70.0.3538.117',
  1030. '71.0.3578.67',
  1031. '72.0.3618.1',
  1032. '72.0.3618.0',
  1033. '71.0.3578.66',
  1034. '70.0.3538.116',
  1035. '72.0.3617.1',
  1036. '72.0.3617.0',
  1037. '71.0.3578.65',
  1038. '70.0.3538.115',
  1039. '72.0.3602.3',
  1040. '71.0.3578.64',
  1041. '72.0.3616.1',
  1042. '72.0.3616.0',
  1043. '71.0.3578.63',
  1044. '70.0.3538.114',
  1045. '71.0.3578.62',
  1046. '72.0.3615.1',
  1047. '72.0.3615.0',
  1048. '71.0.3578.61',
  1049. '70.0.3538.113',
  1050. '72.0.3614.1',
  1051. '72.0.3614.0',
  1052. '71.0.3578.60',
  1053. '70.0.3538.112',
  1054. '72.0.3613.1',
  1055. '72.0.3613.0',
  1056. '71.0.3578.59',
  1057. '70.0.3538.111',
  1058. '72.0.3612.2',
  1059. '72.0.3612.1',
  1060. '72.0.3612.0',
  1061. '70.0.3538.110',
  1062. '71.0.3578.58',
  1063. '70.0.3538.109',
  1064. '72.0.3611.2',
  1065. '72.0.3611.1',
  1066. '72.0.3611.0',
  1067. '71.0.3578.57',
  1068. '70.0.3538.108',
  1069. '72.0.3610.2',
  1070. '71.0.3578.56',
  1071. '71.0.3578.55',
  1072. '72.0.3610.1',
  1073. '72.0.3610.0',
  1074. '71.0.3578.54',
  1075. '70.0.3538.107',
  1076. '71.0.3578.53',
  1077. '72.0.3609.3',
  1078. '71.0.3578.52',
  1079. '72.0.3609.2',
  1080. '71.0.3578.51',
  1081. '72.0.3608.5',
  1082. '72.0.3609.1',
  1083. '72.0.3609.0',
  1084. '71.0.3578.50',
  1085. '70.0.3538.106',
  1086. '72.0.3608.4',
  1087. '72.0.3608.3',
  1088. '72.0.3608.2',
  1089. '71.0.3578.49',
  1090. '72.0.3608.1',
  1091. '72.0.3608.0',
  1092. '70.0.3538.105',
  1093. '71.0.3578.48',
  1094. '72.0.3607.1',
  1095. '72.0.3607.0',
  1096. '71.0.3578.47',
  1097. '70.0.3538.104',
  1098. '72.0.3606.2',
  1099. '72.0.3606.1',
  1100. '72.0.3606.0',
  1101. '71.0.3578.46',
  1102. '70.0.3538.103',
  1103. '70.0.3538.102',
  1104. '72.0.3605.3',
  1105. '72.0.3605.2',
  1106. '72.0.3605.1',
  1107. '72.0.3605.0',
  1108. '71.0.3578.45',
  1109. '70.0.3538.101',
  1110. '71.0.3578.44',
  1111. '71.0.3578.43',
  1112. '70.0.3538.100',
  1113. '70.0.3538.99',
  1114. '71.0.3578.42',
  1115. '72.0.3604.1',
  1116. '72.0.3604.0',
  1117. '71.0.3578.41',
  1118. '70.0.3538.98',
  1119. '71.0.3578.40',
  1120. '72.0.3603.2',
  1121. '72.0.3603.1',
  1122. '72.0.3603.0',
  1123. '71.0.3578.39',
  1124. '70.0.3538.97',
  1125. '72.0.3602.2',
  1126. '71.0.3578.38',
  1127. '71.0.3578.37',
  1128. '72.0.3602.1',
  1129. '72.0.3602.0',
  1130. '71.0.3578.36',
  1131. '70.0.3538.96',
  1132. '72.0.3601.1',
  1133. '72.0.3601.0',
  1134. '71.0.3578.35',
  1135. '70.0.3538.95',
  1136. '72.0.3600.1',
  1137. '72.0.3600.0',
  1138. '71.0.3578.34',
  1139. '70.0.3538.94',
  1140. '72.0.3599.3',
  1141. '72.0.3599.2',
  1142. '72.0.3599.1',
  1143. '72.0.3599.0',
  1144. '71.0.3578.33',
  1145. '70.0.3538.93',
  1146. '72.0.3598.1',
  1147. '72.0.3598.0',
  1148. '71.0.3578.32',
  1149. '70.0.3538.87',
  1150. '72.0.3597.1',
  1151. '72.0.3597.0',
  1152. '72.0.3596.2',
  1153. '71.0.3578.31',
  1154. '70.0.3538.86',
  1155. '71.0.3578.30',
  1156. '71.0.3578.29',
  1157. '72.0.3596.1',
  1158. '72.0.3596.0',
  1159. '71.0.3578.28',
  1160. '70.0.3538.85',
  1161. '72.0.3595.2',
  1162. '72.0.3591.3',
  1163. '72.0.3595.1',
  1164. '72.0.3595.0',
  1165. '71.0.3578.27',
  1166. '70.0.3538.84',
  1167. '72.0.3594.1',
  1168. '72.0.3594.0',
  1169. '71.0.3578.26',
  1170. '70.0.3538.83',
  1171. '72.0.3593.2',
  1172. '72.0.3593.1',
  1173. '72.0.3593.0',
  1174. '71.0.3578.25',
  1175. '70.0.3538.82',
  1176. '72.0.3589.3',
  1177. '72.0.3592.2',
  1178. '72.0.3592.1',
  1179. '72.0.3592.0',
  1180. '71.0.3578.24',
  1181. '72.0.3589.2',
  1182. '70.0.3538.81',
  1183. '70.0.3538.80',
  1184. '72.0.3591.2',
  1185. '72.0.3591.1',
  1186. '72.0.3591.0',
  1187. '71.0.3578.23',
  1188. '70.0.3538.79',
  1189. '71.0.3578.22',
  1190. '72.0.3590.1',
  1191. '72.0.3590.0',
  1192. '71.0.3578.21',
  1193. '70.0.3538.78',
  1194. '70.0.3538.77',
  1195. '72.0.3589.1',
  1196. '72.0.3589.0',
  1197. '71.0.3578.20',
  1198. '70.0.3538.76',
  1199. '71.0.3578.19',
  1200. '70.0.3538.75',
  1201. '72.0.3588.1',
  1202. '72.0.3588.0',
  1203. '71.0.3578.18',
  1204. '70.0.3538.74',
  1205. '72.0.3586.2',
  1206. '72.0.3587.0',
  1207. '71.0.3578.17',
  1208. '70.0.3538.73',
  1209. '72.0.3586.1',
  1210. '72.0.3586.0',
  1211. '71.0.3578.16',
  1212. '70.0.3538.72',
  1213. '72.0.3585.1',
  1214. '72.0.3585.0',
  1215. '71.0.3578.15',
  1216. '70.0.3538.71',
  1217. '71.0.3578.14',
  1218. '72.0.3584.1',
  1219. '72.0.3584.0',
  1220. '71.0.3578.13',
  1221. '70.0.3538.70',
  1222. '72.0.3583.2',
  1223. '71.0.3578.12',
  1224. '72.0.3583.1',
  1225. '72.0.3583.0',
  1226. '71.0.3578.11',
  1227. '70.0.3538.69',
  1228. '71.0.3578.10',
  1229. '72.0.3582.0',
  1230. '72.0.3581.4',
  1231. '71.0.3578.9',
  1232. '70.0.3538.67',
  1233. '72.0.3581.3',
  1234. '72.0.3581.2',
  1235. '72.0.3581.1',
  1236. '72.0.3581.0',
  1237. '71.0.3578.8',
  1238. '70.0.3538.66',
  1239. '72.0.3580.1',
  1240. '72.0.3580.0',
  1241. '71.0.3578.7',
  1242. '70.0.3538.65',
  1243. '71.0.3578.6',
  1244. '72.0.3579.1',
  1245. '72.0.3579.0',
  1246. '71.0.3578.5',
  1247. '70.0.3538.64',
  1248. '71.0.3578.4',
  1249. '71.0.3578.3',
  1250. '71.0.3578.2',
  1251. '71.0.3578.1',
  1252. '71.0.3578.0',
  1253. '70.0.3538.63',
  1254. '69.0.3497.128',
  1255. '70.0.3538.62',
  1256. '70.0.3538.61',
  1257. '70.0.3538.60',
  1258. '70.0.3538.59',
  1259. '71.0.3577.1',
  1260. '71.0.3577.0',
  1261. '70.0.3538.58',
  1262. '69.0.3497.127',
  1263. '71.0.3576.2',
  1264. '71.0.3576.1',
  1265. '71.0.3576.0',
  1266. '70.0.3538.57',
  1267. '70.0.3538.56',
  1268. '71.0.3575.2',
  1269. '70.0.3538.55',
  1270. '69.0.3497.126',
  1271. '70.0.3538.54',
  1272. '71.0.3575.1',
  1273. '71.0.3575.0',
  1274. '71.0.3574.1',
  1275. '71.0.3574.0',
  1276. '70.0.3538.53',
  1277. '69.0.3497.125',
  1278. '70.0.3538.52',
  1279. '71.0.3573.1',
  1280. '71.0.3573.0',
  1281. '70.0.3538.51',
  1282. '69.0.3497.124',
  1283. '71.0.3572.1',
  1284. '71.0.3572.0',
  1285. '70.0.3538.50',
  1286. '69.0.3497.123',
  1287. '71.0.3571.2',
  1288. '70.0.3538.49',
  1289. '69.0.3497.122',
  1290. '71.0.3571.1',
  1291. '71.0.3571.0',
  1292. '70.0.3538.48',
  1293. '69.0.3497.121',
  1294. '71.0.3570.1',
  1295. '71.0.3570.0',
  1296. '70.0.3538.47',
  1297. '69.0.3497.120',
  1298. '71.0.3568.2',
  1299. '71.0.3569.1',
  1300. '71.0.3569.0',
  1301. '70.0.3538.46',
  1302. '69.0.3497.119',
  1303. '70.0.3538.45',
  1304. '71.0.3568.1',
  1305. '71.0.3568.0',
  1306. '70.0.3538.44',
  1307. '69.0.3497.118',
  1308. '70.0.3538.43',
  1309. '70.0.3538.42',
  1310. '71.0.3567.1',
  1311. '71.0.3567.0',
  1312. '70.0.3538.41',
  1313. '69.0.3497.117',
  1314. '71.0.3566.1',
  1315. '71.0.3566.0',
  1316. '70.0.3538.40',
  1317. '69.0.3497.116',
  1318. '71.0.3565.1',
  1319. '71.0.3565.0',
  1320. '70.0.3538.39',
  1321. '69.0.3497.115',
  1322. '71.0.3564.1',
  1323. '71.0.3564.0',
  1324. '70.0.3538.38',
  1325. '69.0.3497.114',
  1326. '71.0.3563.0',
  1327. '71.0.3562.2',
  1328. '70.0.3538.37',
  1329. '69.0.3497.113',
  1330. '70.0.3538.36',
  1331. '70.0.3538.35',
  1332. '71.0.3562.1',
  1333. '71.0.3562.0',
  1334. '70.0.3538.34',
  1335. '69.0.3497.112',
  1336. '70.0.3538.33',
  1337. '71.0.3561.1',
  1338. '71.0.3561.0',
  1339. '70.0.3538.32',
  1340. '69.0.3497.111',
  1341. '71.0.3559.6',
  1342. '71.0.3560.1',
  1343. '71.0.3560.0',
  1344. '71.0.3559.5',
  1345. '71.0.3559.4',
  1346. '70.0.3538.31',
  1347. '69.0.3497.110',
  1348. '71.0.3559.3',
  1349. '70.0.3538.30',
  1350. '69.0.3497.109',
  1351. '71.0.3559.2',
  1352. '71.0.3559.1',
  1353. '71.0.3559.0',
  1354. '70.0.3538.29',
  1355. '69.0.3497.108',
  1356. '71.0.3558.2',
  1357. '71.0.3558.1',
  1358. '71.0.3558.0',
  1359. '70.0.3538.28',
  1360. '69.0.3497.107',
  1361. '71.0.3557.2',
  1362. '71.0.3557.1',
  1363. '71.0.3557.0',
  1364. '70.0.3538.27',
  1365. '69.0.3497.106',
  1366. '71.0.3554.4',
  1367. '70.0.3538.26',
  1368. '71.0.3556.1',
  1369. '71.0.3556.0',
  1370. '70.0.3538.25',
  1371. '71.0.3554.3',
  1372. '69.0.3497.105',
  1373. '71.0.3554.2',
  1374. '70.0.3538.24',
  1375. '69.0.3497.104',
  1376. '71.0.3555.2',
  1377. '70.0.3538.23',
  1378. '71.0.3555.1',
  1379. '71.0.3555.0',
  1380. '70.0.3538.22',
  1381. '69.0.3497.103',
  1382. '71.0.3554.1',
  1383. '71.0.3554.0',
  1384. '70.0.3538.21',
  1385. '69.0.3497.102',
  1386. '71.0.3553.3',
  1387. '70.0.3538.20',
  1388. '69.0.3497.101',
  1389. '71.0.3553.2',
  1390. '69.0.3497.100',
  1391. '71.0.3553.1',
  1392. '71.0.3553.0',
  1393. '70.0.3538.19',
  1394. '69.0.3497.99',
  1395. '69.0.3497.98',
  1396. '69.0.3497.97',
  1397. '71.0.3552.6',
  1398. '71.0.3552.5',
  1399. '71.0.3552.4',
  1400. '71.0.3552.3',
  1401. '71.0.3552.2',
  1402. '71.0.3552.1',
  1403. '71.0.3552.0',
  1404. '70.0.3538.18',
  1405. '69.0.3497.96',
  1406. '71.0.3551.3',
  1407. '71.0.3551.2',
  1408. '71.0.3551.1',
  1409. '71.0.3551.0',
  1410. '70.0.3538.17',
  1411. '69.0.3497.95',
  1412. '71.0.3550.3',
  1413. '71.0.3550.2',
  1414. '71.0.3550.1',
  1415. '71.0.3550.0',
  1416. '70.0.3538.16',
  1417. '69.0.3497.94',
  1418. '71.0.3549.1',
  1419. '71.0.3549.0',
  1420. '70.0.3538.15',
  1421. '69.0.3497.93',
  1422. '69.0.3497.92',
  1423. '71.0.3548.1',
  1424. '71.0.3548.0',
  1425. '70.0.3538.14',
  1426. '69.0.3497.91',
  1427. '71.0.3547.1',
  1428. '71.0.3547.0',
  1429. '70.0.3538.13',
  1430. '69.0.3497.90',
  1431. '71.0.3546.2',
  1432. '69.0.3497.89',
  1433. '71.0.3546.1',
  1434. '71.0.3546.0',
  1435. '70.0.3538.12',
  1436. '69.0.3497.88',
  1437. '71.0.3545.4',
  1438. '71.0.3545.3',
  1439. '71.0.3545.2',
  1440. '71.0.3545.1',
  1441. '71.0.3545.0',
  1442. '70.0.3538.11',
  1443. '69.0.3497.87',
  1444. '71.0.3544.5',
  1445. '71.0.3544.4',
  1446. '71.0.3544.3',
  1447. '71.0.3544.2',
  1448. '71.0.3544.1',
  1449. '71.0.3544.0',
  1450. '69.0.3497.86',
  1451. '70.0.3538.10',
  1452. '69.0.3497.85',
  1453. '70.0.3538.9',
  1454. '69.0.3497.84',
  1455. '71.0.3543.4',
  1456. '70.0.3538.8',
  1457. '71.0.3543.3',
  1458. '71.0.3543.2',
  1459. '71.0.3543.1',
  1460. '71.0.3543.0',
  1461. '70.0.3538.7',
  1462. '69.0.3497.83',
  1463. '71.0.3542.2',
  1464. '71.0.3542.1',
  1465. '71.0.3542.0',
  1466. '70.0.3538.6',
  1467. '69.0.3497.82',
  1468. '69.0.3497.81',
  1469. '71.0.3541.1',
  1470. '71.0.3541.0',
  1471. '70.0.3538.5',
  1472. '69.0.3497.80',
  1473. '71.0.3540.1',
  1474. '71.0.3540.0',
  1475. '70.0.3538.4',
  1476. '69.0.3497.79',
  1477. '70.0.3538.3',
  1478. '71.0.3539.1',
  1479. '71.0.3539.0',
  1480. '69.0.3497.78',
  1481. '68.0.3440.134',
  1482. '69.0.3497.77',
  1483. '70.0.3538.2',
  1484. '70.0.3538.1',
  1485. '70.0.3538.0',
  1486. '69.0.3497.76',
  1487. '68.0.3440.133',
  1488. '69.0.3497.75',
  1489. '70.0.3537.2',
  1490. '70.0.3537.1',
  1491. '70.0.3537.0',
  1492. '69.0.3497.74',
  1493. '68.0.3440.132',
  1494. '70.0.3536.0',
  1495. '70.0.3535.5',
  1496. '70.0.3535.4',
  1497. '70.0.3535.3',
  1498. '69.0.3497.73',
  1499. '68.0.3440.131',
  1500. '70.0.3532.8',
  1501. '70.0.3532.7',
  1502. '69.0.3497.72',
  1503. '69.0.3497.71',
  1504. '70.0.3535.2',
  1505. '70.0.3535.1',
  1506. '70.0.3535.0',
  1507. '69.0.3497.70',
  1508. '68.0.3440.130',
  1509. '69.0.3497.69',
  1510. '68.0.3440.129',
  1511. '70.0.3534.4',
  1512. '70.0.3534.3',
  1513. '70.0.3534.2',
  1514. '70.0.3534.1',
  1515. '70.0.3534.0',
  1516. '69.0.3497.68',
  1517. '68.0.3440.128',
  1518. '70.0.3533.2',
  1519. '70.0.3533.1',
  1520. '70.0.3533.0',
  1521. '69.0.3497.67',
  1522. '68.0.3440.127',
  1523. '70.0.3532.6',
  1524. '70.0.3532.5',
  1525. '70.0.3532.4',
  1526. '69.0.3497.66',
  1527. '68.0.3440.126',
  1528. '70.0.3532.3',
  1529. '70.0.3532.2',
  1530. '70.0.3532.1',
  1531. '69.0.3497.60',
  1532. '69.0.3497.65',
  1533. '69.0.3497.64',
  1534. '70.0.3532.0',
  1535. '70.0.3531.0',
  1536. '70.0.3530.4',
  1537. '70.0.3530.3',
  1538. '70.0.3530.2',
  1539. '69.0.3497.58',
  1540. '68.0.3440.125',
  1541. '69.0.3497.57',
  1542. '69.0.3497.56',
  1543. '69.0.3497.55',
  1544. '69.0.3497.54',
  1545. '70.0.3530.1',
  1546. '70.0.3530.0',
  1547. '69.0.3497.53',
  1548. '68.0.3440.124',
  1549. '69.0.3497.52',
  1550. '70.0.3529.3',
  1551. '70.0.3529.2',
  1552. '70.0.3529.1',
  1553. '70.0.3529.0',
  1554. '69.0.3497.51',
  1555. '70.0.3528.4',
  1556. '68.0.3440.123',
  1557. '70.0.3528.3',
  1558. '70.0.3528.2',
  1559. '70.0.3528.1',
  1560. '70.0.3528.0',
  1561. '69.0.3497.50',
  1562. '68.0.3440.122',
  1563. '70.0.3527.1',
  1564. '70.0.3527.0',
  1565. '69.0.3497.49',
  1566. '68.0.3440.121',
  1567. '70.0.3526.1',
  1568. '70.0.3526.0',
  1569. '68.0.3440.120',
  1570. '69.0.3497.48',
  1571. '69.0.3497.47',
  1572. '68.0.3440.119',
  1573. '68.0.3440.118',
  1574. '70.0.3525.5',
  1575. '70.0.3525.4',
  1576. '70.0.3525.3',
  1577. '68.0.3440.117',
  1578. '69.0.3497.46',
  1579. '70.0.3525.2',
  1580. '70.0.3525.1',
  1581. '70.0.3525.0',
  1582. '69.0.3497.45',
  1583. '68.0.3440.116',
  1584. '70.0.3524.4',
  1585. '70.0.3524.3',
  1586. '69.0.3497.44',
  1587. '70.0.3524.2',
  1588. '70.0.3524.1',
  1589. '70.0.3524.0',
  1590. '70.0.3523.2',
  1591. '69.0.3497.43',
  1592. '68.0.3440.115',
  1593. '70.0.3505.9',
  1594. '69.0.3497.42',
  1595. '70.0.3505.8',
  1596. '70.0.3523.1',
  1597. '70.0.3523.0',
  1598. '69.0.3497.41',
  1599. '68.0.3440.114',
  1600. '70.0.3505.7',
  1601. '69.0.3497.40',
  1602. '70.0.3522.1',
  1603. '70.0.3522.0',
  1604. '70.0.3521.2',
  1605. '69.0.3497.39',
  1606. '68.0.3440.113',
  1607. '70.0.3505.6',
  1608. '70.0.3521.1',
  1609. '70.0.3521.0',
  1610. '69.0.3497.38',
  1611. '68.0.3440.112',
  1612. '70.0.3520.1',
  1613. '70.0.3520.0',
  1614. '69.0.3497.37',
  1615. '68.0.3440.111',
  1616. '70.0.3519.3',
  1617. '70.0.3519.2',
  1618. '70.0.3519.1',
  1619. '70.0.3519.0',
  1620. '69.0.3497.36',
  1621. '68.0.3440.110',
  1622. '70.0.3518.1',
  1623. '70.0.3518.0',
  1624. '69.0.3497.35',
  1625. '69.0.3497.34',
  1626. '68.0.3440.109',
  1627. '70.0.3517.1',
  1628. '70.0.3517.0',
  1629. '69.0.3497.33',
  1630. '68.0.3440.108',
  1631. '69.0.3497.32',
  1632. '70.0.3516.3',
  1633. '70.0.3516.2',
  1634. '70.0.3516.1',
  1635. '70.0.3516.0',
  1636. '69.0.3497.31',
  1637. '68.0.3440.107',
  1638. '70.0.3515.4',
  1639. '68.0.3440.106',
  1640. '70.0.3515.3',
  1641. '70.0.3515.2',
  1642. '70.0.3515.1',
  1643. '70.0.3515.0',
  1644. '69.0.3497.30',
  1645. '68.0.3440.105',
  1646. '68.0.3440.104',
  1647. '70.0.3514.2',
  1648. '70.0.3514.1',
  1649. '70.0.3514.0',
  1650. '69.0.3497.29',
  1651. '68.0.3440.103',
  1652. '70.0.3513.1',
  1653. '70.0.3513.0',
  1654. '69.0.3497.28',
  1655. )
  1656. return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
  1657. std_headers = {
  1658. 'User-Agent': random_user_agent(),
  1659. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  1660. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  1661. 'Accept-Encoding': 'gzip, deflate',
  1662. 'Accept-Language': 'en-us,en;q=0.5',
  1663. }
  1664. USER_AGENTS = {
  1665. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  1666. }
  1667. NO_DEFAULT = object()
  1668. ENGLISH_MONTH_NAMES = [
  1669. 'January', 'February', 'March', 'April', 'May', 'June',
  1670. 'July', 'August', 'September', 'October', 'November', 'December']
  1671. MONTH_NAMES = {
  1672. 'en': ENGLISH_MONTH_NAMES,
  1673. 'fr': [
  1674. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  1675. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  1676. }
  1677. KNOWN_EXTENSIONS = (
  1678. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  1679. 'flv', 'f4v', 'f4a', 'f4b',
  1680. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  1681. 'mkv', 'mka', 'mk3d',
  1682. 'avi', 'divx',
  1683. 'mov',
  1684. 'asf', 'wmv', 'wma',
  1685. '3gp', '3g2',
  1686. 'mp3',
  1687. 'flac',
  1688. 'ape',
  1689. 'wav',
  1690. 'f4f', 'f4m', 'm3u8', 'smil')
  1691. # needed for sanitizing filenames in restricted mode
  1692. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  1693. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  1694. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  1695. DATE_FORMATS = (
  1696. '%d %B %Y',
  1697. '%d %b %Y',
  1698. '%B %d %Y',
  1699. '%B %dst %Y',
  1700. '%B %dnd %Y',
  1701. '%B %drd %Y',
  1702. '%B %dth %Y',
  1703. '%b %d %Y',
  1704. '%b %dst %Y',
  1705. '%b %dnd %Y',
  1706. '%b %drd %Y',
  1707. '%b %dth %Y',
  1708. '%b %dst %Y %I:%M',
  1709. '%b %dnd %Y %I:%M',
  1710. '%b %drd %Y %I:%M',
  1711. '%b %dth %Y %I:%M',
  1712. '%Y %m %d',
  1713. '%Y-%m-%d',
  1714. '%Y/%m/%d',
  1715. '%Y/%m/%d %H:%M',
  1716. '%Y/%m/%d %H:%M:%S',
  1717. '%Y-%m-%d %H:%M',
  1718. '%Y-%m-%d %H:%M:%S',
  1719. '%Y-%m-%d %H:%M:%S.%f',
  1720. '%d.%m.%Y %H:%M',
  1721. '%d.%m.%Y %H.%M',
  1722. '%Y-%m-%dT%H:%M:%SZ',
  1723. '%Y-%m-%dT%H:%M:%S.%fZ',
  1724. '%Y-%m-%dT%H:%M:%S.%f0Z',
  1725. '%Y-%m-%dT%H:%M:%S',
  1726. '%Y-%m-%dT%H:%M:%S.%f',
  1727. '%Y-%m-%dT%H:%M',
  1728. '%b %d %Y at %H:%M',
  1729. '%b %d %Y at %H:%M:%S',
  1730. '%B %d %Y at %H:%M',
  1731. '%B %d %Y at %H:%M:%S',
  1732. )
  1733. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  1734. DATE_FORMATS_DAY_FIRST.extend([
  1735. '%d-%m-%Y',
  1736. '%d.%m.%Y',
  1737. '%d.%m.%y',
  1738. '%d/%m/%Y',
  1739. '%d/%m/%y',
  1740. '%d/%m/%Y %H:%M:%S',
  1741. ])
  1742. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  1743. DATE_FORMATS_MONTH_FIRST.extend([
  1744. '%m-%d-%Y',
  1745. '%m.%d.%Y',
  1746. '%m/%d/%Y',
  1747. '%m/%d/%y',
  1748. '%m/%d/%Y %H:%M:%S',
  1749. ])
  1750. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  1751. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  1752. def preferredencoding():
  1753. """Get preferred encoding.
  1754. Returns the best encoding scheme for the system, based on
  1755. locale.getpreferredencoding() and some further tweaks.
  1756. """
  1757. try:
  1758. pref = locale.getpreferredencoding()
  1759. 'TEST'.encode(pref)
  1760. except Exception:
  1761. pref = 'UTF-8'
  1762. return pref
  1763. def write_json_file(obj, fn):
  1764. """ Encode obj as JSON and write it to fn, atomically if possible """
  1765. fn = encodeFilename(fn)
  1766. if sys.version_info < (3, 0) and sys.platform != 'win32':
  1767. encoding = get_filesystem_encoding()
  1768. # os.path.basename returns a bytes object, but NamedTemporaryFile
  1769. # will fail if the filename contains non ascii characters unless we
  1770. # use a unicode object
  1771. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  1772. # the same for os.path.dirname
  1773. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  1774. else:
  1775. path_basename = os.path.basename
  1776. path_dirname = os.path.dirname
  1777. args = {
  1778. 'suffix': '.tmp',
  1779. 'prefix': path_basename(fn) + '.',
  1780. 'dir': path_dirname(fn),
  1781. 'delete': False,
  1782. }
  1783. # In Python 2.x, json.dump expects a bytestream.
  1784. # In Python 3.x, it writes to a character stream
  1785. if sys.version_info < (3, 0):
  1786. args['mode'] = 'wb'
  1787. else:
  1788. args.update({
  1789. 'mode': 'w',
  1790. 'encoding': 'utf-8',
  1791. })
  1792. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  1793. try:
  1794. with tf:
  1795. json.dump(obj, tf)
  1796. if sys.platform == 'win32':
  1797. # Need to remove existing file on Windows, else os.rename raises
  1798. # WindowsError or FileExistsError.
  1799. try:
  1800. os.unlink(fn)
  1801. except OSError:
  1802. pass
  1803. os.rename(tf.name, fn)
  1804. except Exception:
  1805. try:
  1806. os.remove(tf.name)
  1807. except OSError:
  1808. pass
  1809. raise
  1810. if sys.version_info >= (2, 7):
  1811. def find_xpath_attr(node, xpath, key, val=None):
  1812. """ Find the xpath xpath[@key=val] """
  1813. assert re.match(r'^[a-zA-Z_-]+$', key)
  1814. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  1815. return node.find(expr)
  1816. else:
  1817. def find_xpath_attr(node, xpath, key, val=None):
  1818. for f in node.findall(compat_xpath(xpath)):
  1819. if key not in f.attrib:
  1820. continue
  1821. if val is None or f.attrib.get(key) == val:
  1822. return f
  1823. return None
  1824. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  1825. # the namespace parameter
  1826. def xpath_with_ns(path, ns_map):
  1827. components = [c.split(':') for c in path.split('/')]
  1828. replaced = []
  1829. for c in components:
  1830. if len(c) == 1:
  1831. replaced.append(c[0])
  1832. else:
  1833. ns, tag = c
  1834. replaced.append('{%s}%s' % (ns_map[ns], tag))
  1835. return '/'.join(replaced)
  1836. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1837. def _find_xpath(xpath):
  1838. return node.find(compat_xpath(xpath))
  1839. if isinstance(xpath, (str, compat_str)):
  1840. n = _find_xpath(xpath)
  1841. else:
  1842. for xp in xpath:
  1843. n = _find_xpath(xp)
  1844. if n is not None:
  1845. break
  1846. if n is None:
  1847. if default is not NO_DEFAULT:
  1848. return default
  1849. elif fatal:
  1850. name = xpath if name is None else name
  1851. raise ExtractorError('Could not find XML element %s' % name)
  1852. else:
  1853. return None
  1854. return n
  1855. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1856. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  1857. if n is None or n == default:
  1858. return n
  1859. if n.text is None:
  1860. if default is not NO_DEFAULT:
  1861. return default
  1862. elif fatal:
  1863. name = xpath if name is None else name
  1864. raise ExtractorError('Could not find XML element\'s text %s' % name)
  1865. else:
  1866. return None
  1867. return n.text
  1868. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  1869. n = find_xpath_attr(node, xpath, key)
  1870. if n is None:
  1871. if default is not NO_DEFAULT:
  1872. return default
  1873. elif fatal:
  1874. name = '%s[@%s]' % (xpath, key) if name is None else name
  1875. raise ExtractorError('Could not find XML attribute %s' % name)
  1876. else:
  1877. return None
  1878. return n.attrib[key]
  1879. def get_element_by_id(id, html):
  1880. """Return the content of the tag with the specified ID in the passed HTML document"""
  1881. return get_element_by_attribute('id', id, html)
  1882. def get_element_by_class(class_name, html):
  1883. """Return the content of the first tag with the specified class in the passed HTML document"""
  1884. retval = get_elements_by_class(class_name, html)
  1885. return retval[0] if retval else None
  1886. def get_element_by_attribute(attribute, value, html, escape_value=True):
  1887. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  1888. return retval[0] if retval else None
  1889. def get_elements_by_class(class_name, html):
  1890. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  1891. return get_elements_by_attribute(
  1892. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  1893. html, escape_value=False)
  1894. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  1895. """Return the content of the tag with the specified attribute in the passed HTML document"""
  1896. value = re.escape(value) if escape_value else value
  1897. retlist = []
  1898. for m in re.finditer(r'''(?xs)
  1899. <([a-zA-Z0-9:._-]+)
  1900. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1901. \s+%s=['"]?%s['"]?
  1902. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1903. \s*>
  1904. (?P<content>.*?)
  1905. </\1>
  1906. ''' % (re.escape(attribute), value), html):
  1907. res = m.group('content')
  1908. if res.startswith('"') or res.startswith("'"):
  1909. res = res[1:-1]
  1910. retlist.append(unescapeHTML(res))
  1911. return retlist
  1912. class HTMLAttributeParser(compat_HTMLParser):
  1913. """Trivial HTML parser to gather the attributes for a single element"""
  1914. def __init__(self):
  1915. self.attrs = {}
  1916. compat_HTMLParser.__init__(self)
  1917. def handle_starttag(self, tag, attrs):
  1918. self.attrs = dict(attrs)
  1919. def extract_attributes(html_element):
  1920. """Given a string for an HTML element such as
  1921. <el
  1922. a="foo" B="bar" c="&98;az" d=boz
  1923. empty= noval entity="&amp;"
  1924. sq='"' dq="'"
  1925. >
  1926. Decode and return a dictionary of attributes.
  1927. {
  1928. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  1929. 'empty': '', 'noval': None, 'entity': '&',
  1930. 'sq': '"', 'dq': '\''
  1931. }.
  1932. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  1933. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  1934. """
  1935. parser = HTMLAttributeParser()
  1936. try:
  1937. parser.feed(html_element)
  1938. parser.close()
  1939. # Older Python may throw HTMLParseError in case of malformed HTML
  1940. except compat_HTMLParseError:
  1941. pass
  1942. return parser.attrs
  1943. def clean_html(html):
  1944. """Clean an HTML snippet into a readable string"""
  1945. if html is None: # Convenience for sanitizing descriptions etc.
  1946. return html
  1947. # Newline vs <br />
  1948. html = html.replace('\n', ' ')
  1949. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  1950. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  1951. # Strip html tags
  1952. html = re.sub('<.*?>', '', html)
  1953. # Replace html entities
  1954. html = unescapeHTML(html)
  1955. return html.strip()
  1956. def sanitize_open(filename, open_mode):
  1957. """Try to open the given filename, and slightly tweak it if this fails.
  1958. Attempts to open the given filename. If this fails, it tries to change
  1959. the filename slightly, step by step, until it's either able to open it
  1960. or it fails and raises a final exception, like the standard open()
  1961. function.
  1962. It returns the tuple (stream, definitive_file_name).
  1963. """
  1964. try:
  1965. if filename == '-':
  1966. if sys.platform == 'win32':
  1967. import msvcrt
  1968. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  1969. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  1970. stream = open(encodeFilename(filename), open_mode)
  1971. return (stream, filename)
  1972. except (IOError, OSError) as err:
  1973. if err.errno in (errno.EACCES,):
  1974. raise
  1975. # In case of error, try to remove win32 forbidden chars
  1976. alt_filename = sanitize_path(filename)
  1977. if alt_filename == filename:
  1978. raise
  1979. else:
  1980. # An exception here should be caught in the caller
  1981. stream = open(encodeFilename(alt_filename), open_mode)
  1982. return (stream, alt_filename)
  1983. def timeconvert(timestr):
  1984. """Convert RFC 2822 defined time string into system timestamp"""
  1985. timestamp = None
  1986. timetuple = email.utils.parsedate_tz(timestr)
  1987. if timetuple is not None:
  1988. timestamp = email.utils.mktime_tz(timetuple)
  1989. return timestamp
  1990. def sanitize_filename(s, restricted=False, is_id=False):
  1991. """Sanitizes a string so it could be used as part of a filename.
  1992. If restricted is set, use a stricter subset of allowed characters.
  1993. Set is_id if this is not an arbitrary string, but an ID that should be kept
  1994. if possible.
  1995. """
  1996. def replace_insane(char):
  1997. if restricted and char in ACCENT_CHARS:
  1998. return ACCENT_CHARS[char]
  1999. if char == '?' or ord(char) < 32 or ord(char) == 127:
  2000. return ''
  2001. elif char == '"':
  2002. return '' if restricted else '\''
  2003. elif char == ':':
  2004. return '_-' if restricted else ' -'
  2005. elif char in '\\/|*<>':
  2006. return '_'
  2007. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  2008. return '_'
  2009. if restricted and ord(char) > 127:
  2010. return '_'
  2011. return char
  2012. # Handle timestamps
  2013. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  2014. result = ''.join(map(replace_insane, s))
  2015. if not is_id:
  2016. while '__' in result:
  2017. result = result.replace('__', '_')
  2018. result = result.strip('_')
  2019. # Common case of "Foreign band name - English song title"
  2020. if restricted and result.startswith('-_'):
  2021. result = result[2:]
  2022. if result.startswith('-'):
  2023. result = '_' + result[len('-'):]
  2024. result = result.lstrip('.')
  2025. if not result:
  2026. result = '_'
  2027. return result
  2028. def sanitize_path(s):
  2029. """Sanitizes and normalizes path on Windows"""
  2030. if sys.platform != 'win32':
  2031. return s
  2032. drive_or_unc, _ = os.path.splitdrive(s)
  2033. if sys.version_info < (2, 7) and not drive_or_unc:
  2034. drive_or_unc, _ = os.path.splitunc(s)
  2035. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  2036. if drive_or_unc:
  2037. norm_path.pop(0)
  2038. sanitized_path = [
  2039. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  2040. for path_part in norm_path]
  2041. if drive_or_unc:
  2042. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  2043. return os.path.join(*sanitized_path)
  2044. def sanitize_url(url):
  2045. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  2046. # the number of unwanted failures due to missing protocol
  2047. if url.startswith('//'):
  2048. return 'http:%s' % url
  2049. # Fix some common typos seen so far
  2050. COMMON_TYPOS = (
  2051. # https://github.com/ytdl-org/youtube-dl/issues/15649
  2052. (r'^httpss://', r'https://'),
  2053. # https://bx1.be/lives/direct-tv/
  2054. (r'^rmtp([es]?)://', r'rtmp\1://'),
  2055. )
  2056. for mistake, fixup in COMMON_TYPOS:
  2057. if re.match(mistake, url):
  2058. return re.sub(mistake, fixup, url)
  2059. return url
  2060. def sanitized_Request(url, *args, **kwargs):
  2061. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  2062. def expand_path(s):
  2063. """Expand shell variables and ~"""
  2064. return os.path.expandvars(compat_expanduser(s))
  2065. def orderedSet(iterable):
  2066. """ Remove all duplicates from the input iterable """
  2067. res = []
  2068. for el in iterable:
  2069. if el not in res:
  2070. res.append(el)
  2071. return res
  2072. def _htmlentity_transform(entity_with_semicolon):
  2073. """Transforms an HTML entity to a character."""
  2074. entity = entity_with_semicolon[:-1]
  2075. # Known non-numeric HTML entity
  2076. if entity in compat_html_entities.name2codepoint:
  2077. return compat_chr(compat_html_entities.name2codepoint[entity])
  2078. # TODO: HTML5 allows entities without a semicolon. For example,
  2079. # '&Eacuteric' should be decoded as 'Éric'.
  2080. if entity_with_semicolon in compat_html_entities_html5:
  2081. return compat_html_entities_html5[entity_with_semicolon]
  2082. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  2083. if mobj is not None:
  2084. numstr = mobj.group(1)
  2085. if numstr.startswith('x'):
  2086. base = 16
  2087. numstr = '0%s' % numstr
  2088. else:
  2089. base = 10
  2090. # See https://github.com/ytdl-org/youtube-dl/issues/7518
  2091. try:
  2092. return compat_chr(int(numstr, base))
  2093. except ValueError:
  2094. pass
  2095. # Unknown entity in name, return its literal representation
  2096. return '&%s;' % entity
  2097. def unescapeHTML(s):
  2098. if s is None:
  2099. return None
  2100. assert type(s) == compat_str
  2101. return re.sub(
  2102. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  2103. def get_subprocess_encoding():
  2104. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2105. # For subprocess calls, encode with locale encoding
  2106. # Refer to http://stackoverflow.com/a/9951851/35070
  2107. encoding = preferredencoding()
  2108. else:
  2109. encoding = sys.getfilesystemencoding()
  2110. if encoding is None:
  2111. encoding = 'utf-8'
  2112. return encoding
  2113. def encodeFilename(s, for_subprocess=False):
  2114. """
  2115. @param s The name of the file
  2116. """
  2117. assert type(s) == compat_str
  2118. # Python 3 has a Unicode API
  2119. if sys.version_info >= (3, 0):
  2120. return s
  2121. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  2122. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  2123. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  2124. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2125. return s
  2126. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  2127. if sys.platform.startswith('java'):
  2128. return s
  2129. return s.encode(get_subprocess_encoding(), 'ignore')
  2130. def decodeFilename(b, for_subprocess=False):
  2131. if sys.version_info >= (3, 0):
  2132. return b
  2133. if not isinstance(b, bytes):
  2134. return b
  2135. return b.decode(get_subprocess_encoding(), 'ignore')
  2136. def encodeArgument(s):
  2137. if not isinstance(s, compat_str):
  2138. # Legacy code that uses byte strings
  2139. # Uncomment the following line after fixing all post processors
  2140. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  2141. s = s.decode('ascii')
  2142. return encodeFilename(s, True)
  2143. def decodeArgument(b):
  2144. return decodeFilename(b, True)
  2145. def decodeOption(optval):
  2146. if optval is None:
  2147. return optval
  2148. if isinstance(optval, bytes):
  2149. optval = optval.decode(preferredencoding())
  2150. assert isinstance(optval, compat_str)
  2151. return optval
  2152. def formatSeconds(secs):
  2153. if secs > 3600:
  2154. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  2155. elif secs > 60:
  2156. return '%d:%02d' % (secs // 60, secs % 60)
  2157. else:
  2158. return '%d' % secs
  2159. def make_HTTPS_handler(params, **kwargs):
  2160. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2161. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2162. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2163. if opts_no_check_certificate:
  2164. context.check_hostname = False
  2165. context.verify_mode = ssl.CERT_NONE
  2166. try:
  2167. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2168. except TypeError:
  2169. # Python 2.7.8
  2170. # (create_default_context present but HTTPSHandler has no context=)
  2171. pass
  2172. if sys.version_info < (3, 2):
  2173. return YoutubeDLHTTPSHandler(params, **kwargs)
  2174. else: # Python < 3.4
  2175. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2176. context.verify_mode = (ssl.CERT_NONE
  2177. if opts_no_check_certificate
  2178. else ssl.CERT_REQUIRED)
  2179. context.set_default_verify_paths()
  2180. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2181. def bug_reports_message():
  2182. if ytdl_is_updateable():
  2183. update_cmd = 'type youtube-dl -U to update'
  2184. else:
  2185. update_cmd = 'see https://yt-dl.org/update on how to update'
  2186. msg = '; please report this issue on https://yt-dl.org/bug .'
  2187. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  2188. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  2189. return msg
  2190. class YoutubeDLError(Exception):
  2191. """Base exception for YoutubeDL errors."""
  2192. pass
  2193. class ExtractorError(YoutubeDLError):
  2194. """Error during info extraction."""
  2195. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2196. """ tb, if given, is the original traceback (so that it can be printed out).
  2197. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2198. """
  2199. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2200. expected = True
  2201. if video_id is not None:
  2202. msg = video_id + ': ' + msg
  2203. if cause:
  2204. msg += ' (caused by %r)' % cause
  2205. if not expected:
  2206. msg += bug_reports_message()
  2207. super(ExtractorError, self).__init__(msg)
  2208. self.traceback = tb
  2209. self.exc_info = sys.exc_info() # preserve original exception
  2210. self.cause = cause
  2211. self.video_id = video_id
  2212. def format_traceback(self):
  2213. if self.traceback is None:
  2214. return None
  2215. return ''.join(traceback.format_tb(self.traceback))
  2216. class UnsupportedError(ExtractorError):
  2217. def __init__(self, url):
  2218. super(UnsupportedError, self).__init__(
  2219. 'Unsupported URL: %s' % url, expected=True)
  2220. self.url = url
  2221. class RegexNotFoundError(ExtractorError):
  2222. """Error when a regex didn't match"""
  2223. pass
  2224. class GeoRestrictedError(ExtractorError):
  2225. """Geographic restriction Error exception.
  2226. This exception may be thrown when a video is not available from your
  2227. geographic location due to geographic restrictions imposed by a website.
  2228. """
  2229. def __init__(self, msg, countries=None):
  2230. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2231. self.msg = msg
  2232. self.countries = countries
  2233. class DownloadError(YoutubeDLError):
  2234. """Download Error exception.
  2235. This exception may be thrown by FileDownloader objects if they are not
  2236. configured to continue on errors. They will contain the appropriate
  2237. error message.
  2238. """
  2239. def __init__(self, msg, exc_info=None):
  2240. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2241. super(DownloadError, self).__init__(msg)
  2242. self.exc_info = exc_info
  2243. class SameFileError(YoutubeDLError):
  2244. """Same File exception.
  2245. This exception will be thrown by FileDownloader objects if they detect
  2246. multiple files would have to be downloaded to the same file on disk.
  2247. """
  2248. pass
  2249. class PostProcessingError(YoutubeDLError):
  2250. """Post Processing exception.
  2251. This exception may be raised by PostProcessor's .run() method to
  2252. indicate an error in the postprocessing task.
  2253. """
  2254. def __init__(self, msg):
  2255. super(PostProcessingError, self).__init__(msg)
  2256. self.msg = msg
  2257. class MaxDownloadsReached(YoutubeDLError):
  2258. """ --max-downloads limit has been reached. """
  2259. pass
  2260. class UnavailableVideoError(YoutubeDLError):
  2261. """Unavailable Format exception.
  2262. This exception will be thrown when a video is requested
  2263. in a format that is not available for that video.
  2264. """
  2265. pass
  2266. class ContentTooShortError(YoutubeDLError):
  2267. """Content Too Short exception.
  2268. This exception may be raised by FileDownloader objects when a file they
  2269. download is too small for what the server announced first, indicating
  2270. the connection was probably interrupted.
  2271. """
  2272. def __init__(self, downloaded, expected):
  2273. super(ContentTooShortError, self).__init__(
  2274. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2275. )
  2276. # Both in bytes
  2277. self.downloaded = downloaded
  2278. self.expected = expected
  2279. class XAttrMetadataError(YoutubeDLError):
  2280. def __init__(self, code=None, msg='Unknown error'):
  2281. super(XAttrMetadataError, self).__init__(msg)
  2282. self.code = code
  2283. self.msg = msg
  2284. # Parsing code and msg
  2285. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2286. or 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  2287. self.reason = 'NO_SPACE'
  2288. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2289. self.reason = 'VALUE_TOO_LONG'
  2290. else:
  2291. self.reason = 'NOT_SUPPORTED'
  2292. class XAttrUnavailableError(YoutubeDLError):
  2293. pass
  2294. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2295. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2296. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2297. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2298. if sys.version_info < (3, 0):
  2299. kwargs['strict'] = True
  2300. hc = http_class(*args, **compat_kwargs(kwargs))
  2301. source_address = ydl_handler._params.get('source_address')
  2302. if source_address is not None:
  2303. # This is to workaround _create_connection() from socket where it will try all
  2304. # address data from getaddrinfo() including IPv6. This filters the result from
  2305. # getaddrinfo() based on the source_address value.
  2306. # This is based on the cpython socket.create_connection() function.
  2307. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2308. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2309. host, port = address
  2310. err = None
  2311. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2312. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2313. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2314. if addrs and not ip_addrs:
  2315. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2316. raise socket.error(
  2317. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2318. % (ip_version, source_address[0]))
  2319. for res in ip_addrs:
  2320. af, socktype, proto, canonname, sa = res
  2321. sock = None
  2322. try:
  2323. sock = socket.socket(af, socktype, proto)
  2324. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2325. sock.settimeout(timeout)
  2326. sock.bind(source_address)
  2327. sock.connect(sa)
  2328. err = None # Explicitly break reference cycle
  2329. return sock
  2330. except socket.error as _:
  2331. err = _
  2332. if sock is not None:
  2333. sock.close()
  2334. if err is not None:
  2335. raise err
  2336. else:
  2337. raise socket.error('getaddrinfo returns an empty list')
  2338. if hasattr(hc, '_create_connection'):
  2339. hc._create_connection = _create_connection
  2340. sa = (source_address, 0)
  2341. if hasattr(hc, 'source_address'): # Python 2.7+
  2342. hc.source_address = sa
  2343. else: # Python 2.6
  2344. def _hc_connect(self, *args, **kwargs):
  2345. sock = _create_connection(
  2346. (self.host, self.port), self.timeout, sa)
  2347. if is_https:
  2348. self.sock = ssl.wrap_socket(
  2349. sock, self.key_file, self.cert_file,
  2350. ssl_version=ssl.PROTOCOL_TLSv1)
  2351. else:
  2352. self.sock = sock
  2353. hc.connect = functools.partial(_hc_connect, hc)
  2354. return hc
  2355. def handle_youtubedl_headers(headers):
  2356. filtered_headers = headers
  2357. if 'Youtubedl-no-compression' in filtered_headers:
  2358. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  2359. del filtered_headers['Youtubedl-no-compression']
  2360. return filtered_headers
  2361. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2362. """Handler for HTTP requests and responses.
  2363. This class, when installed with an OpenerDirector, automatically adds
  2364. the standard headers to every HTTP request and handles gzipped and
  2365. deflated responses from web servers. If compression is to be avoided in
  2366. a particular request, the original request in the program code only has
  2367. to include the HTTP header "Youtubedl-no-compression", which will be
  2368. removed before making the real request.
  2369. Part of this code was copied from:
  2370. http://techknack.net/python-urllib2-handlers/
  2371. Andrew Rowls, the author of that code, agreed to release it to the
  2372. public domain.
  2373. """
  2374. def __init__(self, params, *args, **kwargs):
  2375. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2376. self._params = params
  2377. def http_open(self, req):
  2378. conn_class = compat_http_client.HTTPConnection
  2379. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2380. if socks_proxy:
  2381. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2382. del req.headers['Ytdl-socks-proxy']
  2383. return self.do_open(functools.partial(
  2384. _create_http_connection, self, conn_class, False),
  2385. req)
  2386. @staticmethod
  2387. def deflate(data):
  2388. try:
  2389. return zlib.decompress(data, -zlib.MAX_WBITS)
  2390. except zlib.error:
  2391. return zlib.decompress(data)
  2392. def http_request(self, req):
  2393. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  2394. # always respected by websites, some tend to give out URLs with non percent-encoded
  2395. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2396. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2397. # To work around aforementioned issue we will replace request's original URL with
  2398. # percent-encoded one
  2399. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2400. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2401. url = req.get_full_url()
  2402. url_escaped = escape_url(url)
  2403. # Substitute URL if any change after escaping
  2404. if url != url_escaped:
  2405. req = update_Request(req, url=url_escaped)
  2406. for h, v in std_headers.items():
  2407. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2408. # The dict keys are capitalized because of this bug by urllib
  2409. if h.capitalize() not in req.headers:
  2410. req.add_header(h, v)
  2411. req.headers = handle_youtubedl_headers(req.headers)
  2412. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  2413. # Python 2.6 is brain-dead when it comes to fragments
  2414. req._Request__original = req._Request__original.partition('#')[0]
  2415. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2416. return req
  2417. def http_response(self, req, resp):
  2418. old_resp = resp
  2419. # gzip
  2420. if resp.headers.get('Content-encoding', '') == 'gzip':
  2421. content = resp.read()
  2422. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  2423. try:
  2424. uncompressed = io.BytesIO(gz.read())
  2425. except IOError as original_ioerror:
  2426. # There may be junk add the end of the file
  2427. # See http://stackoverflow.com/q/4928560/35070 for details
  2428. for i in range(1, 1024):
  2429. try:
  2430. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  2431. uncompressed = io.BytesIO(gz.read())
  2432. except IOError:
  2433. continue
  2434. break
  2435. else:
  2436. raise original_ioerror
  2437. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  2438. resp.msg = old_resp.msg
  2439. del resp.headers['Content-encoding']
  2440. # deflate
  2441. if resp.headers.get('Content-encoding', '') == 'deflate':
  2442. gz = io.BytesIO(self.deflate(resp.read()))
  2443. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  2444. resp.msg = old_resp.msg
  2445. del resp.headers['Content-encoding']
  2446. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2447. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2448. if 300 <= resp.code < 400:
  2449. location = resp.headers.get('Location')
  2450. if location:
  2451. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2452. if sys.version_info >= (3, 0):
  2453. location = location.encode('iso-8859-1').decode('utf-8')
  2454. else:
  2455. location = location.decode('utf-8')
  2456. location_escaped = escape_url(location)
  2457. if location != location_escaped:
  2458. del resp.headers['Location']
  2459. if sys.version_info < (3, 0):
  2460. location_escaped = location_escaped.encode('utf-8')
  2461. resp.headers['Location'] = location_escaped
  2462. return resp
  2463. https_request = http_request
  2464. https_response = http_response
  2465. def make_socks_conn_class(base_class, socks_proxy):
  2466. assert issubclass(base_class, (
  2467. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2468. url_components = compat_urlparse.urlparse(socks_proxy)
  2469. if url_components.scheme.lower() == 'socks5':
  2470. socks_type = ProxyType.SOCKS5
  2471. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2472. socks_type = ProxyType.SOCKS4
  2473. elif url_components.scheme.lower() == 'socks4a':
  2474. socks_type = ProxyType.SOCKS4A
  2475. def unquote_if_non_empty(s):
  2476. if not s:
  2477. return s
  2478. return compat_urllib_parse_unquote_plus(s)
  2479. proxy_args = (
  2480. socks_type,
  2481. url_components.hostname, url_components.port or 1080,
  2482. True, # Remote DNS
  2483. unquote_if_non_empty(url_components.username),
  2484. unquote_if_non_empty(url_components.password),
  2485. )
  2486. class SocksConnection(base_class):
  2487. def connect(self):
  2488. self.sock = sockssocket()
  2489. self.sock.setproxy(*proxy_args)
  2490. if type(self.timeout) in (int, float):
  2491. self.sock.settimeout(self.timeout)
  2492. self.sock.connect((self.host, self.port))
  2493. if isinstance(self, compat_http_client.HTTPSConnection):
  2494. if hasattr(self, '_context'): # Python > 2.6
  2495. self.sock = self._context.wrap_socket(
  2496. self.sock, server_hostname=self.host)
  2497. else:
  2498. self.sock = ssl.wrap_socket(self.sock)
  2499. return SocksConnection
  2500. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2501. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2502. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2503. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2504. self._params = params
  2505. def https_open(self, req):
  2506. kwargs = {}
  2507. conn_class = self._https_conn_class
  2508. if hasattr(self, '_context'): # python > 2.6
  2509. kwargs['context'] = self._context
  2510. if hasattr(self, '_check_hostname'): # python 3.x
  2511. kwargs['check_hostname'] = self._check_hostname
  2512. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2513. if socks_proxy:
  2514. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2515. del req.headers['Ytdl-socks-proxy']
  2516. return self.do_open(functools.partial(
  2517. _create_http_connection, self, conn_class, True),
  2518. req, **kwargs)
  2519. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2520. _HTTPONLY_PREFIX = '#HttpOnly_'
  2521. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2522. # Store session cookies with `expires` set to 0 instead of an empty
  2523. # string
  2524. for cookie in self:
  2525. if cookie.expires is None:
  2526. cookie.expires = 0
  2527. compat_cookiejar.MozillaCookieJar.save(self, filename, ignore_discard, ignore_expires)
  2528. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2529. """Load cookies from a file."""
  2530. if filename is None:
  2531. if self.filename is not None:
  2532. filename = self.filename
  2533. else:
  2534. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2535. cf = io.StringIO()
  2536. with open(filename) as f:
  2537. for line in f:
  2538. if line.startswith(self._HTTPONLY_PREFIX):
  2539. line = line[len(self._HTTPONLY_PREFIX):]
  2540. cf.write(compat_str(line))
  2541. cf.seek(0)
  2542. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2543. # Session cookies are denoted by either `expires` field set to
  2544. # an empty string or 0. MozillaCookieJar only recognizes the former
  2545. # (see [1]). So we need force the latter to be recognized as session
  2546. # cookies on our own.
  2547. # Session cookies may be important for cookies-based authentication,
  2548. # e.g. usually, when user does not check 'Remember me' check box while
  2549. # logging in on a site, some important cookies are stored as session
  2550. # cookies so that not recognizing them will result in failed login.
  2551. # 1. https://bugs.python.org/issue17164
  2552. for cookie in self:
  2553. # Treat `expires=0` cookies as session cookies
  2554. if cookie.expires == 0:
  2555. cookie.expires = None
  2556. cookie.discard = True
  2557. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2558. def __init__(self, cookiejar=None):
  2559. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2560. def http_response(self, request, response):
  2561. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2562. # characters in Set-Cookie HTTP header of last response (see
  2563. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2564. # In order to at least prevent crashing we will percent encode Set-Cookie
  2565. # header before HTTPCookieProcessor starts processing it.
  2566. # if sys.version_info < (3, 0) and response.headers:
  2567. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2568. # set_cookie = response.headers.get(set_cookie_header)
  2569. # if set_cookie:
  2570. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2571. # if set_cookie != set_cookie_escaped:
  2572. # del response.headers[set_cookie_header]
  2573. # response.headers[set_cookie_header] = set_cookie_escaped
  2574. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2575. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2576. https_response = http_response
  2577. def extract_timezone(date_str):
  2578. m = re.search(
  2579. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  2580. date_str)
  2581. if not m:
  2582. timezone = datetime.timedelta()
  2583. else:
  2584. date_str = date_str[:-len(m.group('tz'))]
  2585. if not m.group('sign'):
  2586. timezone = datetime.timedelta()
  2587. else:
  2588. sign = 1 if m.group('sign') == '+' else -1
  2589. timezone = datetime.timedelta(
  2590. hours=sign * int(m.group('hours')),
  2591. minutes=sign * int(m.group('minutes')))
  2592. return timezone, date_str
  2593. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2594. """ Return a UNIX timestamp from the given date """
  2595. if date_str is None:
  2596. return None
  2597. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2598. if timezone is None:
  2599. timezone, date_str = extract_timezone(date_str)
  2600. try:
  2601. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2602. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2603. return calendar.timegm(dt.timetuple())
  2604. except ValueError:
  2605. pass
  2606. def date_formats(day_first=True):
  2607. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2608. def unified_strdate(date_str, day_first=True):
  2609. """Return a string with the date in the format YYYYMMDD"""
  2610. if date_str is None:
  2611. return None
  2612. upload_date = None
  2613. # Replace commas
  2614. date_str = date_str.replace(',', ' ')
  2615. # Remove AM/PM + timezone
  2616. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2617. _, date_str = extract_timezone(date_str)
  2618. for expression in date_formats(day_first):
  2619. try:
  2620. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2621. except ValueError:
  2622. pass
  2623. if upload_date is None:
  2624. timetuple = email.utils.parsedate_tz(date_str)
  2625. if timetuple:
  2626. try:
  2627. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2628. except ValueError:
  2629. pass
  2630. if upload_date is not None:
  2631. return compat_str(upload_date)
  2632. def unified_timestamp(date_str, day_first=True):
  2633. if date_str is None:
  2634. return None
  2635. date_str = re.sub(r'[,|]', '', date_str)
  2636. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2637. timezone, date_str = extract_timezone(date_str)
  2638. # Remove AM/PM + timezone
  2639. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2640. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2641. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2642. if m:
  2643. date_str = date_str[:-len(m.group('tz'))]
  2644. # Python only supports microseconds, so remove nanoseconds
  2645. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  2646. if m:
  2647. date_str = m.group(1)
  2648. for expression in date_formats(day_first):
  2649. try:
  2650. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2651. return calendar.timegm(dt.timetuple())
  2652. except ValueError:
  2653. pass
  2654. timetuple = email.utils.parsedate_tz(date_str)
  2655. if timetuple:
  2656. return calendar.timegm(timetuple) + pm_delta * 3600
  2657. def determine_ext(url, default_ext='unknown_video'):
  2658. if url is None or '.' not in url:
  2659. return default_ext
  2660. guess = url.partition('?')[0].rpartition('.')[2]
  2661. if re.match(r'^[A-Za-z0-9]+$', guess):
  2662. return guess
  2663. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2664. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2665. return guess.rstrip('/')
  2666. else:
  2667. return default_ext
  2668. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2669. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2670. def date_from_str(date_str):
  2671. """
  2672. Return a datetime object from a string in the format YYYYMMDD or
  2673. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2674. today = datetime.date.today()
  2675. if date_str in ('now', 'today'):
  2676. return today
  2677. if date_str == 'yesterday':
  2678. return today - datetime.timedelta(days=1)
  2679. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2680. if match is not None:
  2681. sign = match.group('sign')
  2682. time = int(match.group('time'))
  2683. if sign == '-':
  2684. time = -time
  2685. unit = match.group('unit')
  2686. # A bad approximation?
  2687. if unit == 'month':
  2688. unit = 'day'
  2689. time *= 30
  2690. elif unit == 'year':
  2691. unit = 'day'
  2692. time *= 365
  2693. unit += 's'
  2694. delta = datetime.timedelta(**{unit: time})
  2695. return today + delta
  2696. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2697. def hyphenate_date(date_str):
  2698. """
  2699. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  2700. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  2701. if match is not None:
  2702. return '-'.join(match.groups())
  2703. else:
  2704. return date_str
  2705. class DateRange(object):
  2706. """Represents a time interval between two dates"""
  2707. def __init__(self, start=None, end=None):
  2708. """start and end must be strings in the format accepted by date"""
  2709. if start is not None:
  2710. self.start = date_from_str(start)
  2711. else:
  2712. self.start = datetime.datetime.min.date()
  2713. if end is not None:
  2714. self.end = date_from_str(end)
  2715. else:
  2716. self.end = datetime.datetime.max.date()
  2717. if self.start > self.end:
  2718. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  2719. @classmethod
  2720. def day(cls, day):
  2721. """Returns a range that only contains the given day"""
  2722. return cls(day, day)
  2723. def __contains__(self, date):
  2724. """Check if the date is in the range"""
  2725. if not isinstance(date, datetime.date):
  2726. date = date_from_str(date)
  2727. return self.start <= date <= self.end
  2728. def __str__(self):
  2729. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  2730. def platform_name():
  2731. """ Returns the platform name as a compat_str """
  2732. res = platform.platform()
  2733. if isinstance(res, bytes):
  2734. res = res.decode(preferredencoding())
  2735. assert isinstance(res, compat_str)
  2736. return res
  2737. def _windows_write_string(s, out):
  2738. """ Returns True if the string was written using special methods,
  2739. False if it has yet to be written out."""
  2740. # Adapted from http://stackoverflow.com/a/3259271/35070
  2741. import ctypes
  2742. import ctypes.wintypes
  2743. WIN_OUTPUT_IDS = {
  2744. 1: -11,
  2745. 2: -12,
  2746. }
  2747. try:
  2748. fileno = out.fileno()
  2749. except AttributeError:
  2750. # If the output stream doesn't have a fileno, it's virtual
  2751. return False
  2752. except io.UnsupportedOperation:
  2753. # Some strange Windows pseudo files?
  2754. return False
  2755. if fileno not in WIN_OUTPUT_IDS:
  2756. return False
  2757. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  2758. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  2759. ('GetStdHandle', ctypes.windll.kernel32))
  2760. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  2761. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  2762. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  2763. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  2764. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  2765. written = ctypes.wintypes.DWORD(0)
  2766. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  2767. FILE_TYPE_CHAR = 0x0002
  2768. FILE_TYPE_REMOTE = 0x8000
  2769. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  2770. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  2771. ctypes.POINTER(ctypes.wintypes.DWORD))(
  2772. ('GetConsoleMode', ctypes.windll.kernel32))
  2773. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  2774. def not_a_console(handle):
  2775. if handle == INVALID_HANDLE_VALUE or handle is None:
  2776. return True
  2777. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  2778. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  2779. if not_a_console(h):
  2780. return False
  2781. def next_nonbmp_pos(s):
  2782. try:
  2783. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  2784. except StopIteration:
  2785. return len(s)
  2786. while s:
  2787. count = min(next_nonbmp_pos(s), 1024)
  2788. ret = WriteConsoleW(
  2789. h, s, count if count else 2, ctypes.byref(written), None)
  2790. if ret == 0:
  2791. raise OSError('Failed to write string')
  2792. if not count: # We just wrote a non-BMP character
  2793. assert written.value == 2
  2794. s = s[1:]
  2795. else:
  2796. assert written.value > 0
  2797. s = s[written.value:]
  2798. return True
  2799. def write_string(s, out=None, encoding=None):
  2800. if out is None:
  2801. out = sys.stderr
  2802. assert type(s) == compat_str
  2803. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  2804. if _windows_write_string(s, out):
  2805. return
  2806. if ('b' in getattr(out, 'mode', '')
  2807. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  2808. byt = s.encode(encoding or preferredencoding(), 'ignore')
  2809. out.write(byt)
  2810. elif hasattr(out, 'buffer'):
  2811. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  2812. byt = s.encode(enc, 'ignore')
  2813. out.buffer.write(byt)
  2814. else:
  2815. out.write(s)
  2816. out.flush()
  2817. def bytes_to_intlist(bs):
  2818. if not bs:
  2819. return []
  2820. if isinstance(bs[0], int): # Python 3
  2821. return list(bs)
  2822. else:
  2823. return [ord(c) for c in bs]
  2824. def intlist_to_bytes(xs):
  2825. if not xs:
  2826. return b''
  2827. return compat_struct_pack('%dB' % len(xs), *xs)
  2828. # Cross-platform file locking
  2829. if sys.platform == 'win32':
  2830. import ctypes.wintypes
  2831. import msvcrt
  2832. class OVERLAPPED(ctypes.Structure):
  2833. _fields_ = [
  2834. ('Internal', ctypes.wintypes.LPVOID),
  2835. ('InternalHigh', ctypes.wintypes.LPVOID),
  2836. ('Offset', ctypes.wintypes.DWORD),
  2837. ('OffsetHigh', ctypes.wintypes.DWORD),
  2838. ('hEvent', ctypes.wintypes.HANDLE),
  2839. ]
  2840. kernel32 = ctypes.windll.kernel32
  2841. LockFileEx = kernel32.LockFileEx
  2842. LockFileEx.argtypes = [
  2843. ctypes.wintypes.HANDLE, # hFile
  2844. ctypes.wintypes.DWORD, # dwFlags
  2845. ctypes.wintypes.DWORD, # dwReserved
  2846. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2847. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2848. ctypes.POINTER(OVERLAPPED) # Overlapped
  2849. ]
  2850. LockFileEx.restype = ctypes.wintypes.BOOL
  2851. UnlockFileEx = kernel32.UnlockFileEx
  2852. UnlockFileEx.argtypes = [
  2853. ctypes.wintypes.HANDLE, # hFile
  2854. ctypes.wintypes.DWORD, # dwReserved
  2855. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2856. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2857. ctypes.POINTER(OVERLAPPED) # Overlapped
  2858. ]
  2859. UnlockFileEx.restype = ctypes.wintypes.BOOL
  2860. whole_low = 0xffffffff
  2861. whole_high = 0x7fffffff
  2862. def _lock_file(f, exclusive):
  2863. overlapped = OVERLAPPED()
  2864. overlapped.Offset = 0
  2865. overlapped.OffsetHigh = 0
  2866. overlapped.hEvent = 0
  2867. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  2868. handle = msvcrt.get_osfhandle(f.fileno())
  2869. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  2870. whole_low, whole_high, f._lock_file_overlapped_p):
  2871. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  2872. def _unlock_file(f):
  2873. assert f._lock_file_overlapped_p
  2874. handle = msvcrt.get_osfhandle(f.fileno())
  2875. if not UnlockFileEx(handle, 0,
  2876. whole_low, whole_high, f._lock_file_overlapped_p):
  2877. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  2878. else:
  2879. # Some platforms, such as Jython, is missing fcntl
  2880. try:
  2881. import fcntl
  2882. def _lock_file(f, exclusive):
  2883. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  2884. def _unlock_file(f):
  2885. fcntl.flock(f, fcntl.LOCK_UN)
  2886. except ImportError:
  2887. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  2888. def _lock_file(f, exclusive):
  2889. raise IOError(UNSUPPORTED_MSG)
  2890. def _unlock_file(f):
  2891. raise IOError(UNSUPPORTED_MSG)
  2892. class locked_file(object):
  2893. def __init__(self, filename, mode, encoding=None):
  2894. assert mode in ['r', 'a', 'w']
  2895. self.f = io.open(filename, mode, encoding=encoding)
  2896. self.mode = mode
  2897. def __enter__(self):
  2898. exclusive = self.mode != 'r'
  2899. try:
  2900. _lock_file(self.f, exclusive)
  2901. except IOError:
  2902. self.f.close()
  2903. raise
  2904. return self
  2905. def __exit__(self, etype, value, traceback):
  2906. try:
  2907. _unlock_file(self.f)
  2908. finally:
  2909. self.f.close()
  2910. def __iter__(self):
  2911. return iter(self.f)
  2912. def write(self, *args):
  2913. return self.f.write(*args)
  2914. def read(self, *args):
  2915. return self.f.read(*args)
  2916. def get_filesystem_encoding():
  2917. encoding = sys.getfilesystemencoding()
  2918. return encoding if encoding is not None else 'utf-8'
  2919. def shell_quote(args):
  2920. quoted_args = []
  2921. encoding = get_filesystem_encoding()
  2922. for a in args:
  2923. if isinstance(a, bytes):
  2924. # We may get a filename encoded with 'encodeFilename'
  2925. a = a.decode(encoding)
  2926. quoted_args.append(compat_shlex_quote(a))
  2927. return ' '.join(quoted_args)
  2928. def smuggle_url(url, data):
  2929. """ Pass additional data in a URL for internal use. """
  2930. url, idata = unsmuggle_url(url, {})
  2931. data.update(idata)
  2932. sdata = compat_urllib_parse_urlencode(
  2933. {'__youtubedl_smuggle': json.dumps(data)})
  2934. return url + '#' + sdata
  2935. def unsmuggle_url(smug_url, default=None):
  2936. if '#__youtubedl_smuggle' not in smug_url:
  2937. return smug_url, default
  2938. url, _, sdata = smug_url.rpartition('#')
  2939. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  2940. data = json.loads(jsond)
  2941. return url, data
  2942. def format_bytes(bytes):
  2943. if bytes is None:
  2944. return 'N/A'
  2945. if type(bytes) is str:
  2946. bytes = float(bytes)
  2947. if bytes == 0.0:
  2948. exponent = 0
  2949. else:
  2950. exponent = int(math.log(bytes, 1024.0))
  2951. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  2952. converted = float(bytes) / float(1024 ** exponent)
  2953. return '%.2f%s' % (converted, suffix)
  2954. def lookup_unit_table(unit_table, s):
  2955. units_re = '|'.join(re.escape(u) for u in unit_table)
  2956. m = re.match(
  2957. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  2958. if not m:
  2959. return None
  2960. num_str = m.group('num').replace(',', '.')
  2961. mult = unit_table[m.group('unit')]
  2962. return int(float(num_str) * mult)
  2963. def parse_filesize(s):
  2964. if s is None:
  2965. return None
  2966. # The lower-case forms are of course incorrect and unofficial,
  2967. # but we support those too
  2968. _UNIT_TABLE = {
  2969. 'B': 1,
  2970. 'b': 1,
  2971. 'bytes': 1,
  2972. 'KiB': 1024,
  2973. 'KB': 1000,
  2974. 'kB': 1024,
  2975. 'Kb': 1000,
  2976. 'kb': 1000,
  2977. 'kilobytes': 1000,
  2978. 'kibibytes': 1024,
  2979. 'MiB': 1024 ** 2,
  2980. 'MB': 1000 ** 2,
  2981. 'mB': 1024 ** 2,
  2982. 'Mb': 1000 ** 2,
  2983. 'mb': 1000 ** 2,
  2984. 'megabytes': 1000 ** 2,
  2985. 'mebibytes': 1024 ** 2,
  2986. 'GiB': 1024 ** 3,
  2987. 'GB': 1000 ** 3,
  2988. 'gB': 1024 ** 3,
  2989. 'Gb': 1000 ** 3,
  2990. 'gb': 1000 ** 3,
  2991. 'gigabytes': 1000 ** 3,
  2992. 'gibibytes': 1024 ** 3,
  2993. 'TiB': 1024 ** 4,
  2994. 'TB': 1000 ** 4,
  2995. 'tB': 1024 ** 4,
  2996. 'Tb': 1000 ** 4,
  2997. 'tb': 1000 ** 4,
  2998. 'terabytes': 1000 ** 4,
  2999. 'tebibytes': 1024 ** 4,
  3000. 'PiB': 1024 ** 5,
  3001. 'PB': 1000 ** 5,
  3002. 'pB': 1024 ** 5,
  3003. 'Pb': 1000 ** 5,
  3004. 'pb': 1000 ** 5,
  3005. 'petabytes': 1000 ** 5,
  3006. 'pebibytes': 1024 ** 5,
  3007. 'EiB': 1024 ** 6,
  3008. 'EB': 1000 ** 6,
  3009. 'eB': 1024 ** 6,
  3010. 'Eb': 1000 ** 6,
  3011. 'eb': 1000 ** 6,
  3012. 'exabytes': 1000 ** 6,
  3013. 'exbibytes': 1024 ** 6,
  3014. 'ZiB': 1024 ** 7,
  3015. 'ZB': 1000 ** 7,
  3016. 'zB': 1024 ** 7,
  3017. 'Zb': 1000 ** 7,
  3018. 'zb': 1000 ** 7,
  3019. 'zettabytes': 1000 ** 7,
  3020. 'zebibytes': 1024 ** 7,
  3021. 'YiB': 1024 ** 8,
  3022. 'YB': 1000 ** 8,
  3023. 'yB': 1024 ** 8,
  3024. 'Yb': 1000 ** 8,
  3025. 'yb': 1000 ** 8,
  3026. 'yottabytes': 1000 ** 8,
  3027. 'yobibytes': 1024 ** 8,
  3028. }
  3029. return lookup_unit_table(_UNIT_TABLE, s)
  3030. def parse_count(s):
  3031. if s is None:
  3032. return None
  3033. s = s.strip()
  3034. if re.match(r'^[\d,.]+$', s):
  3035. return str_to_int(s)
  3036. _UNIT_TABLE = {
  3037. 'k': 1000,
  3038. 'K': 1000,
  3039. 'm': 1000 ** 2,
  3040. 'M': 1000 ** 2,
  3041. 'kk': 1000 ** 2,
  3042. 'KK': 1000 ** 2,
  3043. }
  3044. return lookup_unit_table(_UNIT_TABLE, s)
  3045. def parse_resolution(s):
  3046. if s is None:
  3047. return {}
  3048. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3049. if mobj:
  3050. return {
  3051. 'width': int(mobj.group('w')),
  3052. 'height': int(mobj.group('h')),
  3053. }
  3054. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3055. if mobj:
  3056. return {'height': int(mobj.group(1))}
  3057. mobj = re.search(r'\b([48])[kK]\b', s)
  3058. if mobj:
  3059. return {'height': int(mobj.group(1)) * 540}
  3060. return {}
  3061. def parse_bitrate(s):
  3062. if not isinstance(s, compat_str):
  3063. return
  3064. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3065. if mobj:
  3066. return int(mobj.group(1))
  3067. def month_by_name(name, lang='en'):
  3068. """ Return the number of a month by (locale-independently) English name """
  3069. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3070. try:
  3071. return month_names.index(name) + 1
  3072. except ValueError:
  3073. return None
  3074. def month_by_abbreviation(abbrev):
  3075. """ Return the number of a month by (locale-independently) English
  3076. abbreviations """
  3077. try:
  3078. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3079. except ValueError:
  3080. return None
  3081. def fix_xml_ampersands(xml_str):
  3082. """Replace all the '&' by '&amp;' in XML"""
  3083. return re.sub(
  3084. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3085. '&amp;',
  3086. xml_str)
  3087. def setproctitle(title):
  3088. assert isinstance(title, compat_str)
  3089. # ctypes in Jython is not complete
  3090. # http://bugs.jython.org/issue2148
  3091. if sys.platform.startswith('java'):
  3092. return
  3093. try:
  3094. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3095. except OSError:
  3096. return
  3097. except TypeError:
  3098. # LoadLibrary in Windows Python 2.7.13 only expects
  3099. # a bytestring, but since unicode_literals turns
  3100. # every string into a unicode string, it fails.
  3101. return
  3102. title_bytes = title.encode('utf-8')
  3103. buf = ctypes.create_string_buffer(len(title_bytes))
  3104. buf.value = title_bytes
  3105. try:
  3106. libc.prctl(15, buf, 0, 0, 0)
  3107. except AttributeError:
  3108. return # Strange libc, just skip this
  3109. def remove_start(s, start):
  3110. return s[len(start):] if s is not None and s.startswith(start) else s
  3111. def remove_end(s, end):
  3112. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3113. def remove_quotes(s):
  3114. if s is None or len(s) < 2:
  3115. return s
  3116. for quote in ('"', "'", ):
  3117. if s[0] == quote and s[-1] == quote:
  3118. return s[1:-1]
  3119. return s
  3120. def url_basename(url):
  3121. path = compat_urlparse.urlparse(url).path
  3122. return path.strip('/').split('/')[-1]
  3123. def base_url(url):
  3124. return re.match(r'https?://[^?#&]+/', url).group()
  3125. def urljoin(base, path):
  3126. if isinstance(path, bytes):
  3127. path = path.decode('utf-8')
  3128. if not isinstance(path, compat_str) or not path:
  3129. return None
  3130. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3131. return path
  3132. if isinstance(base, bytes):
  3133. base = base.decode('utf-8')
  3134. if not isinstance(base, compat_str) or not re.match(
  3135. r'^(?:https?:)?//', base):
  3136. return None
  3137. return compat_urlparse.urljoin(base, path)
  3138. class HEADRequest(compat_urllib_request.Request):
  3139. def get_method(self):
  3140. return 'HEAD'
  3141. class PUTRequest(compat_urllib_request.Request):
  3142. def get_method(self):
  3143. return 'PUT'
  3144. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  3145. if get_attr:
  3146. if v is not None:
  3147. v = getattr(v, get_attr, None)
  3148. if v == '':
  3149. v = None
  3150. if v is None:
  3151. return default
  3152. try:
  3153. return int(v) * invscale // scale
  3154. except (ValueError, TypeError):
  3155. return default
  3156. def str_or_none(v, default=None):
  3157. return default if v is None else compat_str(v)
  3158. def str_to_int(int_str):
  3159. """ A more relaxed version of int_or_none """
  3160. if isinstance(int_str, compat_integer_types):
  3161. return int_str
  3162. elif isinstance(int_str, compat_str):
  3163. int_str = re.sub(r'[,\.\+]', '', int_str)
  3164. return int_or_none(int_str)
  3165. def float_or_none(v, scale=1, invscale=1, default=None):
  3166. if v is None:
  3167. return default
  3168. try:
  3169. return float(v) * invscale / scale
  3170. except (ValueError, TypeError):
  3171. return default
  3172. def bool_or_none(v, default=None):
  3173. return v if isinstance(v, bool) else default
  3174. def strip_or_none(v, default=None):
  3175. return v.strip() if isinstance(v, compat_str) else default
  3176. def url_or_none(url):
  3177. if not url or not isinstance(url, compat_str):
  3178. return None
  3179. url = url.strip()
  3180. return url if re.match(r'^(?:[a-zA-Z][\da-zA-Z.+-]*:)?//', url) else None
  3181. def parse_duration(s):
  3182. if not isinstance(s, compat_basestring):
  3183. return None
  3184. s = s.strip()
  3185. days, hours, mins, secs, ms = [None] * 5
  3186. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  3187. if m:
  3188. days, hours, mins, secs, ms = m.groups()
  3189. else:
  3190. m = re.match(
  3191. r'''(?ix)(?:P?
  3192. (?:
  3193. [0-9]+\s*y(?:ears?)?\s*
  3194. )?
  3195. (?:
  3196. [0-9]+\s*m(?:onths?)?\s*
  3197. )?
  3198. (?:
  3199. [0-9]+\s*w(?:eeks?)?\s*
  3200. )?
  3201. (?:
  3202. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3203. )?
  3204. T)?
  3205. (?:
  3206. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3207. )?
  3208. (?:
  3209. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3210. )?
  3211. (?:
  3212. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3213. )?Z?$''', s)
  3214. if m:
  3215. days, hours, mins, secs, ms = m.groups()
  3216. else:
  3217. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3218. if m:
  3219. hours, mins = m.groups()
  3220. else:
  3221. return None
  3222. duration = 0
  3223. if secs:
  3224. duration += float(secs)
  3225. if mins:
  3226. duration += float(mins) * 60
  3227. if hours:
  3228. duration += float(hours) * 60 * 60
  3229. if days:
  3230. duration += float(days) * 24 * 60 * 60
  3231. if ms:
  3232. duration += float(ms)
  3233. return duration
  3234. def prepend_extension(filename, ext, expected_real_ext=None):
  3235. name, real_ext = os.path.splitext(filename)
  3236. return (
  3237. '{0}.{1}{2}'.format(name, ext, real_ext)
  3238. if not expected_real_ext or real_ext[1:] == expected_real_ext
  3239. else '{0}.{1}'.format(filename, ext))
  3240. def replace_extension(filename, ext, expected_real_ext=None):
  3241. name, real_ext = os.path.splitext(filename)
  3242. return '{0}.{1}'.format(
  3243. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  3244. ext)
  3245. def check_executable(exe, args=[]):
  3246. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3247. args can be a list of arguments for a short output (like -version) """
  3248. try:
  3249. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  3250. except OSError:
  3251. return False
  3252. return exe
  3253. def get_exe_version(exe, args=['--version'],
  3254. version_re=None, unrecognized='present'):
  3255. """ Returns the version of the specified executable,
  3256. or False if the executable is not present """
  3257. try:
  3258. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3259. # SIGTTOU if youtube-dl is run in the background.
  3260. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3261. out, _ = subprocess.Popen(
  3262. [encodeArgument(exe)] + args,
  3263. stdin=subprocess.PIPE,
  3264. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  3265. except OSError:
  3266. return False
  3267. if isinstance(out, bytes): # Python 2.x
  3268. out = out.decode('ascii', 'ignore')
  3269. return detect_exe_version(out, version_re, unrecognized)
  3270. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3271. assert isinstance(output, compat_str)
  3272. if version_re is None:
  3273. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3274. m = re.search(version_re, output)
  3275. if m:
  3276. return m.group(1)
  3277. else:
  3278. return unrecognized
  3279. class PagedList(object):
  3280. def __len__(self):
  3281. # This is only useful for tests
  3282. return len(self.getslice())
  3283. class OnDemandPagedList(PagedList):
  3284. def __init__(self, pagefunc, pagesize, use_cache=True):
  3285. self._pagefunc = pagefunc
  3286. self._pagesize = pagesize
  3287. self._use_cache = use_cache
  3288. if use_cache:
  3289. self._cache = {}
  3290. def getslice(self, start=0, end=None):
  3291. res = []
  3292. for pagenum in itertools.count(start // self._pagesize):
  3293. firstid = pagenum * self._pagesize
  3294. nextfirstid = pagenum * self._pagesize + self._pagesize
  3295. if start >= nextfirstid:
  3296. continue
  3297. page_results = None
  3298. if self._use_cache:
  3299. page_results = self._cache.get(pagenum)
  3300. if page_results is None:
  3301. page_results = list(self._pagefunc(pagenum))
  3302. if self._use_cache:
  3303. self._cache[pagenum] = page_results
  3304. startv = (
  3305. start % self._pagesize
  3306. if firstid <= start < nextfirstid
  3307. else 0)
  3308. endv = (
  3309. ((end - 1) % self._pagesize) + 1
  3310. if (end is not None and firstid <= end <= nextfirstid)
  3311. else None)
  3312. if startv != 0 or endv is not None:
  3313. page_results = page_results[startv:endv]
  3314. res.extend(page_results)
  3315. # A little optimization - if current page is not "full", ie. does
  3316. # not contain page_size videos then we can assume that this page
  3317. # is the last one - there are no more ids on further pages -
  3318. # i.e. no need to query again.
  3319. if len(page_results) + startv < self._pagesize:
  3320. break
  3321. # If we got the whole page, but the next page is not interesting,
  3322. # break out early as well
  3323. if end == nextfirstid:
  3324. break
  3325. return res
  3326. class InAdvancePagedList(PagedList):
  3327. def __init__(self, pagefunc, pagecount, pagesize):
  3328. self._pagefunc = pagefunc
  3329. self._pagecount = pagecount
  3330. self._pagesize = pagesize
  3331. def getslice(self, start=0, end=None):
  3332. res = []
  3333. start_page = start // self._pagesize
  3334. end_page = (
  3335. self._pagecount if end is None else (end // self._pagesize + 1))
  3336. skip_elems = start - start_page * self._pagesize
  3337. only_more = None if end is None else end - start
  3338. for pagenum in range(start_page, end_page):
  3339. page = list(self._pagefunc(pagenum))
  3340. if skip_elems:
  3341. page = page[skip_elems:]
  3342. skip_elems = None
  3343. if only_more is not None:
  3344. if len(page) < only_more:
  3345. only_more -= len(page)
  3346. else:
  3347. page = page[:only_more]
  3348. res.extend(page)
  3349. break
  3350. res.extend(page)
  3351. return res
  3352. def uppercase_escape(s):
  3353. unicode_escape = codecs.getdecoder('unicode_escape')
  3354. return re.sub(
  3355. r'\\U[0-9a-fA-F]{8}',
  3356. lambda m: unicode_escape(m.group(0))[0],
  3357. s)
  3358. def lowercase_escape(s):
  3359. unicode_escape = codecs.getdecoder('unicode_escape')
  3360. return re.sub(
  3361. r'\\u[0-9a-fA-F]{4}',
  3362. lambda m: unicode_escape(m.group(0))[0],
  3363. s)
  3364. def escape_rfc3986(s):
  3365. """Escape non-ASCII characters as suggested by RFC 3986"""
  3366. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  3367. s = s.encode('utf-8')
  3368. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  3369. def escape_url(url):
  3370. """Escape URL as suggested by RFC 3986"""
  3371. url_parsed = compat_urllib_parse_urlparse(url)
  3372. return url_parsed._replace(
  3373. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3374. path=escape_rfc3986(url_parsed.path),
  3375. params=escape_rfc3986(url_parsed.params),
  3376. query=escape_rfc3986(url_parsed.query),
  3377. fragment=escape_rfc3986(url_parsed.fragment)
  3378. ).geturl()
  3379. def read_batch_urls(batch_fd):
  3380. def fixup(url):
  3381. if not isinstance(url, compat_str):
  3382. url = url.decode('utf-8', 'replace')
  3383. BOM_UTF8 = '\xef\xbb\xbf'
  3384. if url.startswith(BOM_UTF8):
  3385. url = url[len(BOM_UTF8):]
  3386. url = url.strip()
  3387. if url.startswith(('#', ';', ']')):
  3388. return False
  3389. return url
  3390. with contextlib.closing(batch_fd) as fd:
  3391. return [url for url in map(fixup, fd) if url]
  3392. def urlencode_postdata(*args, **kargs):
  3393. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3394. def update_url_query(url, query):
  3395. if not query:
  3396. return url
  3397. parsed_url = compat_urlparse.urlparse(url)
  3398. qs = compat_parse_qs(parsed_url.query)
  3399. qs.update(query)
  3400. return compat_urlparse.urlunparse(parsed_url._replace(
  3401. query=compat_urllib_parse_urlencode(qs, True)))
  3402. def update_Request(req, url=None, data=None, headers={}, query={}):
  3403. req_headers = req.headers.copy()
  3404. req_headers.update(headers)
  3405. req_data = data or req.data
  3406. req_url = update_url_query(url or req.get_full_url(), query)
  3407. req_get_method = req.get_method()
  3408. if req_get_method == 'HEAD':
  3409. req_type = HEADRequest
  3410. elif req_get_method == 'PUT':
  3411. req_type = PUTRequest
  3412. else:
  3413. req_type = compat_urllib_request.Request
  3414. new_req = req_type(
  3415. req_url, data=req_data, headers=req_headers,
  3416. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3417. if hasattr(req, 'timeout'):
  3418. new_req.timeout = req.timeout
  3419. return new_req
  3420. def _multipart_encode_impl(data, boundary):
  3421. content_type = 'multipart/form-data; boundary=%s' % boundary
  3422. out = b''
  3423. for k, v in data.items():
  3424. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3425. if isinstance(k, compat_str):
  3426. k = k.encode('utf-8')
  3427. if isinstance(v, compat_str):
  3428. v = v.encode('utf-8')
  3429. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3430. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3431. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3432. if boundary.encode('ascii') in content:
  3433. raise ValueError('Boundary overlaps with data')
  3434. out += content
  3435. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3436. return out, content_type
  3437. def multipart_encode(data, boundary=None):
  3438. '''
  3439. Encode a dict to RFC 7578-compliant form-data
  3440. data:
  3441. A dict where keys and values can be either Unicode or bytes-like
  3442. objects.
  3443. boundary:
  3444. If specified a Unicode object, it's used as the boundary. Otherwise
  3445. a random boundary is generated.
  3446. Reference: https://tools.ietf.org/html/rfc7578
  3447. '''
  3448. has_specified_boundary = boundary is not None
  3449. while True:
  3450. if boundary is None:
  3451. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3452. try:
  3453. out, content_type = _multipart_encode_impl(data, boundary)
  3454. break
  3455. except ValueError:
  3456. if has_specified_boundary:
  3457. raise
  3458. boundary = None
  3459. return out, content_type
  3460. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3461. if isinstance(key_or_keys, (list, tuple)):
  3462. for key in key_or_keys:
  3463. if key not in d or d[key] is None or skip_false_values and not d[key]:
  3464. continue
  3465. return d[key]
  3466. return default
  3467. return d.get(key_or_keys, default)
  3468. def try_get(src, getter, expected_type=None):
  3469. if not isinstance(getter, (list, tuple)):
  3470. getter = [getter]
  3471. for get in getter:
  3472. try:
  3473. v = get(src)
  3474. except (AttributeError, KeyError, TypeError, IndexError):
  3475. pass
  3476. else:
  3477. if expected_type is None or isinstance(v, expected_type):
  3478. return v
  3479. def merge_dicts(*dicts):
  3480. merged = {}
  3481. for a_dict in dicts:
  3482. for k, v in a_dict.items():
  3483. if v is None:
  3484. continue
  3485. if (k not in merged
  3486. or (isinstance(v, compat_str) and v
  3487. and isinstance(merged[k], compat_str)
  3488. and not merged[k])):
  3489. merged[k] = v
  3490. return merged
  3491. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  3492. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  3493. US_RATINGS = {
  3494. 'G': 0,
  3495. 'PG': 10,
  3496. 'PG-13': 13,
  3497. 'R': 16,
  3498. 'NC': 18,
  3499. }
  3500. TV_PARENTAL_GUIDELINES = {
  3501. 'TV-Y': 0,
  3502. 'TV-Y7': 7,
  3503. 'TV-G': 0,
  3504. 'TV-PG': 0,
  3505. 'TV-14': 14,
  3506. 'TV-MA': 17,
  3507. }
  3508. def parse_age_limit(s):
  3509. if type(s) == int:
  3510. return s if 0 <= s <= 21 else None
  3511. if not isinstance(s, compat_basestring):
  3512. return None
  3513. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3514. if m:
  3515. return int(m.group('age'))
  3516. if s in US_RATINGS:
  3517. return US_RATINGS[s]
  3518. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3519. if m:
  3520. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3521. return None
  3522. def strip_jsonp(code):
  3523. return re.sub(
  3524. r'''(?sx)^
  3525. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3526. (?:\s*&&\s*(?P=func_name))?
  3527. \s*\(\s*(?P<callback_data>.*)\);?
  3528. \s*?(?://[^\n]*)*$''',
  3529. r'\g<callback_data>', code)
  3530. def js_to_json(code):
  3531. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  3532. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3533. INTEGER_TABLE = (
  3534. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3535. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3536. )
  3537. def fix_kv(m):
  3538. v = m.group(0)
  3539. if v in ('true', 'false', 'null'):
  3540. return v
  3541. elif v.startswith('/*') or v.startswith('//') or v == ',':
  3542. return ""
  3543. if v[0] in ("'", '"'):
  3544. v = re.sub(r'(?s)\\.|"', lambda m: {
  3545. '"': '\\"',
  3546. "\\'": "'",
  3547. '\\\n': '',
  3548. '\\x': '\\u00',
  3549. }.get(m.group(0), m.group(0)), v[1:-1])
  3550. for regex, base in INTEGER_TABLE:
  3551. im = re.match(regex, v)
  3552. if im:
  3553. i = int(im.group(1), base)
  3554. return '"%d":' % i if v.endswith(':') else '%d' % i
  3555. return '"%s"' % v
  3556. return re.sub(r'''(?sx)
  3557. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  3558. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  3559. {comment}|,(?={skip}[\]}}])|
  3560. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  3561. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  3562. [0-9]+(?={skip}:)
  3563. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  3564. def qualities(quality_ids):
  3565. """ Get a numeric quality value out of a list of possible values """
  3566. def q(qid):
  3567. try:
  3568. return quality_ids.index(qid)
  3569. except ValueError:
  3570. return -1
  3571. return q
  3572. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  3573. def limit_length(s, length):
  3574. """ Add ellipses to overly long strings """
  3575. if s is None:
  3576. return None
  3577. ELLIPSES = '...'
  3578. if len(s) > length:
  3579. return s[:length - len(ELLIPSES)] + ELLIPSES
  3580. return s
  3581. def version_tuple(v):
  3582. return tuple(int(e) for e in re.split(r'[-.]', v))
  3583. def is_outdated_version(version, limit, assume_new=True):
  3584. if not version:
  3585. return not assume_new
  3586. try:
  3587. return version_tuple(version) < version_tuple(limit)
  3588. except ValueError:
  3589. return not assume_new
  3590. def ytdl_is_updateable():
  3591. """ Returns if youtube-dl can be updated with -U """
  3592. from zipimport import zipimporter
  3593. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  3594. def args_to_str(args):
  3595. # Get a short string representation for a subprocess command
  3596. return ' '.join(compat_shlex_quote(a) for a in args)
  3597. def error_to_compat_str(err):
  3598. err_str = str(err)
  3599. # On python 2 error byte string must be decoded with proper
  3600. # encoding rather than ascii
  3601. if sys.version_info[0] < 3:
  3602. err_str = err_str.decode(preferredencoding())
  3603. return err_str
  3604. def mimetype2ext(mt):
  3605. if mt is None:
  3606. return None
  3607. ext = {
  3608. 'audio/mp4': 'm4a',
  3609. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  3610. # it's the most popular one
  3611. 'audio/mpeg': 'mp3',
  3612. }.get(mt)
  3613. if ext is not None:
  3614. return ext
  3615. _, _, res = mt.rpartition('/')
  3616. res = res.split(';')[0].strip().lower()
  3617. return {
  3618. '3gpp': '3gp',
  3619. 'smptett+xml': 'tt',
  3620. 'ttaf+xml': 'dfxp',
  3621. 'ttml+xml': 'ttml',
  3622. 'x-flv': 'flv',
  3623. 'x-mp4-fragmented': 'mp4',
  3624. 'x-ms-sami': 'sami',
  3625. 'x-ms-wmv': 'wmv',
  3626. 'mpegurl': 'm3u8',
  3627. 'x-mpegurl': 'm3u8',
  3628. 'vnd.apple.mpegurl': 'm3u8',
  3629. 'dash+xml': 'mpd',
  3630. 'f4m+xml': 'f4m',
  3631. 'hds+xml': 'f4m',
  3632. 'vnd.ms-sstr+xml': 'ism',
  3633. 'quicktime': 'mov',
  3634. 'mp2t': 'ts',
  3635. }.get(res, res)
  3636. def parse_codecs(codecs_str):
  3637. # http://tools.ietf.org/html/rfc6381
  3638. if not codecs_str:
  3639. return {}
  3640. splited_codecs = list(filter(None, map(
  3641. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  3642. vcodec, acodec = None, None
  3643. for full_codec in splited_codecs:
  3644. codec = full_codec.split('.')[0]
  3645. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  3646. if not vcodec:
  3647. vcodec = full_codec
  3648. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  3649. if not acodec:
  3650. acodec = full_codec
  3651. else:
  3652. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  3653. if not vcodec and not acodec:
  3654. if len(splited_codecs) == 2:
  3655. return {
  3656. 'vcodec': splited_codecs[0],
  3657. 'acodec': splited_codecs[1],
  3658. }
  3659. else:
  3660. return {
  3661. 'vcodec': vcodec or 'none',
  3662. 'acodec': acodec or 'none',
  3663. }
  3664. return {}
  3665. def urlhandle_detect_ext(url_handle):
  3666. getheader = url_handle.headers.get
  3667. cd = getheader('Content-Disposition')
  3668. if cd:
  3669. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  3670. if m:
  3671. e = determine_ext(m.group('filename'), default_ext=None)
  3672. if e:
  3673. return e
  3674. return mimetype2ext(getheader('Content-Type'))
  3675. def encode_data_uri(data, mime_type):
  3676. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  3677. def age_restricted(content_limit, age_limit):
  3678. """ Returns True iff the content should be blocked """
  3679. if age_limit is None: # No limit set
  3680. return False
  3681. if content_limit is None:
  3682. return False # Content available for everyone
  3683. return age_limit < content_limit
  3684. def is_html(first_bytes):
  3685. """ Detect whether a file contains HTML by examining its first bytes. """
  3686. BOMS = [
  3687. (b'\xef\xbb\xbf', 'utf-8'),
  3688. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  3689. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  3690. (b'\xff\xfe', 'utf-16-le'),
  3691. (b'\xfe\xff', 'utf-16-be'),
  3692. ]
  3693. for bom, enc in BOMS:
  3694. if first_bytes.startswith(bom):
  3695. s = first_bytes[len(bom):].decode(enc, 'replace')
  3696. break
  3697. else:
  3698. s = first_bytes.decode('utf-8', 'replace')
  3699. return re.match(r'^\s*<', s)
  3700. def determine_protocol(info_dict):
  3701. protocol = info_dict.get('protocol')
  3702. if protocol is not None:
  3703. return protocol
  3704. url = info_dict['url']
  3705. if url.startswith('rtmp'):
  3706. return 'rtmp'
  3707. elif url.startswith('mms'):
  3708. return 'mms'
  3709. elif url.startswith('rtsp'):
  3710. return 'rtsp'
  3711. ext = determine_ext(url)
  3712. if ext == 'm3u8':
  3713. return 'm3u8'
  3714. elif ext == 'f4m':
  3715. return 'f4m'
  3716. return compat_urllib_parse_urlparse(url).scheme
  3717. def render_table(header_row, data):
  3718. """ Render a list of rows, each as a list of values """
  3719. table = [header_row] + data
  3720. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  3721. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  3722. return '\n'.join(format_str % tuple(row) for row in table)
  3723. def _match_one(filter_part, dct):
  3724. COMPARISON_OPERATORS = {
  3725. '<': operator.lt,
  3726. '<=': operator.le,
  3727. '>': operator.gt,
  3728. '>=': operator.ge,
  3729. '=': operator.eq,
  3730. '!=': operator.ne,
  3731. }
  3732. operator_rex = re.compile(r'''(?x)\s*
  3733. (?P<key>[a-z_]+)
  3734. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  3735. (?:
  3736. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  3737. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  3738. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  3739. )
  3740. \s*$
  3741. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  3742. m = operator_rex.search(filter_part)
  3743. if m:
  3744. op = COMPARISON_OPERATORS[m.group('op')]
  3745. actual_value = dct.get(m.group('key'))
  3746. if (m.group('quotedstrval') is not None
  3747. or m.group('strval') is not None
  3748. # If the original field is a string and matching comparisonvalue is
  3749. # a number we should respect the origin of the original field
  3750. # and process comparison value as a string (see
  3751. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  3752. or actual_value is not None and m.group('intval') is not None
  3753. and isinstance(actual_value, compat_str)):
  3754. if m.group('op') not in ('=', '!='):
  3755. raise ValueError(
  3756. 'Operator %s does not support string values!' % m.group('op'))
  3757. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  3758. quote = m.group('quote')
  3759. if quote is not None:
  3760. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  3761. else:
  3762. try:
  3763. comparison_value = int(m.group('intval'))
  3764. except ValueError:
  3765. comparison_value = parse_filesize(m.group('intval'))
  3766. if comparison_value is None:
  3767. comparison_value = parse_filesize(m.group('intval') + 'B')
  3768. if comparison_value is None:
  3769. raise ValueError(
  3770. 'Invalid integer value %r in filter part %r' % (
  3771. m.group('intval'), filter_part))
  3772. if actual_value is None:
  3773. return m.group('none_inclusive')
  3774. return op(actual_value, comparison_value)
  3775. UNARY_OPERATORS = {
  3776. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  3777. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  3778. }
  3779. operator_rex = re.compile(r'''(?x)\s*
  3780. (?P<op>%s)\s*(?P<key>[a-z_]+)
  3781. \s*$
  3782. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  3783. m = operator_rex.search(filter_part)
  3784. if m:
  3785. op = UNARY_OPERATORS[m.group('op')]
  3786. actual_value = dct.get(m.group('key'))
  3787. return op(actual_value)
  3788. raise ValueError('Invalid filter part %r' % filter_part)
  3789. def match_str(filter_str, dct):
  3790. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  3791. return all(
  3792. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  3793. def match_filter_func(filter_str):
  3794. def _match_func(info_dict):
  3795. if match_str(filter_str, info_dict):
  3796. return None
  3797. else:
  3798. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  3799. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  3800. return _match_func
  3801. def parse_dfxp_time_expr(time_expr):
  3802. if not time_expr:
  3803. return
  3804. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  3805. if mobj:
  3806. return float(mobj.group('time_offset'))
  3807. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  3808. if mobj:
  3809. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  3810. def srt_subtitles_timecode(seconds):
  3811. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  3812. def dfxp2srt(dfxp_data):
  3813. '''
  3814. @param dfxp_data A bytes-like object containing DFXP data
  3815. @returns A unicode object containing converted SRT data
  3816. '''
  3817. LEGACY_NAMESPACES = (
  3818. (b'http://www.w3.org/ns/ttml', [
  3819. b'http://www.w3.org/2004/11/ttaf1',
  3820. b'http://www.w3.org/2006/04/ttaf1',
  3821. b'http://www.w3.org/2006/10/ttaf1',
  3822. ]),
  3823. (b'http://www.w3.org/ns/ttml#styling', [
  3824. b'http://www.w3.org/ns/ttml#style',
  3825. ]),
  3826. )
  3827. SUPPORTED_STYLING = [
  3828. 'color',
  3829. 'fontFamily',
  3830. 'fontSize',
  3831. 'fontStyle',
  3832. 'fontWeight',
  3833. 'textDecoration'
  3834. ]
  3835. _x = functools.partial(xpath_with_ns, ns_map={
  3836. 'xml': 'http://www.w3.org/XML/1998/namespace',
  3837. 'ttml': 'http://www.w3.org/ns/ttml',
  3838. 'tts': 'http://www.w3.org/ns/ttml#styling',
  3839. })
  3840. styles = {}
  3841. default_style = {}
  3842. class TTMLPElementParser(object):
  3843. _out = ''
  3844. _unclosed_elements = []
  3845. _applied_styles = []
  3846. def start(self, tag, attrib):
  3847. if tag in (_x('ttml:br'), 'br'):
  3848. self._out += '\n'
  3849. else:
  3850. unclosed_elements = []
  3851. style = {}
  3852. element_style_id = attrib.get('style')
  3853. if default_style:
  3854. style.update(default_style)
  3855. if element_style_id:
  3856. style.update(styles.get(element_style_id, {}))
  3857. for prop in SUPPORTED_STYLING:
  3858. prop_val = attrib.get(_x('tts:' + prop))
  3859. if prop_val:
  3860. style[prop] = prop_val
  3861. if style:
  3862. font = ''
  3863. for k, v in sorted(style.items()):
  3864. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  3865. continue
  3866. if k == 'color':
  3867. font += ' color="%s"' % v
  3868. elif k == 'fontSize':
  3869. font += ' size="%s"' % v
  3870. elif k == 'fontFamily':
  3871. font += ' face="%s"' % v
  3872. elif k == 'fontWeight' and v == 'bold':
  3873. self._out += '<b>'
  3874. unclosed_elements.append('b')
  3875. elif k == 'fontStyle' and v == 'italic':
  3876. self._out += '<i>'
  3877. unclosed_elements.append('i')
  3878. elif k == 'textDecoration' and v == 'underline':
  3879. self._out += '<u>'
  3880. unclosed_elements.append('u')
  3881. if font:
  3882. self._out += '<font' + font + '>'
  3883. unclosed_elements.append('font')
  3884. applied_style = {}
  3885. if self._applied_styles:
  3886. applied_style.update(self._applied_styles[-1])
  3887. applied_style.update(style)
  3888. self._applied_styles.append(applied_style)
  3889. self._unclosed_elements.append(unclosed_elements)
  3890. def end(self, tag):
  3891. if tag not in (_x('ttml:br'), 'br'):
  3892. unclosed_elements = self._unclosed_elements.pop()
  3893. for element in reversed(unclosed_elements):
  3894. self._out += '</%s>' % element
  3895. if unclosed_elements and self._applied_styles:
  3896. self._applied_styles.pop()
  3897. def data(self, data):
  3898. self._out += data
  3899. def close(self):
  3900. return self._out.strip()
  3901. def parse_node(node):
  3902. target = TTMLPElementParser()
  3903. parser = xml.etree.ElementTree.XMLParser(target=target)
  3904. parser.feed(xml.etree.ElementTree.tostring(node))
  3905. return parser.close()
  3906. for k, v in LEGACY_NAMESPACES:
  3907. for ns in v:
  3908. dfxp_data = dfxp_data.replace(ns, k)
  3909. dfxp = compat_etree_fromstring(dfxp_data)
  3910. out = []
  3911. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  3912. if not paras:
  3913. raise ValueError('Invalid dfxp/TTML subtitle')
  3914. repeat = False
  3915. while True:
  3916. for style in dfxp.findall(_x('.//ttml:style')):
  3917. style_id = style.get('id') or style.get(_x('xml:id'))
  3918. if not style_id:
  3919. continue
  3920. parent_style_id = style.get('style')
  3921. if parent_style_id:
  3922. if parent_style_id not in styles:
  3923. repeat = True
  3924. continue
  3925. styles[style_id] = styles[parent_style_id].copy()
  3926. for prop in SUPPORTED_STYLING:
  3927. prop_val = style.get(_x('tts:' + prop))
  3928. if prop_val:
  3929. styles.setdefault(style_id, {})[prop] = prop_val
  3930. if repeat:
  3931. repeat = False
  3932. else:
  3933. break
  3934. for p in ('body', 'div'):
  3935. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  3936. if ele is None:
  3937. continue
  3938. style = styles.get(ele.get('style'))
  3939. if not style:
  3940. continue
  3941. default_style.update(style)
  3942. for para, index in zip(paras, itertools.count(1)):
  3943. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  3944. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  3945. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  3946. if begin_time is None:
  3947. continue
  3948. if not end_time:
  3949. if not dur:
  3950. continue
  3951. end_time = begin_time + dur
  3952. out.append('%d\n%s --> %s\n%s\n\n' % (
  3953. index,
  3954. srt_subtitles_timecode(begin_time),
  3955. srt_subtitles_timecode(end_time),
  3956. parse_node(para)))
  3957. return ''.join(out)
  3958. def cli_option(params, command_option, param):
  3959. param = params.get(param)
  3960. if param:
  3961. param = compat_str(param)
  3962. return [command_option, param] if param is not None else []
  3963. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  3964. param = params.get(param)
  3965. if param is None:
  3966. return []
  3967. assert isinstance(param, bool)
  3968. if separator:
  3969. return [command_option + separator + (true_value if param else false_value)]
  3970. return [command_option, true_value if param else false_value]
  3971. def cli_valueless_option(params, command_option, param, expected_value=True):
  3972. param = params.get(param)
  3973. return [command_option] if param == expected_value else []
  3974. def cli_configuration_args(params, param, default=[]):
  3975. ex_args = params.get(param)
  3976. if ex_args is None:
  3977. return default
  3978. assert isinstance(ex_args, list)
  3979. return ex_args
  3980. class ISO639Utils(object):
  3981. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  3982. _lang_map = {
  3983. 'aa': 'aar',
  3984. 'ab': 'abk',
  3985. 'ae': 'ave',
  3986. 'af': 'afr',
  3987. 'ak': 'aka',
  3988. 'am': 'amh',
  3989. 'an': 'arg',
  3990. 'ar': 'ara',
  3991. 'as': 'asm',
  3992. 'av': 'ava',
  3993. 'ay': 'aym',
  3994. 'az': 'aze',
  3995. 'ba': 'bak',
  3996. 'be': 'bel',
  3997. 'bg': 'bul',
  3998. 'bh': 'bih',
  3999. 'bi': 'bis',
  4000. 'bm': 'bam',
  4001. 'bn': 'ben',
  4002. 'bo': 'bod',
  4003. 'br': 'bre',
  4004. 'bs': 'bos',
  4005. 'ca': 'cat',
  4006. 'ce': 'che',
  4007. 'ch': 'cha',
  4008. 'co': 'cos',
  4009. 'cr': 'cre',
  4010. 'cs': 'ces',
  4011. 'cu': 'chu',
  4012. 'cv': 'chv',
  4013. 'cy': 'cym',
  4014. 'da': 'dan',
  4015. 'de': 'deu',
  4016. 'dv': 'div',
  4017. 'dz': 'dzo',
  4018. 'ee': 'ewe',
  4019. 'el': 'ell',
  4020. 'en': 'eng',
  4021. 'eo': 'epo',
  4022. 'es': 'spa',
  4023. 'et': 'est',
  4024. 'eu': 'eus',
  4025. 'fa': 'fas',
  4026. 'ff': 'ful',
  4027. 'fi': 'fin',
  4028. 'fj': 'fij',
  4029. 'fo': 'fao',
  4030. 'fr': 'fra',
  4031. 'fy': 'fry',
  4032. 'ga': 'gle',
  4033. 'gd': 'gla',
  4034. 'gl': 'glg',
  4035. 'gn': 'grn',
  4036. 'gu': 'guj',
  4037. 'gv': 'glv',
  4038. 'ha': 'hau',
  4039. 'he': 'heb',
  4040. 'iw': 'heb', # Replaced by he in 1989 revision
  4041. 'hi': 'hin',
  4042. 'ho': 'hmo',
  4043. 'hr': 'hrv',
  4044. 'ht': 'hat',
  4045. 'hu': 'hun',
  4046. 'hy': 'hye',
  4047. 'hz': 'her',
  4048. 'ia': 'ina',
  4049. 'id': 'ind',
  4050. 'in': 'ind', # Replaced by id in 1989 revision
  4051. 'ie': 'ile',
  4052. 'ig': 'ibo',
  4053. 'ii': 'iii',
  4054. 'ik': 'ipk',
  4055. 'io': 'ido',
  4056. 'is': 'isl',
  4057. 'it': 'ita',
  4058. 'iu': 'iku',
  4059. 'ja': 'jpn',
  4060. 'jv': 'jav',
  4061. 'ka': 'kat',
  4062. 'kg': 'kon',
  4063. 'ki': 'kik',
  4064. 'kj': 'kua',
  4065. 'kk': 'kaz',
  4066. 'kl': 'kal',
  4067. 'km': 'khm',
  4068. 'kn': 'kan',
  4069. 'ko': 'kor',
  4070. 'kr': 'kau',
  4071. 'ks': 'kas',
  4072. 'ku': 'kur',
  4073. 'kv': 'kom',
  4074. 'kw': 'cor',
  4075. 'ky': 'kir',
  4076. 'la': 'lat',
  4077. 'lb': 'ltz',
  4078. 'lg': 'lug',
  4079. 'li': 'lim',
  4080. 'ln': 'lin',
  4081. 'lo': 'lao',
  4082. 'lt': 'lit',
  4083. 'lu': 'lub',
  4084. 'lv': 'lav',
  4085. 'mg': 'mlg',
  4086. 'mh': 'mah',
  4087. 'mi': 'mri',
  4088. 'mk': 'mkd',
  4089. 'ml': 'mal',
  4090. 'mn': 'mon',
  4091. 'mr': 'mar',
  4092. 'ms': 'msa',
  4093. 'mt': 'mlt',
  4094. 'my': 'mya',
  4095. 'na': 'nau',
  4096. 'nb': 'nob',
  4097. 'nd': 'nde',
  4098. 'ne': 'nep',
  4099. 'ng': 'ndo',
  4100. 'nl': 'nld',
  4101. 'nn': 'nno',
  4102. 'no': 'nor',
  4103. 'nr': 'nbl',
  4104. 'nv': 'nav',
  4105. 'ny': 'nya',
  4106. 'oc': 'oci',
  4107. 'oj': 'oji',
  4108. 'om': 'orm',
  4109. 'or': 'ori',
  4110. 'os': 'oss',
  4111. 'pa': 'pan',
  4112. 'pi': 'pli',
  4113. 'pl': 'pol',
  4114. 'ps': 'pus',
  4115. 'pt': 'por',
  4116. 'qu': 'que',
  4117. 'rm': 'roh',
  4118. 'rn': 'run',
  4119. 'ro': 'ron',
  4120. 'ru': 'rus',
  4121. 'rw': 'kin',
  4122. 'sa': 'san',
  4123. 'sc': 'srd',
  4124. 'sd': 'snd',
  4125. 'se': 'sme',
  4126. 'sg': 'sag',
  4127. 'si': 'sin',
  4128. 'sk': 'slk',
  4129. 'sl': 'slv',
  4130. 'sm': 'smo',
  4131. 'sn': 'sna',
  4132. 'so': 'som',
  4133. 'sq': 'sqi',
  4134. 'sr': 'srp',
  4135. 'ss': 'ssw',
  4136. 'st': 'sot',
  4137. 'su': 'sun',
  4138. 'sv': 'swe',
  4139. 'sw': 'swa',
  4140. 'ta': 'tam',
  4141. 'te': 'tel',
  4142. 'tg': 'tgk',
  4143. 'th': 'tha',
  4144. 'ti': 'tir',
  4145. 'tk': 'tuk',
  4146. 'tl': 'tgl',
  4147. 'tn': 'tsn',
  4148. 'to': 'ton',
  4149. 'tr': 'tur',
  4150. 'ts': 'tso',
  4151. 'tt': 'tat',
  4152. 'tw': 'twi',
  4153. 'ty': 'tah',
  4154. 'ug': 'uig',
  4155. 'uk': 'ukr',
  4156. 'ur': 'urd',
  4157. 'uz': 'uzb',
  4158. 've': 'ven',
  4159. 'vi': 'vie',
  4160. 'vo': 'vol',
  4161. 'wa': 'wln',
  4162. 'wo': 'wol',
  4163. 'xh': 'xho',
  4164. 'yi': 'yid',
  4165. 'ji': 'yid', # Replaced by yi in 1989 revision
  4166. 'yo': 'yor',
  4167. 'za': 'zha',
  4168. 'zh': 'zho',
  4169. 'zu': 'zul',
  4170. }
  4171. @classmethod
  4172. def short2long(cls, code):
  4173. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4174. return cls._lang_map.get(code[:2])
  4175. @classmethod
  4176. def long2short(cls, code):
  4177. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4178. for short_name, long_name in cls._lang_map.items():
  4179. if long_name == code:
  4180. return short_name
  4181. class ISO3166Utils(object):
  4182. # From http://data.okfn.org/data/core/country-list
  4183. _country_map = {
  4184. 'AF': 'Afghanistan',
  4185. 'AX': 'Åland Islands',
  4186. 'AL': 'Albania',
  4187. 'DZ': 'Algeria',
  4188. 'AS': 'American Samoa',
  4189. 'AD': 'Andorra',
  4190. 'AO': 'Angola',
  4191. 'AI': 'Anguilla',
  4192. 'AQ': 'Antarctica',
  4193. 'AG': 'Antigua and Barbuda',
  4194. 'AR': 'Argentina',
  4195. 'AM': 'Armenia',
  4196. 'AW': 'Aruba',
  4197. 'AU': 'Australia',
  4198. 'AT': 'Austria',
  4199. 'AZ': 'Azerbaijan',
  4200. 'BS': 'Bahamas',
  4201. 'BH': 'Bahrain',
  4202. 'BD': 'Bangladesh',
  4203. 'BB': 'Barbados',
  4204. 'BY': 'Belarus',
  4205. 'BE': 'Belgium',
  4206. 'BZ': 'Belize',
  4207. 'BJ': 'Benin',
  4208. 'BM': 'Bermuda',
  4209. 'BT': 'Bhutan',
  4210. 'BO': 'Bolivia, Plurinational State of',
  4211. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4212. 'BA': 'Bosnia and Herzegovina',
  4213. 'BW': 'Botswana',
  4214. 'BV': 'Bouvet Island',
  4215. 'BR': 'Brazil',
  4216. 'IO': 'British Indian Ocean Territory',
  4217. 'BN': 'Brunei Darussalam',
  4218. 'BG': 'Bulgaria',
  4219. 'BF': 'Burkina Faso',
  4220. 'BI': 'Burundi',
  4221. 'KH': 'Cambodia',
  4222. 'CM': 'Cameroon',
  4223. 'CA': 'Canada',
  4224. 'CV': 'Cape Verde',
  4225. 'KY': 'Cayman Islands',
  4226. 'CF': 'Central African Republic',
  4227. 'TD': 'Chad',
  4228. 'CL': 'Chile',
  4229. 'CN': 'China',
  4230. 'CX': 'Christmas Island',
  4231. 'CC': 'Cocos (Keeling) Islands',
  4232. 'CO': 'Colombia',
  4233. 'KM': 'Comoros',
  4234. 'CG': 'Congo',
  4235. 'CD': 'Congo, the Democratic Republic of the',
  4236. 'CK': 'Cook Islands',
  4237. 'CR': 'Costa Rica',
  4238. 'CI': 'Côte d\'Ivoire',
  4239. 'HR': 'Croatia',
  4240. 'CU': 'Cuba',
  4241. 'CW': 'Curaçao',
  4242. 'CY': 'Cyprus',
  4243. 'CZ': 'Czech Republic',
  4244. 'DK': 'Denmark',
  4245. 'DJ': 'Djibouti',
  4246. 'DM': 'Dominica',
  4247. 'DO': 'Dominican Republic',
  4248. 'EC': 'Ecuador',
  4249. 'EG': 'Egypt',
  4250. 'SV': 'El Salvador',
  4251. 'GQ': 'Equatorial Guinea',
  4252. 'ER': 'Eritrea',
  4253. 'EE': 'Estonia',
  4254. 'ET': 'Ethiopia',
  4255. 'FK': 'Falkland Islands (Malvinas)',
  4256. 'FO': 'Faroe Islands',
  4257. 'FJ': 'Fiji',
  4258. 'FI': 'Finland',
  4259. 'FR': 'France',
  4260. 'GF': 'French Guiana',
  4261. 'PF': 'French Polynesia',
  4262. 'TF': 'French Southern Territories',
  4263. 'GA': 'Gabon',
  4264. 'GM': 'Gambia',
  4265. 'GE': 'Georgia',
  4266. 'DE': 'Germany',
  4267. 'GH': 'Ghana',
  4268. 'GI': 'Gibraltar',
  4269. 'GR': 'Greece',
  4270. 'GL': 'Greenland',
  4271. 'GD': 'Grenada',
  4272. 'GP': 'Guadeloupe',
  4273. 'GU': 'Guam',
  4274. 'GT': 'Guatemala',
  4275. 'GG': 'Guernsey',
  4276. 'GN': 'Guinea',
  4277. 'GW': 'Guinea-Bissau',
  4278. 'GY': 'Guyana',
  4279. 'HT': 'Haiti',
  4280. 'HM': 'Heard Island and McDonald Islands',
  4281. 'VA': 'Holy See (Vatican City State)',
  4282. 'HN': 'Honduras',
  4283. 'HK': 'Hong Kong',
  4284. 'HU': 'Hungary',
  4285. 'IS': 'Iceland',
  4286. 'IN': 'India',
  4287. 'ID': 'Indonesia',
  4288. 'IR': 'Iran, Islamic Republic of',
  4289. 'IQ': 'Iraq',
  4290. 'IE': 'Ireland',
  4291. 'IM': 'Isle of Man',
  4292. 'IL': 'Israel',
  4293. 'IT': 'Italy',
  4294. 'JM': 'Jamaica',
  4295. 'JP': 'Japan',
  4296. 'JE': 'Jersey',
  4297. 'JO': 'Jordan',
  4298. 'KZ': 'Kazakhstan',
  4299. 'KE': 'Kenya',
  4300. 'KI': 'Kiribati',
  4301. 'KP': 'Korea, Democratic People\'s Republic of',
  4302. 'KR': 'Korea, Republic of',
  4303. 'KW': 'Kuwait',
  4304. 'KG': 'Kyrgyzstan',
  4305. 'LA': 'Lao People\'s Democratic Republic',
  4306. 'LV': 'Latvia',
  4307. 'LB': 'Lebanon',
  4308. 'LS': 'Lesotho',
  4309. 'LR': 'Liberia',
  4310. 'LY': 'Libya',
  4311. 'LI': 'Liechtenstein',
  4312. 'LT': 'Lithuania',
  4313. 'LU': 'Luxembourg',
  4314. 'MO': 'Macao',
  4315. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4316. 'MG': 'Madagascar',
  4317. 'MW': 'Malawi',
  4318. 'MY': 'Malaysia',
  4319. 'MV': 'Maldives',
  4320. 'ML': 'Mali',
  4321. 'MT': 'Malta',
  4322. 'MH': 'Marshall Islands',
  4323. 'MQ': 'Martinique',
  4324. 'MR': 'Mauritania',
  4325. 'MU': 'Mauritius',
  4326. 'YT': 'Mayotte',
  4327. 'MX': 'Mexico',
  4328. 'FM': 'Micronesia, Federated States of',
  4329. 'MD': 'Moldova, Republic of',
  4330. 'MC': 'Monaco',
  4331. 'MN': 'Mongolia',
  4332. 'ME': 'Montenegro',
  4333. 'MS': 'Montserrat',
  4334. 'MA': 'Morocco',
  4335. 'MZ': 'Mozambique',
  4336. 'MM': 'Myanmar',
  4337. 'NA': 'Namibia',
  4338. 'NR': 'Nauru',
  4339. 'NP': 'Nepal',
  4340. 'NL': 'Netherlands',
  4341. 'NC': 'New Caledonia',
  4342. 'NZ': 'New Zealand',
  4343. 'NI': 'Nicaragua',
  4344. 'NE': 'Niger',
  4345. 'NG': 'Nigeria',
  4346. 'NU': 'Niue',
  4347. 'NF': 'Norfolk Island',
  4348. 'MP': 'Northern Mariana Islands',
  4349. 'NO': 'Norway',
  4350. 'OM': 'Oman',
  4351. 'PK': 'Pakistan',
  4352. 'PW': 'Palau',
  4353. 'PS': 'Palestine, State of',
  4354. 'PA': 'Panama',
  4355. 'PG': 'Papua New Guinea',
  4356. 'PY': 'Paraguay',
  4357. 'PE': 'Peru',
  4358. 'PH': 'Philippines',
  4359. 'PN': 'Pitcairn',
  4360. 'PL': 'Poland',
  4361. 'PT': 'Portugal',
  4362. 'PR': 'Puerto Rico',
  4363. 'QA': 'Qatar',
  4364. 'RE': 'Réunion',
  4365. 'RO': 'Romania',
  4366. 'RU': 'Russian Federation',
  4367. 'RW': 'Rwanda',
  4368. 'BL': 'Saint Barthélemy',
  4369. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4370. 'KN': 'Saint Kitts and Nevis',
  4371. 'LC': 'Saint Lucia',
  4372. 'MF': 'Saint Martin (French part)',
  4373. 'PM': 'Saint Pierre and Miquelon',
  4374. 'VC': 'Saint Vincent and the Grenadines',
  4375. 'WS': 'Samoa',
  4376. 'SM': 'San Marino',
  4377. 'ST': 'Sao Tome and Principe',
  4378. 'SA': 'Saudi Arabia',
  4379. 'SN': 'Senegal',
  4380. 'RS': 'Serbia',
  4381. 'SC': 'Seychelles',
  4382. 'SL': 'Sierra Leone',
  4383. 'SG': 'Singapore',
  4384. 'SX': 'Sint Maarten (Dutch part)',
  4385. 'SK': 'Slovakia',
  4386. 'SI': 'Slovenia',
  4387. 'SB': 'Solomon Islands',
  4388. 'SO': 'Somalia',
  4389. 'ZA': 'South Africa',
  4390. 'GS': 'South Georgia and the South Sandwich Islands',
  4391. 'SS': 'South Sudan',
  4392. 'ES': 'Spain',
  4393. 'LK': 'Sri Lanka',
  4394. 'SD': 'Sudan',
  4395. 'SR': 'Suriname',
  4396. 'SJ': 'Svalbard and Jan Mayen',
  4397. 'SZ': 'Swaziland',
  4398. 'SE': 'Sweden',
  4399. 'CH': 'Switzerland',
  4400. 'SY': 'Syrian Arab Republic',
  4401. 'TW': 'Taiwan, Province of China',
  4402. 'TJ': 'Tajikistan',
  4403. 'TZ': 'Tanzania, United Republic of',
  4404. 'TH': 'Thailand',
  4405. 'TL': 'Timor-Leste',
  4406. 'TG': 'Togo',
  4407. 'TK': 'Tokelau',
  4408. 'TO': 'Tonga',
  4409. 'TT': 'Trinidad and Tobago',
  4410. 'TN': 'Tunisia',
  4411. 'TR': 'Turkey',
  4412. 'TM': 'Turkmenistan',
  4413. 'TC': 'Turks and Caicos Islands',
  4414. 'TV': 'Tuvalu',
  4415. 'UG': 'Uganda',
  4416. 'UA': 'Ukraine',
  4417. 'AE': 'United Arab Emirates',
  4418. 'GB': 'United Kingdom',
  4419. 'US': 'United States',
  4420. 'UM': 'United States Minor Outlying Islands',
  4421. 'UY': 'Uruguay',
  4422. 'UZ': 'Uzbekistan',
  4423. 'VU': 'Vanuatu',
  4424. 'VE': 'Venezuela, Bolivarian Republic of',
  4425. 'VN': 'Viet Nam',
  4426. 'VG': 'Virgin Islands, British',
  4427. 'VI': 'Virgin Islands, U.S.',
  4428. 'WF': 'Wallis and Futuna',
  4429. 'EH': 'Western Sahara',
  4430. 'YE': 'Yemen',
  4431. 'ZM': 'Zambia',
  4432. 'ZW': 'Zimbabwe',
  4433. }
  4434. @classmethod
  4435. def short2full(cls, code):
  4436. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4437. return cls._country_map.get(code.upper())
  4438. class GeoUtils(object):
  4439. # Major IPv4 address blocks per country
  4440. _country_ip_map = {
  4441. 'AD': '46.172.224.0/19',
  4442. 'AE': '94.200.0.0/13',
  4443. 'AF': '149.54.0.0/17',
  4444. 'AG': '209.59.64.0/18',
  4445. 'AI': '204.14.248.0/21',
  4446. 'AL': '46.99.0.0/16',
  4447. 'AM': '46.70.0.0/15',
  4448. 'AO': '105.168.0.0/13',
  4449. 'AP': '182.50.184.0/21',
  4450. 'AQ': '23.154.160.0/24',
  4451. 'AR': '181.0.0.0/12',
  4452. 'AS': '202.70.112.0/20',
  4453. 'AT': '77.116.0.0/14',
  4454. 'AU': '1.128.0.0/11',
  4455. 'AW': '181.41.0.0/18',
  4456. 'AX': '185.217.4.0/22',
  4457. 'AZ': '5.197.0.0/16',
  4458. 'BA': '31.176.128.0/17',
  4459. 'BB': '65.48.128.0/17',
  4460. 'BD': '114.130.0.0/16',
  4461. 'BE': '57.0.0.0/8',
  4462. 'BF': '102.178.0.0/15',
  4463. 'BG': '95.42.0.0/15',
  4464. 'BH': '37.131.0.0/17',
  4465. 'BI': '154.117.192.0/18',
  4466. 'BJ': '137.255.0.0/16',
  4467. 'BL': '185.212.72.0/23',
  4468. 'BM': '196.12.64.0/18',
  4469. 'BN': '156.31.0.0/16',
  4470. 'BO': '161.56.0.0/16',
  4471. 'BQ': '161.0.80.0/20',
  4472. 'BR': '191.128.0.0/12',
  4473. 'BS': '24.51.64.0/18',
  4474. 'BT': '119.2.96.0/19',
  4475. 'BW': '168.167.0.0/16',
  4476. 'BY': '178.120.0.0/13',
  4477. 'BZ': '179.42.192.0/18',
  4478. 'CA': '99.224.0.0/11',
  4479. 'CD': '41.243.0.0/16',
  4480. 'CF': '197.242.176.0/21',
  4481. 'CG': '160.113.0.0/16',
  4482. 'CH': '85.0.0.0/13',
  4483. 'CI': '102.136.0.0/14',
  4484. 'CK': '202.65.32.0/19',
  4485. 'CL': '152.172.0.0/14',
  4486. 'CM': '102.244.0.0/14',
  4487. 'CN': '36.128.0.0/10',
  4488. 'CO': '181.240.0.0/12',
  4489. 'CR': '201.192.0.0/12',
  4490. 'CU': '152.206.0.0/15',
  4491. 'CV': '165.90.96.0/19',
  4492. 'CW': '190.88.128.0/17',
  4493. 'CY': '31.153.0.0/16',
  4494. 'CZ': '88.100.0.0/14',
  4495. 'DE': '53.0.0.0/8',
  4496. 'DJ': '197.241.0.0/17',
  4497. 'DK': '87.48.0.0/12',
  4498. 'DM': '192.243.48.0/20',
  4499. 'DO': '152.166.0.0/15',
  4500. 'DZ': '41.96.0.0/12',
  4501. 'EC': '186.68.0.0/15',
  4502. 'EE': '90.190.0.0/15',
  4503. 'EG': '156.160.0.0/11',
  4504. 'ER': '196.200.96.0/20',
  4505. 'ES': '88.0.0.0/11',
  4506. 'ET': '196.188.0.0/14',
  4507. 'EU': '2.16.0.0/13',
  4508. 'FI': '91.152.0.0/13',
  4509. 'FJ': '144.120.0.0/16',
  4510. 'FK': '80.73.208.0/21',
  4511. 'FM': '119.252.112.0/20',
  4512. 'FO': '88.85.32.0/19',
  4513. 'FR': '90.0.0.0/9',
  4514. 'GA': '41.158.0.0/15',
  4515. 'GB': '25.0.0.0/8',
  4516. 'GD': '74.122.88.0/21',
  4517. 'GE': '31.146.0.0/16',
  4518. 'GF': '161.22.64.0/18',
  4519. 'GG': '62.68.160.0/19',
  4520. 'GH': '154.160.0.0/12',
  4521. 'GI': '95.164.0.0/16',
  4522. 'GL': '88.83.0.0/19',
  4523. 'GM': '160.182.0.0/15',
  4524. 'GN': '197.149.192.0/18',
  4525. 'GP': '104.250.0.0/19',
  4526. 'GQ': '105.235.224.0/20',
  4527. 'GR': '94.64.0.0/13',
  4528. 'GT': '168.234.0.0/16',
  4529. 'GU': '168.123.0.0/16',
  4530. 'GW': '197.214.80.0/20',
  4531. 'GY': '181.41.64.0/18',
  4532. 'HK': '113.252.0.0/14',
  4533. 'HN': '181.210.0.0/16',
  4534. 'HR': '93.136.0.0/13',
  4535. 'HT': '148.102.128.0/17',
  4536. 'HU': '84.0.0.0/14',
  4537. 'ID': '39.192.0.0/10',
  4538. 'IE': '87.32.0.0/12',
  4539. 'IL': '79.176.0.0/13',
  4540. 'IM': '5.62.80.0/20',
  4541. 'IN': '117.192.0.0/10',
  4542. 'IO': '203.83.48.0/21',
  4543. 'IQ': '37.236.0.0/14',
  4544. 'IR': '2.176.0.0/12',
  4545. 'IS': '82.221.0.0/16',
  4546. 'IT': '79.0.0.0/10',
  4547. 'JE': '87.244.64.0/18',
  4548. 'JM': '72.27.0.0/17',
  4549. 'JO': '176.29.0.0/16',
  4550. 'JP': '133.0.0.0/8',
  4551. 'KE': '105.48.0.0/12',
  4552. 'KG': '158.181.128.0/17',
  4553. 'KH': '36.37.128.0/17',
  4554. 'KI': '103.25.140.0/22',
  4555. 'KM': '197.255.224.0/20',
  4556. 'KN': '198.167.192.0/19',
  4557. 'KP': '175.45.176.0/22',
  4558. 'KR': '175.192.0.0/10',
  4559. 'KW': '37.36.0.0/14',
  4560. 'KY': '64.96.0.0/15',
  4561. 'KZ': '2.72.0.0/13',
  4562. 'LA': '115.84.64.0/18',
  4563. 'LB': '178.135.0.0/16',
  4564. 'LC': '24.92.144.0/20',
  4565. 'LI': '82.117.0.0/19',
  4566. 'LK': '112.134.0.0/15',
  4567. 'LR': '102.183.0.0/16',
  4568. 'LS': '129.232.0.0/17',
  4569. 'LT': '78.56.0.0/13',
  4570. 'LU': '188.42.0.0/16',
  4571. 'LV': '46.109.0.0/16',
  4572. 'LY': '41.252.0.0/14',
  4573. 'MA': '105.128.0.0/11',
  4574. 'MC': '88.209.64.0/18',
  4575. 'MD': '37.246.0.0/16',
  4576. 'ME': '178.175.0.0/17',
  4577. 'MF': '74.112.232.0/21',
  4578. 'MG': '154.126.0.0/17',
  4579. 'MH': '117.103.88.0/21',
  4580. 'MK': '77.28.0.0/15',
  4581. 'ML': '154.118.128.0/18',
  4582. 'MM': '37.111.0.0/17',
  4583. 'MN': '49.0.128.0/17',
  4584. 'MO': '60.246.0.0/16',
  4585. 'MP': '202.88.64.0/20',
  4586. 'MQ': '109.203.224.0/19',
  4587. 'MR': '41.188.64.0/18',
  4588. 'MS': '208.90.112.0/22',
  4589. 'MT': '46.11.0.0/16',
  4590. 'MU': '105.16.0.0/12',
  4591. 'MV': '27.114.128.0/18',
  4592. 'MW': '102.70.0.0/15',
  4593. 'MX': '187.192.0.0/11',
  4594. 'MY': '175.136.0.0/13',
  4595. 'MZ': '197.218.0.0/15',
  4596. 'NA': '41.182.0.0/16',
  4597. 'NC': '101.101.0.0/18',
  4598. 'NE': '197.214.0.0/18',
  4599. 'NF': '203.17.240.0/22',
  4600. 'NG': '105.112.0.0/12',
  4601. 'NI': '186.76.0.0/15',
  4602. 'NL': '145.96.0.0/11',
  4603. 'NO': '84.208.0.0/13',
  4604. 'NP': '36.252.0.0/15',
  4605. 'NR': '203.98.224.0/19',
  4606. 'NU': '49.156.48.0/22',
  4607. 'NZ': '49.224.0.0/14',
  4608. 'OM': '5.36.0.0/15',
  4609. 'PA': '186.72.0.0/15',
  4610. 'PE': '186.160.0.0/14',
  4611. 'PF': '123.50.64.0/18',
  4612. 'PG': '124.240.192.0/19',
  4613. 'PH': '49.144.0.0/13',
  4614. 'PK': '39.32.0.0/11',
  4615. 'PL': '83.0.0.0/11',
  4616. 'PM': '70.36.0.0/20',
  4617. 'PR': '66.50.0.0/16',
  4618. 'PS': '188.161.0.0/16',
  4619. 'PT': '85.240.0.0/13',
  4620. 'PW': '202.124.224.0/20',
  4621. 'PY': '181.120.0.0/14',
  4622. 'QA': '37.210.0.0/15',
  4623. 'RE': '102.35.0.0/16',
  4624. 'RO': '79.112.0.0/13',
  4625. 'RS': '93.86.0.0/15',
  4626. 'RU': '5.136.0.0/13',
  4627. 'RW': '41.186.0.0/16',
  4628. 'SA': '188.48.0.0/13',
  4629. 'SB': '202.1.160.0/19',
  4630. 'SC': '154.192.0.0/11',
  4631. 'SD': '102.120.0.0/13',
  4632. 'SE': '78.64.0.0/12',
  4633. 'SG': '8.128.0.0/10',
  4634. 'SI': '188.196.0.0/14',
  4635. 'SK': '78.98.0.0/15',
  4636. 'SL': '102.143.0.0/17',
  4637. 'SM': '89.186.32.0/19',
  4638. 'SN': '41.82.0.0/15',
  4639. 'SO': '154.115.192.0/18',
  4640. 'SR': '186.179.128.0/17',
  4641. 'SS': '105.235.208.0/21',
  4642. 'ST': '197.159.160.0/19',
  4643. 'SV': '168.243.0.0/16',
  4644. 'SX': '190.102.0.0/20',
  4645. 'SY': '5.0.0.0/16',
  4646. 'SZ': '41.84.224.0/19',
  4647. 'TC': '65.255.48.0/20',
  4648. 'TD': '154.68.128.0/19',
  4649. 'TG': '196.168.0.0/14',
  4650. 'TH': '171.96.0.0/13',
  4651. 'TJ': '85.9.128.0/18',
  4652. 'TK': '27.96.24.0/21',
  4653. 'TL': '180.189.160.0/20',
  4654. 'TM': '95.85.96.0/19',
  4655. 'TN': '197.0.0.0/11',
  4656. 'TO': '175.176.144.0/21',
  4657. 'TR': '78.160.0.0/11',
  4658. 'TT': '186.44.0.0/15',
  4659. 'TV': '202.2.96.0/19',
  4660. 'TW': '120.96.0.0/11',
  4661. 'TZ': '156.156.0.0/14',
  4662. 'UA': '37.52.0.0/14',
  4663. 'UG': '102.80.0.0/13',
  4664. 'US': '6.0.0.0/8',
  4665. 'UY': '167.56.0.0/13',
  4666. 'UZ': '84.54.64.0/18',
  4667. 'VA': '212.77.0.0/19',
  4668. 'VC': '207.191.240.0/21',
  4669. 'VE': '186.88.0.0/13',
  4670. 'VG': '66.81.192.0/20',
  4671. 'VI': '146.226.0.0/16',
  4672. 'VN': '14.160.0.0/11',
  4673. 'VU': '202.80.32.0/20',
  4674. 'WF': '117.20.32.0/21',
  4675. 'WS': '202.4.32.0/19',
  4676. 'YE': '134.35.0.0/16',
  4677. 'YT': '41.242.116.0/22',
  4678. 'ZA': '41.0.0.0/11',
  4679. 'ZM': '102.144.0.0/13',
  4680. 'ZW': '102.177.192.0/18',
  4681. }
  4682. @classmethod
  4683. def random_ipv4(cls, code_or_block):
  4684. if len(code_or_block) == 2:
  4685. block = cls._country_ip_map.get(code_or_block.upper())
  4686. if not block:
  4687. return None
  4688. else:
  4689. block = code_or_block
  4690. addr, preflen = block.split('/')
  4691. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  4692. addr_max = addr_min | (0xffffffff >> int(preflen))
  4693. return compat_str(socket.inet_ntoa(
  4694. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  4695. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  4696. def __init__(self, proxies=None):
  4697. # Set default handlers
  4698. for type in ('http', 'https'):
  4699. setattr(self, '%s_open' % type,
  4700. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  4701. meth(r, proxy, type))
  4702. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  4703. def proxy_open(self, req, proxy, type):
  4704. req_proxy = req.headers.get('Ytdl-request-proxy')
  4705. if req_proxy is not None:
  4706. proxy = req_proxy
  4707. del req.headers['Ytdl-request-proxy']
  4708. if proxy == '__noproxy__':
  4709. return None # No Proxy
  4710. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  4711. req.add_header('Ytdl-socks-proxy', proxy)
  4712. # youtube-dl's http/https handlers do wrapping the socket with socks
  4713. return None
  4714. return compat_urllib_request.ProxyHandler.proxy_open(
  4715. self, req, proxy, type)
  4716. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  4717. # released into Public Domain
  4718. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  4719. def long_to_bytes(n, blocksize=0):
  4720. """long_to_bytes(n:long, blocksize:int) : string
  4721. Convert a long integer to a byte string.
  4722. If optional blocksize is given and greater than zero, pad the front of the
  4723. byte string with binary zeros so that the length is a multiple of
  4724. blocksize.
  4725. """
  4726. # after much testing, this algorithm was deemed to be the fastest
  4727. s = b''
  4728. n = int(n)
  4729. while n > 0:
  4730. s = compat_struct_pack('>I', n & 0xffffffff) + s
  4731. n = n >> 32
  4732. # strip off leading zeros
  4733. for i in range(len(s)):
  4734. if s[i] != b'\000'[0]:
  4735. break
  4736. else:
  4737. # only happens when n == 0
  4738. s = b'\000'
  4739. i = 0
  4740. s = s[i:]
  4741. # add back some pad bytes. this could be done more efficiently w.r.t. the
  4742. # de-padding being done above, but sigh...
  4743. if blocksize > 0 and len(s) % blocksize:
  4744. s = (blocksize - len(s) % blocksize) * b'\000' + s
  4745. return s
  4746. def bytes_to_long(s):
  4747. """bytes_to_long(string) : long
  4748. Convert a byte string to a long integer.
  4749. This is (essentially) the inverse of long_to_bytes().
  4750. """
  4751. acc = 0
  4752. length = len(s)
  4753. if length % 4:
  4754. extra = (4 - length % 4)
  4755. s = b'\000' * extra + s
  4756. length = length + extra
  4757. for i in range(0, length, 4):
  4758. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  4759. return acc
  4760. def ohdave_rsa_encrypt(data, exponent, modulus):
  4761. '''
  4762. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  4763. Input:
  4764. data: data to encrypt, bytes-like object
  4765. exponent, modulus: parameter e and N of RSA algorithm, both integer
  4766. Output: hex string of encrypted data
  4767. Limitation: supports one block encryption only
  4768. '''
  4769. payload = int(binascii.hexlify(data[::-1]), 16)
  4770. encrypted = pow(payload, exponent, modulus)
  4771. return '%x' % encrypted
  4772. def pkcs1pad(data, length):
  4773. """
  4774. Padding input data with PKCS#1 scheme
  4775. @param {int[]} data input data
  4776. @param {int} length target length
  4777. @returns {int[]} padded data
  4778. """
  4779. if len(data) > length - 11:
  4780. raise ValueError('Input data too long for PKCS#1 padding')
  4781. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  4782. return [0, 2] + pseudo_random + [0] + data
  4783. def encode_base_n(num, n, table=None):
  4784. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4785. if not table:
  4786. table = FULL_TABLE[:n]
  4787. if n > len(table):
  4788. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  4789. if num == 0:
  4790. return table[0]
  4791. ret = ''
  4792. while num:
  4793. ret = table[num % n] + ret
  4794. num = num // n
  4795. return ret
  4796. def decode_packed_codes(code):
  4797. mobj = re.search(PACKED_CODES_RE, code)
  4798. obfucasted_code, base, count, symbols = mobj.groups()
  4799. base = int(base)
  4800. count = int(count)
  4801. symbols = symbols.split('|')
  4802. symbol_table = {}
  4803. while count:
  4804. count -= 1
  4805. base_n_count = encode_base_n(count, base)
  4806. symbol_table[base_n_count] = symbols[count] or base_n_count
  4807. return re.sub(
  4808. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  4809. obfucasted_code)
  4810. def caesar(s, alphabet, shift):
  4811. if shift == 0:
  4812. return s
  4813. l = len(alphabet)
  4814. return ''.join(
  4815. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  4816. for c in s)
  4817. def rot47(s):
  4818. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  4819. def parse_m3u8_attributes(attrib):
  4820. info = {}
  4821. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  4822. if val.startswith('"'):
  4823. val = val[1:-1]
  4824. info[key] = val
  4825. return info
  4826. def urshift(val, n):
  4827. return val >> n if val >= 0 else (val + 0x100000000) >> n
  4828. # Based on png2str() written by @gdkchan and improved by @yokrysty
  4829. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  4830. def decode_png(png_data):
  4831. # Reference: https://www.w3.org/TR/PNG/
  4832. header = png_data[8:]
  4833. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  4834. raise IOError('Not a valid PNG file.')
  4835. int_map = {1: '>B', 2: '>H', 4: '>I'}
  4836. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  4837. chunks = []
  4838. while header:
  4839. length = unpack_integer(header[:4])
  4840. header = header[4:]
  4841. chunk_type = header[:4]
  4842. header = header[4:]
  4843. chunk_data = header[:length]
  4844. header = header[length:]
  4845. header = header[4:] # Skip CRC
  4846. chunks.append({
  4847. 'type': chunk_type,
  4848. 'length': length,
  4849. 'data': chunk_data
  4850. })
  4851. ihdr = chunks[0]['data']
  4852. width = unpack_integer(ihdr[:4])
  4853. height = unpack_integer(ihdr[4:8])
  4854. idat = b''
  4855. for chunk in chunks:
  4856. if chunk['type'] == b'IDAT':
  4857. idat += chunk['data']
  4858. if not idat:
  4859. raise IOError('Unable to read PNG data.')
  4860. decompressed_data = bytearray(zlib.decompress(idat))
  4861. stride = width * 3
  4862. pixels = []
  4863. def _get_pixel(idx):
  4864. x = idx % stride
  4865. y = idx // stride
  4866. return pixels[y][x]
  4867. for y in range(height):
  4868. basePos = y * (1 + stride)
  4869. filter_type = decompressed_data[basePos]
  4870. current_row = []
  4871. pixels.append(current_row)
  4872. for x in range(stride):
  4873. color = decompressed_data[1 + basePos + x]
  4874. basex = y * stride + x
  4875. left = 0
  4876. up = 0
  4877. if x > 2:
  4878. left = _get_pixel(basex - 3)
  4879. if y > 0:
  4880. up = _get_pixel(basex - stride)
  4881. if filter_type == 1: # Sub
  4882. color = (color + left) & 0xff
  4883. elif filter_type == 2: # Up
  4884. color = (color + up) & 0xff
  4885. elif filter_type == 3: # Average
  4886. color = (color + ((left + up) >> 1)) & 0xff
  4887. elif filter_type == 4: # Paeth
  4888. a = left
  4889. b = up
  4890. c = 0
  4891. if x > 2 and y > 0:
  4892. c = _get_pixel(basex - stride - 3)
  4893. p = a + b - c
  4894. pa = abs(p - a)
  4895. pb = abs(p - b)
  4896. pc = abs(p - c)
  4897. if pa <= pb and pa <= pc:
  4898. color = (color + a) & 0xff
  4899. elif pb <= pc:
  4900. color = (color + b) & 0xff
  4901. else:
  4902. color = (color + c) & 0xff
  4903. current_row.append(color)
  4904. return width, height, pixels
  4905. def write_xattr(path, key, value):
  4906. # This mess below finds the best xattr tool for the job
  4907. try:
  4908. # try the pyxattr module...
  4909. import xattr
  4910. if hasattr(xattr, 'set'): # pyxattr
  4911. # Unicode arguments are not supported in python-pyxattr until
  4912. # version 0.5.0
  4913. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  4914. pyxattr_required_version = '0.5.0'
  4915. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  4916. # TODO: fallback to CLI tools
  4917. raise XAttrUnavailableError(
  4918. 'python-pyxattr is detected but is too old. '
  4919. 'youtube-dl requires %s or above while your version is %s. '
  4920. 'Falling back to other xattr implementations' % (
  4921. pyxattr_required_version, xattr.__version__))
  4922. setxattr = xattr.set
  4923. else: # xattr
  4924. setxattr = xattr.setxattr
  4925. try:
  4926. setxattr(path, key, value)
  4927. except EnvironmentError as e:
  4928. raise XAttrMetadataError(e.errno, e.strerror)
  4929. except ImportError:
  4930. if compat_os_name == 'nt':
  4931. # Write xattrs to NTFS Alternate Data Streams:
  4932. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  4933. assert ':' not in key
  4934. assert os.path.exists(path)
  4935. ads_fn = path + ':' + key
  4936. try:
  4937. with open(ads_fn, 'wb') as f:
  4938. f.write(value)
  4939. except EnvironmentError as e:
  4940. raise XAttrMetadataError(e.errno, e.strerror)
  4941. else:
  4942. user_has_setfattr = check_executable('setfattr', ['--version'])
  4943. user_has_xattr = check_executable('xattr', ['-h'])
  4944. if user_has_setfattr or user_has_xattr:
  4945. value = value.decode('utf-8')
  4946. if user_has_setfattr:
  4947. executable = 'setfattr'
  4948. opts = ['-n', key, '-v', value]
  4949. elif user_has_xattr:
  4950. executable = 'xattr'
  4951. opts = ['-w', key, value]
  4952. cmd = ([encodeFilename(executable, True)]
  4953. + [encodeArgument(o) for o in opts]
  4954. + [encodeFilename(path, True)])
  4955. try:
  4956. p = subprocess.Popen(
  4957. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  4958. except EnvironmentError as e:
  4959. raise XAttrMetadataError(e.errno, e.strerror)
  4960. stdout, stderr = p.communicate()
  4961. stderr = stderr.decode('utf-8', 'replace')
  4962. if p.returncode != 0:
  4963. raise XAttrMetadataError(p.returncode, stderr)
  4964. else:
  4965. # On Unix, and can't find pyxattr, setfattr, or xattr.
  4966. if sys.platform.startswith('linux'):
  4967. raise XAttrUnavailableError(
  4968. "Couldn't find a tool to set the xattrs. "
  4969. "Install either the python 'pyxattr' or 'xattr' "
  4970. "modules, or the GNU 'attr' package "
  4971. "(which contains the 'setfattr' tool).")
  4972. else:
  4973. raise XAttrUnavailableError(
  4974. "Couldn't find a tool to set the xattrs. "
  4975. "Install either the python 'xattr' module, "
  4976. "or the 'xattr' binary.")
  4977. def random_birthday(year_field, month_field, day_field):
  4978. start_date = datetime.date(1950, 1, 1)
  4979. end_date = datetime.date(1995, 12, 31)
  4980. offset = random.randint(0, (end_date - start_date).days)
  4981. random_date = start_date + datetime.timedelta(offset)
  4982. return {
  4983. year_field: str(random_date.year),
  4984. month_field: str(random_date.month),
  4985. day_field: str(random_date.day),
  4986. }