smotri.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # encoding: utf-8
  2. import os.path
  3. import re
  4. import json
  5. import hashlib
  6. import uuid
  7. from .common import InfoExtractor
  8. from ..utils import (
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. ExtractorError,
  12. url_basename,
  13. )
  14. class SmotriIE(InfoExtractor):
  15. IE_DESC = u'Smotri.com'
  16. IE_NAME = u'smotri'
  17. _VALID_URL = r'^https?://(?:www\.)?(?P<url>smotri\.com/video/view/\?id=(?P<videoid>v(?P<realvideoid>[0-9]+)[a-z0-9]{4}))'
  18. _TESTS = [
  19. # real video id 2610366
  20. {
  21. u'url': u'http://smotri.com/video/view/?id=v261036632ab',
  22. u'file': u'v261036632ab.mp4',
  23. u'md5': u'2a7b08249e6f5636557579c368040eb9',
  24. u'info_dict': {
  25. u'title': u'катастрофа с камер видеонаблюдения',
  26. u'uploader': u'rbc2008',
  27. u'uploader_id': u'rbc08',
  28. u'upload_date': u'20131118',
  29. u'description': u'катастрофа с камер видеонаблюдения, видео катастрофа с камер видеонаблюдения',
  30. u'thumbnail': u'http://frame6.loadup.ru/8b/a9/2610366.3.3.jpg',
  31. },
  32. },
  33. # real video id 57591
  34. {
  35. u'url': u'http://smotri.com/video/view/?id=v57591cb20',
  36. u'file': u'v57591cb20.flv',
  37. u'md5': u'830266dfc21f077eac5afd1883091bcd',
  38. u'info_dict': {
  39. u'title': u'test',
  40. u'uploader': u'Support Photofile@photofile',
  41. u'uploader_id': u'support-photofile',
  42. u'upload_date': u'20070704',
  43. u'description': u'test, видео test',
  44. u'thumbnail': u'http://frame4.loadup.ru/03/ed/57591.2.3.jpg',
  45. },
  46. },
  47. # video-password
  48. {
  49. u'url': u'http://smotri.com/video/view/?id=v1390466a13c',
  50. u'file': u'v1390466a13c.mp4',
  51. u'md5': u'f6331cef33cad65a0815ee482a54440b',
  52. u'info_dict': {
  53. u'title': u'TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1',
  54. u'uploader': u'timoxa40',
  55. u'uploader_id': u'timoxa40',
  56. u'upload_date': u'20100404',
  57. u'thumbnail': u'http://frame7.loadup.ru/af/3f/1390466.3.3.jpg',
  58. u'description': u'TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1, видео TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1',
  59. },
  60. u'params': {
  61. u'videopassword': u'qwerty',
  62. },
  63. },
  64. # age limit + video-password
  65. {
  66. u'url': u'http://smotri.com/video/view/?id=v15408898bcf',
  67. u'file': u'v15408898bcf.flv',
  68. u'md5': u'91e909c9f0521adf5ee86fbe073aad70',
  69. u'info_dict': {
  70. u'title': u'этот ролик не покажут по ТВ',
  71. u'uploader': u'zzxxx',
  72. u'uploader_id': u'ueggb',
  73. u'upload_date': u'20101001',
  74. u'thumbnail': u'http://frame3.loadup.ru/75/75/1540889.1.3.jpg',
  75. u'age_limit': 18,
  76. u'description': u'этот ролик не покажут по ТВ, видео этот ролик не покажут по ТВ',
  77. },
  78. u'params': {
  79. u'videopassword': u'333'
  80. }
  81. }
  82. ]
  83. _SUCCESS = 0
  84. _PASSWORD_NOT_VERIFIED = 1
  85. _PASSWORD_DETECTED = 2
  86. _VIDEO_NOT_FOUND = 3
  87. def _search_meta(self, name, html, display_name=None):
  88. if display_name is None:
  89. display_name = name
  90. return self._html_search_regex(
  91. r'<meta itemprop="%s" content="([^"]+)" />' % re.escape(name),
  92. html, display_name, fatal=False)
  93. return self._html_search_meta(name, html, display_name)
  94. def _real_extract(self, url):
  95. mobj = re.match(self._VALID_URL, url)
  96. video_id = mobj.group('videoid')
  97. real_video_id = mobj.group('realvideoid')
  98. # Download video JSON data
  99. video_json_url = 'http://smotri.com/vt.php?id=%s' % real_video_id
  100. video_json_page = self._download_webpage(video_json_url, video_id, u'Downloading video JSON')
  101. video_json = json.loads(video_json_page)
  102. status = video_json['status']
  103. if status == self._VIDEO_NOT_FOUND:
  104. raise ExtractorError(u'Video %s does not exist' % video_id, expected=True)
  105. elif status == self._PASSWORD_DETECTED: # The video is protected by a password, retry with
  106. # video-password set
  107. video_password = self._downloader.params.get('videopassword', None)
  108. if not video_password:
  109. raise ExtractorError(u'This video is protected by a password, use the --video-password option', expected=True)
  110. video_json_url += '&md5pass=%s' % hashlib.md5(video_password.encode('utf-8')).hexdigest()
  111. video_json_page = self._download_webpage(video_json_url, video_id, u'Downloading video JSON (video-password set)')
  112. video_json = json.loads(video_json_page)
  113. status = video_json['status']
  114. if status == self._PASSWORD_NOT_VERIFIED:
  115. raise ExtractorError(u'Video password is invalid', expected=True)
  116. if status != self._SUCCESS:
  117. raise ExtractorError(u'Unexpected status value %s' % status)
  118. # Extract the URL of the video
  119. video_url = video_json['file_data']
  120. # Video JSON does not provide enough meta data
  121. # We will extract some from the video web page instead
  122. video_page_url = 'http://' + mobj.group('url')
  123. video_page = self._download_webpage(video_page_url, video_id, u'Downloading video page')
  124. # Warning if video is unavailable
  125. warning = self._html_search_regex(
  126. r'<div class="videoUnModer">(.*?)</div>', video_page,
  127. u'warning message', default=None)
  128. if warning is not None:
  129. self._downloader.report_warning(
  130. u'Video %s may not be available; smotri said: %s ' %
  131. (video_id, warning))
  132. # Adult content
  133. if re.search(u'EroConfirmText">', video_page) is not None:
  134. self.report_age_confirmation()
  135. confirm_string = self._html_search_regex(
  136. r'<a href="/video/view/\?id=%s&confirm=([^"]+)" title="[^"]+">' % video_id,
  137. video_page, u'confirm string')
  138. confirm_url = video_page_url + '&confirm=%s' % confirm_string
  139. video_page = self._download_webpage(confirm_url, video_id, u'Downloading video page (age confirmed)')
  140. adult_content = True
  141. else:
  142. adult_content = False
  143. # Extract the rest of meta data
  144. video_title = self._search_meta(u'name', video_page, u'title')
  145. if not video_title:
  146. video_title = os.path.splitext(url_basename(video_url))[0]
  147. video_description = self._search_meta(u'description', video_page)
  148. END_TEXT = u' на сайте Smotri.com'
  149. if video_description and video_description.endswith(END_TEXT):
  150. video_description = video_description[:-len(END_TEXT)]
  151. START_TEXT = u'Смотреть онлайн ролик '
  152. if video_description and video_description.startswith(START_TEXT):
  153. video_description = video_description[len(START_TEXT):]
  154. video_thumbnail = self._search_meta(u'thumbnail', video_page)
  155. upload_date_str = self._search_meta(u'uploadDate', video_page, u'upload date')
  156. if upload_date_str:
  157. upload_date_m = re.search(r'(?P<year>\d{4})\.(?P<month>\d{2})\.(?P<day>\d{2})T', upload_date_str)
  158. video_upload_date = (
  159. (
  160. upload_date_m.group('year') +
  161. upload_date_m.group('month') +
  162. upload_date_m.group('day')
  163. )
  164. if upload_date_m else None
  165. )
  166. else:
  167. video_upload_date = None
  168. duration_str = self._search_meta(u'duration', video_page)
  169. if duration_str:
  170. duration_m = re.search(r'T(?P<hours>[0-9]{2})H(?P<minutes>[0-9]{2})M(?P<seconds>[0-9]{2})S', duration_str)
  171. video_duration = (
  172. (
  173. (int(duration_m.group('hours')) * 60 * 60) +
  174. (int(duration_m.group('minutes')) * 60) +
  175. int(duration_m.group('seconds'))
  176. )
  177. if duration_m else None
  178. )
  179. else:
  180. video_duration = None
  181. video_uploader = self._html_search_regex(
  182. u'<div class="DescrUser"><div>Автор.*?onmouseover="popup_user_info[^"]+">(.*?)</a>',
  183. video_page, u'uploader', fatal=False, flags=re.MULTILINE|re.DOTALL)
  184. video_uploader_id = self._html_search_regex(
  185. u'<div class="DescrUser"><div>Автор.*?onmouseover="popup_user_info\\(.*?\'([^\']+)\'\\);">',
  186. video_page, u'uploader id', fatal=False, flags=re.MULTILINE|re.DOTALL)
  187. video_view_count = self._html_search_regex(
  188. u'Общее количество просмотров.*?<span class="Number">(\\d+)</span>',
  189. video_page, u'view count', fatal=False, flags=re.MULTILINE|re.DOTALL)
  190. return {
  191. 'id': video_id,
  192. 'url': video_url,
  193. 'title': video_title,
  194. 'thumbnail': video_thumbnail,
  195. 'description': video_description,
  196. 'uploader': video_uploader,
  197. 'upload_date': video_upload_date,
  198. 'uploader_id': video_uploader_id,
  199. 'duration': video_duration,
  200. 'view_count': video_view_count,
  201. 'age_limit': 18 if adult_content else 0,
  202. 'video_page_url': video_page_url
  203. }
  204. class SmotriCommunityIE(InfoExtractor):
  205. IE_DESC = u'Smotri.com community videos'
  206. IE_NAME = u'smotri:community'
  207. _VALID_URL = r'^https?://(?:www\.)?smotri\.com/community/video/(?P<communityid>[0-9A-Za-z_\'-]+)'
  208. def _real_extract(self, url):
  209. mobj = re.match(self._VALID_URL, url)
  210. community_id = mobj.group('communityid')
  211. url = 'http://smotri.com/export/rss/video/by/community/-/%s/video.xml' % community_id
  212. rss = self._download_xml(url, community_id, u'Downloading community RSS')
  213. entries = [self.url_result(video_url.text, 'Smotri')
  214. for video_url in rss.findall('./channel/item/link')]
  215. description_text = rss.find('./channel/description').text
  216. community_title = self._html_search_regex(
  217. u'^Видео сообщества "([^"]+)"$', description_text, u'community title')
  218. return self.playlist_result(entries, community_id, community_title)
  219. class SmotriUserIE(InfoExtractor):
  220. IE_DESC = u'Smotri.com user videos'
  221. IE_NAME = u'smotri:user'
  222. _VALID_URL = r'^https?://(?:www\.)?smotri\.com/user/(?P<userid>[0-9A-Za-z_\'-]+)'
  223. def _real_extract(self, url):
  224. mobj = re.match(self._VALID_URL, url)
  225. user_id = mobj.group('userid')
  226. url = 'http://smotri.com/export/rss/user/video/-/%s/video.xml' % user_id
  227. rss = self._download_xml(url, user_id, u'Downloading user RSS')
  228. entries = [self.url_result(video_url.text, 'Smotri')
  229. for video_url in rss.findall('./channel/item/link')]
  230. description_text = rss.find('./channel/description').text
  231. user_nickname = self._html_search_regex(
  232. u'^Видео режиссера (.*)$', description_text,
  233. u'user nickname')
  234. return self.playlist_result(entries, user_id, user_nickname)
  235. class SmotriBroadcastIE(InfoExtractor):
  236. IE_DESC = u'Smotri.com broadcasts'
  237. IE_NAME = u'smotri:broadcast'
  238. _VALID_URL = r'^https?://(?:www\.)?(?P<url>smotri\.com/live/(?P<broadcastid>[^/]+))/?.*'
  239. def _real_extract(self, url):
  240. mobj = re.match(self._VALID_URL, url)
  241. broadcast_id = mobj.group('broadcastid')
  242. broadcast_url = 'http://' + mobj.group('url')
  243. broadcast_page = self._download_webpage(broadcast_url, broadcast_id, u'Downloading broadcast page')
  244. if re.search(u'>Режиссер с логином <br/>"%s"<br/> <span>не существует<' % broadcast_id, broadcast_page) is not None:
  245. raise ExtractorError(u'Broadcast %s does not exist' % broadcast_id, expected=True)
  246. # Adult content
  247. if re.search(u'EroConfirmText">', broadcast_page) is not None:
  248. (username, password) = self._get_login_info()
  249. if username is None:
  250. raise ExtractorError(u'Erotic broadcasts allowed only for registered users, '
  251. u'use --username and --password options to provide account credentials.', expected=True)
  252. # Log in
  253. login_form_strs = {
  254. u'login-hint53': '1',
  255. u'confirm_erotic': '1',
  256. u'login': username,
  257. u'password': password,
  258. }
  259. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  260. # chokes on unicode
  261. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  262. login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
  263. login_url = broadcast_url + '/?no_redirect=1'
  264. request = compat_urllib_request.Request(login_url, login_data)
  265. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  266. broadcast_page = self._download_webpage(
  267. request, broadcast_id, note=u'Logging in and confirming age')
  268. if re.search(u'>Неверный логин или пароль<', broadcast_page) is not None:
  269. raise ExtractorError(u'Unable to log in: bad username or password', expected=True)
  270. adult_content = True
  271. else:
  272. adult_content = False
  273. ticket = self._html_search_regex(
  274. u'window\.broadcast_control\.addFlashVar\\(\'file\', \'([^\']+)\'\\);',
  275. broadcast_page, u'broadcast ticket')
  276. url = 'http://smotri.com/broadcast/view/url/?ticket=%s' % ticket
  277. broadcast_password = self._downloader.params.get('videopassword', None)
  278. if broadcast_password:
  279. url += '&pass=%s' % hashlib.md5(broadcast_password.encode('utf-8')).hexdigest()
  280. broadcast_json_page = self._download_webpage(url, broadcast_id, u'Downloading broadcast JSON')
  281. try:
  282. broadcast_json = json.loads(broadcast_json_page)
  283. protected_broadcast = broadcast_json['_pass_protected'] == 1
  284. if protected_broadcast and not broadcast_password:
  285. raise ExtractorError(u'This broadcast is protected by a password, use the --video-password option', expected=True)
  286. broadcast_offline = broadcast_json['is_play'] == 0
  287. if broadcast_offline:
  288. raise ExtractorError(u'Broadcast %s is offline' % broadcast_id, expected=True)
  289. rtmp_url = broadcast_json['_server']
  290. if not rtmp_url.startswith('rtmp://'):
  291. raise ExtractorError(u'Unexpected broadcast rtmp URL')
  292. broadcast_playpath = broadcast_json['_streamName']
  293. broadcast_thumbnail = broadcast_json['_imgURL']
  294. broadcast_title = broadcast_json['title']
  295. broadcast_description = broadcast_json['description']
  296. broadcaster_nick = broadcast_json['nick']
  297. broadcaster_login = broadcast_json['login']
  298. rtmp_conn = 'S:%s' % uuid.uuid4().hex
  299. except KeyError:
  300. if protected_broadcast:
  301. raise ExtractorError(u'Bad broadcast password', expected=True)
  302. raise ExtractorError(u'Unexpected broadcast JSON')
  303. return {
  304. 'id': broadcast_id,
  305. 'url': rtmp_url,
  306. 'title': broadcast_title,
  307. 'thumbnail': broadcast_thumbnail,
  308. 'description': broadcast_description,
  309. 'uploader': broadcaster_nick,
  310. 'uploader_id': broadcaster_login,
  311. 'age_limit': 18 if adult_content else 0,
  312. 'ext': 'flv',
  313. 'play_path': broadcast_playpath,
  314. 'rtmp_live': True,
  315. 'rtmp_conn': rtmp_conn
  316. }