]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/shahid.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / shahid.py
CommitLineData
3b4b66b5 1import json
78466fca
RA
2import math
3import re
3b4b66b5 4
78466fca 5from .aws import AWSIE
3d2623a8 6from ..networking.exceptions import HTTPError
02c126a7 7from ..utils import (
02c126a7 8 ExtractorError,
78466fca 9 InAdvancePagedList,
e897bd82 10 clean_html,
c576ef1e
S
11 int_or_none,
12 parse_iso8601,
41aa4425 13 str_or_none,
3b4b66b5 14 urlencode_postdata,
84c0ed50 15)
114ed20e 16
3be3c622 17
78466fca
RA
18class ShahidBaseIE(AWSIE):
19 _AWS_PROXY_HOST = 'api2.shahid.net'
20 _AWS_API_KEY = '2RRtuMHx95aNI1Kvtn2rChEuwsCogUd4samGPjLh'
b73612a2 21 _VALID_URL_BASE = r'https?://shahid\.mbc\.net/[a-z]{2}/'
78466fca
RA
22
23 def _handle_error(self, e):
24 fail_data = self._parse_json(
3d2623a8 25 e.cause.response.read().decode('utf-8'), None, fatal=False)
78466fca
RA
26 if fail_data:
27 faults = fail_data.get('faults', [])
28 faults_message = ', '.join([clean_html(fault['userMessage']) for fault in faults if fault.get('userMessage')])
29 if faults_message:
30 raise ExtractorError(faults_message, expected=True)
31
32 def _call_api(self, path, video_id, request=None):
33 query = {}
34 if request:
35 query['request'] = json.dumps(request)
36 try:
37 return self._aws_execute_api({
38 'uri': '/proxy/v2/' + path,
39 'access_key': 'AKIAI6X4TYCIXM2B7MUQ',
40 'secret_key': '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',
41 }, video_id, query)
42 except ExtractorError as e:
3d2623a8 43 if isinstance(e.cause, HTTPError):
78466fca
RA
44 self._handle_error(e)
45 raise
46
47
48class ShahidIE(ShahidBaseIE):
3b4b66b5 49 _NETRC_MACHINE = 'shahid'
b73612a2 50 _VALID_URL = ShahidBaseIE._VALID_URL_BASE + r'(?:serie|show|movie)s/[^/]+/(?P<type>episode|clip|movie)-(?P<id>\d+)'
c576ef1e 51 _TESTS = [{
10db0d2f 52 'url': 'https://shahid.mbc.net/ar/shows/%D9%85%D8%AA%D8%AD%D9%81-%D8%A7%D9%84%D8%AF%D8%AD%D9%8A%D8%AD-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D9%83%D9%84%D9%8A%D8%A8-1/clip-816924',
c576ef1e 53 'info_dict': {
10db0d2f 54 'id': '816924',
5de5ab89 55 'ext': 'mp4',
10db0d2f 56 'title': 'متحف الدحيح الموسم 1 كليب 1',
57 'timestamp': 1602806400,
58 'upload_date': '20201016',
59 'description': 'برومو',
60 'duration': 22,
61 'categories': ['كوميديا'],
114ed20e 62 },
c576ef1e
S
63 'params': {
64 # m3u8 download
65 'skip_download': True,
114ed20e 66 }
3b4b66b5 67 }, {
414e7094 68 'url': 'https://shahid.mbc.net/ar/movies/%D8%A7%D9%84%D9%82%D9%86%D8%A7%D8%B5%D8%A9/movie-151746',
3b4b66b5 69 'only_matching': True
c576ef1e
S
70 }, {
71 # shahid plus subscriber only
414e7094 72 'url': 'https://shahid.mbc.net/ar/series/%D9%85%D8%B1%D8%A7%D9%8A%D8%A7-2011-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D8%A7%D9%84%D8%AD%D9%84%D9%82%D8%A9-1/episode-90511',
c576ef1e 73 'only_matching': True
b73612a2 74 }, {
75 'url': 'https://shahid.mbc.net/en/shows/Ramez-Fi-Al-Shallal-season-1-episode-1/episode-359319',
76 'only_matching': True
c576ef1e 77 }]
114ed20e 78
52efa4b3 79 def _perform_login(self, username, password):
78466fca
RA
80 try:
81 user_data = self._download_json(
82 'https://shahid.mbc.net/wd/service/users/login',
83 None, 'Logging in', data=json.dumps({
52efa4b3 84 'email': username,
78466fca
RA
85 'password': password,
86 'basic': 'false',
87 }).encode('utf-8'), headers={
88 'Content-Type': 'application/json; charset=UTF-8',
89 })['user']
90 except ExtractorError as e:
3d2623a8 91 if isinstance(e.cause, HTTPError):
78466fca
RA
92 self._handle_error(e)
93 raise
414e7094 94
3b4b66b5
RA
95 self._download_webpage(
96 'https://shahid.mbc.net/populateContext',
97 None, 'Populate Context', data=urlencode_postdata({
98 'firstName': user_data['firstName'],
99 'lastName': user_data['lastName'],
100 'userName': user_data['email'],
101 'csg_user_name': user_data['email'],
102 'subscriberId': user_data['id'],
103 'sessionId': user_data['sessionId'],
104 }))
105
114ed20e 106 def _real_extract(self, url):
5ad28e7f 107 page_type, video_id = self._match_valid_url(url).groups()
414e7094
RA
108 if page_type == 'clip':
109 page_type = 'episode'
c576ef1e 110
78466fca 111 playout = self._call_api(
10db0d2f 112 'playout/new/url/' + video_id, video_id)['playout']
a62fd1af 113
a06916d9 114 if not self.get_param('allow_unplayable_formats') and playout.get('drm'):
88acdbc2 115 self.report_drm(video_id)
2334762b 116
10db0d2f 117 formats = self._extract_m3u8_formats(re.sub(
118 # https://docs.aws.amazon.com/mediapackage/latest/ug/manifest-filtering.html
119 r'aws\.manifestfilter=[\w:;,-]+&?',
120 '', playout['url']), video_id, 'mp4')
3be3c622 121
78466fca
RA
122 # video = self._call_api(
123 # 'product/id', video_id, {
124 # 'id': video_id,
125 # 'productType': 'ASSET',
126 # 'productSubType': page_type.upper()
127 # })['productModel']
128
129 response = self._download_json(
3b4b66b5
RA
130 'http://api.shahid.net/api/v1_1/%s/%s' % (page_type, video_id),
131 video_id, 'Downloading video JSON', query={
132 'apiKey': 'sh@hid0nlin3',
133 'hash': 'b2wMCTHpSmyxGqQjJFOycRmLSex+BpTK/ooxy6vHaqs=',
78466fca
RA
134 })
135 data = response.get('data', {})
136 error = data.get('error')
137 if error:
138 raise ExtractorError(
139 '%s returned error: %s' % (self.IE_NAME, '\n'.join(error.values())),
140 expected=True)
c576ef1e 141
78466fca 142 video = data[page_type]
c576ef1e 143 title = video['title']
c576ef1e
S
144 categories = [
145 category['name']
146 for category in video.get('genres', []) if 'name' in category]
a62fd1af 147
114ed20e 148 return {
149 'id': video_id,
150 'title': title,
41aa4425
RA
151 'description': video.get('description'),
152 'thumbnail': video.get('thumbnailUrl'),
153 'duration': int_or_none(video.get('duration')),
154 'timestamp': parse_iso8601(video.get('referenceDate')),
c576ef1e 155 'categories': categories,
41aa4425
RA
156 'series': video.get('showTitle') or video.get('showName'),
157 'season': video.get('seasonTitle'),
158 'season_number': int_or_none(video.get('seasonNumber')),
159 'season_id': str_or_none(video.get('seasonId')),
160 'episode_number': int_or_none(video.get('number')),
161 'episode_id': video_id,
114ed20e 162 'formats': formats,
163 }
78466fca
RA
164
165
166class ShahidShowIE(ShahidBaseIE):
b73612a2 167 _VALID_URL = ShahidBaseIE._VALID_URL_BASE + r'(?:show|serie)s/[^/]+/(?:show|series)-(?P<id>\d+)'
78466fca
RA
168 _TESTS = [{
169 'url': 'https://shahid.mbc.net/ar/shows/%D8%B1%D8%A7%D9%85%D8%B2-%D9%82%D8%B1%D8%B4-%D8%A7%D9%84%D8%A8%D8%AD%D8%B1/show-79187',
170 'info_dict': {
171 'id': '79187',
172 'title': 'رامز قرش البحر',
173 'description': 'md5:c88fa7e0f02b0abd39d417aee0d046ff',
174 },
175 'playlist_mincount': 32,
176 }, {
177 'url': 'https://shahid.mbc.net/ar/series/How-to-live-Longer-(The-Big-Think)/series-291861',
178 'only_matching': True
179 }]
180 _PAGE_SIZE = 30
181
182 def _real_extract(self, url):
183 show_id = self._match_id(url)
184
185 product = self._call_api(
186 'playableAsset', show_id, {'showId': show_id})['productModel']
187 playlist = product['playlist']
188 playlist_id = playlist['id']
189 show = product.get('show', {})
190
191 def page_func(page_num):
192 playlist = self._call_api(
193 'product/playlist', show_id, {
194 'playListId': playlist_id,
195 'pageNumber': page_num,
196 'pageSize': 30,
197 'sorts': [{
198 'order': 'DESC',
199 'type': 'SORTDATE'
200 }],
201 })
202 for product in playlist.get('productList', {}).get('products', []):
203 product_url = product.get('productUrl', []).get('url')
204 if not product_url:
205 continue
206 yield self.url_result(
207 product_url, 'Shahid',
208 str_or_none(product.get('id')),
209 product.get('title'))
210
211 entries = InAdvancePagedList(
212 page_func,
213 math.ceil(playlist['count'] / self._PAGE_SIZE),
214 self._PAGE_SIZE)
215
216 return self.playlist_result(
217 entries, show_id, show.get('title'), show.get('description'))