[hketv] Add extractor
[youtube-dl] / youtube_dl / extractor / hketv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from .common import InfoExtractor
5 from ..compat import compat_str
6 from ..utils import (
7     clean_html,
8     ExtractorError,
9     int_or_none,
10     merge_dicts,
11     str_or_none,
12     str_to_int,
13     try_get,
14     unified_strdate,
15     urlencode_postdata,
16     urljoin,
17 )
18
19
20 class HKETVIE(InfoExtractor):
21     IE_NAME = 'hketv'
22     IE_DESC = '香港教育局教育電視 (HKETV) Educational Television, Hong Kong Educational Bureau'
23     _GEO_BYPASS = False
24     _GEO_COUNTRIES = ['HK']
25     _VALID_URL = r'https?://(?:www\.)?hkedcity\.net/etv/resource/(?P<id>[0-9]+)'
26     _TESTS = [{
27         'url': 'https://www.hkedcity.net/etv/resource/2932360618',
28         'md5': 'f193712f5f7abb208ddef3c5ea6ed0b7',
29         'info_dict': {
30             'id': '2932360618',
31             'ext': 'mp4',
32             'title': '喜閱一生(共享閱讀樂) (中、英文字幕可供選擇)',
33             'description': '本節目輯錄了「閱讀滿Fun嘉年華」和「二○一八響應世界閱讀日――悅愛閱讀・愈讀愈愛」的活動花絮,並由學者、作家、演藝界人士等,分享培養子女閱讀興趣和習慣的方法,以及呼籲大家一同分享閱讀的樂趣。',
34             'upload_date': '20181024',
35             'duration': 900,
36             'subtitles': {
37                 'en': [{
38                     'url': 'https://apps.hkedcity.net/media/mediaplayer/caption.php?f=74395&lang=en',
39                     'ext': 'srt',
40                 }],
41                 'zh-Hant': [{
42                     'url': 'https://apps.hkedcity.net/media/mediaplayer/caption.php?f=74395&lang=qmt',
43                     'ext': 'srt',
44                 }],
45             }
46         },
47     }, {
48         'url': 'https://www.hkedcity.net/etv/resource/972641418',
49         'md5': '1ed494c1c6cf7866a8290edad9b07dc9',
50         'info_dict': {
51             'id': '972641418',
52             'ext': 'mp4',
53             'title': '衣冠楚楚 (天使系列之一)',
54             'description': '天國仙境,有兩位可愛的天使小姐妹。她們對幾千年來天使衣著一成不變頗有不滿。她們下望人世間:只見人們穿著七彩繽紛、款式各異的服裝,漂亮極了。天使姐妹決定下凡考察衣著,以設計天使新裝。  下到人間,姐妹試穿各式各樣的衣著,引發連串奇特有趣的情節:她們穿著校服在街上閒逛時,被女警誤認為逃學而送回學校,到校後又被體育老師誤認為是新同學,匆匆忙忙換上運動服後在操場上大顯神通。她們穿著護士服在醫院散步時,又被誤認為當班護士,而投入追尋失蹤病童、治病救人的工作中去。姐妹倆還到過玩具店,與布娃娃們談論衣著。她們也去過服裝設計學校,被當成小模特兒而試穿各式服裝。最令姐妹倆興奮的是一場盛大的民族服裝表演會。身穿盛裝的十二個民族的少女在台上翩翩起舞,各種服飾七彩繽紛、美不勝收。姐妹們情不自禁地穿上民族服裝,小天使變成了少數民族姑娘……最後天使姐妹回到天上,對於天使究竟穿甚麼樣的衣服好,她們還是拿不定主意。  節目通過天使姐妹的奇特經歷,反復示範各式衣服鞋襪的正確讀音及談論衣著時的常用句式,並以盛大的民族服裝表演活動,帶出有關服裝的文化知識。內容豐富而饒有趣味。',
55             'upload_date': '20070109',
56             'duration': 907,
57             'subtitles': {},
58         },
59     }]
60
61     _CC_LANGS = {
62         '中文(繁體中文)': 'zh-Hant',
63         '中文(简体中文)': 'zh-Hans',
64         'English': 'en',
65         'Bahasa Indonesia': 'id',
66         '\u0939\u093f\u0928\u094d\u0926\u0940': 'hi',
67         '\u0928\u0947\u092a\u093e\u0932\u0940': 'ne',
68         'Tagalog': 'tl',
69         '\u0e44\u0e17\u0e22': 'th',
70         '\u0627\u0631\u062f\u0648': 'ur',
71     }
72
73     def _real_extract(self, url):
74         video_id = self._match_id(url)
75         webpage = self._download_webpage(url, video_id)
76         title = self._html_search_meta('ed_title', webpage, fatal=True)
77
78         file_id = self._html_search_regex(r'post_var\["file_id"\]\s*=\s*(.+?);', webpage, 'file ID')
79         curr_url = self._html_search_regex(r'post_var\["curr_url"\]\s*=\s*"(.+?)";', webpage, 'curr URL')
80         data = {
81             'action': 'get_info',
82             'curr_url': curr_url,
83             'file_id': file_id,
84             'video_url': file_id,
85         }
86         _APPS_BASE_URL = 'https://apps.hkedcity.net'
87         handler_url = _APPS_BASE_URL + '/media/play/handler.php'
88
89         response = self._download_json(
90             handler_url, video_id,
91             data=urlencode_postdata(data),
92             headers=merge_dicts({'Content-Type': 'application/x-www-form-urlencoded'},
93                                 self.geo_verification_headers()))
94
95         result = response['result']
96
97         formats = []
98         subtitles = {}
99
100         if response.get('success') and response.get('access'):
101             width = int_or_none(result.get('width'))
102             height = int_or_none(result.get('height'))
103
104             playlist0 = try_get(result, lambda x: x['playlist'][0], dict)
105             fmts = playlist0.get('sources')
106             for fmt in fmts:
107                 file_path = fmt.get('file')
108                 if file_path:
109                     file_url = urljoin(_APPS_BASE_URL, file_path)
110                     # If we ever wanted to provide the final resolved URL that
111                     # does not require cookies, albeit with a shorter lifespan:
112                     #     urlh = self._downloader.urlopen(file_url)
113                     #     resolved_url = urlh.geturl()
114
115                     label = fmt.get('label')
116                     w = None
117                     h = None
118                     if label == 'HD':
119                         h = 720
120                     elif label == 'SD':
121                         h = 360
122                     if h:
123                         if width and height:
124                             w = h * width // height
125                         else:
126                             w = h * 4 // 3
127
128                     formats.append({
129                         'format_id': label,
130                         'ext': fmt.get('type'),
131                         'url': file_url,
132                         'width': w,
133                         'height': h,
134                     })
135
136             tracks = playlist0.get('tracks', [])
137             for track in tracks:
138                 if not isinstance(track, dict):
139                     continue
140                 track_kind = str_or_none(track.get('kind'))
141                 if not track_kind or not isinstance(track_kind, compat_str):
142                     continue
143                 if track_kind.lower() not in ('captions', 'subtitles'):
144                     continue
145                 track_url = urljoin(_APPS_BASE_URL, track.get('file'))
146                 if not track_url:
147                     continue
148                 track_label = track.get('label')
149                 subtitles.setdefault(self._CC_LANGS.get(track_label, track_label), []).append({
150                     'url': self._proto_relative_url(track_url),
151                     'ext': 'srt',
152                 })
153
154         else:
155             error = clean_html(response.get('access_err_msg'))
156             if 'Video streaming is not available in your country' in error:
157                 self.raise_geo_restricted(msg=error, countries=self._GEO_COUNTRIES)
158             else:
159                 raise ExtractorError(error)
160
161         # Likes
162         emotion = self._download_json(
163             'https://emocounter.hkedcity.net/handler.php',
164             video_id,
165             data=urlencode_postdata({
166                 'action': 'get_emotion',
167                 'data[bucket_id]': 'etv',
168                 'data[identifier]': video_id,
169             }),
170             headers={'Content-Type': 'application/x-www-form-urlencoded'},
171             fatal=False)
172         like_count = int_or_none(try_get(emotion, lambda x: x['data']['emotion_data'][0]['count']))
173
174         return {
175             'id': video_id,
176             'title': title,
177             'description': self._html_search_meta('description', webpage, fatal=False),
178             'upload_date': unified_strdate(self._html_search_meta('ed_date', webpage, fatal=False), day_first=False),
179             'duration': int_or_none(result.get('length')),
180             'formats': formats,
181             'subtitles': subtitles,
182             'thumbnail': urljoin(_APPS_BASE_URL, result.get('image')),
183             'view_count': str_to_int(result.get('view_count')),
184             'like_count': like_count,
185         }