fc2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import re
  2. from .common import InfoExtractor
  3. from ..compat import compat_parse_qs
  4. from ..dependencies import websockets
  5. from ..utils import (
  6. ExtractorError,
  7. WebSocketsWrapper,
  8. js_to_json,
  9. sanitized_Request,
  10. traverse_obj,
  11. update_url_query,
  12. urlencode_postdata,
  13. urljoin,
  14. )
  15. class FC2IE(InfoExtractor):
  16. _VALID_URL = r'^(?:https?://video\.fc2\.com/(?:[^/]+/)*content/|fc2:)(?P<id>[^/]+)'
  17. IE_NAME = 'fc2'
  18. _NETRC_MACHINE = 'fc2'
  19. _TESTS = [{
  20. 'url': 'http://video.fc2.com/en/content/20121103kUan1KHs',
  21. 'md5': 'a6ebe8ebe0396518689d963774a54eb7',
  22. 'info_dict': {
  23. 'id': '20121103kUan1KHs',
  24. 'ext': 'flv',
  25. 'title': 'Boxing again with Puff',
  26. },
  27. }, {
  28. 'url': 'http://video.fc2.com/en/content/20150125cEva0hDn/',
  29. 'info_dict': {
  30. 'id': '20150125cEva0hDn',
  31. 'ext': 'mp4',
  32. },
  33. 'params': {
  34. 'username': 'ytdl@yt-dl.org',
  35. 'password': '(snip)',
  36. },
  37. 'skip': 'requires actual password',
  38. }, {
  39. 'url': 'http://video.fc2.com/en/a/content/20130926eZpARwsF',
  40. 'only_matching': True,
  41. }]
  42. def _login(self):
  43. username, password = self._get_login_info()
  44. if username is None or password is None:
  45. return False
  46. # Log in
  47. login_form_strs = {
  48. 'email': username,
  49. 'password': password,
  50. 'done': 'video',
  51. 'Submit': ' Login ',
  52. }
  53. login_data = urlencode_postdata(login_form_strs)
  54. request = sanitized_Request(
  55. 'https://secure.id.fc2.com/index.php?mode=login&switch_language=en', login_data)
  56. login_results = self._download_webpage(request, None, note='Logging in', errnote='Unable to log in')
  57. if 'mode=redirect&login=done' not in login_results:
  58. self.report_warning('unable to log in: bad username or password')
  59. return False
  60. # this is also needed
  61. login_redir = sanitized_Request('http://id.fc2.com/?mode=redirect&login=done')
  62. self._download_webpage(
  63. login_redir, None, note='Login redirect', errnote='Login redirect failed')
  64. return True
  65. def _real_extract(self, url):
  66. video_id = self._match_id(url)
  67. self._login()
  68. webpage = None
  69. if not url.startswith('fc2:'):
  70. webpage = self._download_webpage(url, video_id)
  71. self.cookiejar.clear_session_cookies() # must clear
  72. self._login()
  73. title, thumbnail, description = None, None, None
  74. if webpage is not None:
  75. title = self._html_search_regex(
  76. (r'<h2\s+class="videoCnt_title">([^<]+?)</h2>',
  77. r'\s+href="[^"]+"\s*title="([^"]+?)"\s*rel="nofollow">\s*<img',
  78. # there's two matches in the webpage
  79. r'\s+href="[^"]+"\s*title="([^"]+?)"\s*rel="nofollow">\s*\1'),
  80. webpage,
  81. 'title', fatal=False)
  82. thumbnail = self._og_search_thumbnail(webpage)
  83. description = self._og_search_description(webpage, default=None)
  84. vidplaylist = self._download_json(
  85. 'https://video.fc2.com/api/v3/videoplaylist/%s?sh=1&fs=0' % video_id, video_id,
  86. note='Downloading info page')
  87. vid_url = traverse_obj(vidplaylist, ('playlist', 'nq'))
  88. if not vid_url:
  89. raise ExtractorError('Unable to extract video URL')
  90. vid_url = urljoin('https://video.fc2.com/', vid_url)
  91. return {
  92. 'id': video_id,
  93. 'title': title,
  94. 'url': vid_url,
  95. 'ext': 'mp4',
  96. 'protocol': 'm3u8_native',
  97. 'description': description,
  98. 'thumbnail': thumbnail,
  99. }
  100. class FC2EmbedIE(InfoExtractor):
  101. _VALID_URL = r'https?://video\.fc2\.com/flv2\.swf\?(?P<query>.+)'
  102. IE_NAME = 'fc2:embed'
  103. _TEST = {
  104. 'url': 'http://video.fc2.com/flv2.swf?t=201404182936758512407645&i=20130316kwishtfitaknmcgd76kjd864hso93htfjcnaogz629mcgfs6rbfk0hsycma7shkf85937cbchfygd74&i=201403223kCqB3Ez&d=2625&sj=11&lang=ja&rel=1&from=11&cmt=1&tk=TlRBM09EQTNNekU9&tl=プリズン・ブレイク%20S1-01%20マイケル%20【吹替】',
  105. 'md5': 'b8aae5334cb691bdb1193a88a6ab5d5a',
  106. 'info_dict': {
  107. 'id': '201403223kCqB3Ez',
  108. 'ext': 'flv',
  109. 'title': 'プリズン・ブレイク S1-01 マイケル 【吹替】',
  110. 'thumbnail': r're:^https?://.*\.jpg$',
  111. },
  112. }
  113. def _real_extract(self, url):
  114. mobj = self._match_valid_url(url)
  115. query = compat_parse_qs(mobj.group('query'))
  116. video_id = query['i'][-1]
  117. title = query.get('tl', ['FC2 video %s' % video_id])[0]
  118. sj = query.get('sj', [None])[0]
  119. thumbnail = None
  120. if sj:
  121. # See thumbnailImagePath() in ServerConst.as of flv2.swf
  122. thumbnail = 'http://video%s-thumbnail.fc2.com/up/pic/%s.jpg' % (
  123. sj, '/'.join((video_id[:6], video_id[6:8], video_id[-2], video_id[-1], video_id)))
  124. return {
  125. '_type': 'url_transparent',
  126. 'ie_key': FC2IE.ie_key(),
  127. 'url': 'fc2:%s' % video_id,
  128. 'title': title,
  129. 'thumbnail': thumbnail,
  130. }
  131. class FC2LiveIE(InfoExtractor):
  132. _VALID_URL = r'https?://live\.fc2\.com/(?P<id>\d+)'
  133. IE_NAME = 'fc2:live'
  134. _TESTS = [{
  135. 'url': 'https://live.fc2.com/57892267/',
  136. 'info_dict': {
  137. 'id': '57892267',
  138. 'title': 'どこまで・・・',
  139. 'uploader': 'あつあげ',
  140. 'uploader_id': '57892267',
  141. 'thumbnail': r're:https?://.+fc2.+',
  142. },
  143. 'skip': 'livestream',
  144. }]
  145. def _real_extract(self, url):
  146. if not websockets:
  147. raise ExtractorError('websockets library is not available. Please install it.', expected=True)
  148. video_id = self._match_id(url)
  149. webpage = self._download_webpage('https://live.fc2.com/%s/' % video_id, video_id)
  150. self._set_cookie('live.fc2.com', 'js-player_size', '1')
  151. member_api = self._download_json(
  152. 'https://live.fc2.com/api/memberApi.php', video_id, data=urlencode_postdata({
  153. 'channel': '1',
  154. 'profile': '1',
  155. 'user': '1',
  156. 'streamid': video_id
  157. }), note='Requesting member info')
  158. control_server = self._download_json(
  159. 'https://live.fc2.com/api/getControlServer.php', video_id, note='Downloading ControlServer data',
  160. data=urlencode_postdata({
  161. 'channel_id': video_id,
  162. 'mode': 'play',
  163. 'orz': '',
  164. 'channel_version': member_api['data']['channel_data']['version'],
  165. 'client_version': '2.1.0\n [1]',
  166. 'client_type': 'pc',
  167. 'client_app': 'browser_hls',
  168. 'ipv6': '',
  169. }), headers={'X-Requested-With': 'XMLHttpRequest'})
  170. self._set_cookie('live.fc2.com', 'l_ortkn', control_server['orz_raw'])
  171. ws_url = update_url_query(control_server['url'], {'control_token': control_server['control_token']})
  172. playlist_data = None
  173. self.to_screen('%s: Fetching HLS playlist info via WebSocket' % video_id)
  174. ws = WebSocketsWrapper(ws_url, {
  175. 'Cookie': str(self._get_cookies('https://live.fc2.com/'))[12:],
  176. 'Origin': 'https://live.fc2.com',
  177. 'Accept': '*/*',
  178. 'User-Agent': self.get_param('http_headers')['User-Agent'],
  179. })
  180. self.write_debug('Sending HLS server request')
  181. while True:
  182. recv = ws.recv()
  183. if not recv:
  184. continue
  185. data = self._parse_json(recv, video_id, fatal=False)
  186. if not data or not isinstance(data, dict):
  187. continue
  188. if data.get('name') == 'connect_complete':
  189. break
  190. ws.send(r'{"name":"get_hls_information","arguments":{},"id":1}')
  191. while True:
  192. recv = ws.recv()
  193. if not recv:
  194. continue
  195. data = self._parse_json(recv, video_id, fatal=False)
  196. if not data or not isinstance(data, dict):
  197. continue
  198. if data.get('name') == '_response_' and data.get('id') == 1:
  199. self.write_debug('Goodbye')
  200. playlist_data = data
  201. break
  202. self.write_debug('Server said: %s%s' % (recv[:100], '...' if len(recv) > 100 else ''))
  203. if not playlist_data:
  204. raise ExtractorError('Unable to fetch HLS playlist info via WebSocket')
  205. formats = []
  206. for name, playlists in playlist_data['arguments'].items():
  207. if not isinstance(playlists, list):
  208. continue
  209. for pl in playlists:
  210. if pl.get('status') == 0 and 'master_playlist' in pl.get('url'):
  211. formats.extend(self._extract_m3u8_formats(
  212. pl['url'], video_id, ext='mp4', m3u8_id=name, live=True,
  213. headers={
  214. 'Origin': 'https://live.fc2.com',
  215. 'Referer': url,
  216. }))
  217. for fmt in formats:
  218. fmt.update({
  219. 'protocol': 'fc2_live',
  220. 'ws': ws,
  221. })
  222. title = self._html_search_meta(('og:title', 'twitter:title'), webpage, 'live title', fatal=False)
  223. if not title:
  224. title = self._html_extract_title(webpage, 'html title', fatal=False)
  225. if title:
  226. # remove service name in <title>
  227. title = re.sub(r'\s+-\s+.+$', '', title)
  228. uploader = None
  229. if title:
  230. match = self._search_regex(r'^(.+?)\s*\[(.+?)\]$', title, 'title and uploader', default=None, group=(1, 2))
  231. if match and all(match):
  232. title, uploader = match
  233. live_info_view = self._search_regex(r'(?s)liveInfoView\s*:\s*({.+?}),\s*premiumStateView', webpage, 'user info', fatal=False) or None
  234. if live_info_view:
  235. # remove jQuery code from object literal
  236. live_info_view = re.sub(r'\$\(.+?\)[^,]+,', '"",', live_info_view)
  237. live_info_view = self._parse_json(js_to_json(live_info_view), video_id)
  238. return {
  239. 'id': video_id,
  240. 'title': title or traverse_obj(live_info_view, 'title'),
  241. 'description': self._html_search_meta(
  242. ('og:description', 'twitter:description'),
  243. webpage, 'live description', fatal=False) or traverse_obj(live_info_view, 'info'),
  244. 'formats': formats,
  245. 'uploader': uploader or traverse_obj(live_info_view, 'name'),
  246. 'uploader_id': video_id,
  247. 'thumbnail': traverse_obj(live_info_view, 'thumb'),
  248. 'is_live': True,
  249. }