jiocinema.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import base64
  2. import itertools
  3. import json
  4. import random
  5. import re
  6. import string
  7. import time
  8. from .common import InfoExtractor
  9. from ..utils import (
  10. ExtractorError,
  11. float_or_none,
  12. int_or_none,
  13. jwt_decode_hs256,
  14. parse_age_limit,
  15. try_call,
  16. url_or_none,
  17. )
  18. from ..utils.traversal import traverse_obj
  19. class JioCinemaBaseIE(InfoExtractor):
  20. _NETRC_MACHINE = 'jiocinema'
  21. _GEO_BYPASS = False
  22. _ACCESS_TOKEN = None
  23. _REFRESH_TOKEN = None
  24. _GUEST_TOKEN = None
  25. _USER_ID = None
  26. _DEVICE_ID = None
  27. _API_HEADERS = {'Origin': 'https://www.jiocinema.com', 'Referer': 'https://www.jiocinema.com/'}
  28. _APP_NAME = {'appName': 'RJIL_JioCinema'}
  29. _APP_VERSION = {'appVersion': '5.0.0'}
  30. _API_SIGNATURES = 'o668nxgzwff'
  31. _METADATA_API_BASE = 'https://content-jiovoot.voot.com/psapi'
  32. _ACCESS_HINT = 'the `accessToken` from your browser local storage'
  33. _LOGIN_HINT = (
  34. 'Log in with "-u phone -p <PHONE_NUMBER>" to authenticate with OTP, '
  35. f'or use "-u token -p <ACCESS_TOKEN>" to log in with {_ACCESS_HINT}. '
  36. 'If you have previously logged in with yt-dlp and your session '
  37. 'has been cached, you can use "-u device -p <DEVICE_ID>"')
  38. def _cache_token(self, token_type):
  39. assert token_type in ('access', 'refresh', 'all')
  40. if token_type in ('access', 'all'):
  41. self.cache.store(
  42. JioCinemaBaseIE._NETRC_MACHINE, f'{JioCinemaBaseIE._DEVICE_ID}-access', JioCinemaBaseIE._ACCESS_TOKEN)
  43. if token_type in ('refresh', 'all'):
  44. self.cache.store(
  45. JioCinemaBaseIE._NETRC_MACHINE, f'{JioCinemaBaseIE._DEVICE_ID}-refresh', JioCinemaBaseIE._REFRESH_TOKEN)
  46. def _call_api(self, url, video_id, note='Downloading API JSON', headers={}, data={}):
  47. return self._download_json(
  48. url, video_id, note, data=json.dumps(data, separators=(',', ':')).encode(), headers={
  49. 'Content-Type': 'application/json',
  50. 'Accept': 'application/json',
  51. **self._API_HEADERS,
  52. **headers,
  53. }, expected_status=(400, 403, 474))
  54. def _call_auth_api(self, service, endpoint, note, headers={}, data={}):
  55. return self._call_api(
  56. f'https://auth-jiocinema.voot.com/{service}service/apis/v4/{endpoint}',
  57. None, note=note, headers=headers, data=data)
  58. def _refresh_token(self):
  59. if not JioCinemaBaseIE._REFRESH_TOKEN or not JioCinemaBaseIE._DEVICE_ID:
  60. raise ExtractorError('User token has expired', expected=True)
  61. response = self._call_auth_api(
  62. 'token', 'refreshtoken', 'Refreshing token',
  63. headers={'accesstoken': self._ACCESS_TOKEN}, data={
  64. **self._APP_NAME,
  65. 'deviceId': self._DEVICE_ID,
  66. 'refreshToken': self._REFRESH_TOKEN,
  67. **self._APP_VERSION,
  68. })
  69. refresh_token = response.get('refreshTokenId')
  70. if refresh_token and refresh_token != JioCinemaBaseIE._REFRESH_TOKEN:
  71. JioCinemaBaseIE._REFRESH_TOKEN = refresh_token
  72. self._cache_token('refresh')
  73. JioCinemaBaseIE._ACCESS_TOKEN = response['authToken']
  74. self._cache_token('access')
  75. def _fetch_guest_token(self):
  76. JioCinemaBaseIE._DEVICE_ID = ''.join(random.choices(string.digits, k=10))
  77. guest_token = self._call_auth_api(
  78. 'token', 'guest', 'Downloading guest token', data={
  79. **self._APP_NAME,
  80. 'deviceType': 'phone',
  81. 'os': 'ios',
  82. 'deviceId': self._DEVICE_ID,
  83. 'freshLaunch': False,
  84. 'adId': self._DEVICE_ID,
  85. **self._APP_VERSION,
  86. })
  87. self._GUEST_TOKEN = guest_token['authToken']
  88. self._USER_ID = guest_token['userId']
  89. def _call_login_api(self, endpoint, guest_token, data, note):
  90. return self._call_auth_api(
  91. 'user', f'loginotp/{endpoint}', note, headers={
  92. **self.geo_verification_headers(),
  93. 'accesstoken': self._GUEST_TOKEN,
  94. **self._APP_NAME,
  95. **traverse_obj(guest_token, 'data', {
  96. 'deviceType': ('deviceType', {str}),
  97. 'os': ('os', {str}),
  98. })}, data=data)
  99. def _is_token_expired(self, token):
  100. return (try_call(lambda: jwt_decode_hs256(token)['exp']) or 0) <= int(time.time() - 180)
  101. def _perform_login(self, username, password):
  102. if self._ACCESS_TOKEN and not self._is_token_expired(self._ACCESS_TOKEN):
  103. return
  104. UUID_RE = r'[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}'
  105. if username.lower() == 'token':
  106. if try_call(lambda: jwt_decode_hs256(password)):
  107. JioCinemaBaseIE._ACCESS_TOKEN = password
  108. refresh_hint = 'the `refreshToken` UUID from your browser local storage'
  109. refresh_token = self._configuration_arg('refresh_token', [''], ie_key=JioCinemaIE)[0]
  110. if not refresh_token:
  111. self.to_screen(
  112. 'To extend the life of your login session, in addition to your access token, '
  113. 'you can pass --extractor-args "jiocinema:refresh_token=REFRESH_TOKEN" '
  114. f'where REFRESH_TOKEN is {refresh_hint}')
  115. elif re.fullmatch(UUID_RE, refresh_token):
  116. JioCinemaBaseIE._REFRESH_TOKEN = refresh_token
  117. else:
  118. self.report_warning(f'Invalid refresh_token value. Use {refresh_hint}')
  119. else:
  120. raise ExtractorError(
  121. f'The password given could not be decoded as a token; use {self._ACCESS_HINT}', expected=True)
  122. elif username.lower() == 'device' and re.fullmatch(rf'(?:{UUID_RE}|\d+)', password):
  123. JioCinemaBaseIE._REFRESH_TOKEN = self.cache.load(JioCinemaBaseIE._NETRC_MACHINE, f'{password}-refresh')
  124. JioCinemaBaseIE._ACCESS_TOKEN = self.cache.load(JioCinemaBaseIE._NETRC_MACHINE, f'{password}-access')
  125. if not JioCinemaBaseIE._REFRESH_TOKEN or not JioCinemaBaseIE._ACCESS_TOKEN:
  126. raise ExtractorError(f'Failed to load cached tokens for device ID "{password}"', expected=True)
  127. elif username.lower() == 'phone' and re.fullmatch(r'\+?\d+', password):
  128. self._fetch_guest_token()
  129. guest_token = jwt_decode_hs256(self._GUEST_TOKEN)
  130. initial_data = {
  131. 'number': base64.b64encode(password.encode()).decode(),
  132. **self._APP_VERSION,
  133. }
  134. response = self._call_login_api('send', guest_token, initial_data, 'Requesting OTP')
  135. if not traverse_obj(response, ('OTPInfo', {dict})):
  136. raise ExtractorError('There was a problem with the phone number login attempt')
  137. is_iphone = guest_token.get('os') == 'ios'
  138. response = self._call_login_api('verify', guest_token, {
  139. 'deviceInfo': {
  140. 'consumptionDeviceName': 'iPhone' if is_iphone else 'Android',
  141. 'info': {
  142. 'platform': {'name': 'iPhone OS' if is_iphone else 'Android'},
  143. 'androidId': self._DEVICE_ID,
  144. 'type': 'iOS' if is_iphone else 'Android',
  145. },
  146. },
  147. **initial_data,
  148. 'otp': self._get_tfa_info('the one-time password sent to your phone'),
  149. }, 'Submitting OTP')
  150. if traverse_obj(response, 'code') == 1043:
  151. raise ExtractorError('Wrong OTP', expected=True)
  152. JioCinemaBaseIE._REFRESH_TOKEN = response['refreshToken']
  153. JioCinemaBaseIE._ACCESS_TOKEN = response['authToken']
  154. else:
  155. raise ExtractorError(self._LOGIN_HINT, expected=True)
  156. user_token = jwt_decode_hs256(JioCinemaBaseIE._ACCESS_TOKEN)['data']
  157. JioCinemaBaseIE._USER_ID = user_token['userId']
  158. JioCinemaBaseIE._DEVICE_ID = user_token['deviceId']
  159. if JioCinemaBaseIE._REFRESH_TOKEN and username != 'device':
  160. self._cache_token('all')
  161. if self.get_param('cachedir') is not False:
  162. self.to_screen(
  163. f'NOTE: For subsequent logins you can use "-u device -p {JioCinemaBaseIE._DEVICE_ID}"')
  164. elif not JioCinemaBaseIE._REFRESH_TOKEN:
  165. JioCinemaBaseIE._REFRESH_TOKEN = self.cache.load(
  166. JioCinemaBaseIE._NETRC_MACHINE, f'{JioCinemaBaseIE._DEVICE_ID}-refresh')
  167. if JioCinemaBaseIE._REFRESH_TOKEN:
  168. self._cache_token('access')
  169. self.to_screen(f'Logging in as device ID "{JioCinemaBaseIE._DEVICE_ID}"')
  170. if self._is_token_expired(JioCinemaBaseIE._ACCESS_TOKEN):
  171. self._refresh_token()
  172. class JioCinemaIE(JioCinemaBaseIE):
  173. IE_NAME = 'jiocinema'
  174. _VALID_URL = r'https?://(?:www\.)?jiocinema\.com/?(?:movies?/[^/?#]+/|tv-shows/(?:[^/?#]+/){3})(?P<id>\d{3,})'
  175. _TESTS = [{
  176. 'url': 'https://www.jiocinema.com/tv-shows/agnisakshi-ek-samjhauta/1/pradeep-to-stop-the-wedding/3759931',
  177. 'info_dict': {
  178. 'id': '3759931',
  179. 'ext': 'mp4',
  180. 'title': 'Pradeep to stop the wedding?',
  181. 'description': 'md5:75f72d1d1a66976633345a3de6d672b1',
  182. 'episode': 'Pradeep to stop the wedding?',
  183. 'episode_number': 89,
  184. 'season': 'Agnisakshi…Ek Samjhauta-S1',
  185. 'season_number': 1,
  186. 'series': 'Agnisakshi Ek Samjhauta',
  187. 'duration': 1238.0,
  188. 'thumbnail': r're:https?://.+\.jpg',
  189. 'age_limit': 13,
  190. 'season_id': '3698031',
  191. 'upload_date': '20230606',
  192. 'timestamp': 1686009600,
  193. 'release_date': '20230607',
  194. 'genres': ['Drama'],
  195. },
  196. 'params': {'skip_download': 'm3u8'},
  197. }, {
  198. 'url': 'https://www.jiocinema.com/movies/bhediya/3754021/watch',
  199. 'info_dict': {
  200. 'id': '3754021',
  201. 'ext': 'mp4',
  202. 'title': 'Bhediya',
  203. 'description': 'md5:a6bf2900371ac2fc3f1447401a9f7bb0',
  204. 'episode': 'Bhediya',
  205. 'duration': 8500.0,
  206. 'thumbnail': r're:https?://.+\.jpg',
  207. 'age_limit': 13,
  208. 'upload_date': '20230525',
  209. 'timestamp': 1685026200,
  210. 'release_date': '20230524',
  211. 'genres': ['Comedy'],
  212. },
  213. 'params': {'skip_download': 'm3u8'},
  214. }]
  215. def _extract_formats_and_subtitles(self, playback, video_id):
  216. m3u8_url = traverse_obj(playback, (
  217. 'data', 'playbackUrls', lambda _, v: v['streamtype'] == 'hls', 'url', {url_or_none}, any))
  218. if not m3u8_url: # DRM-only content only serves dash urls
  219. self.report_drm(video_id)
  220. formats, subtitles = self._extract_m3u8_formats_and_subtitles(m3u8_url, video_id, m3u8_id='hls')
  221. self._remove_duplicate_formats(formats)
  222. return {
  223. # '/_definst_/smil:vod/' m3u8 manifests claim to have 720p+ formats but max out at 480p
  224. 'formats': traverse_obj(formats, (
  225. lambda _, v: '/_definst_/smil:vod/' not in v['url'] or v['height'] <= 480)),
  226. 'subtitles': subtitles,
  227. }
  228. def _real_extract(self, url):
  229. video_id = self._match_id(url)
  230. if not self._ACCESS_TOKEN and self._is_token_expired(self._GUEST_TOKEN):
  231. self._fetch_guest_token()
  232. elif self._ACCESS_TOKEN and self._is_token_expired(self._ACCESS_TOKEN):
  233. self._refresh_token()
  234. playback = self._call_api(
  235. f'https://apis-jiovoot.voot.com/playbackjv/v3/{video_id}', video_id,
  236. 'Downloading playback JSON', headers={
  237. **self.geo_verification_headers(),
  238. 'accesstoken': self._ACCESS_TOKEN or self._GUEST_TOKEN,
  239. **self._APP_NAME,
  240. 'deviceid': self._DEVICE_ID,
  241. 'uniqueid': self._USER_ID,
  242. 'x-apisignatures': self._API_SIGNATURES,
  243. 'x-platform': 'androidweb',
  244. 'x-platform-token': 'web',
  245. }, data={
  246. '4k': False,
  247. 'ageGroup': '18+',
  248. 'appVersion': '3.4.0',
  249. 'bitrateProfile': 'xhdpi',
  250. 'capability': {
  251. 'drmCapability': {
  252. 'aesSupport': 'yes',
  253. 'fairPlayDrmSupport': 'none',
  254. 'playreadyDrmSupport': 'none',
  255. 'widevineDRMSupport': 'none',
  256. },
  257. 'frameRateCapability': [{
  258. 'frameRateSupport': '30fps',
  259. 'videoQuality': '1440p',
  260. }],
  261. },
  262. 'continueWatchingRequired': False,
  263. 'dolby': False,
  264. 'downloadRequest': False,
  265. 'hevc': False,
  266. 'kidsSafe': False,
  267. 'manufacturer': 'Windows',
  268. 'model': 'Windows',
  269. 'multiAudioRequired': True,
  270. 'osVersion': '10',
  271. 'parentalPinValid': True,
  272. 'x-apisignatures': self._API_SIGNATURES,
  273. })
  274. status_code = traverse_obj(playback, ('code', {int}))
  275. if status_code == 474:
  276. self.raise_geo_restricted(countries=['IN'])
  277. elif status_code == 1008:
  278. error_msg = 'This content is only available for premium users'
  279. if self._ACCESS_TOKEN:
  280. raise ExtractorError(error_msg, expected=True)
  281. self.raise_login_required(f'{error_msg}. {self._LOGIN_HINT}', method=None)
  282. elif status_code == 400:
  283. raise ExtractorError('The requested content is not available', expected=True)
  284. elif status_code is not None and status_code != 200:
  285. raise ExtractorError(
  286. f'JioCinema says: {traverse_obj(playback, ("message", {str})) or status_code}')
  287. metadata = self._download_json(
  288. f'{self._METADATA_API_BASE}/voot/v1/voot-web/content/query/asset-details',
  289. video_id, fatal=False, query={
  290. 'ids': f'include:{video_id}',
  291. 'responseType': 'common',
  292. 'devicePlatformType': 'desktop',
  293. })
  294. return {
  295. 'id': video_id,
  296. 'http_headers': self._API_HEADERS,
  297. **self._extract_formats_and_subtitles(playback, video_id),
  298. **traverse_obj(playback, ('data', {
  299. # fallback metadata
  300. 'title': ('name', {str}),
  301. 'description': ('fullSynopsis', {str}),
  302. 'series': ('show', 'name', {str}, {lambda x: x or None}),
  303. 'season': ('tournamentName', {str}, {lambda x: x if x != 'Season 0' else None}),
  304. 'season_number': ('episode', 'season', {int_or_none}, {lambda x: x or None}),
  305. 'episode': ('fullTitle', {str}),
  306. 'episode_number': ('episode', 'episodeNo', {int_or_none}, {lambda x: x or None}),
  307. 'age_limit': ('ageNemonic', {parse_age_limit}),
  308. 'duration': ('totalDuration', {float_or_none}),
  309. 'thumbnail': ('images', {url_or_none}),
  310. })),
  311. **traverse_obj(metadata, ('result', 0, {
  312. 'title': ('fullTitle', {str}),
  313. 'description': ('fullSynopsis', {str}),
  314. 'series': ('showName', {str}, {lambda x: x or None}),
  315. 'season': ('seasonName', {str}, {lambda x: x or None}),
  316. 'season_number': ('season', {int_or_none}),
  317. 'season_id': ('seasonId', {str}, {lambda x: x or None}),
  318. 'episode': ('fullTitle', {str}),
  319. 'episode_number': ('episode', {int_or_none}),
  320. 'timestamp': ('uploadTime', {int_or_none}),
  321. 'release_date': ('telecastDate', {str}),
  322. 'age_limit': ('ageNemonic', {parse_age_limit}),
  323. 'duration': ('duration', {float_or_none}),
  324. 'genres': ('genres', ..., {str}),
  325. 'thumbnail': ('seo', 'ogImage', {url_or_none}),
  326. })),
  327. }
  328. class JioCinemaSeriesIE(JioCinemaBaseIE):
  329. IE_NAME = 'jiocinema:series'
  330. _VALID_URL = r'https?://(?:www\.)?jiocinema\.com/tv-shows/(?P<slug>[\w-]+)/(?P<id>\d{3,})'
  331. _TESTS = [{
  332. 'url': 'https://www.jiocinema.com/tv-shows/naagin/3499917',
  333. 'info_dict': {
  334. 'id': '3499917',
  335. 'title': 'naagin',
  336. },
  337. 'playlist_mincount': 120,
  338. }, {
  339. 'url': 'https://www.jiocinema.com/tv-shows/mtv-splitsvilla-x5/3499820',
  340. 'info_dict': {
  341. 'id': '3499820',
  342. 'title': 'mtv-splitsvilla-x5',
  343. },
  344. 'playlist_mincount': 310,
  345. }]
  346. def _entries(self, series_id):
  347. seasons = traverse_obj(self._download_json(
  348. f'{self._METADATA_API_BASE}/voot/v1/voot-web/view/show/{series_id}', series_id,
  349. 'Downloading series metadata JSON', query={'responseType': 'common'}), (
  350. 'trays', lambda _, v: v['trayId'] == 'season-by-show-multifilter',
  351. 'trayTabs', lambda _, v: v['id']))
  352. for season_num, season in enumerate(seasons, start=1):
  353. season_id = season['id']
  354. label = season.get('label') or season_num
  355. for page_num in itertools.count(1):
  356. episodes = traverse_obj(self._download_json(
  357. f'{self._METADATA_API_BASE}/voot/v1/voot-web/content/generic/series-wise-episode',
  358. season_id, f'Downloading season {label} page {page_num} JSON', query={
  359. 'sort': 'episode:asc',
  360. 'id': season_id,
  361. 'responseType': 'common',
  362. 'page': page_num,
  363. }), ('result', lambda _, v: v['id'] and url_or_none(v['slug'])))
  364. if not episodes:
  365. break
  366. for episode in episodes:
  367. yield self.url_result(
  368. episode['slug'], JioCinemaIE, **traverse_obj(episode, {
  369. 'video_id': 'id',
  370. 'video_title': ('fullTitle', {str}),
  371. 'season_number': ('season', {int_or_none}),
  372. 'episode_number': ('episode', {int_or_none}),
  373. }))
  374. def _real_extract(self, url):
  375. slug, series_id = self._match_valid_url(url).group('slug', 'id')
  376. return self.playlist_result(self._entries(series_id), series_id, slug)