py_ali.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # coding=utf-8
  2. # !/usr/bin/python
  3. import sys
  4. sys.path.append('..')
  5. from base.spider import Spider
  6. import json
  7. import requests
  8. import time
  9. import re
  10. class Spider(Spider): # 元类 默认的元类 type
  11. def getName(self):
  12. return "阿里云盘"
  13. def init(self, extend=""):
  14. print("============{0}============".format(extend))
  15. pass
  16. def homeContent(self, filter):
  17. result = {}
  18. return result
  19. def homeVideoContent(self):
  20. result = {}
  21. return result
  22. def categoryContent(self, tid, pg, filter, extend):
  23. result = {}
  24. return result
  25. def searchContent(self, key, quick):
  26. result = {}
  27. return result
  28. def isVideoFormat(self, url):
  29. pass
  30. def manualVideoCheck(self):
  31. pass
  32. def playerContent(self, flag, id, vipFlags):
  33. if flag == 'AliYun':
  34. return self.originContent(flag, id, vipFlags)
  35. elif flag == 'AliYun原画':
  36. return self.fhdContent(flag, id, vipFlags)
  37. else:
  38. return {}
  39. def fhdContent(self, flag, id, vipFlags):
  40. if not self.login():
  41. return {}
  42. ids = id.split('+')
  43. shareId = ids[0]
  44. shareToken = ids[1]
  45. fileId = ids[2]
  46. category = ids[3]
  47. subtitle = ids[4]
  48. url = self.getDownloadUrl(shareId, shareToken, fileId, category)
  49. noRsp = requests.get(url, headers=self.header, allow_redirects=False, verify=False)
  50. realUrl = ''
  51. if 'Location' in noRsp.headers:
  52. realUrl = noRsp.headers['Location']
  53. if 'location' in noRsp.headers and len(realUrl) == 0:
  54. realUrl = noRsp.headers['location']
  55. newHeader = {
  56. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
  57. "referer": "https://www.aliyundrive.com/",
  58. }
  59. subtitleUrl = self.subtitleContent(id)
  60. result = {
  61. 'parse': '0',
  62. 'playUrl': '',
  63. 'url': realUrl,
  64. 'header': newHeader,
  65. 'subt': subtitleUrl
  66. }
  67. return result
  68. def subtitleContent(self, id):
  69. ids = id.split('+')
  70. shareId = ids[0]
  71. shareToken = ids[1]
  72. fileId = ids[2]
  73. category = ids[3]
  74. subtitle = ids[4]
  75. if len(subtitle) == 0:
  76. return ""
  77. customHeader = self.header.copy()
  78. customHeader['x-share-token'] = shareToken
  79. customHeader['authorization'] = self.authorization
  80. jo = {
  81. "expire_sec": 600,
  82. "share_id": shareId,
  83. "file_id": subtitle,
  84. "image_url_process": "image/resize,w_1920/format,jpeg",
  85. "image_thumbnail_process": "image/resize,w_1920/format,jpeg",
  86. "get_streams_url": True
  87. # ,
  88. # "drive_id": "183237630"
  89. }
  90. downloadUrl = 'https://api.aliyundrive.com/v2/file/get_share_link_download_url'
  91. resultJo = requests.post(downloadUrl, json=jo, headers=customHeader).json()
  92. print(resultJo)
  93. noRsp = requests.get(resultJo['download_url'], headers=self.header, allow_redirects=False, verify=False)
  94. realUrl = ''
  95. if 'Location' in noRsp.headers:
  96. realUrl = noRsp.headers['Location']
  97. if 'location' in noRsp.headers and len(realUrl) == 0:
  98. realUrl = noRsp.headers['location']
  99. return realUrl
  100. def originContent(self, flag, id, vipFlags):
  101. if not self.login():
  102. return {}
  103. ids = id.split('+')
  104. shareId = ids[0]
  105. shareToken = ids[1]
  106. fileId = ids[2]
  107. subtitle = ids[4]
  108. url = '{0}?do=push_agent&api=python&type=m3u8&share_id={1}&file_id={2}'.format(self.localProxyUrl, shareId,
  109. fileId)
  110. subtitleUrl = self.subtitleContent(id)
  111. newHeader = {
  112. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
  113. "referer": "https://www.aliyundrive.com/",
  114. }
  115. result = {
  116. 'parse': '0',
  117. 'playUrl': '',
  118. 'url': url,
  119. 'header': newHeader,
  120. 'subt': subtitleUrl
  121. }
  122. return result
  123. def detailContent(self, array):
  124. tid = array[0]
  125. m = re.search('www.aliyundrive.com\\/s\\/([^\\/]+)(\\/folder\\/([^\\/]+))?', tid)
  126. col = m.groups()
  127. shareId = col[0]
  128. fileId = col[2]
  129. infoUrl = 'https://api.aliyundrive.com/adrive/v3/share_link/get_share_by_anonymous'
  130. infoForm = {'share_id': shareId}
  131. infoRsp = requests.post(infoUrl, json=infoForm, headers=self.header)
  132. infoJo = json.loads(infoRsp.text)
  133. infoJa = []
  134. if 'file_infos' in infoJo:
  135. infoJa = infoJo['file_infos']
  136. if len(infoJa) <= 0:
  137. return ''
  138. fileInfo = {}
  139. fileInfo = infoJa[0]
  140. if fileId == None or len(fileId) <= 0:
  141. fileId = fileInfo['file_id']
  142. vodList = {
  143. 'vod_id': tid,
  144. 'vod_name': infoJo['share_name'],
  145. 'vod_pic': infoJo['avatar'],
  146. 'vod_content': tid,
  147. 'vod_play_from': 'AliYun$$$AliYun原画'
  148. }
  149. fileType = fileInfo['type']
  150. if fileType != 'folder':
  151. if fileType != 'file' or fileInfo['category'] != 'video':
  152. return ''
  153. fileId = 'root'
  154. shareToken = self.getToken(shareId, '')
  155. hashMap = {}
  156. dirname = self.dirname
  157. self.listFiles(hashMap, shareId, shareToken, fileId, dirname)
  158. sortedMap = sorted(hashMap.items(), key=lambda x: x[0])
  159. arrayList = []
  160. playList = []
  161. for sm in sortedMap:
  162. arrayList.append(sm[0] + '$' + sm[1])
  163. playList.append('#'.join(arrayList))
  164. playList.append('#'.join(arrayList))
  165. vodList['vod_play_url'] = '$$$'.join(playList)
  166. result = {
  167. 'list': [vodList]
  168. }
  169. return result
  170. authorization = ''
  171. dirname = ''
  172. timeoutTick = 0
  173. localTime = 0
  174. expiresIn = 0
  175. shareTokenMap = {}
  176. expiresMap = {}
  177. localMedia = {}
  178. header = {
  179. "Referer": "https://www.aliyundrive.com/",
  180. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36"
  181. }
  182. localProxyUrl = 'http://127.0.0.1:UndCover/proxy'
  183. def redirectResponse(tUrl):
  184. rsp = requests.get(tUrl, allow_redirects=False, verify=False)
  185. if 'Location' in rsp.headers:
  186. return redirectResponse(rsp.headers['Location'])
  187. else:
  188. return rsp
  189. def getDownloadUrl(self, shareId, token, fileId, category):
  190. lShareId = shareId
  191. lFileId = fileId
  192. params = {
  193. "share_id": lShareId,
  194. "category": "live_transcoding",
  195. "file_id": lFileId,
  196. "template_id": ""
  197. }
  198. customHeader = self.header.copy()
  199. customHeader['x-share-token'] = token
  200. customHeader['authorization'] = self.authorization
  201. url = 'https://api.aliyundrive.com/v2/file/get_share_link_video_preview_play_info'
  202. if category == 'video':
  203. rsp = requests.post(url, json=params, headers=customHeader)
  204. rspJo = json.loads(rsp.text)
  205. lShareId = rspJo['share_id']
  206. lFileId = rspJo['file_id']
  207. jo = {
  208. }
  209. if category == 'video':
  210. jo['share_id'] = lShareId
  211. jo['file_id'] = lFileId
  212. jo['expire_sec'] = 600
  213. if category == 'audio':
  214. jo['share_id'] = lShareId
  215. jo['file_id'] = lFileId
  216. jo['get_audio_play_info'] = True
  217. downloadUrl = 'https://api.aliyundrive.com/v2/file/get_share_link_download_url'
  218. downloadRsp = requests.post(downloadUrl, json=jo, headers=customHeader)
  219. resultJo = json.loads(downloadRsp.text)
  220. return resultJo['download_url']
  221. def getMediaSlice(self, shareId, token, fileId):
  222. params = {
  223. "share_id": shareId,
  224. "category": "live_transcoding",
  225. "file_id": fileId,
  226. "template_id": ""
  227. }
  228. customHeader = self.header.copy()
  229. customHeader['x-share-token'] = token
  230. customHeader['authorization'] = self.authorization
  231. url = 'https://api.aliyundrive.com/v2/file/get_share_link_video_preview_play_info'
  232. rsp = requests.post(url, json=params, headers=customHeader)
  233. rspJo = json.loads(rsp.text)
  234. quality = ['FHD', 'HD', 'SD']
  235. videoList = rspJo['video_preview_play_info']['live_transcoding_task_list']
  236. highUrl = ''
  237. for q in quality:
  238. if len(highUrl) > 0:
  239. break
  240. for video in videoList:
  241. if (video['template_id'] == q):
  242. highUrl = video['url']
  243. break
  244. if len(highUrl) == 0:
  245. highUrl = videoList[0]['url']
  246. noRsp = requests.get(highUrl, headers=self.header, allow_redirects=False, verify=False)
  247. m3u8Url = ''
  248. if 'Location' in noRsp.headers:
  249. m3u8Url = noRsp.headers['Location']
  250. if 'location' in noRsp.headers and len(m3u8Url) == 0:
  251. m3u8Url = noRsp.headers['location']
  252. m3u8Rsp = requests.get(m3u8Url, headers=self.header)
  253. m3u8Content = m3u8Rsp.text
  254. tmpArray = m3u8Url.split('/')[0:-1]
  255. host = '/'.join(tmpArray) + '/'
  256. m3u8List = []
  257. mediaMap = {}
  258. slices = m3u8Content.split("\n")
  259. count = 0
  260. for slice in slices:
  261. tmpSlice = slice
  262. if 'x-oss-expires' in tmpSlice:
  263. count = count + 1
  264. mediaMap[str(count)] = host + tmpSlice
  265. tmpSlice = "{0}?do=push_agent&api=python&type=media&share_id={1}&file_id={2}&media_id={3}".format(
  266. self.localProxyUrl, shareId, fileId, count)
  267. m3u8List.append(tmpSlice)
  268. self.localMedia[fileId] = mediaMap
  269. return '\n'.join(m3u8List)
  270. def proxyMedia(self, map):
  271. shareId = map['share_id']
  272. fileId = map['file_id']
  273. mediaId = map['media_id']
  274. shareToken = self.getToken(shareId, '')
  275. refresh = False
  276. url = ''
  277. ts = 0
  278. if fileId in self.localMedia:
  279. fileMap = self.localMedia[fileId]
  280. if mediaId in fileMap:
  281. url = fileMap[mediaId]
  282. if len(url) > 0:
  283. ts = int(self.regStr(url, "x-oss-expires=(\\d+)&"))
  284. self.localTime = int(time.time())
  285. if ts - self.localTime <= 60:
  286. self.getMediaSlice(shareId, shareToken, fileId)
  287. url = self.localMedia[fileId][mediaId]
  288. action = {
  289. 'url': url,
  290. 'header': self.header,
  291. 'param': '',
  292. 'type': 'stream',
  293. 'after': ''
  294. }
  295. return [200, "video/MP2T", action, ""]
  296. def proxyM3U8(self, map):
  297. shareId = map['share_id']
  298. fileId = map['file_id']
  299. shareToken = self.getToken(shareId, '')
  300. content = self.getMediaSlice(shareId, shareToken, fileId)
  301. action = {
  302. 'url': '',
  303. 'header': '',
  304. 'param': '',
  305. 'type': 'string',
  306. 'after': ''
  307. }
  308. return [200, "application/octet-stream", action, content]
  309. def localProxy(self, param):
  310. if not self.login():
  311. return {}
  312. typ = param['type']
  313. if typ == "m3u8":
  314. return self.proxyM3U8(param)
  315. if typ == "media":
  316. return self.proxyMedia(param)
  317. return None
  318. def getToken(self, shareId, sharePwd):
  319. self.localTime = int(time.time())
  320. shareToken = ''
  321. if shareId in self.shareTokenMap:
  322. shareToken = self.shareTokenMap[shareId]
  323. # todo
  324. expire = self.expiresMap[shareId]
  325. if len(shareToken) > 0 and expire - self.localTime > 600:
  326. return shareToken
  327. params = {
  328. 'share_id': shareId,
  329. 'share_pwd': sharePwd
  330. }
  331. url = 'https://api.aliyundrive.com/v2/share_link/get_share_token'
  332. rsp = requests.post(url, json=params, headers=self.header)
  333. jo = json.loads(rsp.text)
  334. newShareToken = jo['share_token']
  335. self.expiresMap[shareId] = self.localTime + int(jo['expires_in'])
  336. self.shareTokenMap[shareId] = newShareToken
  337. # print(self.expiresMap)
  338. # print(self.shareTokenMap)
  339. return newShareToken
  340. def listFiles(self, map, shareId, shareToken, fileId, dirname, subtitle={}):
  341. url = 'https://api.aliyundrive.com/adrive/v3/file/list'
  342. newHeader = self.header.copy()
  343. newHeader['x-share-token'] = shareToken
  344. params = {
  345. 'image_thumbnail_process': 'image/resize,w_160/format,jpeg',
  346. 'image_url_process': 'image/resize,w_1920/format,jpeg',
  347. 'limit': 200,
  348. 'order_by': 'updated_at',
  349. 'order_direction': 'DESC',
  350. 'parent_file_id': fileId,
  351. 'share_id': shareId,
  352. 'video_thumbnail_process': 'video/snapshot,t_1000,f_jpg,ar_auto,w_300'
  353. }
  354. maker = ''
  355. arrayList = []
  356. for i in range(1, 51):
  357. if i >= 2 and len(maker) == 0:
  358. break
  359. params['marker'] = maker
  360. rsp = requests.post(url, json=params, headers=newHeader)
  361. jo = json.loads(rsp.text)
  362. ja = jo['items']
  363. for jt in ja:
  364. if jt['type'] == 'folder':
  365. al = jt['file_id'] + '@@@' + jt['name']
  366. arrayList.append(al)
  367. else:
  368. if 'video' in jt['mime_type'] or 'video' in jt['category']:
  369. repStr = '[' + dirname + ']' + jt['name'].replace("#", "_").replace("$", "_").replace(jt['file_extension'], '')[0:-1]
  370. map[repStr] = shareId + "+" + shareToken + "+" + jt['file_id'] + "+" + jt['category'] + "+"
  371. elif 'others' == jt['category'] and (
  372. 'srt' == jt['file_extension'] or 'ass' == jt['file_extension']):
  373. repStr = '[' + dirname + ']' + jt['name'].replace("#", "_").replace("$", "_").replace(jt['file_extension'], '')[0:-1]
  374. subtitle[repStr] = jt['file_id']
  375. maker = jo['next_marker']
  376. i = i + 1
  377. for item in arrayList:
  378. if '@@@' in item:
  379. items = item.split('@@@')
  380. item = items[0]
  381. dirname = items[1]
  382. self.listFiles(map, shareId, shareToken, item, dirname, subtitle)
  383. for key in map.keys():
  384. for subKey in subtitle.keys():
  385. if key in subKey and map[key][-1] == "+":
  386. map[key] = map[key] + subtitle[subKey]
  387. break
  388. def login(self):
  389. self.localTime = int(time.time())
  390. url = 'https://api.aliyundrive.com/token/refresh'
  391. if len(self.authorization) == 0 or self.timeoutTick - self.localTime <= 600:
  392. form = {
  393. 'refresh_token': 'ab0b9a7555e84175bbc6f8e60310ae49'
  394. }
  395. rsp = requests.post(url, json=form, headers=self.header)
  396. jo = json.loads(rsp.text)
  397. if rsp.status_code == 200:
  398. self.authorization = jo['token_type'] + ' ' + jo['access_token']
  399. self.expiresIn = int(jo['expires_in'])
  400. self.timeoutTick = self.localTime + self.expiresIn
  401. return True
  402. return False
  403. else:
  404. return True
  405. # print(self.authorization)
  406. # print(self.timeoutTick)
  407. # print(self.localTime)
  408. # print(self.expiresIn)