googledrive.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import re
  2. from .common import InfoExtractor
  3. from ..compat import compat_parse_qs
  4. from ..utils import (
  5. determine_ext,
  6. ExtractorError,
  7. get_element_by_class,
  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. @classmethod
  77. def _extract_embed_urls(cls, 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. yield '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', default=None)
  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. else:
  233. self.report_warning(
  234. get_element_by_class('uc-error-subcaption', confirmation_webpage)
  235. or get_element_by_class('uc-error-caption', confirmation_webpage)
  236. or 'unable to extract confirmation code')
  237. if not formats and reason:
  238. self.raise_no_formats(reason, expected=True)
  239. hl = get_value('hl')
  240. subtitles_id = None
  241. ttsurl = get_value('ttsurl')
  242. if ttsurl:
  243. # the video Id for subtitles will be the last value in the ttsurl
  244. # query string
  245. subtitles_id = ttsurl.encode('utf-8').decode(
  246. 'unicode_escape').split('=')[-1]
  247. self.cookiejar.clear(domain='.google.com', path='/', name='NID')
  248. return {
  249. 'id': video_id,
  250. 'title': title,
  251. 'thumbnail': 'https://drive.google.com/thumbnail?id=' + video_id,
  252. 'duration': int_or_none(get_value('length_seconds')),
  253. 'formats': formats,
  254. 'subtitles': self.extract_subtitles(video_id, subtitles_id, hl),
  255. 'automatic_captions': self.extract_automatic_captions(
  256. video_id, subtitles_id, hl),
  257. }
  258. class GoogleDriveFolderIE(InfoExtractor):
  259. IE_NAME = 'GoogleDrive:Folder'
  260. _VALID_URL = r'https?://(?:docs|drive)\.google\.com/drive/folders/(?P<id>[\w-]{28,})'
  261. _TESTS = [{
  262. 'url': 'https://drive.google.com/drive/folders/1dQ4sx0-__Nvg65rxTSgQrl7VyW_FZ9QI',
  263. 'info_dict': {
  264. 'id': '1dQ4sx0-__Nvg65rxTSgQrl7VyW_FZ9QI',
  265. 'title': 'Forrest'
  266. },
  267. 'playlist_count': 3,
  268. }]
  269. _BOUNDARY = '=====vc17a3rwnndj====='
  270. _REQUEST = "/drive/v2beta/files?openDrive=true&reason=102&syncType=0&errorRecovery=false&q=trashed%20%3D%20false%20and%20'{folder_id}'%20in%20parents&fields=kind%2CnextPageToken%2Citems(kind%2CmodifiedDate%2CmodifiedByMeDate%2ClastViewedByMeDate%2CfileSize%2Cowners(kind%2CpermissionId%2Cid)%2ClastModifyingUser(kind%2CpermissionId%2Cid)%2ChasThumbnail%2CthumbnailVersion%2Ctitle%2Cid%2CresourceKey%2Cshared%2CsharedWithMeDate%2CuserPermission(role)%2CexplicitlyTrashed%2CmimeType%2CquotaBytesUsed%2Ccopyable%2CfileExtension%2CsharingUser(kind%2CpermissionId%2Cid)%2Cspaces%2Cversion%2CteamDriveId%2ChasAugmentedPermissions%2CcreatedDate%2CtrashingUser(kind%2CpermissionId%2Cid)%2CtrashedDate%2Cparents(id)%2CshortcutDetails(targetId%2CtargetMimeType%2CtargetLookupStatus)%2Ccapabilities(canCopy%2CcanDownload%2CcanEdit%2CcanAddChildren%2CcanDelete%2CcanRemoveChildren%2CcanShare%2CcanTrash%2CcanRename%2CcanReadTeamDrive%2CcanMoveTeamDriveItem)%2Clabels(starred%2Ctrashed%2Crestricted%2Cviewed))%2CincompleteSearch&appDataFilter=NO_APP_DATA&spaces=drive&pageToken={page_token}&maxResults=50&supportsTeamDrives=true&includeItemsFromAllDrives=true&corpora=default&orderBy=folder%2Ctitle_natural%20asc&retryCount=0&key={key} HTTP/1.1"
  271. _DATA = f'''--{_BOUNDARY}
  272. content-type: application/http
  273. content-transfer-encoding: binary
  274. GET %s
  275. --{_BOUNDARY}
  276. '''
  277. def _call_api(self, folder_id, key, data, **kwargs):
  278. response = self._download_webpage(
  279. 'https://clients6.google.com/batch/drive/v2beta',
  280. folder_id, data=data.encode('utf-8'),
  281. headers={
  282. 'Content-Type': 'text/plain;charset=UTF-8;',
  283. 'Origin': 'https://drive.google.com',
  284. }, query={
  285. '$ct': f'multipart/mixed; boundary="{self._BOUNDARY}"',
  286. 'key': key
  287. }, **kwargs)
  288. return self._search_json('', response, 'api response', folder_id, **kwargs) or {}
  289. def _get_folder_items(self, folder_id, key):
  290. page_token = ''
  291. while page_token is not None:
  292. request = self._REQUEST.format(folder_id=folder_id, page_token=page_token, key=key)
  293. page = self._call_api(folder_id, key, self._DATA % request)
  294. yield from page['items']
  295. page_token = page.get('nextPageToken')
  296. def _real_extract(self, url):
  297. folder_id = self._match_id(url)
  298. webpage = self._download_webpage(url, folder_id)
  299. key = self._search_regex(r'"(\w{39})"', webpage, 'key')
  300. folder_info = self._call_api(folder_id, key, self._DATA % f'/drive/v2beta/files/{folder_id} HTTP/1.1', fatal=False)
  301. return self.playlist_from_matches(
  302. self._get_folder_items(folder_id, key), folder_id, folder_info.get('title'),
  303. ie=GoogleDriveIE, getter=lambda item: f'https://drive.google.com/file/d/{item["id"]}')