py_bilibili_tvbox1222.py 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855
  1. # coding=utf-8
  2. # !/usr/bin/python
  3. import sys, os, json
  4. from base.spider import Spider
  5. from requests import session, utils, head, get as requests_get
  6. from requests.adapters import HTTPAdapter, Retry
  7. from concurrent.futures import ThreadPoolExecutor, as_completed
  8. import threading
  9. import hashlib
  10. import time
  11. import random
  12. import base64
  13. from functools import reduce
  14. from urllib.parse import quote, urlencode
  15. sys.path.append('..')
  16. dirname, filename = os.path.split(os.path.abspath(__file__))
  17. sys.path.append(dirname)
  18. class Spider(Spider):
  19. #默认设置
  20. defaultConfig = {
  21. 'currentVersion': "20231222_1",
  22. #【建议通过扫码确认】设置Cookie,在双引号内填写
  23. 'raw_cookie_line': "",
  24. #如果主cookie没有vip,可以设置第二cookie,仅用于播放会员番剧,所有的操作、记录还是在主cookie,不会同步到第二cookie
  25. 'raw_cookie_vip': "",
  26. #主页默认显示20图
  27. 'maxHomeVideoContent': '20',
  28. #收藏标签默认显示追番1,追剧2,默认收藏夹0
  29. 'favMode': '0',
  30. #部分视频列表分页,限制每次加载数量
  31. 'page_size': 12,
  32. #上传播放进度间隔时间,单位秒,b站默认间隔15,0则不上传播放历史
  33. 'heartbeatInterval': '15',
  34. #视频默认画质ID
  35. 'vodDefaultQn': '80',
  36. #视频默认解码ID
  37. 'vodDefaultCodec': '7',
  38. #音频默认码率ID
  39. 'vodDefaultAudio': '30280',
  40. #获取视频热门评论
  41. 'show_vod_hot_reply': True,
  42. #从正片中拆分出番剧的预告
  43. 'hide_bangumi_preview': True,
  44. #登陆会员账号后,影视播放页不显示会员专享的标签,更简洁
  45. 'hide_bangumi_vip_badge': True,
  46. #番剧(热门)列表使用横图
  47. 'bangumi_horizontal_cover': True,
  48. #非会员播放会员专享视频时,添加一个页面可以使用解析源,解析源自行解决
  49. 'bangumi_vip_parse': True,
  50. #付费视频添加一个页面可以使用解析,解析源自行解决
  51. 'bangumi_pay_parse': True,
  52. #是否显示直播标签筛选中分区的细化标签, 0为不显示,1为显示
  53. 'showLiveFilterTag': '1',
  54. #主页标签排序, 未登录或cookie失效时自动隐藏动态、收藏、关注、历史
  55. 'cateManual': [
  56. "动态",
  57. "推荐",
  58. "影视",
  59. "直播",
  60. "频道",
  61. "收藏",
  62. "关注",
  63. "历史",
  64. "搜索",
  65. ],
  66. #自定义推荐标签的筛选
  67. 'tuijianLis': [
  68. "热门",
  69. "排行榜",
  70. "每周必看",
  71. "入站必刷",
  72. "番剧时间表",
  73. "国创时间表"
  74. ],
  75. 'rankingLis': [
  76. "动画",
  77. "音乐",
  78. "舞蹈",
  79. "游戏",
  80. "鬼畜",
  81. "知识",
  82. "科技",
  83. "运动",
  84. "生活",
  85. "美食",
  86. "动物",
  87. "汽车",
  88. "时尚",
  89. "娱乐",
  90. "影视",
  91. "原创",
  92. "新人",
  93. ],
  94. }
  95. #在动态标签的筛选中固定显示他,n为用户名或任意都可以,v必须为准确的UID
  96. focus_on_up_list = [
  97. #{"n":"徐云流浪中国", "v":"697166795"},
  98. ]
  99. #在搜索标签的筛选中固定显示搜索词
  100. focus_on_search_key = []
  101. def getName(self):
  102. return "哔哩哔哩"
  103. def load_config(self):
  104. try:
  105. with open(f"{dirname}/config.json",encoding="utf-8") as f:
  106. self.userConfig = json.load(f)
  107. users = self.userConfig.get('users', {})
  108. if users.get('master') and users['master'].get('cookies_dic'):
  109. self.session_master.cookies = utils.cookiejar_from_dict(users['master']['cookies_dic'])
  110. self.userid = users['master']['userid']
  111. if users.get('fake') and users['fake'].get('cookies_dic'):
  112. self.session_fake.cookies = utils.cookiejar_from_dict(users['fake']['cookies_dic'])
  113. except:
  114. self.userConfig = {}
  115. self.userConfig = {**self.defaultConfig, **self.userConfig}
  116. dump_config_lock = threading.Lock()
  117. def dump_config(self):
  118. needSaveConfig = ['users', 'channel_list', 'cateLive', 'cateManualLive', 'cateManualLiveExtra']
  119. userConfig_new = {}
  120. for key, value in self.userConfig.items():
  121. dafalutValue = self.defaultConfig.get(key)
  122. if dafalutValue != None and value != dafalutValue or key in needSaveConfig:
  123. userConfig_new[key] = value
  124. self.dump_config_lock.acquire()
  125. with open(f"{dirname}/config.json", 'w', encoding="utf-8") as f:
  126. data = json.dumps(userConfig_new, indent=1, ensure_ascii=False)
  127. f.write(data)
  128. self.dump_config_lock.release()
  129. pool = ThreadPoolExecutor(max_workers=8)
  130. task_pool = []
  131. # 主页
  132. def homeContent(self, filter):
  133. self.pool.submit(self.add_live_filter)
  134. self.pool.submit(self.add_channel_filter)
  135. self.pool.submit(self.add_search_key)
  136. self.pool.submit(self.add_focus_on_up_filter)
  137. self.pool.submit(self.get_tuijian_filter)
  138. self.pool.submit(self.add_fav_filter)
  139. #self.pool.submit(self.homeVideoContent)
  140. needLogin = ['频道', '动态', '收藏', '关注', '历史']
  141. cateManual = self.userConfig['cateManual']
  142. if not self.userid and not 'UP' in cateManual or not '动态' in cateManual and not 'UP' in cateManual:
  143. cateManual += ['UP']
  144. classes = []
  145. for k in cateManual:
  146. if k in needLogin and not self.userid:
  147. continue
  148. classes.append({
  149. 'type_name': k,
  150. 'type_id': k
  151. })
  152. self.add_focus_on_up_filter_event.wait()
  153. if 'UP' in cateManual:
  154. self.config["filter"].update({'UP': self.config["filter"].pop('动态')})
  155. result = {'class': classes}
  156. self.add_live_filter_event.wait()
  157. self.add_channel_filter_event.wait()
  158. self.add_fav_filter_event.wait()
  159. self.add_search_key_event.wait()
  160. if filter:
  161. result['filters'] = self.config['filter']
  162. self.pool.submit(self.dump_config)
  163. return result
  164. # 用户cookies
  165. userid = csrf = ''
  166. session_master = session()
  167. session_vip = session()
  168. session_fake = session()
  169. con = threading.Condition()
  170. getCookie_event = threading.Event()
  171. retries = Retry(total=5,
  172. #status_forcelist=[ 500, 502, 503, 504 ],
  173. backoff_factor=0.1)
  174. adapter = HTTPAdapter(max_retries=retries)
  175. session_master.mount('https://', adapter)
  176. session_vip.mount('https://', adapter)
  177. session_fake.mount('https://', adapter)
  178. def getCookie_dosth(self, co):
  179. c = co.strip().split('=', 1)
  180. if not '%' in c[1]:
  181. c[1] = quote(c[1])
  182. return c
  183. def getCookie(self, _type='master'):
  184. raw_cookie = 'raw_cookie_line'
  185. if _type == 'vip':
  186. raw_cookie = 'raw_cookie_vip'
  187. raw_cookie = self.userConfig.get(raw_cookie)
  188. users = self.userConfig.get('users', {})
  189. user = users.get(_type, {})
  190. if not raw_cookie and not user:
  191. if _type == 'master':
  192. self.getCookie_event.set()
  193. with self.con:
  194. self.con.notifyAll()
  195. return
  196. cookies_dic = user.get('cookies_dic', {})
  197. if raw_cookie:
  198. cookies_dic = dict(map(self.getCookie_dosth, raw_cookie.split(';')))
  199. cookies = utils.cookiejar_from_dict(cookies_dic)
  200. url = 'https://api.bilibili.com/x/web-interface/nav'
  201. content = self.fetch(url, headers=self.header, cookies=cookies)
  202. res = json.loads(content.text)
  203. user['isLogin'] = 0
  204. if res["code"] == 0:
  205. user['isLogin'] = 1
  206. user['userid'] = res["data"]['mid']
  207. user['face'] = res['data']['face']
  208. user['uname'] = res['data']['uname']
  209. user['cookies_dic'] = cookies_dic
  210. user['isVIP'] = int(res['data']['vipStatus'])
  211. if _type == 'master':
  212. self.session_master.cookies = cookies
  213. self.userid = user['userid']
  214. self.csrf = cookies_dic['bili_jct']
  215. if user['isVIP']:
  216. self.session_vip.cookies = cookies
  217. else:
  218. self.userid = ''
  219. users[_type] = user
  220. with self.con:
  221. if len(user) > 1:
  222. self.userConfig.update({'users': users})
  223. if _type == 'master':
  224. self.getCookie_event.set()
  225. getFakeCookie_event = threading.Event()
  226. def getFakeCookie(self, fromSearch=None):
  227. if self.session_fake.cookies:
  228. self.getFakeCookie_event.set()
  229. header = {}
  230. header['User-Agent'] = self.header['User-Agent']
  231. rsp = self.fetch('https://space.bilibili.com/2/video', headers=header)
  232. self.session_fake.cookies = rsp.cookies
  233. self.getFakeCookie_event.set()
  234. with self.con:
  235. users = self.userConfig.get('users', {})
  236. users['fake'] = {'cookies_dic': dict(rsp.cookies)}
  237. self.userConfig.update({'users': users})
  238. if not fromSearch:
  239. self.getCookie_event.wait()
  240. if not self.session_master.cookies:
  241. self.session_master.cookies = rsp.cookies
  242. def get_fav_list_dict(self, fav):
  243. fav_dict = {
  244. 'n': fav['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').strip(),
  245. 'v': fav['id']}
  246. return fav_dict
  247. add_fav_filter_event = threading.Event()
  248. def add_fav_filter(self):
  249. users = self.userConfig.get('users', {})
  250. if users.get('master') and users['master'].get('userid'):
  251. userid = self.userConfig['users']['master']['userid']
  252. else:
  253. self.getCookie_event.wait()
  254. userid = self.userid
  255. fav_list = []
  256. if userid:
  257. url = 'https://api.bilibili.com/x/v3/fav/folder/created/list-all?up_mid=%s&jsonp=jsonp' % str(userid)
  258. jo = self._get_sth(url).json()
  259. if jo['code'] == 0 and jo.get('data'):
  260. fav = jo['data'].get('list')
  261. fav_list = list(map(self.get_fav_list_dict, fav))
  262. fav_top = [{"n": "追番", "v": "1"},{"n": "追剧", "v": "2"}]
  263. fav_config = self.config["filter"].get('收藏')
  264. if fav_config:
  265. fav_config.insert(0, {
  266. "key": "mlid",
  267. "name": "分区",
  268. "value": fav_top + fav_list,
  269. })
  270. self.add_fav_filter_event.set()
  271. self.userConfig["fav_list"] = fav_list
  272. def get_channel_list_dict(self, channel):
  273. channel_dict = {
  274. 'n': channel['name'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').strip(),
  275. 'v': channel['id']}
  276. return channel_dict
  277. def get_channel_list(self):
  278. url = 'https://api.bilibili.com/x/web-interface/web/channel/category/channel/list?id=100&offset=0&page_size=15'
  279. jo = self._get_sth(url, 'fake').json()
  280. channel_list = []
  281. if jo['code'] == 0:
  282. channel = jo['data'].get('channels')
  283. self.userConfig['channel_list'] = list(map(self.get_channel_list_dict, channel))
  284. return self.userConfig['channel_list']
  285. add_channel_filter_event = threading.Event()
  286. def add_channel_filter(self):
  287. channel_list = self.userConfig.get('channel_list', '')
  288. channel_list_task = self.pool.submit(self.get_channel_list)
  289. if not channel_list:
  290. channel_list = channel_list_task.result()
  291. channel_config = self.config["filter"].get('频道', [])
  292. if channel_config:
  293. channel_config.insert(0, {
  294. "key": "cid",
  295. "name": "分区",
  296. "value": channel_list,
  297. })
  298. self.config["filter"]['频道'] = channel_config
  299. self.add_channel_filter_event.set()
  300. add_focus_on_up_filter_event = threading.Event()
  301. def add_focus_on_up_filter(self):
  302. first_list = [{"n": "上个视频的UP主", "v": "上个视频的UP主"}]
  303. up_list = self.focus_on_up_list
  304. if not self.session_master.cookies:
  305. self.getCookie_event.wait()
  306. focus_on_up_list_mid = list(map(lambda x: x['v'], up_list))
  307. if self.session_master.cookies:
  308. url = 'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?timezone_offset=-480&type=video&page=1'
  309. jo = self._get_sth(url).json()
  310. if jo['code'] == 0 and jo.get('data'):
  311. up = jo['data'].get('items', [])
  312. for u in map(lambda x: {'n': x['modules']["module_author"]['name'], 'v': str(x['modules']["module_author"]['mid'])}, up):
  313. if not u in up_list and not u['v'] in focus_on_up_list_mid:
  314. up_list.append(u)
  315. last_list = [{"n": "登录与设置", "v": "登录"}]
  316. up_list = first_list + up_list
  317. up_list += last_list
  318. dynamic_config = self.config["filter"].get('动态', [])
  319. if dynamic_config:
  320. dynamic_config.insert(0, {
  321. "key": "mid",
  322. "name": "UP主",
  323. "value": up_list,
  324. })
  325. self.config["filter"]['动态'] = dynamic_config
  326. self.add_focus_on_up_filter_event.set()
  327. def get_live_parent_area_list(self, parent_area):
  328. name = parent_area['name']
  329. id = str(parent_area['id'])
  330. area = parent_area['list']
  331. area_dict = list(map(lambda area: {'n': area['name'], 'v': str(area['parent_id']) + '_' + str(area['id'])}, area))
  332. live_area = {'key': 'tid', 'name': name, 'value': area_dict}
  333. cateLive_name = {'id': id + '_0', 'value': live_area}
  334. return (name, cateLive_name)
  335. def get_live_list(self):
  336. url = 'https://api.live.bilibili.com/xlive/web-interface/v1/index/getWebAreaList?source_id=2'
  337. jo = self._get_sth(url, 'fake').json()
  338. cateLive = {}
  339. if jo['code'] == 0:
  340. parent = jo['data']['data']
  341. self.userConfig['cateLive'] = dict(self.pool.map(self.get_live_parent_area_list, parent))
  342. return self.userConfig['cateLive']
  343. def set_default_cateManualLive(self):
  344. cateManualLive = [{'n': '推荐', 'v': '推荐'},]
  345. for name in self.userConfig['cateLive']:
  346. area_dict = {'n': name, 'v': self.userConfig['cateLive'][name]['id']}
  347. cateManualLive.append(area_dict)
  348. self.defaultConfig['cateManualLive'] = cateManualLive
  349. return cateManualLive
  350. add_live_filter_event = threading.Event()
  351. def add_live_filter(self):
  352. cateLive = self.userConfig.get('cateLive', {})
  353. cateLive_task = self.pool.submit(self.get_live_list)
  354. if not cateLive:
  355. cateLive = cateLive_task.result()
  356. default_cateManualLive_task = self.pool.submit(self.set_default_cateManualLive)
  357. self.config["filter"]['直播'] = []
  358. #分区栏
  359. cateManualLive = self.userConfig.get('cateManualLive', [])
  360. if not cateManualLive:
  361. cateManualLive = default_cateManualLive_task.result()
  362. if cateManualLive:
  363. live_area = {'key': 'tid', 'name': '分区', 'value': cateManualLive}
  364. self.config["filter"]['直播'].append(live_area)
  365. #显示分区细分
  366. if int(self.userConfig['showLiveFilterTag']):
  367. for name in cateLive.values():
  368. if len(name['value']['value']) == 1:
  369. continue
  370. self.config["filter"]['直播'].append(name['value'])
  371. self.add_live_filter_event.set()
  372. add_search_key_event = threading.Event()
  373. def add_search_key(self):
  374. focus_on_search_key = self.focus_on_search_key
  375. url = 'https://api.bilibili.com/x/web-interface/search/square?limit=10&platform=web'
  376. jo = self._get_sth(url, 'fake').json()
  377. cateLive = {}
  378. if jo['code'] == 0:
  379. trending = jo['data']['trending'].get('list', [])
  380. focus_on_search_key += list(map(lambda x:x['keyword'], trending))
  381. keyword = {"key": "keyword", "name": "搜索词","value": []}
  382. keyword["value"] = list(map(lambda i: {'n': i, 'v': i}, focus_on_search_key))
  383. self.config["filter"]['搜索'].insert(0, keyword)
  384. self.add_search_key_event.set()
  385. def get_tuijian_filter(self):
  386. tuijian_filter = {"番剧时间表": "10001", "国创时间表": "10004", "排行榜": "0", "动画": "1", "音乐": "3", "舞蹈": "129", "游戏": "4", "鬼畜": "119", "知识": "36", "科技": "188", "运动": "234", "生活": "160", "美食": "211", "动物": "217", "汽车": "223", "时尚": "155", "娱乐": "5", "影视": "181", "原创": "origin", "新人": "rookie"}
  387. _dic = [{'n': 'tuijianLis', 'v': '分区'}, {'n': 'rankingLis', 'v': '排行榜'}]
  388. filter_lis = []
  389. for d in _dic:
  390. _filter = {"key": "tid" ,'name': d['v'],"value": []}
  391. t_lis = self.userConfig.get(d['n'], [])
  392. for t in t_lis:
  393. tf = tuijian_filter.get(t)
  394. if not tf:
  395. tf = t
  396. tf_dict = {'n': t, 'v': tf}
  397. _filter["value"].append(tf_dict)
  398. filter_lis.append(_filter)
  399. self.config["filter"]['推荐'] = filter_lis
  400. def __init__(self):
  401. self.load_config()
  402. self.pool.submit(self.getCookie)
  403. self.pool.submit(self.getFakeCookie)
  404. self.pool.submit(self.getCookie, 'vip')
  405. wts = round(time.time())
  406. self.pool.submit(self.get_wbiKey, wts)
  407. def init(self, extend=""):
  408. print("============{0}============".format(extend))
  409. pass
  410. def isVideoFormat(self, url):
  411. pass
  412. def manualVideoCheck(self):
  413. pass
  414. # 降低内存占用
  415. def format_img(self, img):
  416. img += "@672w_378h_1c.webp"
  417. if not img.startswith('http'):
  418. img = 'https:' + img
  419. return img
  420. def pagination(self, array, pg):
  421. max_number = self.userConfig['page_size'] * int(pg)
  422. min_number = max_number - self.userConfig['page_size']
  423. return array[min_number:max_number]
  424. # 将超过10000的数字换成成以万和亿为单位
  425. def zh(self, num):
  426. if int(num) >= 100000000:
  427. p = round(float(num) / float(100000000), 1)
  428. p = str(p) + '亿'
  429. else:
  430. if int(num) >= 10000:
  431. p = round(float(num) / float(10000), 1)
  432. p = str(p) + '万'
  433. else:
  434. p = str(num)
  435. return p
  436. # 将秒数转化为 时分秒的格式
  437. def second_to_time(self, a):
  438. a = int(a)
  439. if a < 3600:
  440. result = time.strftime("%M:%S", time.gmtime(a))
  441. else:
  442. result = time.strftime("%H:%M:%S", time.gmtime(a))
  443. if str(result).startswith('0'):
  444. result = str(result).replace('0', '', 1)
  445. return result
  446. # 字符串时分秒以及分秒形式转换成秒
  447. def str2sec(self, x):
  448. x = str(x)
  449. try:
  450. h, m, s = x.strip().split(':') # .split()函数将其通过':'分隔开,.strip()函数用来除去空格
  451. return int(h) * 3600 + int(m) * 60 + int(s) # int()函数转换成整数运算
  452. except:
  453. m, s = x.strip().split(':') # .split()函数将其通过':'分隔开,.strip()函数用来除去空格
  454. return int(m) * 60 + int(s) # int()函数转换成整数运算
  455. # 按时间过滤
  456. def filter_duration(self, vodlist, key):
  457. if key == '0':
  458. return vodlist
  459. else:
  460. vod_list_new = [i for i in vodlist if
  461. self.time_diff1[key][0] <= self.str2sec(str(i["vod_remarks"])) < self.time_diff1[key][1]]
  462. return vod_list_new
  463. # 提取番剧id
  464. def find_bangumi_id(self, url):
  465. aid = str(url).split('/')[-1]
  466. if not aid:
  467. aid = str(url).split('/')[-2]
  468. aid = aid.split('?')[0]
  469. return aid
  470. # 登录二维码
  471. def get_Login_qrcode(self, pg):
  472. result = {}
  473. if int(pg) != 1:
  474. return result
  475. video = [{
  476. "vod_id": 'setting_tab&filter',
  477. "vod_name": '标签与筛选',
  478. "vod_pic": 'https://www.bilibili.com/favicon.ico'
  479. },{
  480. "vod_id": 'setting_liveExtra',
  481. "vod_name": '查看直播细化标签',
  482. "vod_pic": 'https://www.bilibili.com/favicon.ico'
  483. }]
  484. url = 'https://passport.bilibili.com/x/passport-login/web/qrcode/generate'
  485. jo = self._get_sth(url, 'fake').json()
  486. if jo['code'] == 0:
  487. id = jo['data']['qrcode_key']
  488. url = jo['data']['url']
  489. account = {'master': '主账号', 'vip': '副账号'}
  490. isLogin = {0: '未登录', 1: '已登录'}
  491. isVIP = {0: '', 1: '👑'}
  492. users = self.userConfig.get('users', {})
  493. for _type, typeName in account.items():
  494. user = users.get(_type)
  495. if user:
  496. video.append({
  497. "vod_id": 'setting_login_' + id,
  498. "vod_name": user['uname'],
  499. "vod_pic": self.format_img(user['face']),
  500. "vod_remarks": isVIP[user['isVIP']] + typeName + ' ' + isLogin[user['isLogin']]
  501. })
  502. pic_url = {'qrcode': url, 'chs': '208x117'}
  503. video.append({
  504. "vod_id": 'setting_login_' + id,
  505. 'vod_pic': 'https://swf.ming92.tk/?' + urlencode(pic_url),
  506. })
  507. result['list'] = video
  508. result['page'] = 1
  509. result['pagecount'] = 1
  510. result['limit'] = 1
  511. result['total'] = 1
  512. return result
  513. time_diff1 = {'1': [0, 300],
  514. '2': [300, 900], '3': [900, 1800], '4': [1800, 3600],
  515. '5': [3600, 99999999999999999999999999999999]
  516. }
  517. time_diff = '0'
  518. dynamic_offset = ''
  519. def get_dynamic(self, pg, mid, order):
  520. if mid == '0':
  521. result = {}
  522. if int(pg) == 1:
  523. self.dynamic_offset = ''
  524. url = 'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?timezone_offset=-480&type=video&offset=%s&page=%s' % (self.dynamic_offset, pg)
  525. jo = self._get_sth(url).json()
  526. if jo['code'] == 0:
  527. self.dynamic_offset = jo['data'].get('offset')
  528. videos = []
  529. vodList = jo['data']['items']
  530. for vod in vodList:
  531. if not vod['visible']:
  532. continue
  533. up = vod['modules']["module_author"]['name']
  534. ivod = vod['modules']['module_dynamic']['major']['archive']
  535. aid = str(ivod['aid']).strip()
  536. title = ivod['title'].strip().replace("<em class=\"keyword\">", "").replace("</em>", "")
  537. img = ivod['cover'].strip()
  538. # remark = str(ivod['duration_text']).strip()
  539. remark = str(self.second_to_time(self.str2sec(ivod['duration_text']))).strip() + ' 🆙' + str(
  540. up).strip() # 显示分钟数+up主名字
  541. videos.append({
  542. "vod_id": 'av' + aid,
  543. "vod_name": title,
  544. "vod_pic": self.format_img(img),
  545. "vod_remarks": remark
  546. })
  547. result['list'] = videos
  548. result['page'] = pg
  549. result['pagecount'] = 9999
  550. result['limit'] = 99
  551. result['total'] = 999999
  552. return result
  553. else:
  554. return self.get_up_videos(mid=mid, pg=pg, order=order)
  555. def get_found_vod(self, vod):
  556. aid = vod.get('aid', '')
  557. if not aid:
  558. aid = vod.get('id', '')
  559. goto = vod.get('goto', '')
  560. if not goto or goto and goto == 'av':
  561. aid = 'av' + str(aid).strip()
  562. elif goto == 'ad':
  563. return []
  564. title = vod['title'].strip()
  565. img = vod['pic'].strip()
  566. is_followed = vod.get('is_followed')
  567. if goto == 'live':
  568. room_info = vod['room_info']
  569. remark = ''
  570. live_status = room_info.get('live_status', '')
  571. if live_status:
  572. remark = '直播中 '
  573. else:
  574. return []
  575. remark += '👁' + room_info['watched_show']['text_small'] + ' 🆙' + vod['owner']['name'].strip()
  576. else:
  577. rcmd_reason = vod.get('rcmd_reason', '')
  578. if rcmd_reason and type(rcmd_reason) == dict and rcmd_reason.get('content'):
  579. reason= ' 🔥' + rcmd_reason['content'].strip()
  580. if '人气飙升' in reason:
  581. reason= ' 🔥人气飙升'
  582. elif is_followed:
  583. reason = ' 已关注'
  584. else:
  585. #reason = " 💬" + self.zh(vod['stat']['danmaku'])
  586. reason = ' 🆙' + vod['owner']['name'].strip()
  587. remark = str(self.second_to_time(vod['duration'])).strip() + " ▶" + self.zh(vod['stat']['view']) + reason
  588. video = [{
  589. "vod_id": aid,
  590. "vod_name": title,
  591. "vod_pic": self.format_img(img),
  592. "vod_remarks": remark
  593. }]
  594. for v in self.pool.map(self.get_found_vod, vod.get('others', [])):
  595. video.extend(v)
  596. return video
  597. _popSeriesInit = 0
  598. def get_found(self, tid, rid, pg):
  599. result = {}
  600. if tid == '推荐':
  601. query = self.encrypt_wbi(fresh_type=4, feed_version='V8', brush=1, fresh_idx=pg, fresh_idx_1h=pg, ps=self.userConfig['page_size'])[0]
  602. url = f'https://api.bilibili.com/x/web-interface/wbi/index/top/feed/rcmd?{query}'
  603. else:
  604. url = 'https://api.bilibili.com/x/web-interface/ranking/v2?rid={0}&type={1}'.format(rid, tid)
  605. if tid == '热门':
  606. url = 'https://api.bilibili.com/x/web-interface/popular?pn={0}&ps={1}'.format(pg, self.userConfig['page_size'])
  607. elif tid == "入站必刷":
  608. url = 'https://api.bilibili.com/x/web-interface/popular/precious'
  609. elif tid == "每周必看":
  610. if not self._popSeriesInit or int(pg) == 1:
  611. url = 'https://api.bilibili.com/x/web-interface/popular/series/list'
  612. jo = self._get_sth(url, 'fake').json()
  613. number = self._popSeriesInit = jo['data']['list'][0]['number']
  614. self._popSeriesNum = [int(number), 1]
  615. else:
  616. number = self._popSeriesNum[0]
  617. url = 'https://api.bilibili.com/x/web-interface/popular/series/one?number=' + str(number)
  618. jo = self._get_sth(url).json()
  619. if jo['code'] == 0:
  620. videos = []
  621. vodList = jo['data'].get('item')
  622. if not vodList:
  623. vodList = jo['data']['list']
  624. if len(vodList) > self.userConfig['page_size']:
  625. if tid == "每周必看":
  626. _tmp_pg = int(self._popSeriesNum[1])
  627. value = len(vodList) / self.userConfig['page_size'] - _tmp_pg
  628. if value > 0:
  629. value += 1
  630. if not int(value):
  631. self._popSeriesNum = [int(number) - 1, 1]
  632. else:
  633. self._popSeriesNum[1] = _tmp_pg + 1
  634. else:
  635. _tmp_pg = pg
  636. vodList = self.pagination(vodList, _tmp_pg)
  637. for v in self.pool.map(self.get_found_vod, vodList):
  638. videos.extend(v)
  639. result['list'] = videos
  640. result['page'] = pg
  641. result['pagecount'] = 9999
  642. result['limit'] = 99
  643. result['total'] = 999999
  644. return result
  645. def get_bangumi(self, tid, pg, order, season_status):
  646. result = {}
  647. if order == '追番剧':
  648. url = 'https://api.bilibili.com/x/space/bangumi/follow/list?type={0}&vmid={1}&pn={2}&ps={3}'.format(tid, self.userid, pg, self.userConfig['page_size'])
  649. jo = self._get_sth(url).json()
  650. else:
  651. url = 'https://api.bilibili.com/pgc/season/index/result?type=1&season_type={0}&page={1}&order={2}&season_status={3}&pagesize={4}'.format(tid, pg, order, season_status, self.userConfig['page_size'])
  652. if order == '热门':
  653. if tid == '1':
  654. url = 'https://api.bilibili.com/pgc/web/rank/list?season_type={0}&day=3'.format(tid)
  655. else:
  656. url = 'https://api.bilibili.com/pgc/season/rank/web/list?season_type={0}&day=3'.format(tid)
  657. jo = self._get_sth(url, 'fake').json()
  658. if jo['code'] == 0:
  659. if 'data' in jo:
  660. vodList = jo['data']['list']
  661. else:
  662. vodList = jo['result']['list']
  663. if len(vodList) > self.userConfig['page_size']:
  664. vodList = self.pagination(vodList, pg)
  665. videos = []
  666. for vod in vodList:
  667. aid = str(vod['season_id']).strip()
  668. title = vod['title']
  669. img = vod.get('ss_horizontal_cover')
  670. if not img or tid == '1' and not self.userConfig['bangumi_horizontal_cover']:
  671. if vod.get('first_ep_info') and 'cover' in vod['first_ep_info']:
  672. img = vod['first_ep_info']['cover']
  673. elif vod.get('first_ep') and 'cover' in vod['first_ep']:
  674. img = vod['first_ep']['cover']
  675. else:
  676. img = vod['cover'].strip()
  677. remark = vod.get('index_show', '')
  678. if not remark and vod.get('new_ep') and vod['new_ep'].get('index_show'):
  679. remark = vod['new_ep']['index_show']
  680. remark = remark.replace('更新至', '🆕')
  681. stat = vod.get('stat')
  682. if stat:
  683. remark = '▶' + self.zh(stat.get('view')) + ' ' + remark
  684. videos.append({
  685. "vod_id": 'ss' + aid,
  686. "vod_name": title,
  687. "vod_pic": self.format_img(img),
  688. "vod_remarks": remark
  689. })
  690. result['list'] = videos
  691. result['page'] = pg
  692. result['pagecount'] = 9999
  693. result['limit'] = 90
  694. result['total'] = 999999
  695. return result
  696. def get_timeline(self, tid, pg):
  697. result = {}
  698. url = 'https://api.bilibili.com/pgc/web/timeline/v2?season_type={0}&day_before=2&day_after=4'.format(tid)
  699. jo = self._get_sth(url, 'fake').json()
  700. if jo['code'] == 0:
  701. videos1 = []
  702. vodList = jo['result']['latest']
  703. for vod in vodList:
  704. aid = str(vod['season_id']).strip()
  705. title = vod['title'].strip()
  706. img = vod['ep_cover'].strip()
  707. remark = '🆕' + vod['pub_index'] + ' ❤ ' + vod['follows'].replace('系列', '').replace('追番', '')
  708. videos1.append({
  709. "vod_id": 'ss' + aid,
  710. "vod_name": title,
  711. "vod_pic": self.format_img(img),
  712. "vod_remarks": remark
  713. })
  714. videos2 = []
  715. vodList2 = jo['result']['timeline']
  716. for i in range(len(vodList2)):
  717. vodList = vodList2[i]['episodes']
  718. for vod in vodList:
  719. if str(vod['published']) == "0":
  720. aid = str(vod['season_id']).strip()
  721. title = str(vod['title']).strip()
  722. img = str(vod['ep_cover']).strip()
  723. date = str(time.strftime("%m-%d %H:%M", time.localtime(vod['pub_ts'])))
  724. remark = date + " " + vod['pub_index']
  725. videos2.append({
  726. "vod_id": 'ss' + aid,
  727. "vod_name": title,
  728. "vod_pic": self.format_img(img),
  729. "vod_remarks": remark
  730. })
  731. result['list'] = videos2 + videos1
  732. result['page'] = 1
  733. result['pagecount'] = 1
  734. result['limit'] = 90
  735. result['total'] = 999999
  736. return result
  737. def get_live(self, pg, parent_area_id, area_id):
  738. result = {}
  739. if parent_area_id == '推荐':
  740. url = 'https://api.live.bilibili.com/xlive/web-interface/v1/webMain/getList?platform=web&page=%s' % pg
  741. jo = self._get_sth(url).json()
  742. else:
  743. url = 'https://api.live.bilibili.com/xlive/web-interface/v1/second/getList?platform=web&parent_area_id=%s&area_id=%s&sort_type=online&page=%s' % (parent_area_id, area_id, pg)
  744. if parent_area_id == '热门':
  745. url = 'https://api.live.bilibili.com/room/v1/room/get_user_recommend?page=%s&page_size=%s' % (pg, self.userConfig['page_size'])
  746. jo = self._get_sth(url, 'fake').json()
  747. if jo['code'] == 0:
  748. videos = []
  749. vodList = jo['data']
  750. if 'recommend_room_list' in vodList:
  751. vodList = vodList['recommend_room_list']
  752. elif 'list' in vodList:
  753. vodList = vodList['list']
  754. for vod in vodList:
  755. aid = str(vod['roomid']).strip()
  756. title = vod['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  757. img = vod.get('user_cover')
  758. if not img:
  759. img = vod.get('cover')
  760. remark = '👁' + vod['watched_show']['text_small'].strip() + " 🆙" + vod['uname'].strip()
  761. videos.append({
  762. "vod_id": aid,
  763. "vod_name": title,
  764. "vod_pic": self.format_img(img),
  765. "vod_remarks": remark
  766. })
  767. result['list'] = videos
  768. result['page'] = pg
  769. result['pagecount'] = 9999
  770. result['limit'] = 99
  771. result['total'] = 999999
  772. return result
  773. def get_up_series(self, mid, pg):
  774. result = {}
  775. url = 'https://api.bilibili.com/x/polymer/web-space/seasons_series_list?mid=%s&page_num=%s&page_size=%s' % (mid, pg, self.userConfig['page_size'])
  776. jo = self._get_sth(url, 'fake').json()
  777. if jo['code'] == 0:
  778. videos = []
  779. jo = jo['data']['items_lists']
  780. vodList = jo['seasons_list'] + jo['series_list']
  781. for vod in vodList:
  782. vod = vod.get('meta')
  783. aid = str(vod.get('season_id', '')).strip()
  784. if aid:
  785. aid = 'list_' + str(mid) + '_season_' + aid
  786. else:
  787. aid = 'list_' + str(mid) + '_series_' + str(vod.get('series_id', '')).strip()
  788. title = vod['name'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  789. img = vod.get('cover')
  790. remark = vod.get('description', '').strip()
  791. videos.append({
  792. "vod_id": aid,
  793. "vod_name": title,
  794. "vod_pic": self.format_img(img),
  795. "vod_remarks": remark
  796. })
  797. result['list'] = videos
  798. result['page'] = pg
  799. result['pagecount'] = 9999
  800. result['limit'] = 99
  801. result['total'] = 999999
  802. return result
  803. get_up_videos_result = {}
  804. def get_up_videos(self, mid, pg, order):
  805. result = {}
  806. if not mid.isdigit():
  807. if int(pg) == 1:
  808. self.get_up_videos_mid = mid = self.detailContent_args.get('mid', '')
  809. if not mid in self.get_up_videos_result:
  810. self.get_up_videos_result.clear()
  811. self.get_up_videos_result[mid] = []
  812. else:
  813. mid = self.get_up_videos_mid
  814. if not mid in self.up_info or int(pg) == 1:
  815. self.get_up_info_event.clear()
  816. self.pool.submit(self.get_up_info, mid)
  817. Space = order2 = ''
  818. if order == 'oldest':
  819. order2 = order
  820. order = 'pubdate'
  821. elif order == 'quicksearch':
  822. Space = '投稿: '
  823. videos = self.get_up_videos_result.get(mid, [])
  824. if videos:
  825. result['list'] = videos
  826. return result
  827. elif order == 'series':
  828. return self.get_up_series(mid=mid, pg=pg)
  829. tmp_pg = pg
  830. if order2:
  831. self.get_up_info_event.wait()
  832. tmp_pg = self.up_info[mid]['vod_pc'] - int(pg) + 1
  833. query = self.encrypt_wbi(mid=mid, pn=tmp_pg, ps=self.userConfig['page_size'], order=order)[0]
  834. url = f'https://api.bilibili.com/x/space/wbi/arc/search?{query}'
  835. jo = self._get_sth(url, 'fake').json()
  836. videos = []
  837. if jo['code'] == 0:
  838. vodList = jo['data']['list']['vlist']
  839. for vod in vodList:
  840. aid = str(vod['aid']).strip()
  841. title = vod['title'].strip().replace("<em class=\"keyword\">", "").replace("</em>", "")
  842. img = vod['pic'].strip()
  843. remark = self.second_to_time(self.str2sec(str(vod['length']).strip())) + " ▶" + self.zh(vod['play'])
  844. if not Space:
  845. remark += " 💬" + self.zh(vod['video_review'])
  846. videos.append({
  847. "vod_id": 'av' + aid,
  848. "vod_name": Space + title,
  849. "vod_pic": self.format_img(img),
  850. "vod_remarks": remark
  851. })
  852. if order2:
  853. videos.reverse()
  854. if int(pg) == 1:
  855. self.get_up_info_event.wait()
  856. up_info = self.up_info[mid]
  857. vodname = up_info['name'] + " 个人主页"
  858. if Space:
  859. vodname = 'UP: ' + up_info['name']
  860. gotoUPHome={
  861. "vod_id": 'up' + str(mid),
  862. "vod_name": vodname,
  863. "vod_pic": self.format_img(up_info['face']),
  864. "vod_remarks": up_info['following'] + ' 👥' + up_info['fans'] + ' 🎬' + str(up_info['vod_count'])
  865. }
  866. videos.insert(0, gotoUPHome)
  867. if Space:
  868. self.get_up_videos_result[mid] = videos
  869. result['list'] = videos
  870. result['page'] = pg
  871. result['pagecount'] = 99
  872. result['limit'] = 99
  873. result['total'] = 999999
  874. return result
  875. history_view_at = 0
  876. def get_history(self, type, pg):
  877. result = {}
  878. if int(pg) == 1:
  879. self.history_view_at = 0
  880. url = 'https://api.bilibili.com/x/web-interface/history/cursor?ps={0}&view_at={1}&type={2}'.format(self.userConfig['page_size'], self.history_view_at, type)
  881. if type == '稍后再看':
  882. url = 'https://api.bilibili.com/x/v2/history/toview'
  883. jo = self._get_sth(url).json()
  884. if jo['code'] == 0:
  885. videos = []
  886. vodList = jo['data'].get('list', [])
  887. if type == '稍后再看':
  888. vodList = self.pagination(vodList, pg)
  889. else:
  890. self.history_view_at = jo['data']['cursor']['view_at']
  891. for vod in vodList:
  892. history = vod.get('history', '')
  893. if history:
  894. business = history['business']
  895. aid = str(history['oid']).strip()
  896. img = vod['cover'].strip()
  897. part = str(history['part']).strip()
  898. else:
  899. business = 'archive'
  900. aid = str(vod["aid"]).strip()
  901. img = vod['pic'].strip()
  902. part = str(vod['page']['part']).strip()
  903. if business == 'article':
  904. continue
  905. elif business == 'pgc':
  906. aid = 'ep' + str(history['epid'])
  907. _total = vod['total']
  908. part = vod.get('show_title')
  909. elif business == 'archive':
  910. aid = 'av' + aid
  911. _total = vod['videos']
  912. title = vod['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  913. if business == 'live':
  914. live_status = vod.get('badge', '')
  915. remark = live_status + ' 🆙' + vod['author_name'].strip()
  916. else:
  917. if str(vod['progress']) == '-1':
  918. remark = '已看完'
  919. elif str(vod['progress']) == '0':
  920. remark = '刚开始看'
  921. else:
  922. process = str(self.second_to_time(vod['progress'])).strip()
  923. remark = '看到 ' + process
  924. if not _total in [0, 1] and part:
  925. remark += ' (' + str(part) + ')'
  926. videos.append({
  927. "vod_id": aid,
  928. "vod_name": title,
  929. "vod_pic": self.format_img(img),
  930. "vod_remarks": remark
  931. })
  932. result['list'] = videos
  933. result['page'] = pg
  934. result['pagecount'] = 9999
  935. result['limit'] = 90
  936. result['total'] = 999999
  937. return result
  938. def get_fav_detail(self, pg, mlid, order):
  939. result = {}
  940. url = 'https://api.bilibili.com/x/v3/fav/resource/list?media_id=%s&order=%s&pn=%s&ps=10&platform=web&type=0' % (mlid, order, pg)
  941. jo = self._get_sth(url).json()
  942. if jo['code'] == 0:
  943. videos = []
  944. vodList = jo['data'].get('medias', [])
  945. for vod in vodList:
  946. # 只展示类型为 视频的条目
  947. # 过滤去掉收藏中的 已失效视频;如果不喜欢可以去掉这个 if条件
  948. if vod.get('type') in [2] and vod.get('title') != '已失效视频':
  949. aid = str(vod['id']).strip()
  950. title = vod['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",
  951. '"')
  952. img = vod['cover'].strip()
  953. remark = str(self.second_to_time(vod['duration'])).strip() + " ▶" + self.zh(vod['cnt_info']['play']) + " 💬" + self.zh(vod['cnt_info']['danmaku'])
  954. videos.append({
  955. "vod_id": 'av' + aid + '_mlid' + str(mlid),
  956. "vod_name": title,
  957. "vod_pic": self.format_img(img),
  958. "vod_remarks": remark
  959. })
  960. # videos=self.filter_duration(videos, duration_diff)
  961. result['list'] = videos
  962. result['page'] = pg
  963. result['pagecount'] = 9999
  964. result['limit'] = 99
  965. result['total'] = 999999
  966. return result
  967. def get_up_videoNum(self, mid):
  968. info={}
  969. url = "https://api.bilibili.com/x/space/navnum?mid={0}".format(mid)
  970. jRoot = self._get_sth(url).json()
  971. if jRoot['code'] == 0:
  972. info['vod_count'] = str(jRoot['data']['video']).strip()
  973. pc = divmod(int(info['vod_count']), self.userConfig['page_size'])
  974. vod_pc = pc[0]
  975. if pc[1] != 0:
  976. vod_pc += 1
  977. info['vod_pc'] = vod_pc
  978. return info
  979. get_up_info_event = threading.Event()
  980. up_info = {}
  981. def get_up_info(self, mid, **kwargs):
  982. get_up_videoNum = self.pool.submit(self.get_up_videoNum, mid)
  983. data = kwargs.get('data')
  984. if not data:
  985. url = "https://api.bilibili.com/x/web-interface/card?mid={0}".format(mid)
  986. jRoot = self._get_sth(url).json()
  987. if jRoot['code'] == 0:
  988. data = jRoot['data']
  989. else:
  990. self.get_up_info_event.set()
  991. return {}
  992. jo = data['card']
  993. info = {}
  994. info['following'] = '未关注'
  995. if data['following']:
  996. info['following'] = '已关注'
  997. info['name'] = info['crname'] = jo['name'].replace("<em class=\"keyword\">", "").replace("</em>", "")
  998. info['face'] = jo['face']
  999. info['fans'] = self.zh(jo['fans'])
  1000. info['like_num'] = self.zh(data['like_num'])
  1001. info['desc'] = jo['Official']['desc'] + " " + jo['Official']['title']
  1002. info.update(get_up_videoNum.result())
  1003. self.up_info[mid] = info
  1004. self.get_up_info_event.set()
  1005. return info
  1006. def get_vod_relation(self, query):
  1007. url = f'https://api.bilibili.com/x/web-interface/archive/relation?{query}'
  1008. jo = self._get_sth(url).json()
  1009. relation = []
  1010. if jo['code'] == 0:
  1011. jo = jo['data']
  1012. if jo['attention']:
  1013. relation.append('已关注')
  1014. else:
  1015. relation.append('未关注')
  1016. triple = []
  1017. if jo['favorite']:
  1018. triple.append('⭐')
  1019. if jo['like']:
  1020. triple.append('👍')
  1021. coin = jo.get('coin')
  1022. if coin:
  1023. triple.append('💰'*coin)
  1024. if len(triple) == 3:
  1025. relation.append('👍💰⭐')
  1026. else:
  1027. relation.extend(triple)
  1028. if jo['dislike']:
  1029. relation.append('👎')
  1030. if jo['season_fav']:
  1031. relation.append('已订阅合集')
  1032. return relation
  1033. def get_channel(self, pg, cid, order):
  1034. result = {}
  1035. if str(pg) == '1':
  1036. self.channel_offset = ''
  1037. if order == "featured":
  1038. url = 'https://api.bilibili.com/x/web-interface/web/channel/featured/list?channel_id={0}&filter_type=0&offset={1}&page_size={2}'.format(cid, self.channel_offset, self.userConfig['page_size'])
  1039. else:
  1040. url = 'https://api.bilibili.com/x/web-interface/web/channel/multiple/list?channel_id={0}&sort_type={1}&offset={2}&page_size={3}'.format(cid, order, self.channel_offset, self.userConfig['page_size'])
  1041. jo = self._get_sth(url, 'master').json()
  1042. if jo.get('code') == 0:
  1043. self.channel_offset = jo['data'].get('offset')
  1044. videos = []
  1045. vodList = jo['data']['list']
  1046. if pg == '1' and 'items' in vodList[0]:
  1047. vodList_rank = vodList[0]['items']
  1048. del (vodList[0])
  1049. vodList = vodList_rank + vodList
  1050. for vod in vodList:
  1051. if 'uri' in vod and 'bangumi' in vod['uri']:
  1052. aid = self.find_bangumi_id(vod['uri'])
  1053. else:
  1054. aid = 'av' + str(vod['id']).strip()
  1055. title = vod['name'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  1056. img = vod['cover'].strip()
  1057. remark = "▶" + str(vod['view_count'])
  1058. duration = vod.get('duration', '')
  1059. if duration:
  1060. remark = str(self.second_to_time(self.str2sec(duration))).strip() + ' ' + remark
  1061. danmaku = vod.get('danmaku', '')
  1062. like_count = vod.get('like_count', '')
  1063. follow_count = vod.get('follow_count', '')
  1064. if danmaku:
  1065. remark += " 💬" + self.zh(danmaku)
  1066. elif like_count:
  1067. remark += " 👍" + str(like_count)
  1068. elif follow_count:
  1069. remark += " ❤" + str(follow_count)
  1070. videos.append({
  1071. "vod_id": aid,
  1072. "vod_name": title,
  1073. "vod_pic": self.format_img(img),
  1074. "vod_remarks": remark
  1075. })
  1076. result['list'] = videos
  1077. result['page'] = pg
  1078. result['pagecount'] = 9999
  1079. result['limit'] = 99
  1080. result['total'] = 999999
  1081. return result
  1082. def get_follow(self, pg, sort):
  1083. result = {}
  1084. if sort == "最常访问":
  1085. url = 'https://api.bilibili.com/x/relation/followings?vmid={0}&pn={1}&ps=10&order=desc&order_type=attention' .format(self.userid, pg)
  1086. elif sort == "最近关注":
  1087. url = 'https://api.bilibili.com/x/relation/followings?vmid={0}&pn={1}&ps=10&order=desc&order_type='.format(self.userid, pg)
  1088. elif sort == "正在直播":
  1089. url = 'https://api.live.bilibili.com/xlive/web-ucenter/v1/xfetter/GetWebList?page={0}&page_size=10'.format(pg)
  1090. elif sort == "最近访问":
  1091. url = 'https://api.bilibili.com/x/v2/history?pn={0}&ps=15'.format(pg)
  1092. elif sort == "特别关注":
  1093. url = 'https://api.bilibili.com/x/relation/tag?mid={0}&tagid=-10&pn={1}&ps=10'.format(self.userid, pg)
  1094. elif sort == "悄悄关注":
  1095. url = 'https://api.bilibili.com/x/relation/whispers?pn={0}&ps=10'.format(pg)
  1096. else:
  1097. url = 'https://api.bilibili.com/x/relation/followers?vmid={0}&pn={1}&ps=10&order=desc&order_type=attention'.format(self.userid, pg)
  1098. jo = self._get_sth(url).json()
  1099. if jo['code'] != 0:
  1100. return result
  1101. if sort == "特别关注" or sort == "最近访问":
  1102. vodList = jo['data']
  1103. elif sort == "正在直播":
  1104. vodList = jo['data']['rooms']
  1105. else:
  1106. vodList = jo['data']['list']
  1107. if int(pg) == 1:
  1108. self.recently_up_list = []
  1109. follow = []
  1110. for f in vodList:
  1111. remark = ''
  1112. if sort == "最近访问":
  1113. mid = 'up' + str(f['owner']['mid'])
  1114. if mid in self.recently_up_list:
  1115. continue
  1116. self.recently_up_list.append(mid)
  1117. title = str(f['owner']['name']).strip()
  1118. img = str(f['owner']['face']).strip()
  1119. elif sort == "正在直播":
  1120. mid = str(f['room_id'])
  1121. title = f['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  1122. img = f['cover_from_user'].strip()
  1123. remark = f['uname'].strip()
  1124. else:
  1125. mid = 'up' + str(f['mid'])
  1126. title = str(f['uname']).strip()
  1127. img = str(f['face']).strip()
  1128. if 'special' in f and f['special'] == 1:
  1129. remark = '特别关注'
  1130. follow.append({
  1131. "vod_id": mid,
  1132. "vod_name": title,
  1133. "vod_pic": self.format_img(img),
  1134. "vod_remarks": remark
  1135. })
  1136. result['list'] = follow
  1137. result['page'] = pg
  1138. result['pagecount'] = 9999
  1139. result['limit'] = 99
  1140. result['total'] = 999999
  1141. return result
  1142. homeVideoContent_result = {}
  1143. def homeVideoContent(self):
  1144. if not self.homeVideoContent_result:
  1145. videos = self.get_found(rid='0', tid='all', pg=1)['list'][0:int(self.userConfig['maxHomeVideoContent'])]
  1146. self.homeVideoContent_result['list'] = videos
  1147. return self.homeVideoContent_result
  1148. def categoryContent(self, tid, pg, filter, extend):
  1149. self.stop_heartbeat_event.set()
  1150. if tid == "推荐":
  1151. if 'tid' in extend:
  1152. tid = extend['tid']
  1153. if tid.isdigit():
  1154. tid = int(tid)
  1155. if tid > 10000:
  1156. tid -= 10000
  1157. return self.get_timeline(tid=tid, pg=pg)
  1158. rid = tid
  1159. tid = 'all'
  1160. return self.get_found(tid=tid, rid=rid, pg=pg)
  1161. rid = '0'
  1162. return self.get_found(tid=tid, rid=rid, pg=pg)
  1163. elif tid == "影视":
  1164. tid = '1'
  1165. order = '热门'
  1166. season_status = '-1'
  1167. if 'tid' in extend:
  1168. tid = extend['tid']
  1169. if 'order' in extend:
  1170. order = extend['order']
  1171. if 'season_status' in extend:
  1172. if order == '热门':
  1173. order = '2'
  1174. season_status = extend['season_status']
  1175. return self.get_bangumi(tid, pg, order, season_status)
  1176. elif tid == "动态":
  1177. mid = '0'
  1178. order = 'pubdate'
  1179. if 'mid' in extend:
  1180. mid = extend['mid']
  1181. if 'order' in extend:
  1182. order = extend['order']
  1183. if mid == '0' and not self.userid or mid == '登录':
  1184. return self.get_Login_qrcode(pg)
  1185. return self.get_dynamic(pg=pg, mid=mid, order=order)
  1186. elif tid == '频道':
  1187. order = 'hot'
  1188. cid = random.choice(self.userConfig['channel_list'])
  1189. cid = cid['v']
  1190. if 'order' in extend:
  1191. order = extend['order']
  1192. if 'cid' in extend:
  1193. cid = extend['cid']
  1194. return self.get_channel(pg=pg, cid=cid, order=order)
  1195. elif tid == '直播':
  1196. tid = "热门"
  1197. area_id = '0'
  1198. if 'tid' in extend:
  1199. tid = extend['tid']
  1200. if '_' in tid:
  1201. tids = tid.split('_')
  1202. tid = tids[0]
  1203. area_id = tids[1]
  1204. return self.get_live(pg=pg, parent_area_id=tid, area_id=area_id)
  1205. elif tid == "UP":
  1206. mid = self.detailContent_args.get('mid', '')
  1207. if 'mid' in extend:
  1208. mid = extend['mid']
  1209. if not mid or mid == '登录':
  1210. return self.get_Login_qrcode(pg)
  1211. up_config = self.config["filter"].get('UP')
  1212. if not mid and up_config:
  1213. for i in up_config:
  1214. if i['key'] == 'mid':
  1215. if len(i['value']) > 1:
  1216. mid = i['value'][1]['v']
  1217. break
  1218. order = 'pubdate'
  1219. if 'order' in extend:
  1220. order = extend['order']
  1221. return self.get_up_videos(mid=mid, pg=pg, order=order)
  1222. elif tid == "关注":
  1223. sort = "最常访问"
  1224. if 'sort' in extend:
  1225. sort = extend['sort']
  1226. return self.get_follow(pg, sort)
  1227. elif tid == "收藏":
  1228. mlid = str(self.userConfig['favMode'])
  1229. if 'mlid' in extend:
  1230. mlid = extend['mlid']
  1231. fav_config = self.config["filter"].get('收藏')
  1232. if mlid in ['1', '2']:
  1233. return self.get_bangumi(tid=mlid, pg=pg, order='追番剧', season_status='')
  1234. elif mlid == '0' and fav_config:
  1235. for i in fav_config:
  1236. if i['key'] == 'mlid':
  1237. if len(i['value']) > 1:
  1238. mlid = i['value'][2]['v']
  1239. break
  1240. order = 'mtime'
  1241. if 'order' in extend:
  1242. order = extend['order']
  1243. return self.get_fav_detail(pg=pg, mlid=mlid, order=order)
  1244. elif tid == '历史':
  1245. type = 'all'
  1246. if 'type' in extend:
  1247. type = extend['type']
  1248. if type == 'UP主':
  1249. return self.get_follow(pg=pg, sort='最近访问')
  1250. return self.get_history(type=type, pg=pg)
  1251. else:
  1252. duration_diff = '0'
  1253. if 'duration' in extend:
  1254. duration_diff = extend['duration']
  1255. type = 'video'
  1256. if 'type' in extend:
  1257. type = extend['type']
  1258. order = 'totalrank'
  1259. if 'order' in extend:
  1260. order = extend['order']
  1261. keyword = str(self.search_key)
  1262. search_config = self.config["filter"].get('搜索')
  1263. if not keyword and search_config:
  1264. for i in search_config:
  1265. if i['key'] == 'keyword':
  1266. if len(i['value']) > 0:
  1267. keyword = i['value'][0]['v']
  1268. break
  1269. if 'keyword' in extend:
  1270. keyword = extend['keyword']
  1271. return self.get_search_content(key=keyword, pg=pg, duration_diff=duration_diff, order=order, type=type, ps=self.userConfig['page_size'])
  1272. def get_search_content(self, key, pg, duration_diff, order, type, ps):
  1273. value = None
  1274. if not str(pg).isdigit():
  1275. value = pg
  1276. pg = 1
  1277. query = self.encrypt_wbi(keyword=key, page=pg, duration=duration_diff, order=order, search_type=type, page_size=ps)[0]
  1278. url = f'https://api.bilibili.com/x/web-interface/wbi/search/type?{query}'
  1279. jo = self._get_sth(url, 'fake').json()
  1280. result = {}
  1281. if jo.get('code') == 0 and 'result' in jo['data']:
  1282. videos = []
  1283. vodList = jo['data'].get('result')
  1284. if vodList and type == 'live':
  1285. vodList = vodList.get('live_room')
  1286. if not vodList:
  1287. return result
  1288. for vod in vodList:
  1289. if type != vod['type']:
  1290. continue
  1291. title = ''
  1292. if type == 'bili_user':
  1293. aid = 'up' + str(vod['mid']).strip()
  1294. img = vod['upic'].strip()
  1295. remark = '👥' + self.zh(vod['fans']) + " 🎬" + self.zh(vod['videos'])
  1296. title = vod['uname']
  1297. elif type == 'live':
  1298. aid = str(vod['roomid']).strip()
  1299. img = vod['cover'].strip()
  1300. remark = '👁' + self.zh(vod['online']) + ' 🆙' + vod['uname']
  1301. elif 'media' in type:
  1302. aid = str(vod['season_id']).strip()
  1303. if self.detailContent_args:
  1304. seasons = self.detailContent_args.get('seasons')
  1305. if seasons:
  1306. bangumi_seasons_id = []
  1307. for ss in self.detailContent_args['seasons']:
  1308. bangumi_seasons_id.append(ss['vod_id'])
  1309. if aid + 'ss' in bangumi_seasons_id:
  1310. continue
  1311. aid = 'ss' + aid
  1312. img = vod['cover'].strip()
  1313. remark = str(vod['index_show']).strip().replace('更新至', '🆕')
  1314. else:
  1315. aid = 'av' + str(vod['aid']).strip()
  1316. img = vod['pic'].strip()
  1317. remark = str(self.second_to_time(self.str2sec(vod['duration']))).strip() + " ▶" + self.zh(vod['play'])
  1318. if value == None:
  1319. remark += " 💬" + self.zh(vod['danmaku'])
  1320. if not title:
  1321. title = vod['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').replace('&amp;', '&')
  1322. if value:
  1323. title = value + title
  1324. videos.append({
  1325. "vod_id": aid,
  1326. "vod_name": title,
  1327. "vod_pic": self.format_img(img),
  1328. "vod_remarks": remark
  1329. })
  1330. result['list'] = videos
  1331. result['page'] = pg
  1332. result['pagecount'] = 9999
  1333. result['limit'] = 99
  1334. result['total'] = 999999
  1335. return result
  1336. def cleanSpace(self, str):
  1337. return str.replace('\n', '').replace('\t', '').replace('\r', '').replace(' ', '')
  1338. def get_normal_episodes(self, episode):
  1339. aid = episode.get('aid', '')
  1340. if not aid:
  1341. aid = self.detailContent_args['aid']
  1342. cid = episode.get('cid', '')
  1343. ep_title = episode.get('title', '')
  1344. if not ep_title:
  1345. ep_title = episode.get('part', '')
  1346. duration = episode.get('duration', '')
  1347. if not duration:
  1348. page = episode.get('page', '')
  1349. if page:
  1350. duration = page['duration']
  1351. badge = long_title = preview = parse = ''
  1352. epid = episode.get('ep_id', '')
  1353. if 'redirect_url' in episode and 'bangumi' in episode['redirect_url']:
  1354. epid = self.find_bangumi_id(episode['redirect_url'])
  1355. if epid:
  1356. if duration and str(duration).endswith('000'):
  1357. duration = int(duration / 1000)
  1358. if ep_title.isdigit():
  1359. ep_title = '第' + ep_title + self.detailContent_args['title_type']
  1360. badge = episode.get('badge', '')
  1361. if not self.session_vip.cookies and badge == '会员' and self.userConfig['bangumi_vip_parse'] or badge == '付费' and self.userConfig['bangumi_pay_parse']:
  1362. parse = '1'
  1363. if self.session_vip.cookies and self.userConfig['hide_bangumi_vip_badge']:
  1364. badge = badge.replace('会员', '')
  1365. if self.userConfig['hide_bangumi_preview'] and badge == '预告':
  1366. badge = badge.replace('预告', '')
  1367. preview = '1'
  1368. if badge:
  1369. badge = '【' + badge + '】'
  1370. long_title = episode.get('long_title', '')
  1371. if not badge and long_title:
  1372. long_title = ' ' + long_title
  1373. title = ep_title + badge + long_title
  1374. title = title.replace("#", "﹟").replace("$", "﹩")
  1375. url = f"{title}${aid}_{cid}_{epid}_{duration}_"
  1376. fromep = self.detailContent_args.get('fromep', '')
  1377. if fromep == 'ep' + str(epid):
  1378. self.detailContent_args['fromep'] = url
  1379. replyList = self.detailContent_args.get('Reply')
  1380. if fromep == 'ep' + str(epid) or not fromep and replyList == None:
  1381. self.detailContent_args['Reply'] = ''
  1382. if self.userConfig['show_vod_hot_reply']:
  1383. self.get_vod_hot_reply_event.clear()
  1384. self.pool.submit(self.get_vod_hot_reply, aid)
  1385. ssid = self.detailContent_args.get('ssid', '')
  1386. if ssid:
  1387. if preview:
  1388. return url, ''
  1389. if parse:
  1390. self.detailContent_args['parse'] = 1
  1391. if long_title:
  1392. long_title = '【解析】' + long_title
  1393. ep_title += long_title
  1394. parseurl = f"{ep_title}${aid}_{cid}_{epid}_{duration}_{parse}"
  1395. if fromep == 'ep' + str(epid):
  1396. self.detailContent_args['fromep'] += '#' + parseurl
  1397. else:
  1398. parseurl = url
  1399. return url, parseurl
  1400. else:
  1401. return url
  1402. def get_ugc_season(self, section, sections_len):
  1403. if sections_len > 1:
  1404. sec_title = self.detailContent_args['season_title'] + ' ' + section['title']
  1405. else:
  1406. sec_title = self.detailContent_args['season_title']
  1407. sec_title = sec_title.replace("#", "﹟").replace("$", "﹩")
  1408. episodes = section.get('episodes')
  1409. playUrl = '#'.join(map(self.get_normal_episodes, episodes))
  1410. result = (sec_title, playUrl)
  1411. return result
  1412. get_vod_hot_reply_event = threading.Event()
  1413. def get_vod_hot_reply(self, oid):
  1414. query = self.encrypt_wbi(type=1, ps=30, oid=str(oid))[0]
  1415. url = f'http://api.bilibili.com/x/v2/reply/wbi/main?{query}'
  1416. jRoot = self._get_sth(url, 'fake').json()
  1417. if jRoot['code'] == 0:
  1418. replies = jRoot['data'].get('replies')
  1419. top_replies = jRoot['data'].get('top_replies')
  1420. if replies and top_replies:
  1421. replies = top_replies + replies
  1422. if replies:
  1423. up_mid = jRoot['data']['upper']['mid']
  1424. ReplyList = []
  1425. Reply_jump = []
  1426. for r in replies:
  1427. rpid = r['rpid']
  1428. sex = r['member']['sex']
  1429. if sex and sex == '女':
  1430. sex = '👧'
  1431. else:
  1432. sex = '👦'
  1433. name = sex + r['member']['uname'] + ':'
  1434. mid = r['mid']
  1435. if mid == up_mid:
  1436. name = '🆙' + name
  1437. like = '👍' + self.zh(r['like'])
  1438. message = r['content']['message']
  1439. if '/note-app/' in message:
  1440. continue
  1441. content = like + ' ' + name + message
  1442. content = content.replace("#", "﹟").replace("$", "﹩")
  1443. content += '$' + str(oid) + '_' + str(rpid) + '_notplay_reply'
  1444. ReplyList.append(content)
  1445. jump_url = r['content'].get('jump_url',{})
  1446. for key, value in jump_url.items():
  1447. if not value.get('app_url_schema') and not value.get('pc_url'):
  1448. if key.startswith('https://www.bilibili.com/'):
  1449. key = str(key).split('?')[0].split('/')
  1450. while key[-1] == '':
  1451. key.pop(-1)
  1452. key = key[-1]
  1453. if key.startswith('https://b23.tv/') or key.startswith('BV') or key.startswith('ep') or key.startswith('ss'):
  1454. title = str(value['title']).replace("#", "﹟").replace("$", "﹩")
  1455. vod = {'vod_id': str(key), 'vod_name': '评论:' + title}
  1456. if not vod in Reply_jump:
  1457. Reply_jump.append(vod)
  1458. title = '快搜:' + str(key) +' ' + title
  1459. content = title + '$ '
  1460. ReplyList.append(content)
  1461. self.detailContent_args['Reply'] = '#'.join(ReplyList)
  1462. self.detailContent_args['Reply_jump'] = Reply_jump
  1463. self.get_vod_hot_reply_event.set()
  1464. detailContent_args = {}
  1465. def detailContent(self, array):
  1466. try:
  1467. for t in self.task_pool:
  1468. t.cancel()
  1469. finally:
  1470. self.stop_heartbeat_event.set()
  1471. aid = array[0]
  1472. if aid.startswith('edgeid'):
  1473. return self.interaction_detailContent(aid)
  1474. elif aid.startswith('list'):
  1475. return self.series_detailContent(aid)
  1476. self.detailContent_args = {}
  1477. if aid.startswith('https://b23.tv/'):
  1478. try:
  1479. r = requests_get(url=aid, headers=self.header, allow_redirects=False)
  1480. url = r.headers['Location'].split('?')[0].split('/')
  1481. while url[-1] == '':
  1482. url.pop(-1)
  1483. aid = url[-1]
  1484. if not aid.startswith('BV', 0, 2):
  1485. return {}
  1486. except:
  1487. return {}
  1488. id = mlid = urlargs = ''
  1489. self.get_vod_hot_reply_event.set()
  1490. if aid.startswith('setting'):
  1491. aid = aid.split('_')
  1492. if aid[1] == 'tab&filter':
  1493. return self.setting_tab_filter_detailContent()
  1494. elif aid[1] == 'liveExtra':
  1495. return self.setting_liveExtra_detailContent()
  1496. elif aid[1] == 'login':
  1497. key = aid[2]
  1498. return self.setting_login_detailContent(key)
  1499. elif aid.startswith('av') or aid.startswith('BV'):
  1500. for i in aid.split('_'):
  1501. if i.startswith('av'):
  1502. id = i.replace('av', '', 1)
  1503. query = self.encrypt_wbi(aid=id)[0]
  1504. elif i.startswith('BV'):
  1505. id = i
  1506. query = self.encrypt_wbi(bvid=id)[0]
  1507. elif i.startswith('mlid'):
  1508. mlid = i.replace('mlid', '', 1)
  1509. #获取热门评论
  1510. if self.userConfig['show_vod_hot_reply']:
  1511. self.detailContent_args['Reply'] = ''
  1512. self.get_vod_hot_reply_event.clear()
  1513. self.pool.submit(self.get_vod_hot_reply, id)
  1514. elif 'up' in aid:
  1515. return self.up_detailContent(array)
  1516. elif 'ss' in aid or 'ep' in aid:
  1517. return self.ysContent(array)
  1518. elif aid.isdigit():
  1519. return self.live_detailContent(array)
  1520. relation = self.pool.submit(self.get_vod_relation, query)
  1521. url = f'https://api.bilibili.com/x/web-interface/wbi/view/detail?{query}'
  1522. jRoot = self._get_sth(url, 'fake').json()
  1523. if jRoot['code'] != 0:
  1524. return {}
  1525. jo = jRoot['data']['View']
  1526. redirect_url = jo.get('redirect_url', '')
  1527. if 'bangumi' in redirect_url:
  1528. array[0] = self.find_bangumi_id(redirect_url)
  1529. return self.ysContent(array)
  1530. self.detailContent_args['mid'] = up_mid = str(jo['owner']['mid'])
  1531. self.detailContent_args['aid'] = aid = jo.get('aid')
  1532. up_info = self.pool.submit(self.get_up_info, mid=up_mid, data=jRoot['data'].get('Card'))
  1533. #相关合集
  1534. ugc_season = jo.get('ugc_season')
  1535. if ugc_season:
  1536. self.detailContent_args['season_title'] = ugc_season['title']
  1537. sections = ugc_season['sections']
  1538. sections_len = len(sections)
  1539. ugc_season_task = []
  1540. for section in sections:
  1541. t = self.pool.submit(self.get_ugc_season, section, sections_len)
  1542. ugc_season_task.append(t)
  1543. #相关推荐
  1544. jo_Related = jRoot['data'].get('Related')
  1545. #正片
  1546. pages = jo['pages']
  1547. title = jo['title'].replace("<em class=\"keyword\">", "").replace("</em>", "")
  1548. pic = jo['pic']
  1549. desc = jo['desc'].strip()
  1550. typeName = jo['tname']
  1551. date = time.strftime("%Y%m%d", time.localtime(jo['pubdate'])) # 投稿时间本地年月日表示
  1552. stat = jo['stat']
  1553. # 演员项展示视频状态,包括以下内容:
  1554. remark = []
  1555. remark.append('▶' + self.zh(stat['view']))
  1556. remark.append('💬' + self.zh(stat['danmaku']))
  1557. remark.append('👍' + self.zh(stat['like']))
  1558. remark.append('💰' + self.zh(stat['coin']))
  1559. remark.append('⭐' + self.zh(stat['favorite']))
  1560. _is_stein_gate = jo['rights'].get('is_stein_gate', 0)
  1561. vod = {
  1562. "vod_id": 'av' + str(aid),
  1563. "vod_name": title,
  1564. "vod_pic": pic,
  1565. "type_name": typeName,
  1566. "vod_year": date,
  1567. "vod_content": desc
  1568. }
  1569. vod['vod_actor'] = " ".join(remark)
  1570. vod['vod_area'] = "bilidanmu"
  1571. secondP = []
  1572. if self.userid:
  1573. #做点什么
  1574. follow = '➕关注$1_notplay_follow'
  1575. unfollow = '➖取关$2_notplay_follow'
  1576. like = '👍点赞$1_notplay_like'
  1577. unlike = '👍🏻取消点赞$2_notplay_like'
  1578. coin1 = '👍💰投币$1_notplay_coin'
  1579. coin2 = '👍💰💰$2_notplay_coin'
  1580. triple = '👍💰⭐三连$notplay_triple'
  1581. secondPList = [follow, triple, like, coin1, coin2, unfollow, unlike]
  1582. if mlid:
  1583. favdel = f"☆取消收藏${mlid}_del_notplay_fav"
  1584. secondPList.append(favdel)
  1585. for fav in self.userConfig.get("fav_list", []):
  1586. folder = fav['n'].replace("#", "﹟").replace("$", "﹩")
  1587. ids = fav['v']
  1588. fav = '⭐{}${}_add_notplay_fav'.format(folder, ids)
  1589. secondPList.append(fav)
  1590. defaultQn = int(self.userConfig['vodDefaultQn'])
  1591. if defaultQn > 80:
  1592. secondPList.append('⚠️限高1080$80_notplay_vodTMPQn')
  1593. secondP = ['#'.join(secondPList)]
  1594. AllPt = []
  1595. AllPu = []
  1596. if pages:
  1597. AllPt = ['视频分集']
  1598. if _is_stein_gate:
  1599. AllPt = ['互动视频【快搜继续】']
  1600. AllPu = ['#'.join(self.pool.map(self.get_normal_episodes, pages))]
  1601. if secondP:
  1602. AllPt.append('做点什么')
  1603. AllPu.extend(secondP)
  1604. if self.userConfig['show_vod_hot_reply']:
  1605. self.get_vod_hot_reply_event.wait()
  1606. replyList = self.detailContent_args.get('Reply', '')
  1607. if replyList:
  1608. AllPt.append('热门评论')
  1609. AllPu.extend([replyList])
  1610. if jo_Related:
  1611. AllPt.append('相关推荐')
  1612. AllPu.append('#'.join(self.pool.map(self.get_normal_episodes, jo_Related)))
  1613. if ugc_season:
  1614. for t in as_completed(ugc_season_task):
  1615. AllPt.append(t.result()[0])
  1616. AllPu.append(t.result()[1])
  1617. vod['vod_play_from'] = "$$$".join(AllPt)
  1618. vod['vod_play_url'] = "$$$".join(AllPu)
  1619. #视频关系
  1620. up_info = up_info.result()
  1621. vod['vod_director'] = '🆙 ' + up_info['crname'] + ' 👥 ' + up_info['fans'] + ' ' + ' '.join(relation.result())
  1622. #互动视频套用
  1623. if _is_stein_gate:
  1624. self.detailContent_args['AllPt'] = AllPt.copy()
  1625. self.detailContent_args['AllPu'] = AllPu.copy()
  1626. self.detailContent_args['vod_list'] = vod.copy()
  1627. result = {
  1628. 'list': [
  1629. vod
  1630. ]
  1631. }
  1632. return result
  1633. def series_detailContent(self, array):
  1634. mid, type, sid = array.replace('list_', '').split('_')
  1635. pg = 1
  1636. ps = 99
  1637. vod = {"vod_id": array, "vod_play_from": "B站"}
  1638. urlL = []
  1639. while True:
  1640. if type == 'season':
  1641. url = 'https://api.bilibili.com/x/polymer/web-space/seasons_archives_list?mid=%s&season_id=%s&page_num=%s&page_size=%s' % (mid, sid, pg, ps)
  1642. else:
  1643. url = 'https://api.bilibili.com/x/series/archives?mid=%s&series_id=%s&pn=%s&ps=%s' % (mid, sid, pg, ps)
  1644. jo = self._get_sth(url, 'fake').json()
  1645. data = jo.get('data')
  1646. if not vod.get("vod_name"):
  1647. if data.get('meta'):
  1648. vod["vod_name"] = data['meta']['name']
  1649. vod["vod_pic"] = data['meta']['cover']
  1650. vod["vod_content"] = data['meta']['description']
  1651. else:
  1652. vod["vod_name"] = data['archives'][0]['title']
  1653. playUrl = '#'.join(map(self.get_normal_episodes, data.get('archives')))
  1654. urlL.append(playUrl)
  1655. total = data['page']['total']
  1656. if (ps * pg) >= total:
  1657. break
  1658. pg += 1
  1659. vod['vod_play_url'] = '#'.join(urlL)
  1660. up_info = self.up_info[mid]
  1661. vod['vod_director'] = '🆙 ' + up_info['name'] + " " + up_info['following']
  1662. result = {
  1663. 'list': [
  1664. vod
  1665. ]
  1666. }
  1667. return result
  1668. def interaction_detailContent(self, array=''):
  1669. array = array.split('_')
  1670. cid = edgeid = 0
  1671. for i in array:
  1672. if i.startswith('edgeid'):
  1673. edgeid = i.replace('edgeid', '')
  1674. elif i.startswith('cid'):
  1675. cid = i.replace('cid', '')
  1676. aid = self.detailContent_args.get('aid')
  1677. graph_version = self.detailContent_args.get('graph_version')
  1678. url = 'https://api.bilibili.com/x/stein/edgeinfo_v2?aid={0}&graph_version={1}&edge_id={2}'.format(aid, graph_version, edgeid)
  1679. data = self._get_sth(url, 'fake').json().get('data')
  1680. result = {}
  1681. if data:
  1682. questions = data['edges'].get('questions', [])
  1683. choice_lis = []
  1684. for question in questions:
  1685. q_title = str(question.get('title', ''))
  1686. if q_title:
  1687. q_title += ' '
  1688. for choice in question.get('choices', []):
  1689. c_edgeid = str(choice['id'])
  1690. c_cid = str(choice['cid'])
  1691. option = str(choice.get('option', ''))
  1692. choice_lis.append({
  1693. "vod_id": 'edgeid' + c_edgeid + '_' + 'cid' + c_cid,
  1694. "vod_name": '互动:' + q_title + option,
  1695. })
  1696. self.detailContent_args['interaction'] = choice_lis.copy()
  1697. if edgeid:
  1698. AllPt = self.detailContent_args['AllPt'].copy()
  1699. if not choice_lis:
  1700. AllPt[0] = '互动视频'
  1701. AllPu = self.detailContent_args['AllPu'].copy()
  1702. title = str(data['title']).replace("#", "﹟").replace("$", "﹩")
  1703. url = '{0}${1}_{2}'.format(title, aid, cid)
  1704. AllPu[0] = url
  1705. vod = self.detailContent_args['vod_list'].copy()
  1706. vod['vod_play_from'] = "$$$".join(AllPt)
  1707. vod['vod_play_url'] = "$$$".join(AllPu)
  1708. result['list'] = [vod]
  1709. return result
  1710. def up_detailContent(self, array):
  1711. self.detailContent_args['mid'] = mid = array[0].replace('up', '')
  1712. up_info = self.pool.submit(self.get_up_info, mid)
  1713. first = '是否关注$ '
  1714. follow = '关注$1_notplay_follow'
  1715. unfollow = '取消关注$2_notplay_follow'
  1716. qqfollow = '悄悄关注$3_notplay_follow'
  1717. spfollow = '特别关注$-10_notplay_special_follow'
  1718. unspfollow = '取消特别关注$0_notplay_special_follow'
  1719. Space = ' $_'
  1720. doWhat = [follow, spfollow, qqfollow, Space, Space, Space, unfollow, unspfollow]
  1721. doWhat = '#'.join(doWhat)
  1722. up_info = up_info.result()
  1723. vod = {
  1724. "vod_id": 'up' + str(mid),
  1725. "vod_name": up_info['name'] + " 个人主页",
  1726. "vod_pic": up_info['face'],
  1727. "vod_director": '🆙 ' + up_info['name'] + " " + up_info['following'] + ' UID:' + str(mid),
  1728. "vod_content": up_info['desc'],
  1729. 'vod_play_from': '关注TA$$$动态标签筛选查看视频投稿',
  1730. 'vod_play_url': doWhat
  1731. }
  1732. remark = "👥 " + up_info['fans'] + " 🎬 " + up_info['vod_count'] + " 👍 " + up_info['like_num']
  1733. vod["vod_actor"] = remark
  1734. result = {
  1735. 'list': [
  1736. vod
  1737. ]
  1738. }
  1739. return result
  1740. def setting_login_detailContent(self, key):
  1741. cookie_dic_tmp = self.cookie_dic_tmp.get(key, '')
  1742. message = ''
  1743. if not cookie_dic_tmp:
  1744. message = self.get_cookies(key)
  1745. if message:
  1746. message = f"【{message}】通过手机客户端扫码确认登录后点击相应按钮设置账号"
  1747. else:
  1748. message = '【已扫码并确认登录】请点击相应按钮设置当前获取的账号为:'
  1749. vod = {
  1750. "vod_name": "登录与设置",
  1751. "vod_content": '通过手机客户端扫码并确认登录后,点击相应按钮设置cookie,设置后不需要管嗅探结果,直接返回二维码页面刷新,查看是否显示已登录,已登录即可重新打开APP以加载全部标签',
  1752. }
  1753. vod_play_from = ['登录$$$退出登录']
  1754. vod_play_url = []
  1755. first = message + '$ '
  1756. login = '设置为主账号,动态收藏关注等内容源于此$' + str(key) + '_master_login_setting'
  1757. login_vip = '设置为备用的VIP账号,仅用于播放会员番剧$' + str(key) + '_vip_login_setting'
  1758. vod_play_url.append('#'.join([first, login, login_vip]))
  1759. second = '点击相应按钮退出账号>>>$ '
  1760. logout = '退出主账号$master_logout_setting'
  1761. logout_vip = '退出备用的VIP账号$vip_logout_setting'
  1762. vod_play_url.append('#'.join([second, logout, logout_vip]))
  1763. cate_lis = [{
  1764. 'f': '主页站点推荐栏',
  1765. 'c': 'maxHomeVideoContent',
  1766. 'd': {
  1767. '3': '3图',
  1768. '4': '4图',
  1769. '5': '5图',
  1770. '6': '6图',
  1771. '8': '8图',
  1772. '9': '9图',
  1773. '10': '10图',
  1774. '20': '20图',
  1775. }
  1776. },{
  1777. 'f': '视频画质',
  1778. 'c': 'vodDefaultQn',
  1779. 'd': self.vod_qn_id
  1780. },{
  1781. 'f': '视频编码',
  1782. 'c': 'vodDefaultCodec',
  1783. 'd': self.vod_codec_id
  1784. },{
  1785. 'f': '音频码率',
  1786. 'c': 'vodDefaultAudio',
  1787. 'd': self.vod_audio_id
  1788. },{
  1789. 'f': '收藏默认显示',
  1790. 'c': 'favMode',
  1791. 'd': {
  1792. '0': '默认收藏夹',
  1793. '1': '追番',
  1794. '2': '追剧',
  1795. }
  1796. },{
  1797. 'f': '上传播放进度',
  1798. 'c': 'heartbeatInterval',
  1799. 'd': {
  1800. '0': '关',
  1801. '15': '开',
  1802. }
  1803. },{
  1804. 'f': '直播筛选细化',
  1805. 'c': 'showLiveFilterTag',
  1806. 'd': {
  1807. '0': '关',
  1808. '1': '开',
  1809. }
  1810. }]
  1811. for cate in cate_lis:
  1812. vod_play_from.append(cate['f'])
  1813. defaultConfig = cate['d'][str(int(self.userConfig[cate['c']]))]
  1814. if 'vodDefaultAudio' == cate['c']:
  1815. defaultConfig = str(defaultConfig).replace('000', 'k')
  1816. url = ['当前:' + defaultConfig + '$ ']
  1817. for id, name in cate['d'].items():
  1818. if 'vodDefaultAudio' == cate['c']:
  1819. name = str(name).replace('000', 'k')
  1820. url.append(name + '$' + str(id) + '_' + cate['c'] + '_setting')
  1821. vod_play_url.append('#'.join(url))
  1822. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1823. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1824. result = {
  1825. 'list': [
  1826. vod
  1827. ]
  1828. }
  1829. return result
  1830. def setting_tab_filter_detailContent(self):
  1831. vod = {
  1832. "vod_name": "标签与筛选",
  1833. "vod_content": '依次点击各标签,同一标签第一次点击为添加,第二次删除,可以返回到二维码页后重进本页查看预览,最后点击保存,未选择的将追加到末尾,如果未保存就重启app,将丢失未保存的配置',
  1834. }
  1835. vod_play_from = []
  1836. vod_play_url = []
  1837. cate_lis = [
  1838. {'n': 'cateManual', 'v': '标签'},
  1839. {'n': 'tuijianLis', 'v': '推荐[分区]'},
  1840. {'n': 'rankingLis', 'v': '推荐[排行榜]'},
  1841. {'n': 'cateManualLive', 'v': '直播'},
  1842. ]
  1843. for cate in cate_lis:
  1844. _List = cate['n']
  1845. vod_play_from.append(cate['v'])
  1846. List_tmp = self.userConfig.get(str(_List) + '_tmp', [])
  1847. status = ''
  1848. if List_tmp:
  1849. status = '【未保存】'
  1850. else:
  1851. List_tmp = self.userConfig.get(_List, [])
  1852. if not List_tmp:
  1853. List_tmp = self.defaultConfig.get(_List)
  1854. if List_tmp and type(List_tmp[0]) == dict:
  1855. List_tmp = list(map(lambda x:x['n'], List_tmp))
  1856. url = ['当前: ' + ','.join(List_tmp) + '$ ', f"{status}点击这里保存$_{_List}_save_setting", f"点击这里恢复默认并保存$_{_List}_clear_setting"]
  1857. defaultConfig = self.defaultConfig[_List].copy()
  1858. if _List == 'cateManual' and not 'UP' in defaultConfig:
  1859. defaultConfig.append('UP')
  1860. elif _List == 'cateManualLive':
  1861. extra_live_filter = self.userConfig.get('cateManualLiveExtra', [])
  1862. defaultConfig.extend(extra_live_filter.copy())
  1863. for name in defaultConfig:
  1864. value = str(name)
  1865. if type(name) == dict:
  1866. value = name['n'] + '@@@' + name['v'].replace('_', '@@@')
  1867. name = name['n']
  1868. url.append(f"{name}${value}_{_List}_setting")
  1869. vod_play_url.append('#'.join(url))
  1870. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1871. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1872. result = {
  1873. 'list': [
  1874. vod
  1875. ]
  1876. }
  1877. return result
  1878. def setting_liveExtra_detailContent(self):
  1879. vod = {
  1880. "vod_name": "查看直播细化标签",
  1881. "vod_content": '点击想要添加的标签,同一标签第一次点击为添加,第二次删除,完成后在[标签与筛选]页继续操作,以添加到直播筛选分区列中',
  1882. }
  1883. vod_play_from = ['已添加']
  1884. cateManualLiveExtra = self.userConfig.get('cateManualLiveExtra', [])
  1885. vod_play_url = ['点击相应标签(只)可以删除$ #清空$clear_liveFilter_setting']
  1886. for name in cateManualLiveExtra:
  1887. value = name['v']
  1888. name = name['n']
  1889. vod_play_url.append(name + '$' + 'del_' + name + '_' + value + '_liveFilter_setting')
  1890. vod_play_url = ['#'.join(vod_play_url)]
  1891. cateLive = self.userConfig.get('cateLive', {})
  1892. for parent, parent_dic in cateLive.items():
  1893. area_dic = parent_dic['value']['value']
  1894. if len(area_dic) == 1:
  1895. continue
  1896. vod_play_from.append(parent)
  1897. url = []
  1898. for area in area_dic:
  1899. name = str(area['n']).replace('_', '-').replace("#", "﹟").replace("$", "﹩")
  1900. id = str(area['v']).replace('_', '@@@').replace("#", "﹟").replace("$", "﹩")
  1901. url.append(name + '$add_' + name + '_' + id + '_liveFilter_setting')
  1902. vod_play_url.append('#'.join(url))
  1903. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1904. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1905. result = {
  1906. 'list': [
  1907. vod
  1908. ]
  1909. }
  1910. return result
  1911. def get_all_season(self, season):
  1912. season_id = str(season['season_id'])
  1913. season_title = season['season_title']
  1914. if season_id == self.detailContent_args['ssid']:
  1915. self.detailContent_args['s_title'] = season_title
  1916. pic = season['cover']
  1917. remark = season['new_ep']['index_show']
  1918. result = {
  1919. "vod_id": season_id + 'ss',
  1920. "vod_name": '系列:' + season_title,
  1921. "vod_pic": self.format_img(pic),
  1922. "vod_remarks": remark}
  1923. return result
  1924. def get_bangumi_section(self, section):
  1925. sec_title = section['title'].replace("#", "﹟").replace("$", "﹩")
  1926. sec_type = section['type']
  1927. if sec_type in [1, 2] and len(section['episode_ids']) == 0:
  1928. episodes = section['episodes']
  1929. playUrl = '#'.join(map(lambda x: self.get_normal_episodes(x)[0], episodes))
  1930. return (sec_title, playUrl)
  1931. def ysContent(self, array):
  1932. aid = array[0]
  1933. if 'ep' in aid:
  1934. self.detailContent_args['fromep'] = aid
  1935. aid = 'ep_id=' + aid.replace('ep', '')
  1936. elif 'ss' in aid:
  1937. aid = 'season_id=' + aid.replace('ss', '')
  1938. url = "https://api.bilibili.com/pgc/view/web/season?{0}".format(aid)
  1939. jo = self._get_sth(url, 'fake').json().get('result', {})
  1940. self.detailContent_args['ssid'] = str(jo['season_id'])
  1941. title = jo['title']
  1942. self.detailContent_args['s_title'] = jo['season_title']
  1943. self.detailContent_args['title_type'] = '集'
  1944. if jo['type'] in [1, 4]:
  1945. self.detailContent_args['title_type'] = '话'
  1946. #添加系列到搜索
  1947. seasons = jo.get('seasons')
  1948. if len(seasons) == 1:
  1949. self.detailContent_args['s_title'] = seasons[0]['season_title']
  1950. seasons = 0
  1951. else:
  1952. self.detailContent_args['seasons'] = list(self.pool.map(self.get_all_season, seasons))
  1953. #获取正片
  1954. episodes = jo.get('episodes')
  1955. #获取花絮
  1956. section_task = []
  1957. for s in jo.get('section', []):
  1958. if s:
  1959. t = self.pool.submit(self.get_bangumi_section, s)
  1960. section_task.append(t)
  1961. pic = jo['cover']
  1962. typeName = jo['share_sub_title']
  1963. date = jo['publish']['pub_time'][0:4]
  1964. dec = jo['evaluate']
  1965. remark = jo['new_ep']['desc']
  1966. stat = jo['stat']
  1967. # 演员和导演框展示视频状态,包括以下内容:
  1968. status = "▶" + self.zh(stat['views']) + " ❤" + self.zh(stat['favorites'])
  1969. vod = {
  1970. "vod_id": 'ss' + self.detailContent_args['ssid'],
  1971. "vod_name": title,
  1972. "vod_pic": pic,
  1973. "type_name": typeName,
  1974. "vod_year": date,
  1975. "vod_actor": status,
  1976. "vod_content": dec
  1977. }
  1978. vod["vod_area"] = "bilidanmu"
  1979. vod["vod_remarks"] = remark
  1980. ZhuiPf = []
  1981. ZhuiPu = []
  1982. if self.userid:
  1983. ZhuiPf = ['追番剧']
  1984. ZhuiPu = '❤追番剧$add_notplay_zhui#💔取消追番剧$del_notplay_zhui'
  1985. defaultQn = int(self.userConfig['vodDefaultQn'])
  1986. if defaultQn > 80:
  1987. ZhuiPu += '#⚠️限高1080$80_notplay_vodTMPQn'
  1988. ZhuiPu = [ZhuiPu]
  1989. if seasons:
  1990. ZhuiPf.append('更多系列')
  1991. ZhuiPu.append('更多系列在快速搜索中查看$ #')
  1992. FirstPf = []
  1993. FirstPu = []
  1994. PreviewPf = []
  1995. PreviewPu = []
  1996. ParsePf = []
  1997. ParsePu = []
  1998. if episodes:
  1999. for x, y in self.pool.map(self.get_normal_episodes, episodes):
  2000. if y:
  2001. FirstPu.append(x)
  2002. ParsePu.append(y)
  2003. else:
  2004. PreviewPu.append(x)
  2005. if FirstPu:
  2006. FirstPf = [self.detailContent_args['s_title']]
  2007. FirstPu = ['#'.join(FirstPu)]
  2008. if PreviewPu:
  2009. PreviewPf = ['预告']
  2010. PreviewPu = ['#'.join(PreviewPu)]
  2011. if not self.detailContent_args.get('parse'):
  2012. ParsePu = []
  2013. if ParsePu:
  2014. ParsePf = [str(self.detailContent_args['s_title']) + '【解析】']
  2015. ParsePu = ['#'.join(ParsePu)]
  2016. fromL = ParsePf + FirstPf + PreviewPf
  2017. urlL = ParsePu + FirstPu + PreviewPu
  2018. for t in as_completed(section_task):
  2019. s = t.result()
  2020. if s:
  2021. if s[0] == '预告':
  2022. PreviewPu = ['#'.join(s[1])]
  2023. else:
  2024. fromL.append(s[0])
  2025. urlL.append(s[1])
  2026. fromep = self.detailContent_args.get('fromep', '')
  2027. if fromep:
  2028. fromL = ['B站'] + fromL
  2029. urlL = [fromep] + urlL
  2030. if self.userConfig['show_vod_hot_reply']:
  2031. self.get_vod_hot_reply_event.wait()
  2032. ReplyPu = self.detailContent_args.get('Reply', '')
  2033. if ReplyPu:
  2034. ZhuiPf.append('热门评论')
  2035. ZhuiPu.append(ReplyPu)
  2036. fromL.insert(1, '$$$'.join(ZhuiPf))
  2037. urlL.insert(1, '$$$'.join(ZhuiPu))
  2038. vod['vod_play_from'] = '$$$'.join(fromL)
  2039. vod['vod_play_url'] = '$$$'.join(urlL)
  2040. result = {
  2041. 'list': [
  2042. vod
  2043. ]
  2044. }
  2045. return result
  2046. def get_live_api2_playurl(self, room_id):
  2047. playFrom = []
  2048. playUrl = []
  2049. url = 'https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo?room_id={0}&qn=0&platform=web&protocol=0,1&format=0,1,2&codec=0,1&dolby=5&panorama=1'.format(room_id)
  2050. jo = self._get_sth(url, 'vip').json()
  2051. if jo['code'] == 0:
  2052. playurl_info = jo['data'].get('playurl_info', '')
  2053. if playurl_info:
  2054. stream = playurl_info['playurl']['stream']
  2055. liveDic = {
  2056. 'codec': {'avc': '0', 'hevc': '1'},
  2057. 'format': {'flv': '0', 'ts': '1', 'fmp4': '2'},
  2058. }
  2059. liveDic['qn'] = dict(self.pool.map(lambda x:(x['qn'], x['desc']), playurl_info['playurl']['g_qn_desc']))
  2060. vodList = []
  2061. for i in stream:
  2062. vodList.extend(i['format'])
  2063. api2_playUrl = {}
  2064. for v in vodList:
  2065. format = str(v.get('format_name'))
  2066. for c in v['codec']:
  2067. codec = str(c.get('codec_name'))
  2068. accept_qn = c.get('accept_qn')
  2069. for qn in accept_qn:
  2070. url = format + '_' + codec + f"$live_{room_id}_" + str(qn) + '_' + liveDic['format'][format] + '_' + liveDic['codec'][codec]
  2071. if not api2_playUrl.get(liveDic['qn'][qn]):
  2072. api2_playUrl[liveDic['qn'][qn]] = []
  2073. api2_playUrl[liveDic['qn'][qn]].append(url)
  2074. for key, value in api2_playUrl.items():
  2075. playFrom.append(key)
  2076. playUrl.append('#'.join(value))
  2077. result = {'From': playFrom, 'url': playUrl}
  2078. return result
  2079. def live_detailContent(self, array):
  2080. room_id = array[0]
  2081. get_live_api2_playurl = self.pool.submit(self.get_live_api2_playurl, room_id)
  2082. url = "https://api.live.bilibili.com/room/v1/Room/get_info?room_id=" + str(room_id)
  2083. jRoot = self._get_sth(url, 'fake').json()
  2084. result = {}
  2085. if jRoot.get('code') == 0:
  2086. jo = jRoot['data']
  2087. self.detailContent_args['mid'] = mid = str(jo["uid"])
  2088. up_info = self.pool.submit(self.get_up_info, mid)
  2089. title = jo['title'].replace("<em class=\"keyword\">", "").replace("</em>", "")
  2090. pic = jo.get("user_cover")
  2091. desc = jo.get('description')
  2092. typeName = jo.get('parent_area_name') + '--' + jo.get('area_name')
  2093. live_status = jo.get('live_status', '')
  2094. if live_status:
  2095. live_status = "开播时间:" + jo.get('live_time').replace('-', '.')
  2096. else:
  2097. live_status = "未开播"
  2098. vod = {
  2099. "vod_id": room_id,
  2100. "vod_name": title,
  2101. "vod_pic": pic,
  2102. "type_name": typeName,
  2103. "vod_content": desc,
  2104. }
  2105. remark = "房间号:" + room_id + " " + live_status
  2106. vod["vod_actor"] = remark
  2107. vod["vod_area"] = "bililivedanmu"
  2108. secondPFrom = ''
  2109. secondP = ''
  2110. if self.userid:
  2111. secondPFrom = '关注Ta'
  2112. first = '是否关注$ '
  2113. follow = '➕关注$1_notplay_follow'
  2114. unfollow = '➖取关$2_notplay_follow'
  2115. secondPList = [first, follow, unfollow]
  2116. secondP = '#'.join(secondPList)
  2117. playFrom = get_live_api2_playurl.result().get('From', [])
  2118. playUrl = get_live_api2_playurl.result().get('url', [])
  2119. if secondPFrom:
  2120. playFrom.insert(1, secondPFrom)
  2121. playUrl.insert(1, secondP)
  2122. vod['vod_play_from'] = '$$$'.join(playFrom)
  2123. vod['vod_play_url'] = '$$$'.join(playUrl)
  2124. up_info = up_info.result()
  2125. vod["vod_director"] = '🆙 ' + up_info['crname'] + " 👥 " + self.zh(jo.get('attention')) + ' ' + up_info['following']
  2126. result['list'] = [vod]
  2127. return result
  2128. search_key = ''
  2129. def searchContent(self, key, quick):
  2130. if not self.session_fake.cookies:
  2131. self.pool.submit(self.getFakeCookie, True)
  2132. for t in self.task_pool:
  2133. t.cancel()
  2134. self.task_pool = []
  2135. self.search_key = key
  2136. mid = self.detailContent_args.get('mid', '')
  2137. if quick and mid:
  2138. get_up_videos = self.pool.submit(self.get_up_videos, mid, 1, 'quicksearch')
  2139. types = {'video': '','media_bangumi': '番剧: ', 'media_ft': '影视: ', 'bili_user': '用户: ', 'live': '直播: '}
  2140. for type, value in types.items():
  2141. t = self.pool.submit(self.get_search_content, key = key, pg = value, duration_diff = 0, order = '', type = type, ps = self.userConfig['page_size'])
  2142. self.task_pool.append(t)
  2143. result = {}
  2144. vodList = []
  2145. for t in as_completed(self.task_pool):
  2146. res = t.result().get('list', [])
  2147. vodList.extend(res)
  2148. self.task_pool.remove(t)
  2149. if quick:
  2150. if mid:
  2151. vodList = self.detailContent_args.get('interaction', []) + get_up_videos.result().get('list', []) + self.detailContent_args.get('Reply_jump', []) + vodList
  2152. else:
  2153. vodList = self.detailContent_args.get('seasons', []) + vodList
  2154. result['list'] = vodList
  2155. return result
  2156. stop_heartbeat_event = threading.Event()
  2157. def start_heartbeat(self, aid, cid, ssid, epid, duration):
  2158. query = self.encrypt_wbi(aid=aid, cid=cid)[0]
  2159. url = f'https://api.bilibili.com/x/player/wbi/v2?{query}'
  2160. data = self._get_sth(url).json().get('data',{})
  2161. interaction = data.get('interaction', {})
  2162. if interaction.get('graph_version'):
  2163. graph_version = interaction.get('graph_version')
  2164. old = self.detailContent_args.get('graph_version')
  2165. if old != graph_version:
  2166. self.detailContent_args['graph_version'] = graph_version
  2167. self.pool.submit(self.interaction_detailContent)
  2168. heartbeatInterval = int(self.userConfig['heartbeatInterval'])
  2169. if not self.userid or not heartbeatInterval:
  2170. return
  2171. if not duration:
  2172. url = 'https://api.bilibili.com/x/web-interface/view?aid={0}&cid={1}'.format(aid, cid)
  2173. jRoot = self._get_sth(url, 'fake').json()
  2174. duration = jRoot['data']['duration']
  2175. played_time = 0
  2176. duration = int(duration)
  2177. if int(data.get('last_play_cid', 0)) == int(cid):
  2178. last_play_time = int(data.get('last_play_time'))
  2179. if last_play_time > 0:
  2180. played_time = int(last_play_time / 1000)
  2181. heartbeat_times = int((duration - played_time) / heartbeatInterval) + 1
  2182. url = 'https://api.bilibili.com/x/click-interface/web/heartbeat'
  2183. data = {'aid': str(aid), 'cid': str(cid), 'csrf': str(self.csrf)}
  2184. if ssid:
  2185. data['sid'] = str(ssid)
  2186. data['epid'] = str(epid)
  2187. data['type'] = '4'
  2188. heartbeat_count = 0
  2189. self.stop_heartbeat_event.clear()
  2190. while True:
  2191. if heartbeat_count == heartbeatInterval or self.stop_heartbeat_event.is_set():
  2192. played_time += heartbeat_count
  2193. heartbeat_count = 0
  2194. if not heartbeat_count:
  2195. heartbeat_times -= 1
  2196. if not heartbeat_times:
  2197. #播完为-1
  2198. played_time = -1
  2199. self.stop_heartbeat_event.set()
  2200. data['played_time'] = str(played_time)
  2201. data = self.encrypt_wbi(**data)[1]
  2202. self.pool.submit(self._post_sth, url=url, data=data)
  2203. if self.stop_heartbeat_event.is_set():
  2204. break
  2205. time.sleep(1)
  2206. heartbeat_count += 1
  2207. wbi_key = {}
  2208. def get_wbiKey(self, wts):
  2209. r = self.fetch("https://api.bilibili.com/x/web-interface/nav", headers=self.header)
  2210. wbi_img_url = r.json()['data']['wbi_img']['img_url']
  2211. wbi_sub_url = r.json()['data']['wbi_img']['sub_url']
  2212. oe = [46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12,
  2213. 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62,
  2214. 11, 36, 20, 34, 44, 52]
  2215. ae = wbi_img_url.split("/")[-1].split(".")[0] + wbi_sub_url.split("/")[-1].split(".")[0]
  2216. le = reduce(lambda s, i: s + ae[i], oe, "")[:32]
  2217. self.wbi_key = {
  2218. "key": le,
  2219. "wts": wts
  2220. }
  2221. def encrypt_wbi(self, **params):
  2222. wts = round(time.time())
  2223. if not self.wbi_key or abs(self.wbi_key['wts']) < 120:
  2224. self.get_wbiKey(wts)
  2225. params["wts"] = wts
  2226. params["dm_img_list"] = []
  2227. dm_rand = ['QQ','Qg','Qw','RA','RQ']
  2228. params["dm_img_str"] = random.choice(dm_rand)
  2229. params["dm_cover_img_str"] = random.choice(dm_rand)
  2230. params = dict(sorted(params.items()))
  2231. params = {k : ''.join(filter(lambda chr: chr not in "!'()*", str(v))) for k, v in params.items()}
  2232. Ae = urlencode(params)
  2233. w_rid = hashlib.md5((Ae + self.wbi_key['key']).encode(encoding='utf-8')).hexdigest()
  2234. params['w_rid'] = w_rid
  2235. return [Ae + "&w_rid=" + w_rid, params]
  2236. def _get_sth(self, url, _type='master'):
  2237. if _type == 'vip' and self.session_vip.cookies:
  2238. rsp = self.session_vip.get(url, headers=self.header)
  2239. elif _type == 'fake':
  2240. if not self.session_fake.cookies:
  2241. self.getFakeCookie_event.wait()
  2242. rsp = self.session_fake.get(url, headers=self.header)
  2243. else:
  2244. rsp = self.session_master.get(url, headers=self.header)
  2245. return rsp
  2246. def _post_sth(self, url, data):
  2247. return self.session_master.post(url, headers=self.header, data=data)
  2248. def post_live_history(self, room_id):
  2249. data = {'room_id': str(room_id), 'platform': 'pc', 'csrf': str(self.csrf)}
  2250. url = 'https://api.live.bilibili.com/xlive/web-room/v1/index/roomEntryAction'
  2251. self._post_sth(url=url, data=data)
  2252. def do_notplay(self, ids):
  2253. aid = self.detailContent_args.get('aid')
  2254. mid = self.detailContent_args.get('mid')
  2255. ssid = self.detailContent_args.get('ssid')
  2256. data = {'csrf': str(self.csrf)}
  2257. url = ''
  2258. if 'vodTMPQn' in ids:
  2259. self.detailContent_args['vodTMPQn'] = str(ids[0])
  2260. return
  2261. elif 'follow' in ids:
  2262. if 'special' in ids:
  2263. data.update({'fids': str(mid), 'tagids': str(ids[0])})
  2264. url = 'https://api.bilibili.com/x/relation/tags/addUsers'
  2265. else:
  2266. data.update({'fid': str(mid), 'act': str(ids[0])})
  2267. url = 'https://api.bilibili.com/x/relation/modify'
  2268. elif 'zhui' in ids:
  2269. data.update({'season_id': str(ssid)})
  2270. url = 'https://api.bilibili.com/pgc/web/follow/' + str(ids[0])
  2271. elif 'like' in ids:
  2272. data.update({'aid': str(aid), 'like': str(ids[0])})
  2273. url = 'https://api.bilibili.com/x/web-interface/archive/like'
  2274. elif 'coin' in ids:
  2275. data.update({'aid': str(aid), 'multiply': str(ids[0]), 'select_like': '1'})
  2276. url = 'https://api.bilibili.com/x/web-interface/coin/add'
  2277. elif 'fav' in ids:
  2278. data.update({'rid': str(aid), 'type': '2'})
  2279. data[ids[1] + '_media_ids'] = str(ids[0])
  2280. url = 'https://api.bilibili.com/x/v3/fav/resource/deal'
  2281. elif 'triple' in ids:
  2282. data.update({'aid': str(aid)})
  2283. url = 'https://api.bilibili.com/x/web-interface/archive/like/triple'
  2284. elif 'reply' in ids:
  2285. data.update({'oid': str(ids[0]), 'rpid': str(ids[1]), 'type': '1', 'action': '1'})
  2286. url = 'http://api.bilibili.com/x/v2/reply/action'
  2287. self._post_sth(url=url, data=data)
  2288. self.fetch(url='http://127.0.0.1:9978/action?do=refresh&type=detail')
  2289. def get_cid(self, aid):
  2290. url = "https://api.bilibili.com/x/web-interface/view?aid=%s" % str(aid)
  2291. jo = self._get_sth(url).json().get('data', {})
  2292. cid = jo['cid']
  2293. dur = jo['duration']
  2294. epid = ''
  2295. if 'redirect_url' in jo and 'bangumi' in jo['redirect_url']:
  2296. epid = self.find_bangumi_id(jo['redirect_url'])
  2297. return cid, dur, epid
  2298. cookie_dic_tmp = {}
  2299. def get_cookies(self, key):
  2300. url = 'https://passport.bilibili.com/x/passport-login/web/qrcode/poll?qrcode_key=' + key
  2301. jo = self._get_sth(url, 'fake').json()
  2302. if jo['code'] == 0:
  2303. message = jo['data']['message']
  2304. if not message:
  2305. self.cookie_dic_tmp[key] = dict(self.session_fake.cookies)
  2306. self.pool.submit(self.getFakeCookie)
  2307. return message
  2308. return '网络错误'
  2309. def set_cookie(self, key, _type):
  2310. cookie_dic_tmp = self.cookie_dic_tmp.get(key, '')
  2311. if not cookie_dic_tmp:
  2312. message = self.get_cookies(key)
  2313. if message:
  2314. return
  2315. users = self.userConfig.get('users', {})
  2316. users[_type] = {'cookies_dic': self.cookie_dic_tmp.get(key, {})}
  2317. self.userConfig.update({'users': users})
  2318. self.getCookie(_type)
  2319. self.dump_config()
  2320. def unset_cookie(self, _type):
  2321. if _type == 'vip':
  2322. self.session_vip.cookies.clear()
  2323. else:
  2324. self.session_master.cookies = self.session_fake.cookies
  2325. self.userid = self.csrf = ''
  2326. if _type in self.userConfig.get('users', {}):
  2327. self.userConfig['users'].pop(_type)
  2328. self.dump_config()
  2329. def set_normal_default(self, id, type):
  2330. self.userConfig[type] = str(id)
  2331. self.dump_config()
  2332. def set_normal_cateManual(self, name, _List, action):
  2333. List_tmp = self.userConfig.get(str(_List) + '_tmp')
  2334. if not List_tmp:
  2335. List_tmp = self.userConfig[str(_List) + '_tmp'] = []
  2336. if action == 'save':
  2337. for _item in self.defaultConfig[_List]:
  2338. if not _item in List_tmp.copy():
  2339. self.userConfig[str(_List) + '_tmp'].append(_item)
  2340. self.userConfig[_List] = self.userConfig[str(_List) + '_tmp'].copy()
  2341. self.userConfig.pop(_List + '_tmp')
  2342. self.dump_config()
  2343. elif action == 'clear':
  2344. self.userConfig[_List] = self.defaultConfig[_List].copy()
  2345. self.userConfig.pop(str(_List) + '_tmp')
  2346. self.dump_config()
  2347. else:
  2348. if _List == 'cateManualLive':
  2349. name = name.split('@@@')
  2350. if len(name) == 3:
  2351. name[1] += '_' + str(name[2])
  2352. name = {'n': name[0], 'v': str(name[1])}
  2353. if name in List_tmp:
  2354. self.userConfig[str(_List) + '_tmp'].remove(name)
  2355. else:
  2356. self.userConfig[str(_List) + '_tmp'].append(name)
  2357. def add_cateManualLiveExtra(self, action, name, id):
  2358. _Extra = self.userConfig.get('cateManualLiveExtra', [])
  2359. if not _Extra:
  2360. _Extra = self.userConfig['cateManualLiveExtra'] = []
  2361. if action == 'clear':
  2362. for _ext in _Extra:
  2363. _ext['v'] = _ext['v'].replace('@@@', '_')
  2364. if _ext in self.userConfig.get('cateManualLive', []):
  2365. self.userConfig['cateManualLive'].remove(_ext)
  2366. if _ext in self.userConfig.get('cateManualLive_tmp', []):
  2367. self.userConfig['cateManualLive_tmp'].remove(_ext)
  2368. self.userConfig.pop('cateManualLiveExtra')
  2369. elif id in list(map(lambda x:x['v'], self.userConfig.get('cateManualLiveExtra', []))):
  2370. area_dict = {'n': name, 'v': id}
  2371. self.userConfig['cateManualLiveExtra'].remove(area_dict)
  2372. area_dict['v'] = id.replace('@@@', '_')
  2373. if area_dict in self.userConfig.get('cateManualLive', []):
  2374. self.userConfig['cateManualLive'].remove(area_dict)
  2375. if area_dict in self.userConfig.get('cateManualLive_tmp', []):
  2376. self.userConfig['cateManualLive_tmp'].remove(area_dict)
  2377. else:
  2378. area_dict = {'n': name, 'v': id}
  2379. self.userConfig['cateManualLiveExtra'].append(area_dict)
  2380. self.dump_config()
  2381. vod_qn_id = {
  2382. '127': "8K",
  2383. '126': "杜比视界",
  2384. '125': "HDR",
  2385. '120': "4K",
  2386. '116': "1080P60帧",
  2387. '112': "1080P+",
  2388. '80': "1080P",
  2389. '64': "720P",
  2390. }
  2391. vod_codec_id = {
  2392. '7': 'avc',
  2393. '12': 'hevc',
  2394. '13': 'av1',
  2395. }
  2396. vod_audio_id = {
  2397. '30280': '192000',
  2398. '30232': '132000',
  2399. '30216': '64000',
  2400. }
  2401. def _testUrl(self, url):
  2402. status = head(url, headers=self.header).status_code
  2403. if status == 200:
  2404. return url
  2405. def get_fastesUrl(self, ja):
  2406. url = ja.get('baseUrl', ja.get('url', ''))
  2407. baseUrl = ja.get('backup_url', [])
  2408. baseUrl.insert(0, url)
  2409. task_pool = []
  2410. for l in baseUrl:
  2411. t = self.pool.submit(self._testUrl, l)
  2412. task_pool.append(t)
  2413. for t in as_completed(task_pool):
  2414. l = t.result()
  2415. if l:
  2416. url = l
  2417. break
  2418. return url
  2419. def get_dash_media(self, video):
  2420. qnid = str(video.get('id'))
  2421. codecid = video.get('codecid', '')
  2422. media_codecs = video.get('codecs')
  2423. media_bandwidth = video.get('bandwidth')
  2424. media_startWithSAP = video.get('startWithSap')
  2425. media_mimeType = video.get('mimeType')
  2426. media_BaseURL = self.get_fastesUrl(video).replace('&', '&amp;')
  2427. media_SegmentBase_indexRange = video['SegmentBase'].get('indexRange')
  2428. media_SegmentBase_Initialization = video['SegmentBase'].get('Initialization')
  2429. mediaType = media_mimeType.split('/')[0]
  2430. media_type_params = ''
  2431. if mediaType == 'video':
  2432. media_frameRate = video.get('frameRate')
  2433. media_sar = video.get('sar')
  2434. media_width = video.get('width')
  2435. media_height = video.get('height')
  2436. media_type_params = f"height='{media_height}' width='{media_width}' frameRate='{media_frameRate}' sar='{media_sar}'"
  2437. elif mediaType == 'audio':
  2438. audioSamplingRate = self.vod_audio_id.get(qnid, '192000')
  2439. media_type_params = f"numChannels='2' sampleRate='{audioSamplingRate}'"
  2440. qnid += '_' + str(codecid)
  2441. result = f"""
  2442. <Representation id="{qnid}" bandwidth="{media_bandwidth}" codecs="{media_codecs}" mimeType="{media_mimeType}" {media_type_params} startWithSAP="{media_startWithSAP}">
  2443. <BaseURL>{media_BaseURL}</BaseURL>
  2444. <SegmentBase indexRange="{media_SegmentBase_indexRange}">
  2445. <Initialization range="{media_SegmentBase_Initialization}"/>
  2446. </SegmentBase>
  2447. </Representation>"""
  2448. return result
  2449. def get_dash_media_list(self, media_lis):
  2450. if not media_lis:
  2451. return ""
  2452. mediaType = media_lis[0]['mimeType'].split('/')[0]
  2453. defaultQn = defaultCodec = ''
  2454. if mediaType == 'video':
  2455. defaultQn = vodTMPQn = self.detailContent_args.get('vodTMPQn')
  2456. if vodTMPQn:
  2457. vodTMPQn = int(vodTMPQn)
  2458. defaultQn = str(defaultQn)
  2459. else:
  2460. defaultQn = str(self.userConfig['vodDefaultQn'])
  2461. vodTMPQn = 120
  2462. defaultCodec = str(self.userConfig['vodDefaultCodec'])
  2463. elif mediaType == 'audio':
  2464. defaultQn = str(self.userConfig['vodDefaultAudio'])
  2465. defaultCodec = '0'
  2466. qn_codec = list(map(lambda x: str(x['id']) + '_' + str(x['codecid']), media_lis))
  2467. Qn_available_lis = []
  2468. #按设定的质量和设定的编码找
  2469. if defaultQn + '_' + defaultCodec in qn_codec:
  2470. Qn_available_lis.append(media_lis[qn_codec.index(defaultQn + '_' + defaultCodec)])
  2471. #按设定的质量找推荐的编码
  2472. if not Qn_available_lis and mediaType == 'video':
  2473. for c in self.vod_codec_id.keys():
  2474. if defaultQn + '_' + str(c) in qn_codec:
  2475. Qn_available_lis.append(media_lis[qn_codec.index(defaultQn + '_' + str(c))])
  2476. #找4K及以下最高可用画质/音质
  2477. if not Qn_available_lis:
  2478. qn_top = ''
  2479. for q in qn_codec:
  2480. q_c = q.split('_')
  2481. if qn_top and int(qn_top) > int(q_c[0]):
  2482. break
  2483. elif mediaType == 'video' and int(q_c[0]) <= vodTMPQn and not qn_top or mediaType == 'audio' and not qn_top or int(q_c[0]) == qn_top:
  2484. qn_top = int(q_c[0])
  2485. #匹配设定的编码,否则全部
  2486. if mediaType == 'video' and str(q_c[1]) == defaultCodec:
  2487. Qn_available_lis = [media_lis[qn_codec.index(str(q))]]
  2488. break
  2489. Qn_available_lis.append(media_lis[qn_codec.index(str(q))])
  2490. result = f"""
  2491. <AdaptationSet>
  2492. <ContentComponent contentType="{mediaType}"/>{''.join(map(self.get_dash_media, Qn_available_lis))}
  2493. </AdaptationSet>"""
  2494. return result
  2495. def get_dash(self, ja):
  2496. duration = ja.get('duration')
  2497. minBufferTime = ja.get('minBufferTime')
  2498. video_list = self.pool.submit(self.get_dash_media_list, ja.get('video'))
  2499. audio_list = self.pool.submit(self.get_dash_media_list, ja.get('audio'))
  2500. mpd = f"""<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd" type="static" mediaPresentationDuration="PT{duration}S" minBufferTime="PT{minBufferTime}S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
  2501. <Period duration="PT{duration}S" start="PT0S">{video_list.result()}{audio_list.result()}
  2502. </Period>
  2503. </MPD>"""
  2504. with open(f"{dirname}/playurl.mpd", 'w', encoding="utf-8") as f:
  2505. f.write(mpd)
  2506. def get_durl(self, ja):
  2507. maxSize = -1
  2508. position = -1
  2509. for i in range(len(ja)):
  2510. tmpJo = ja[i]
  2511. if maxSize < int(tmpJo['size']):
  2512. maxSize = int(tmpJo['size'])
  2513. position = i
  2514. url = ''
  2515. if len(ja) > 0:
  2516. if position == -1:
  2517. position = 0
  2518. url = ja[position]['url']
  2519. return url
  2520. def miao(self, m):
  2521. m = str(m).partition('.')[2] #取小数部分
  2522. if len(m)==0:m = '000' #补齐三位小数
  2523. if len(m)==1:m = m + '00'
  2524. if len(m)==2:m = m + '0'
  2525. return m #返回标准三位的毫秒数
  2526. def down_sub(self, url):
  2527. data = self._get_sth(url, 'fake').json()['body']
  2528. srt = ''
  2529. i=1
  2530. for d in data:
  2531. f = round(d['from'],3) # 开始时间 (round(n,3)四舍五入为三位小数)
  2532. t = round(d['to'],3) # 结束时间
  2533. c = d['content'] # 字幕内容
  2534. ff = time.strftime("%H:%M:%S",time.gmtime(f)) + ',' + self.miao(f) # 开始时间,秒数转 时:分:秒 格式,加逗号、毫秒修正为三位
  2535. tt = time.strftime("%H:%M:%S",time.gmtime(t)) + ',' + self.miao(t) # 结束时间,处理方式同上
  2536. srt += str(i) + '\n' + ff + ' ' + '-->' + ' ' + tt + '\n' + c + '\n\n' # 格式化为Srt字幕
  2537. i += 1
  2538. return srt
  2539. localProxyUrl = 'http://127.0.0.1:UndCover/proxy?siteType=3&siteKey=py_bilibili&type='
  2540. def get_subs(self, aid, cid):
  2541. result = []
  2542. query = self.encrypt_wbi(aid=aid, cid=cid)[0]
  2543. url = f'https://api.bilibili.com/x/player/wbi/v2?{query}'
  2544. jRoot = self._get_sth(url, 'master').json()
  2545. if jRoot['code'] == 0:
  2546. for sub in jRoot['data']['subtitle'].get('subtitles', []):
  2547. lanDoc = str(sub.get('lan_doc', ''))
  2548. lanUrl = sub.get('subtitle_url')
  2549. if lanUrl.startswith('//'):
  2550. lanUrl = 'https:' + lanUrl
  2551. lanUrl = quote(lanUrl)
  2552. result.append(
  2553. {
  2554. "url": f"{self.localProxyUrl}subtitle&url={lanUrl}",
  2555. "name": lanDoc,
  2556. "format": "application/x-subrip"
  2557. }
  2558. )
  2559. if result:
  2560. result.insert(0,
  2561. {
  2562. "url": "",
  2563. "name": " ",
  2564. "format": "application/x-subrip"
  2565. }
  2566. )
  2567. return result
  2568. def getSupportFormat(self, jo):
  2569. return jo['quality'], jo['new_description']
  2570. def playerContent(self, flag, id, vipFlags):
  2571. try:
  2572. for t in self.task_pool:
  2573. t.cancel()
  2574. finally:
  2575. self.stop_heartbeat_event.set()
  2576. result = {'playUrl': '', 'url': ''}
  2577. ids = id.split("_")
  2578. if 'live' == ids[0]:
  2579. return self.live_playerContent(flag, id, vipFlags)
  2580. if len(ids) < 2:
  2581. return result
  2582. aid = ids[0]
  2583. cid = ids[1]
  2584. if 'setting' in ids:
  2585. if 'liveFilter' in ids:
  2586. id = ids[2]
  2587. self.add_cateManualLiveExtra(aid, cid, id)
  2588. elif cid in ['cateManual', 'cateManualLive', 'tuijianLis', 'rankingLis']:
  2589. action = ids[2]
  2590. self.set_normal_cateManual(aid, cid, action)
  2591. elif 'login' in ids:
  2592. self.set_cookie(aid, cid)
  2593. elif 'logout' in ids:
  2594. self.unset_cookie(aid)
  2595. else:
  2596. self.set_normal_default(aid, cid)
  2597. return result
  2598. elif 'notplay' in ids:
  2599. self.pool.submit(self.do_notplay, ids)
  2600. return result
  2601. aid, cid, epid, dur, parse = id.split("_")
  2602. ssid = ''
  2603. if not cid:
  2604. cidResult = self.get_cid(aid)
  2605. cid = cidResult[0]
  2606. dur = cidResult[1]
  2607. epid = cidResult[2]
  2608. vodTMPQn = self.detailContent_args.get('vodTMPQn', self.userConfig['vodDefaultQn'])
  2609. query = self.encrypt_wbi(avid=aid, cid=cid, qn=vodTMPQn, fnval=4048, fnver=0, fourk=1)[0]
  2610. url = f'https://api.bilibili.com/x/player/wbi/playurl?{query}'
  2611. if epid:
  2612. if parse:
  2613. url = 'https://www.bilibili.com/bangumi/play/ep' + str(epid)
  2614. result["url"] = url
  2615. result["flag"] = 'bilibili'
  2616. result["parse"] = '1'
  2617. result['jx'] = '1'
  2618. result["header"] = str({"User-Agent": self.header["User-Agent"]})
  2619. result["danmaku"] = 'https://api.bilibili.com/x/v1/dm/list.so?oid=' + str(cid)
  2620. return result
  2621. url = 'https://api.bilibili.com/pgc/player/web/v2/playurl?aid={}&cid={}&qn={}&fnval=4048&fnver=0&fourk=1'.format(aid, cid, vodTMPQn)
  2622. jRoot = self._get_sth(url, 'vip').json()
  2623. if jRoot['code'] == 0:
  2624. if 'data' in jRoot:
  2625. jo = jRoot['data']
  2626. elif 'result' in jRoot:
  2627. jo = jRoot['result']
  2628. if 'video_info' in jo:
  2629. jr = jo['view_info']['report']
  2630. ssid = jr['season_id']
  2631. epid = jr['ep_id']
  2632. jo = jo['video_info']
  2633. else:
  2634. return result
  2635. else:
  2636. return result
  2637. ja = jo.get('dash')
  2638. if ja:
  2639. self.get_dash(ja)
  2640. result["url"] = f"{dirname}/playurl.mpd"
  2641. else:
  2642. result["url"] = self.get_durl(jo.get('durl', {}))
  2643. result["parse"] = '0'
  2644. result["contentType"] = ''
  2645. result["header"] = self.header
  2646. #回传播放记录
  2647. heartbeat = self.pool.submit(self.start_heartbeat, aid, cid, ssid, epid, dur)
  2648. self.task_pool.append(heartbeat)
  2649. return result
  2650. def live_playerContent(self, flag, id, vipFlags):
  2651. api, room_id, qn, format, codec = id.split("_")
  2652. # 回传观看直播记录
  2653. if self.userid and int(self.userConfig['heartbeatInterval']) > 0:
  2654. self.pool.submit(self.post_live_history, room_id)
  2655. url = 'https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo?room_id={0}&protocol=0,1&format={1}&codec={2}&qn={3}&ptype=8&platform=web&dolby=5&panorama=1'.format(room_id, format, codec, qn)
  2656. jo = self._get_sth(url, 'vip').json()
  2657. result = {'playUrl': '', 'url': ''}
  2658. if jo['code'] == 0:
  2659. try:
  2660. playurl = jo['data']['playurl_info'].get('playurl')
  2661. codec = playurl['stream'][0]['format'][0]['codec'][0]
  2662. except:
  2663. return result
  2664. base_url = str(codec['base_url'])
  2665. host = str(codec['url_info'][0]['host'])
  2666. extra = str(codec['url_info'][0]['extra'])
  2667. playurl = host + base_url + extra
  2668. result["url"] = playurl
  2669. if ".flv" in playurl:
  2670. result["contentType"] = 'video/x-flv'
  2671. else:
  2672. result["contentType"] = ''
  2673. else:
  2674. return result
  2675. result["parse"] = '0'
  2676. result["header"] = {
  2677. "Referer": "https://live.bilibili.com",
  2678. "User-Agent": self.header["User-Agent"]
  2679. }
  2680. return result
  2681. def localProxy(self, param):
  2682. action = {
  2683. 'url': '',
  2684. 'header': '',
  2685. 'param': '',
  2686. 'type': 'string',
  2687. 'after': ''
  2688. }
  2689. return [200, "video/MP2T", action, ""]
  2690. config = {
  2691. "player": {},
  2692. "filter": {
  2693. "关注": [{"key": "sort", "name": "分类",
  2694. "value": [{"n": "正在直播", "v": "正在直播"}, {"n": "最常访问", "v": "最常访问"},
  2695. {"n": "最近关注", "v": "最近关注"}, {"n": "特别关注", "v": "特别关注"},
  2696. {"n": "悄悄关注", "v": "悄悄关注"}, {"n": "我的粉丝", "v": "我的粉丝"}]}],
  2697. "动态": [{"key": "order", "name": "投稿排序",
  2698. "value": [{"n": "最新发布", "v": "pubdate"}, {"n": "最多播放", "v": "click"},
  2699. {"n": "最多收藏", "v": "stow"}, {"n": "最早发布", "v": "oldest"}, {"n": "合集和列表", "v": "series"}]}, ],
  2700. "影视": [{"key": "tid", "name": "分类",
  2701. "value": [{"n": "番剧", "v": "1"}, {"n": "国创", "v": "4"}, {"n": "电影", "v": "2"},
  2702. {"n": "电视剧", "v": "5"}, {"n": "纪录片", "v": "3"}, {"n": "综艺", "v": "7"}]},
  2703. {"key": "order", "name": "排序",
  2704. "value": [{"n": "热门", "v": "热门"}, {"n": "播放数量", "v": "2"}, {"n": "更新时间", "v": "0"},
  2705. {"n": "最高评分", "v": "4"}, {"n": "弹幕数量", "v": "1"}, {"n": "追看人数", "v": "3"},
  2706. {"n": "开播时间", "v": "5"}, {"n": "上映时间", "v": "6"}]},
  2707. {"key": "season_status", "name": "付费",
  2708. "value": [{"n": "全部", "v": "-1"}, {"n": "免费", "v": "1"},
  2709. {"n": "付费", "v": "2%2C6"}, {"n": "大会员", "v": "4%2C6"}]}],
  2710. "频道": [{"key": "order", "name": "排序",
  2711. "value": [{"n": "近期热门", "v": "hot"}, {"n": "月播放量", "v": "view"},
  2712. {"n": "最新投稿", "v": "new"}, {"n": "频道精选", "v": "featured"}, ]}, ],
  2713. "收藏": [{"key": "order", "name": "排序",
  2714. "value": [{"n": "收藏时间", "v": "mtime"}, {"n": "播放量", "v": "view"},
  2715. {"n": "投稿时间", "v": "pubtime"}]}, ],
  2716. "历史": [{"key": "type", "name": "分类",
  2717. "value": [{"n": "全部", "v": "all"}, {"n": "视频", "v": "archive"}, {"n": "直播", "v": "live"}, {"n": "UP主", "v": "UP主"}, {"n": "稍后再看", "v": "稍后再看"}]}, ],
  2718. "搜索": [{"key": "type", "name": "类型",
  2719. "value": [{"n": "视频", "v": "video"}, {"n": "番剧", "v": "media_bangumi"}, {"n": "影视", "v": "media_ft"},
  2720. {"n": "直播", "v": "live"}, {"n": "用户", "v": "bili_user"}]},
  2721. {"key": "order", "name": "视频排序",
  2722. "value": [{"n": "综合排序", "v": "totalrank"}, {"n": "最多点击", "v": "click"}, {"n": "最新发布", "v": "pubdate"},
  2723. {"n": "最多收藏", "v": "stow"}, {"n": "最多弹幕", "v": "dm"}]},
  2724. {"key": "duration", "name": "视频时长",
  2725. "value": [{"n": "全部", "v": "0"}, {"n": "60分钟以上", "v": "4"}, {"n": "30~60分钟", "v": "3"},
  2726. {"n": "5~30分钟", "v": "2"}, {"n": "5分钟以下", "v": "1"}]}],
  2727. }
  2728. }
  2729. header = {
  2730. 'Origin': 'https://www.bilibili.com',
  2731. 'Referer': 'https://www.bilibili.com',
  2732. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Safari/605.1.15'
  2733. }