PageRenderTime 102ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/youtube_dl/utils.py

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