[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / shahid.py
blobf0a3b6b7d7fb59267f99eccd65b561d618d291f1
1 import json
2 import math
3 import re
5 from .aws import AWSIE
6 from ..networking.exceptions import HTTPError
7 from ..utils import (
8 ExtractorError,
9 InAdvancePagedList,
10 clean_html,
11 int_or_none,
12 parse_iso8601,
13 str_or_none,
14 urlencode_postdata,
18 class ShahidBaseIE(AWSIE):
19 _AWS_PROXY_HOST = 'api2.shahid.net'
20 _AWS_API_KEY = '2RRtuMHx95aNI1Kvtn2rChEuwsCogUd4samGPjLh'
21 _VALID_URL_BASE = r'https?://shahid\.mbc\.net/[a-z]{2}/'
23 def _handle_error(self, e):
24 fail_data = self._parse_json(
25 e.cause.response.read().decode('utf-8'), None, fatal=False)
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)
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:
43 if isinstance(e.cause, HTTPError):
44 self._handle_error(e)
45 raise
48 class ShahidIE(ShahidBaseIE):
49 _NETRC_MACHINE = 'shahid'
50 _VALID_URL = ShahidBaseIE._VALID_URL_BASE + r'(?:serie|show|movie)s/[^/]+/(?P<type>episode|clip|movie)-(?P<id>\d+)'
51 _TESTS = [{
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',
53 'info_dict': {
54 'id': '816924',
55 'ext': 'mp4',
56 'title': 'متحف الدحيح الموسم 1 كليب 1',
57 'timestamp': 1602806400,
58 'upload_date': '20201016',
59 'description': 'برومو',
60 'duration': 22,
61 'categories': ['كوميديا'],
63 'params': {
64 # m3u8 download
65 'skip_download': True,
67 }, {
68 'url': 'https://shahid.mbc.net/ar/movies/%D8%A7%D9%84%D9%82%D9%86%D8%A7%D8%B5%D8%A9/movie-151746',
69 'only_matching': True,
70 }, {
71 # shahid plus subscriber only
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',
73 'only_matching': True,
74 }, {
75 'url': 'https://shahid.mbc.net/en/shows/Ramez-Fi-Al-Shallal-season-1-episode-1/episode-359319',
76 'only_matching': True,
79 def _perform_login(self, username, password):
80 try:
81 user_data = self._download_json(
82 'https://shahid.mbc.net/wd/service/users/login',
83 None, 'Logging in', data=json.dumps({
84 'email': username,
85 'password': password,
86 'basic': 'false',
87 }).encode(), headers={
88 'Content-Type': 'application/json; charset=UTF-8',
89 })['user']
90 except ExtractorError as e:
91 if isinstance(e.cause, HTTPError):
92 self._handle_error(e)
93 raise
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'],
106 def _real_extract(self, url):
107 page_type, video_id = self._match_valid_url(url).groups()
108 if page_type == 'clip':
109 page_type = 'episode'
111 playout = self._call_api(
112 'playout/new/url/' + video_id, video_id)['playout']
114 if not self.get_param('allow_unplayable_formats') and playout.get('drm'):
115 self.report_drm(video_id)
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')
122 # video = self._call_api(
123 # 'product/id', video_id, {
124 # 'id': video_id,
125 # 'productType': 'ASSET',
126 # 'productSubType': page_type.upper()
127 # })['productModel']
129 response = self._download_json(
130 f'http://api.shahid.net/api/v1_1/{page_type}/{video_id}',
131 video_id, 'Downloading video JSON', query={
132 'apiKey': 'sh@hid0nlin3',
133 'hash': 'b2wMCTHpSmyxGqQjJFOycRmLSex+BpTK/ooxy6vHaqs=',
135 data = response.get('data', {})
136 error = data.get('error')
137 if error:
138 raise ExtractorError(
139 '{} returned error: {}'.format(self.IE_NAME, '\n'.join(error.values())),
140 expected=True)
142 video = data[page_type]
143 title = video['title']
144 categories = [
145 category['name']
146 for category in video.get('genres', []) if 'name' in category]
148 return {
149 'id': video_id,
150 'title': title,
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')),
155 'categories': categories,
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,
162 'formats': formats,
166 class ShahidShowIE(ShahidBaseIE):
167 _VALID_URL = ShahidBaseIE._VALID_URL_BASE + r'(?:show|serie)s/[^/]+/(?:show|series)-(?P<id>\d+)'
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',
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,
180 _PAGE_SIZE = 30
182 def _real_extract(self, url):
183 show_id = self._match_id(url)
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', {})
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',
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'))
211 entries = InAdvancePagedList(
212 page_func,
213 math.ceil(playlist['count'] / self._PAGE_SIZE),
214 self._PAGE_SIZE)
216 return self.playlist_result(
217 entries, show_id, show.get('title'), show.get('description'))