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