]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/extractor/sonyliv.py
[ie/vidly] Add extractor (#8612)
[yt-dlp.git] / yt_dlp / extractor / sonyliv.py
index a5026b2e025db747575e1c4fc4fe364ab78ea51d..4379572592ca78cde793a81e1b7458f8b7177ae5 100644 (file)
@@ -1,17 +1,17 @@
-# coding: utf-8
-from __future__ import unicode_literals
-
 import datetime
+import json
 import math
 import random
 import time
 import uuid
 
 from .common import InfoExtractor
-from ..compat import compat_HTTPError
+from ..networking.exceptions import HTTPError
 from ..utils import (
     ExtractorError,
     int_or_none,
+    jwt_decode_hs256,
+    try_call,
     try_get,
 )
 
@@ -75,31 +75,47 @@ def _get_device_id(self):
                 t[i] = '{:x}'.format(3 & n | 8)
         return ''.join(t) + '-' + str(int(time.time() * 1000))
 
-    def _login(self, username, password):
-        if username.lower() == 'token' and len(password) > 1198:
-            return password
+    def _perform_login(self, username, password):
+        self._HEADERS['device_id'] = self._get_device_id()
+        self._HEADERS['content-type'] = 'application/json'
+
+        if username.lower() == 'token' and try_call(lambda: jwt_decode_hs256(password)):
+            self._HEADERS['authorization'] = password
+            self.report_login()
+            return
         elif len(username) != 10 or not username.isdigit():
             raise ExtractorError(f'Invalid username/password; {self._LOGIN_HINT}')
 
         self.report_login()
-        data = '''{"mobileNumber":"%s","channelPartnerID":"MSMIND","country":"IN","timestamp":"%s",
-        "otpSize":6,"loginType":"REGISTERORSIGNIN","isMobileMandatory":true}
-         ''' % (username, datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%MZ"))
         otp_request_json = self._download_json(
             'https://apiv2.sonyliv.com/AGL/1.6/A/ENG/WEB/IN/HR/CREATEOTP-V2',
-            None, note='Sending OTP', data=data.encode(), headers=self._HEADERS)
+            None, note='Sending OTP', headers=self._HEADERS, data=json.dumps({
+                'mobileNumber': username,
+                'channelPartnerID': 'MSMIND',
+                'country': 'IN',
+                'timestamp': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%MZ'),
+                'otpSize': 6,
+                'loginType': 'REGISTERORSIGNIN',
+                'isMobileMandatory': True,
+            }).encode())
         if otp_request_json['resultCode'] == 'KO':
             raise ExtractorError(otp_request_json['message'], expected=True)
-        otp_code = self._get_tfa_info('OTP')
-        data = '''{"channelPartnerID":"MSMIND","mobileNumber":"%s","country":"IN","otp":"%s",
-        "dmaId":"IN","ageConfirmation":true,"timestamp":"%s","isMobileMandatory":true}
-         ''' % (username, otp_code, datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%MZ"))
+
         otp_verify_json = self._download_json(
             'https://apiv2.sonyliv.com/AGL/2.0/A/ENG/WEB/IN/HR/CONFIRMOTP-V2',
-            None, note='Verifying OTP', data=data.encode(), headers=self._HEADERS)
+            None, note='Verifying OTP', headers=self._HEADERS, data=json.dumps({
+                'channelPartnerID': 'MSMIND',
+                'mobileNumber': username,
+                'country': 'IN',
+                'otp': self._get_tfa_info('OTP'),
+                'dmaId': 'IN',
+                'ageConfirmation': True,
+                'timestamp': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%MZ'),
+                'isMobileMandatory': True,
+            }).encode())
         if otp_verify_json['resultCode'] == 'KO':
             raise ExtractorError(otp_request_json['message'], expected=True)
-        return otp_verify_json['resultObj']['accessToken']
+        self._HEADERS['authorization'] = otp_verify_json['resultObj']['accessToken']
 
     def _call_api(self, version, path, video_id):
         try:
@@ -107,24 +123,19 @@ def _call_api(self, version, path, video_id):
                 'https://apiv2.sonyliv.com/AGL/%s/A/ENG/WEB/%s' % (version, path),
                 video_id, headers=self._HEADERS)['resultObj']
         except ExtractorError as e:
-            if isinstance(e.cause, compat_HTTPError) and e.cause.code == 406 and self._parse_json(
-                    e.cause.read().decode(), video_id)['message'] == 'Please subscribe to watch this content':
+            if isinstance(e.cause, HTTPError) and e.cause.status == 406 and self._parse_json(
+                    e.cause.response.read().decode(), video_id)['message'] == 'Please subscribe to watch this content':
                 self.raise_login_required(self._LOGIN_HINT, method=None)
-            if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
+            if isinstance(e.cause, HTTPError) and e.cause.status == 403:
                 message = self._parse_json(
-                    e.cause.read().decode(), video_id)['message']
+                    e.cause.response.read().decode(), video_id)['message']
                 if message == 'Geoblocked Country':
                     self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
                 raise ExtractorError(message)
             raise
 
-    def _real_initialize(self):
+    def _initialize_pre_login(self):
         self._HEADERS['security_token'] = self._call_api('1.4', 'ALL/GETTOKEN', None)
-        username, password = self._get_login_info()
-        if username:
-            self._HEADERS['device_id'] = self._get_device_id()
-            self._HEADERS['content-type'] = 'application/json'
-            self._HEADERS['authorization'] = self._login(username, password)
 
     def _real_extract(self, url):
         video_id = self._match_id(url)
@@ -143,7 +154,6 @@ def _real_extract(self, url):
             video_id, 'mp4', m3u8_id='hls', headers=headers, fatal=False))
         for f in formats:
             f.setdefault('http_headers', {}).update(headers)
-        self._sort_formats(formats)
 
         metadata = self._call_api(
             '1.6', 'IN/DETAIL/' + video_id, video_id)['containers'][0]['metadata']