googledrive.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import compat_parse_qs
  5. from ..utils import (
  6. determine_ext,
  7. ExtractorError,
  8. int_or_none,
  9. lowercase_escape,
  10. try_get,
  11. update_url_query,
  12. )
  13. class GoogleDriveIE(InfoExtractor):
  14. _VALID_URL = r'''(?x)
  15. https?://
  16. (?:
  17. (?:docs|drive)\.google\.com/
  18. (?:
  19. (?:uc|open)\?.*?id=|
  20. file/d/
  21. )|
  22. video\.google\.com/get_player\?.*?docid=
  23. )
  24. (?P<id>[a-zA-Z0-9_-]{28,})
  25. '''
  26. _TESTS = [{
  27. 'url': 'https://drive.google.com/file/d/0ByeS4oOUV-49Zzh4R1J6R09zazQ/edit?pli=1',
  28. 'md5': '5c602afbbf2c1db91831f5d82f678554',
  29. 'info_dict': {
  30. 'id': '0ByeS4oOUV-49Zzh4R1J6R09zazQ',
  31. 'ext': 'mp4',
  32. 'title': 'Big Buck Bunny.mp4',
  33. 'duration': 45,
  34. }
  35. }, {
  36. # video can't be watched anonymously due to view count limit reached,
  37. # but can be downloaded (see https://github.com/ytdl-org/youtube-dl/issues/14046)
  38. 'url': 'https://drive.google.com/file/d/0B-vUyvmDLdWDcEt4WjBqcmI2XzQ/view',
  39. 'only_matching': True,
  40. }, {
  41. # video id is longer than 28 characters
  42. 'url': 'https://drive.google.com/file/d/1ENcQ_jeCuj7y19s66_Ou9dRP4GKGsodiDQ/edit',
  43. 'only_matching': True,
  44. }, {
  45. 'url': 'https://drive.google.com/open?id=0B2fjwgkl1A_CX083Tkowdmt6d28',
  46. 'only_matching': True,
  47. }, {
  48. 'url': 'https://drive.google.com/uc?id=0B2fjwgkl1A_CX083Tkowdmt6d28',
  49. 'only_matching': True,
  50. }]
  51. _FORMATS_EXT = {
  52. '5': 'flv',
  53. '6': 'flv',
  54. '13': '3gp',
  55. '17': '3gp',
  56. '18': 'mp4',
  57. '22': 'mp4',
  58. '34': 'flv',
  59. '35': 'flv',
  60. '36': '3gp',
  61. '37': 'mp4',
  62. '38': 'mp4',
  63. '43': 'webm',
  64. '44': 'webm',
  65. '45': 'webm',
  66. '46': 'webm',
  67. '59': 'mp4',
  68. }
  69. _BASE_URL_CAPTIONS = 'https://drive.google.com/timedtext'
  70. _CAPTIONS_ENTRY_TAG = {
  71. 'subtitles': 'track',
  72. 'automatic_captions': 'target',
  73. }
  74. _caption_formats_ext = []
  75. _captions_xml = None
  76. @staticmethod
  77. def _extract_url(webpage):
  78. mobj = re.search(
  79. r'<iframe[^>]+src="https?://(?:video\.google\.com/get_player\?.*?docid=|(?:docs|drive)\.google\.com/file/d/)(?P<id>[a-zA-Z0-9_-]{28,})',
  80. webpage)
  81. if mobj:
  82. return 'https://drive.google.com/file/d/%s' % mobj.group('id')
  83. def _download_subtitles_xml(self, video_id, subtitles_id, hl):
  84. if self._captions_xml:
  85. return
  86. self._captions_xml = self._download_xml(
  87. self._BASE_URL_CAPTIONS, video_id, query={
  88. 'id': video_id,
  89. 'vid': subtitles_id,
  90. 'hl': hl,
  91. 'v': video_id,
  92. 'type': 'list',
  93. 'tlangs': '1',
  94. 'fmts': '1',
  95. 'vssids': '1',
  96. }, note='Downloading subtitles XML',
  97. errnote='Unable to download subtitles XML', fatal=False)
  98. if self._captions_xml:
  99. for f in self._captions_xml.findall('format'):
  100. if f.attrib.get('fmt_code') and not f.attrib.get('default'):
  101. self._caption_formats_ext.append(f.attrib['fmt_code'])
  102. def _get_captions_by_type(self, video_id, subtitles_id, caption_type,
  103. origin_lang_code=None):
  104. if not subtitles_id or not caption_type:
  105. return
  106. captions = {}
  107. for caption_entry in self._captions_xml.findall(
  108. self._CAPTIONS_ENTRY_TAG[caption_type]):
  109. caption_lang_code = caption_entry.attrib.get('lang_code')
  110. if not caption_lang_code:
  111. continue
  112. caption_format_data = []
  113. for caption_format in self._caption_formats_ext:
  114. query = {
  115. 'vid': subtitles_id,
  116. 'v': video_id,
  117. 'fmt': caption_format,
  118. 'lang': (caption_lang_code if origin_lang_code is None
  119. else origin_lang_code),
  120. 'type': 'track',
  121. 'name': '',
  122. 'kind': '',
  123. }
  124. if origin_lang_code is not None:
  125. query.update({'tlang': caption_lang_code})
  126. caption_format_data.append({
  127. 'url': update_url_query(self._BASE_URL_CAPTIONS, query),
  128. 'ext': caption_format,
  129. })
  130. captions[caption_lang_code] = caption_format_data
  131. return captions
  132. def _get_subtitles(self, video_id, subtitles_id, hl):
  133. if not subtitles_id or not hl:
  134. return
  135. self._download_subtitles_xml(video_id, subtitles_id, hl)
  136. if not self._captions_xml:
  137. return
  138. return self._get_captions_by_type(video_id, subtitles_id, 'subtitles')
  139. def _get_automatic_captions(self, video_id, subtitles_id, hl):
  140. if not subtitles_id or not hl:
  141. return
  142. self._download_subtitles_xml(video_id, subtitles_id, hl)
  143. if not self._captions_xml:
  144. return
  145. track = self._captions_xml.find('track')
  146. if track is None:
  147. return
  148. origin_lang_code = track.attrib.get('lang_code')
  149. if not origin_lang_code:
  150. return
  151. return self._get_captions_by_type(
  152. video_id, subtitles_id, 'automatic_captions', origin_lang_code)
  153. def _real_extract(self, url):
  154. video_id = self._match_id(url)
  155. video_info = compat_parse_qs(self._download_webpage(
  156. 'https://drive.google.com/get_video_info',
  157. video_id, query={'docid': video_id}))
  158. def get_value(key):
  159. return try_get(video_info, lambda x: x[key][0])
  160. reason = get_value('reason')
  161. title = get_value('title')
  162. if not title and reason:
  163. raise ExtractorError(reason, expected=True)
  164. formats = []
  165. fmt_stream_map = (get_value('fmt_stream_map') or '').split(',')
  166. fmt_list = (get_value('fmt_list') or '').split(',')
  167. if fmt_stream_map and fmt_list:
  168. resolutions = {}
  169. for fmt in fmt_list:
  170. mobj = re.search(
  171. r'^(?P<format_id>\d+)/(?P<width>\d+)[xX](?P<height>\d+)', fmt)
  172. if mobj:
  173. resolutions[mobj.group('format_id')] = (
  174. int(mobj.group('width')), int(mobj.group('height')))
  175. for fmt_stream in fmt_stream_map:
  176. fmt_stream_split = fmt_stream.split('|')
  177. if len(fmt_stream_split) < 2:
  178. continue
  179. format_id, format_url = fmt_stream_split[:2]
  180. f = {
  181. 'url': lowercase_escape(format_url),
  182. 'format_id': format_id,
  183. 'ext': self._FORMATS_EXT[format_id],
  184. }
  185. resolution = resolutions.get(format_id)
  186. if resolution:
  187. f.update({
  188. 'width': resolution[0],
  189. 'height': resolution[1],
  190. })
  191. formats.append(f)
  192. source_url = update_url_query(
  193. 'https://drive.google.com/uc', {
  194. 'id': video_id,
  195. 'export': 'download',
  196. })
  197. def request_source_file(source_url, kind):
  198. return self._request_webpage(
  199. source_url, video_id, note='Requesting %s file' % kind,
  200. errnote='Unable to request %s file' % kind, fatal=False)
  201. urlh = request_source_file(source_url, 'source')
  202. if urlh:
  203. def add_source_format(urlh):
  204. formats.append({
  205. # Use redirect URLs as download URLs in order to calculate
  206. # correct cookies in _calc_cookies.
  207. # Using original URLs may result in redirect loop due to
  208. # google.com's cookies mistakenly used for googleusercontent.com
  209. # redirect URLs (see #23919).
  210. 'url': urlh.geturl(),
  211. 'ext': determine_ext(title, 'mp4').lower(),
  212. 'format_id': 'source',
  213. 'quality': 1,
  214. })
  215. if urlh.headers.get('Content-Disposition'):
  216. add_source_format(urlh)
  217. else:
  218. confirmation_webpage = self._webpage_read_content(
  219. urlh, url, video_id, note='Downloading confirmation page',
  220. errnote='Unable to confirm download', fatal=False)
  221. if confirmation_webpage:
  222. confirm = self._search_regex(
  223. r'confirm=([^&"\']+)', confirmation_webpage,
  224. 'confirmation code', fatal=False)
  225. if confirm:
  226. confirmed_source_url = update_url_query(source_url, {
  227. 'confirm': confirm,
  228. })
  229. urlh = request_source_file(confirmed_source_url, 'confirmed source')
  230. if urlh and urlh.headers.get('Content-Disposition'):
  231. add_source_format(urlh)
  232. if not formats and reason:
  233. raise ExtractorError(reason, expected=True)
  234. self._sort_formats(formats)
  235. hl = get_value('hl')
  236. subtitles_id = None
  237. ttsurl = get_value('ttsurl')
  238. if ttsurl:
  239. # the video Id for subtitles will be the last value in the ttsurl
  240. # query string
  241. subtitles_id = ttsurl.encode('utf-8').decode(
  242. 'unicode_escape').split('=')[-1]
  243. return {
  244. 'id': video_id,
  245. 'title': title,
  246. 'thumbnail': 'https://drive.google.com/thumbnail?id=' + video_id,
  247. 'duration': int_or_none(get_value('length_seconds')),
  248. 'formats': formats,
  249. 'subtitles': self.extract_subtitles(video_id, subtitles_id, hl),
  250. 'automatic_captions': self.extract_automatic_captions(
  251. video_id, subtitles_id, hl),
  252. }