odnoklassniki.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import urllib.parse
  2. from .common import InfoExtractor
  3. from ..compat import compat_etree_fromstring
  4. from ..networking import HEADRequest
  5. from ..utils import (
  6. ExtractorError,
  7. float_or_none,
  8. int_or_none,
  9. qualities,
  10. smuggle_url,
  11. traverse_obj,
  12. unescapeHTML,
  13. unified_strdate,
  14. unsmuggle_url,
  15. url_or_none,
  16. urlencode_postdata,
  17. )
  18. class OdnoklassnikiIE(InfoExtractor):
  19. _VALID_URL = r'''(?x)
  20. https?://
  21. (?:(?:www|m|mobile)\.)?
  22. (?:odnoklassniki|ok)\.ru/
  23. (?:
  24. video(?P<embed>embed)?/|
  25. web-api/video/moviePlayer/|
  26. live/|
  27. dk\?.*?st\.mvId=
  28. )
  29. (?P<id>[\d-]+)
  30. '''
  31. _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:odnoklassniki|ok)\.ru/videoembed/.+?)\1']
  32. _TESTS = [{
  33. 'note': 'Coub embedded',
  34. 'url': 'http://ok.ru/video/1484130554189',
  35. 'info_dict': {
  36. 'id': '1keok9',
  37. 'ext': 'mp4',
  38. 'timestamp': 1545580896,
  39. 'view_count': int,
  40. 'thumbnail': r're:^https?://.*\.jpg$',
  41. 'title': 'Народная забава',
  42. 'uploader': 'Nevata',
  43. 'upload_date': '20181223',
  44. 'age_limit': 0,
  45. 'uploader_id': 'nevata.s',
  46. 'like_count': int,
  47. 'duration': 8.08,
  48. 'repost_count': int,
  49. },
  50. }, {
  51. 'note': 'vk.com embedded',
  52. 'url': 'https://ok.ru/video/3568183087575',
  53. 'info_dict': {
  54. 'id': '-165101755_456243749',
  55. 'ext': 'mp4',
  56. 'uploader_id': '-165101755',
  57. 'duration': 132,
  58. 'timestamp': 1642869935,
  59. 'upload_date': '20220122',
  60. 'thumbnail': str,
  61. 'title': str,
  62. 'uploader': str,
  63. },
  64. 'skip': 'vk extractor error',
  65. }, {
  66. # metadata in JSON, webm_dash with Firefox UA
  67. 'url': 'http://ok.ru/video/20079905452',
  68. 'md5': '8f477d8931c531374a3e36daec617b2c',
  69. 'info_dict': {
  70. 'id': '20079905452',
  71. 'ext': 'webm',
  72. 'title': 'Культура меняет нас (прекрасный ролик!))',
  73. 'thumbnail': str,
  74. 'duration': 100,
  75. 'upload_date': '20141207',
  76. 'uploader_id': '330537914540',
  77. 'uploader': 'Виталий Добровольский',
  78. 'like_count': int,
  79. 'age_limit': 0,
  80. },
  81. 'params': {
  82. 'format': 'bv[ext=webm]',
  83. 'http_headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:102.0) Gecko/20100101 Firefox/102.0'},
  84. },
  85. }, {
  86. # metadataUrl
  87. 'url': 'http://ok.ru/video/63567059965189-0?fromTime=5',
  88. 'md5': '2bae2f58eefe1b3d26f3926c4a64d2f3',
  89. 'info_dict': {
  90. 'id': '63567059965189-0',
  91. 'ext': 'mp4',
  92. 'title': 'Девушка без комплексов ...',
  93. 'thumbnail': str,
  94. 'duration': 191,
  95. 'upload_date': '20150518',
  96. 'uploader_id': '534380003155',
  97. 'uploader': '☭ Андрей Мещанинов ☭',
  98. 'like_count': int,
  99. 'age_limit': 0,
  100. 'start_time': 5,
  101. },
  102. 'params': {'skip_download': 'm3u8'},
  103. }, {
  104. # YouTube embed (metadataUrl, provider == USER_YOUTUBE)
  105. 'url': 'https://ok.ru/video/3952212382174',
  106. 'md5': '5fb5f83ce16cb212d6bf887282b5da53',
  107. 'info_dict': {
  108. 'id': '5axVgHHDBvU',
  109. 'ext': 'mp4',
  110. 'title': 'Youtube-dl 101: What is it and HOW to use it! Full Download Walkthrough and Guide',
  111. 'description': 'md5:b57209eeb9d5c2f20c984dfb58862097',
  112. 'uploader': 'Lod Mer',
  113. 'uploader_id': '575186401502',
  114. 'duration': 1529,
  115. 'age_limit': 0,
  116. 'upload_date': '20210405',
  117. 'comment_count': int,
  118. 'live_status': 'not_live',
  119. 'view_count': int,
  120. 'thumbnail': 'https://i.mycdn.me/i?r=AEHujHvw2RjEbemUCNEorZbxYpb_p_9AcN2FmGik64Krkcmz37YtlY093oAM5-HIEAt7Zi9s0CiBOSDmbngC-I-k&fn=external_8',
  121. 'uploader_url': 'https://www.youtube.com/@MrKewlkid94',
  122. 'channel_follower_count': int,
  123. 'tags': ['youtube-dl', 'youtube playlists', 'download videos', 'download audio'],
  124. 'channel_id': 'UCVGtvURtEURYHtJFUegdSug',
  125. 'like_count': int,
  126. 'availability': 'public',
  127. 'channel_url': 'https://www.youtube.com/channel/UCVGtvURtEURYHtJFUegdSug',
  128. 'categories': ['Education'],
  129. 'playable_in_embed': True,
  130. 'channel': 'BornToReact',
  131. },
  132. }, {
  133. # YouTube embed (metadata, provider == USER_YOUTUBE, no metadata.movie.title field)
  134. 'url': 'http://ok.ru/video/62036049272859-0',
  135. 'info_dict': {
  136. 'id': '62036049272859-0',
  137. 'ext': 'mp4',
  138. 'title': 'МУЗЫКА ДОЖДЯ .',
  139. 'description': 'md5:6f1867132bd96e33bf53eda1091e8ed0',
  140. 'upload_date': '20120106',
  141. 'uploader_id': '473534735899',
  142. 'uploader': 'МARINA D',
  143. 'age_limit': 0,
  144. },
  145. 'params': {
  146. 'skip_download': True,
  147. },
  148. 'skip': 'Video has not been found',
  149. }, {
  150. 'note': 'Only available in mobile webpage',
  151. 'url': 'https://m.ok.ru/video/2361249957145',
  152. 'info_dict': {
  153. 'id': '2361249957145',
  154. 'ext': 'mp4',
  155. 'title': 'Быковское крещение',
  156. 'duration': 3038.181,
  157. 'thumbnail': r're:^https?://i\.mycdn\.me/videoPreview\?.+',
  158. },
  159. }, {
  160. 'note': 'subtitles',
  161. 'url': 'https://ok.ru/video/4249587550747',
  162. 'info_dict': {
  163. 'id': '4249587550747',
  164. 'ext': 'mp4',
  165. 'title': 'Small Country An African Childhood (2020) (1080p) +subtitle',
  166. 'uploader': 'Sunflower Movies',
  167. 'uploader_id': '595802161179',
  168. 'upload_date': '20220816',
  169. 'duration': 6728,
  170. 'age_limit': 0,
  171. 'thumbnail': r're:^https?://i\.mycdn\.me/videoPreview\?.+',
  172. 'like_count': int,
  173. 'subtitles': dict,
  174. },
  175. 'params': {
  176. 'skip_download': True,
  177. },
  178. }, {
  179. 'url': 'http://ok.ru/web-api/video/moviePlayer/20079905452',
  180. 'only_matching': True,
  181. }, {
  182. 'url': 'http://www.ok.ru/video/20648036891',
  183. 'only_matching': True,
  184. }, {
  185. 'url': 'http://www.ok.ru/videoembed/20648036891',
  186. 'only_matching': True,
  187. }, {
  188. 'url': 'http://m.ok.ru/video/20079905452',
  189. 'only_matching': True,
  190. }, {
  191. 'url': 'http://mobile.ok.ru/video/20079905452',
  192. 'only_matching': True,
  193. }, {
  194. 'url': 'https://www.ok.ru/live/484531969818',
  195. 'only_matching': True,
  196. }, {
  197. 'url': 'https://m.ok.ru/dk?st.cmd=movieLayer&st.discId=863789452017&st.retLoc=friend&st.rtu=%2Fdk%3Fst.cmd%3DfriendMovies%26st.mode%3Down%26st.mrkId%3D%257B%2522uploadedMovieMarker%2522%253A%257B%2522marker%2522%253A%25221519410114503%2522%252C%2522hasMore%2522%253Atrue%257D%252C%2522sharedMovieMarker%2522%253A%257B%2522marker%2522%253Anull%252C%2522hasMore%2522%253Afalse%257D%257D%26st.friendId%3D561722190321%26st.frwd%3Don%26_prevCmd%3DfriendMovies%26tkn%3D7257&st.discType=MOVIE&st.mvId=863789452017&_prevCmd=friendMovies&tkn=3648#lst#',
  198. 'only_matching': True,
  199. }, {
  200. # Paid video
  201. 'url': 'https://ok.ru/video/954886983203',
  202. 'only_matching': True,
  203. }, {
  204. 'url': 'https://ok.ru/videoembed/2932705602075',
  205. 'info_dict': {
  206. 'id': '2932705602075',
  207. 'ext': 'mp4',
  208. 'thumbnail': 'https://i.mycdn.me/videoPreview?id=1369902483995&type=37&idx=2&tkn=fqlnoQD_xwq5ovIlKfgNyU08qmM&fn=external_8',
  209. 'title': 'Boosty для тебя!',
  210. 'uploader_id': '597811038747',
  211. 'like_count': 0,
  212. 'duration': 35,
  213. },
  214. }]
  215. _WEBPAGE_TESTS = [{
  216. 'url': 'https://boosty.to/ikakprosto/posts/56cedaca-b56a-4dfd-b3ed-98c79cfa0167',
  217. 'info_dict': {
  218. 'id': '3950343629563',
  219. 'ext': 'mp4',
  220. 'thumbnail': 'https://i.mycdn.me/videoPreview?id=2776238394107&type=37&idx=11&tkn=F3ejkUFcpuI4DnMRxrDGcH5YcmM&fn=external_8',
  221. 'title': 'Заяц Бусти.mp4',
  222. 'uploader_id': '571368965883',
  223. 'like_count': 0,
  224. 'duration': 10444,
  225. },
  226. 'skip': 'Site no longer embeds',
  227. }]
  228. def _clear_cookies(self, cdn_url):
  229. # Direct http downloads will fail if CDN cookies are set
  230. # so we need to reset them after each format extraction
  231. self.cookiejar.clear(domain='.mycdn.me')
  232. self.cookiejar.clear(domain=urllib.parse.urlparse(cdn_url).hostname)
  233. @classmethod
  234. def _extract_embed_urls(cls, url, webpage):
  235. for x in super()._extract_embed_urls(url, webpage):
  236. yield smuggle_url(x, {'referrer': url})
  237. def _real_extract(self, url):
  238. try:
  239. return self._extract_desktop(url)
  240. except ExtractorError as e:
  241. try:
  242. return self._extract_mobile(url)
  243. except ExtractorError:
  244. # error message of desktop webpage is in English
  245. raise e
  246. def _extract_desktop(self, url):
  247. start_time = int_or_none(urllib.parse.parse_qs(
  248. urllib.parse.urlparse(url).query).get('fromTime', [None])[0])
  249. url, smuggled = unsmuggle_url(url, {})
  250. video_id, is_embed = self._match_valid_url(url).group('id', 'embed')
  251. mode = 'videoembed' if is_embed else 'video'
  252. webpage = self._download_webpage(
  253. f'https://ok.ru/{mode}/{video_id}', video_id,
  254. note='Downloading desktop webpage',
  255. headers={'Referer': smuggled['referrer']} if smuggled.get('referrer') else {})
  256. error = self._search_regex(
  257. r'[^>]+class="vp_video_stub_txt"[^>]*>([^<]+)<',
  258. webpage, 'error', default=None)
  259. # Direct link from boosty
  260. if (error == 'The author of this video has not been found or is blocked'
  261. and not smuggled.get('referrer') and mode == 'videoembed'):
  262. return self._extract_desktop(smuggle_url(url, {'referrer': 'https://boosty.to'}))
  263. elif error:
  264. raise ExtractorError(error, expected=True)
  265. player = self._parse_json(
  266. unescapeHTML(self._search_regex(
  267. rf'data-options=(?P<quote>["\'])(?P<player>{{.+?{video_id}.+?}})(?P=quote)',
  268. webpage, 'player', group='player')),
  269. video_id)
  270. # embedded external player
  271. if player.get('isExternalPlayer') and player.get('url'):
  272. return self.url_result(player['url'])
  273. flashvars = player['flashvars']
  274. metadata = flashvars.get('metadata')
  275. if metadata:
  276. metadata = self._parse_json(metadata, video_id)
  277. else:
  278. data = {}
  279. st_location = flashvars.get('location')
  280. if st_location:
  281. data['st.location'] = st_location
  282. metadata = self._download_json(
  283. urllib.parse.unquote(flashvars['metadataUrl']),
  284. video_id, 'Downloading metadata JSON',
  285. data=urlencode_postdata(data))
  286. movie = metadata['movie']
  287. # Some embedded videos may not contain title in movie dict (e.g.
  288. # http://ok.ru/video/62036049272859-0) thus we allow missing title
  289. # here and it's going to be extracted later by an extractor that
  290. # will process the actual embed.
  291. provider = metadata.get('provider')
  292. title = movie['title'] if provider == 'UPLOADED_ODKL' else movie.get('title')
  293. thumbnail = movie.get('poster')
  294. duration = int_or_none(movie.get('duration'))
  295. author = metadata.get('author', {})
  296. uploader_id = author.get('id')
  297. uploader = author.get('name')
  298. upload_date = unified_strdate(self._html_search_meta(
  299. 'ya:ovs:upload_date', webpage, 'upload date', default=None))
  300. age_limit = None
  301. adult = self._html_search_meta(
  302. 'ya:ovs:adult', webpage, 'age limit', default=None)
  303. if adult:
  304. age_limit = 18 if adult == 'true' else 0
  305. like_count = int_or_none(metadata.get('likeCount'))
  306. subtitles = {}
  307. for sub in traverse_obj(metadata, ('movie', 'subtitleTracks', ...), expected_type=dict):
  308. sub_url = sub.get('url')
  309. if not sub_url:
  310. continue
  311. subtitles.setdefault(sub.get('language') or 'en', []).append({
  312. 'url': sub_url,
  313. 'ext': 'vtt',
  314. })
  315. info = {
  316. 'id': video_id,
  317. 'title': title,
  318. 'thumbnail': thumbnail,
  319. 'duration': duration,
  320. 'upload_date': upload_date,
  321. 'uploader': uploader,
  322. 'uploader_id': uploader_id,
  323. 'like_count': like_count,
  324. 'age_limit': age_limit,
  325. 'start_time': start_time,
  326. 'subtitles': subtitles,
  327. }
  328. # pladform
  329. if provider == 'OPEN_GRAPH':
  330. info.update({
  331. '_type': 'url_transparent',
  332. 'url': movie['contentId'],
  333. })
  334. return info
  335. if provider == 'USER_YOUTUBE':
  336. info.update({
  337. '_type': 'url_transparent',
  338. 'url': movie['contentId'],
  339. })
  340. return info
  341. assert title
  342. if provider == 'LIVE_TV_APP':
  343. info['title'] = title
  344. quality = qualities(('4', '0', '1', '2', '3', '5', '6', '7'))
  345. formats = [{
  346. 'url': f['url'],
  347. 'ext': 'mp4',
  348. 'format_id': f.get('name'),
  349. } for f in traverse_obj(metadata, ('videos', lambda _, v: url_or_none(v['url'])))]
  350. m3u8_url = traverse_obj(metadata, 'hlsManifestUrl', 'ondemandHls')
  351. if m3u8_url:
  352. formats.extend(self._extract_m3u8_formats(
  353. m3u8_url, video_id, 'mp4', 'm3u8_native',
  354. m3u8_id='hls', fatal=False))
  355. self._clear_cookies(m3u8_url)
  356. for mpd_id, mpd_key in [('dash', 'ondemandDash'), ('webm', 'metadataWebmUrl')]:
  357. mpd_url = metadata.get(mpd_key)
  358. if mpd_url:
  359. formats.extend(self._extract_mpd_formats(
  360. mpd_url, video_id, mpd_id=mpd_id, fatal=False))
  361. self._clear_cookies(mpd_url)
  362. dash_manifest = metadata.get('metadataEmbedded')
  363. if dash_manifest:
  364. formats.extend(self._parse_mpd_formats(
  365. compat_etree_fromstring(dash_manifest), 'mpd'))
  366. for fmt in formats:
  367. fmt_type = self._search_regex(
  368. r'\btype[/=](\d)', fmt['url'],
  369. 'format type', default=None)
  370. if fmt_type:
  371. fmt['quality'] = quality(fmt_type)
  372. # Live formats
  373. m3u8_url = metadata.get('hlsMasterPlaylistUrl')
  374. if m3u8_url:
  375. formats.extend(self._extract_m3u8_formats(
  376. m3u8_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
  377. self._clear_cookies(m3u8_url)
  378. rtmp_url = metadata.get('rtmpUrl')
  379. if rtmp_url:
  380. formats.append({
  381. 'url': rtmp_url,
  382. 'format_id': 'rtmp',
  383. 'ext': 'flv',
  384. })
  385. if not formats:
  386. payment_info = metadata.get('paymentInfo')
  387. if payment_info:
  388. self.raise_no_formats('This video is paid, subscribe to download it', expected=True)
  389. info['formats'] = formats
  390. return info
  391. def _extract_mobile(self, url):
  392. video_id = self._match_id(url)
  393. webpage = self._download_webpage(
  394. f'http://m.ok.ru/video/{video_id}', video_id,
  395. note='Downloading mobile webpage')
  396. error = self._search_regex(
  397. r'видео</a>\s*<div\s+class="empty">(.+?)</div>',
  398. webpage, 'error', default=None)
  399. if error:
  400. raise ExtractorError(error, expected=True)
  401. json_data = self._search_regex(
  402. r'data-video="(.+?)"', webpage, 'json data')
  403. json_data = self._parse_json(unescapeHTML(json_data), video_id) or {}
  404. redirect_url = self._request_webpage(HEADRequest(
  405. json_data['videoSrc']), video_id, 'Requesting download URL').url
  406. self._clear_cookies(redirect_url)
  407. return {
  408. 'id': video_id,
  409. 'title': json_data.get('videoName'),
  410. 'duration': float_or_none(json_data.get('videoDuration'), scale=1000),
  411. 'thumbnail': json_data.get('videoPosterSrc'),
  412. 'formats': [{
  413. 'format_id': 'mobile',
  414. 'url': redirect_url,
  415. 'ext': 'mp4',
  416. }],
  417. }