py_bilibili1222.py 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778
  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
  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. if dirname.startswith('/data/'):
  18. dirname = os.path.abspath(os.path.join(dirname, ".."))
  19. dirname = os.path.abspath(os.path.join(dirname, ".."))
  20. dirname = f"{dirname}/files"
  21. sys.path.append(dirname)
  22. class Spider(Spider):
  23. #默认设置
  24. defaultConfig = {
  25. 'currentVersion': "20231222_1",
  26. #【建议通过扫码确认】设置Cookie,在双引号内填写
  27. 'raw_cookie_line': "SESSDATA=7624af93%2C1696008331%2C862c8%2A42; bili_jct=141a474ef3ce8cf2fedf384e68f6625d; DedeUserID=3493271303096985; DedeUserID__ckMd5=212a836c164605b7",
  28. #如果主cookie没有vip,可以设置第二cookie,仅用于播放会员番剧,所有的操作、记录还是在主cookie,不会同步到第二cookie
  29. 'raw_cookie_vip': "SESSDATA=7624af93%2C1696008331%2C862c8%2A42; bili_jct=141a474ef3ce8cf2fedf384e68f6625d; DedeUserID=3493271303096985; DedeUserID__ckMd5=212a836c164605b7",
  30. #主页默认显示20图
  31. 'maxHomeVideoContent': '20',
  32. #收藏标签默认显示追番1,追剧2,默认收藏夹0
  33. 'favMode': '0',
  34. #部分视频列表分页,限制每次加载数量
  35. 'page_size': 12,
  36. #上传播放进度间隔时间,单位秒,b站默认间隔15,0则不上传播放历史
  37. 'heartbeatInterval': '15',
  38. #视频默认画质ID
  39. 'vodDefaultQn': '80',
  40. #视频默认解码ID
  41. 'vodDefaultCodec': '7',
  42. #音频默认码率ID
  43. 'vodDefaultAudio': '30280',
  44. #获取视频热门评论
  45. 'show_vod_hot_reply': True,
  46. #从正片中拆分出番剧的预告
  47. 'hide_bangumi_preview': True,
  48. #登陆会员账号后,影视播放页不显示会员专享的标签,更简洁
  49. 'hide_bangumi_vip_badge': True,
  50. #番剧(热门)列表使用横图
  51. 'bangumi_horizontal_cover': True,
  52. #非会员播放会员专享视频时,添加一个页面可以使用解析源,解析源自行解决
  53. 'bangumi_vip_parse': True,
  54. #付费视频添加一个页面可以使用解析,解析源自行解决
  55. 'bangumi_pay_parse': True,
  56. #是否显示直播标签筛选中分区的细化标签, 0为不显示,1为显示
  57. 'showLiveFilterTag': '1',
  58. #主页标签排序, 未登录或cookie失效时自动隐藏动态、收藏、关注、历史
  59. 'cateManual': [
  60. "动态",
  61. "推荐",
  62. "影视",
  63. "直播",
  64. "频道",
  65. "收藏",
  66. "关注",
  67. "历史",
  68. "搜索",
  69. ],
  70. #自定义推荐标签的筛选
  71. 'tuijianLis': [
  72. "热门",
  73. "排行榜",
  74. "每周必看",
  75. "入站必刷",
  76. "番剧时间表",
  77. "国创时间表"
  78. ],
  79. 'rankingLis': [
  80. "动画",
  81. "音乐",
  82. "舞蹈",
  83. "游戏",
  84. "鬼畜",
  85. "知识",
  86. "科技",
  87. "运动",
  88. "生活",
  89. "美食",
  90. "动物",
  91. "汽车",
  92. "时尚",
  93. "娱乐",
  94. "影视",
  95. "原创",
  96. "新人",
  97. ],
  98. }
  99. #在动态标签的筛选中固定显示他,n为用户名或任意都可以,v必须为准确的UID
  100. focus_on_up_list = [
  101. #{"n":"徐云流浪中国", "v":"697166795"},
  102. ]
  103. #在搜索标签的筛选中固定显示搜索词
  104. focus_on_search_key = []
  105. def getName(self):
  106. return "哔哩哔哩"
  107. def load_config(self):
  108. try:
  109. with open(f"{dirname}/config.json",encoding="utf-8") as f:
  110. self.userConfig = json.load(f)
  111. users = self.userConfig.get('users', {})
  112. if users.get('master') and users['master'].get('cookies_dic'):
  113. self.session_master.cookies = utils.cookiejar_from_dict(users['master']['cookies_dic'])
  114. self.userid = users['master']['userid']
  115. if users.get('fake') and users['fake'].get('cookies_dic'):
  116. self.session_fake.cookies = utils.cookiejar_from_dict(users['fake']['cookies_dic'])
  117. except:
  118. self.userConfig = {}
  119. self.userConfig = {**self.defaultConfig, **self.userConfig}
  120. dump_config_lock = threading.Lock()
  121. def dump_config(self):
  122. needSaveConfig = ['users', 'channel_list', 'cateLive', 'cateManualLive', 'cateManualLiveExtra']
  123. userConfig_new = {}
  124. for key, value in self.userConfig.items():
  125. dafalutValue = self.defaultConfig.get(key)
  126. if dafalutValue != None and value != dafalutValue or key in needSaveConfig:
  127. userConfig_new[key] = value
  128. self.dump_config_lock.acquire()
  129. with open(f"{dirname}/config.json", 'w', encoding="utf-8") as f:
  130. data = json.dumps(userConfig_new, indent=1, ensure_ascii=False)
  131. f.write(data)
  132. self.dump_config_lock.release()
  133. pool = ThreadPoolExecutor(max_workers=8)
  134. task_pool = []
  135. # 主页
  136. def homeContent(self, filter):
  137. self.pool.submit(self.add_live_filter)
  138. self.pool.submit(self.add_channel_filter)
  139. self.pool.submit(self.add_search_key)
  140. self.pool.submit(self.add_focus_on_up_filter)
  141. self.pool.submit(self.get_tuijian_filter)
  142. self.pool.submit(self.add_fav_filter)
  143. #self.pool.submit(self.homeVideoContent)
  144. needLogin = ['频道', '动态', '收藏', '关注', '历史']
  145. cateManual = self.userConfig['cateManual']
  146. if not self.userid:
  147. cateManual += ['登录']
  148. classes = []
  149. for k in cateManual:
  150. if k in needLogin and not self.userid:
  151. continue
  152. classes.append({
  153. 'type_name': k,
  154. 'type_id': k
  155. })
  156. self.add_focus_on_up_filter_event.wait()
  157. result = {'class': classes}
  158. self.add_live_filter_event.wait()
  159. self.add_channel_filter_event.wait()
  160. self.add_fav_filter_event.wait()
  161. self.add_search_key_event.wait()
  162. if filter:
  163. result['filters'] = self.config['filter']
  164. self.pool.submit(self.dump_config)
  165. return result
  166. # 用户cookies
  167. userid = csrf = ''
  168. session_master = session()
  169. session_vip = session()
  170. session_fake = session()
  171. con = threading.Condition()
  172. getCookie_event = threading.Event()
  173. retries = Retry(total=5,
  174. #status_forcelist=[ 500, 502, 503, 504 ],
  175. backoff_factor=0.1)
  176. adapter = HTTPAdapter(max_retries=retries)
  177. session_master.mount('https://', adapter)
  178. session_vip.mount('https://', adapter)
  179. session_fake.mount('https://', adapter)
  180. def getCookie_dosth(self, co):
  181. c = co.strip().split('=', 1)
  182. if not '%' in c[1]:
  183. c[1] = quote(c[1])
  184. return c
  185. def getCookie(self, _type='master'):
  186. raw_cookie = 'raw_cookie_line'
  187. if _type == 'vip':
  188. raw_cookie = 'raw_cookie_vip'
  189. raw_cookie = self.userConfig.get(raw_cookie)
  190. users = self.userConfig.get('users', {})
  191. user = users.get(_type, {})
  192. if not raw_cookie and not user:
  193. if _type == 'master':
  194. self.getCookie_event.set()
  195. with self.con:
  196. self.con.notifyAll()
  197. return
  198. cookies_dic = user.get('cookies_dic', {})
  199. if raw_cookie:
  200. cookies_dic = dict(map(self.getCookie_dosth, raw_cookie.split(';')))
  201. cookies = utils.cookiejar_from_dict(cookies_dic)
  202. url = 'https://api.bilibili.com/x/web-interface/nav'
  203. content = self.fetch(url, headers=self.header, cookies=cookies)
  204. res = json.loads(content.text)
  205. user['isLogin'] = 0
  206. if res["code"] == 0:
  207. user['isLogin'] = 1
  208. user['userid'] = res["data"]['mid']
  209. user['face'] = res['data']['face']
  210. user['uname'] = res['data']['uname']
  211. user['cookies_dic'] = cookies_dic
  212. user['isVIP'] = int(res['data']['vipStatus'])
  213. if _type == 'master':
  214. self.session_master.cookies = cookies
  215. self.userid = user['userid']
  216. self.csrf = cookies_dic['bili_jct']
  217. if user['isVIP']:
  218. self.session_vip.cookies = cookies
  219. else:
  220. self.userid = ''
  221. users[_type] = user
  222. with self.con:
  223. if len(user) > 1:
  224. self.userConfig.update({'users': users})
  225. if _type == 'master':
  226. self.getCookie_event.set()
  227. getFakeCookie_event = threading.Event()
  228. def getFakeCookie(self, fromSearch=None):
  229. if self.session_fake.cookies:
  230. self.getFakeCookie_event.set()
  231. header = {}
  232. header['User-Agent'] = self.header['User-Agent']
  233. rsp = self.fetch('https://space.bilibili.com/2/video', headers=header)
  234. self.session_fake.cookies = rsp.cookies
  235. self.getFakeCookie_event.set()
  236. with self.con:
  237. users = self.userConfig.get('users', {})
  238. users['fake'] = {'cookies_dic': dict(rsp.cookies)}
  239. self.userConfig.update({'users': users})
  240. if not fromSearch:
  241. self.getCookie_event.wait()
  242. if not self.session_master.cookies:
  243. self.session_master.cookies = rsp.cookies
  244. def get_fav_list_dict(self, fav):
  245. fav_dict = {
  246. 'n': fav['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').strip(),
  247. 'v': fav['id']}
  248. return fav_dict
  249. add_fav_filter_event = threading.Event()
  250. def add_fav_filter(self):
  251. users = self.userConfig.get('users', {})
  252. if users.get('master') and users['master'].get('userid'):
  253. userid = self.userConfig['users']['master']['userid']
  254. else:
  255. self.getCookie_event.wait()
  256. userid = self.userid
  257. fav_list = []
  258. if userid:
  259. url = 'https://api.bilibili.com/x/v3/fav/folder/created/list-all?up_mid=%s&jsonp=jsonp' % str(userid)
  260. jo = self._get_sth(url).json()
  261. if jo['code'] == 0 and jo.get('data'):
  262. fav = jo['data'].get('list')
  263. fav_list = list(map(self.get_fav_list_dict, fav))
  264. fav_top = [{"n": "追番", "v": "1"},{"n": "追剧", "v": "2"}]
  265. fav_config = self.config["filter"].get('收藏')
  266. if fav_config:
  267. fav_config.insert(0, {
  268. "key": "mlid",
  269. "name": "分区",
  270. "value": fav_top + fav_list,
  271. })
  272. self.add_fav_filter_event.set()
  273. self.userConfig["fav_list"] = fav_list
  274. def get_channel_list_dict(self, channel):
  275. channel_dict = {
  276. 'n': channel['name'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').strip(),
  277. 'v': channel['id']}
  278. return channel_dict
  279. def get_channel_list(self):
  280. url = 'https://api.bilibili.com/x/web-interface/web/channel/category/channel/list?id=100&offset=0&page_size=15'
  281. jo = self._get_sth(url, 'fake').json()
  282. channel_list = []
  283. if jo['code'] == 0:
  284. channel = jo['data'].get('channels')
  285. self.userConfig['channel_list'] = list(map(self.get_channel_list_dict, channel))
  286. return self.userConfig['channel_list']
  287. add_channel_filter_event = threading.Event()
  288. def add_channel_filter(self):
  289. channel_list = self.userConfig.get('channel_list', '')
  290. channel_list_task = self.pool.submit(self.get_channel_list)
  291. if not channel_list:
  292. channel_list = channel_list_task.result()
  293. channel_config = self.config["filter"].get('频道', [])
  294. if channel_config:
  295. channel_config.insert(0, {
  296. "key": "cid",
  297. "name": "分区",
  298. "value": channel_list,
  299. })
  300. self.config["filter"]['频道'] = channel_config
  301. self.add_channel_filter_event.set()
  302. add_focus_on_up_filter_event = threading.Event()
  303. def add_focus_on_up_filter(self):
  304. up_list = self.focus_on_up_list
  305. if not self.session_master.cookies:
  306. self.getCookie_event.wait()
  307. focus_on_up_list_mid = list(map(lambda x: x['v'], up_list))
  308. if self.session_master.cookies:
  309. url = 'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?timezone_offset=-480&type=video&page=1'
  310. jo = self._get_sth(url).json()
  311. if jo['code'] == 0 and jo.get('data'):
  312. up = jo['data'].get('items', [])
  313. for u in map(lambda x: {'n': x['modules']["module_author"]['name'], 'v': str(x['modules']["module_author"]['mid'])}, up):
  314. if not u in up_list and not u['v'] in focus_on_up_list_mid:
  315. up_list.append(u)
  316. last_list = [{"n": "登录与设置", "v": "登录"}]
  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['crname'] = '[a=cr:{"id": "' + mid + '_pubdate_getupvideos","name": "' + info['name'].replace('"', '\\"') + '"}/]' + info['name'] + '[/a]'
  999. info['face'] = jo['face']
  1000. info['fans'] = self.zh(jo['fans'])
  1001. info['like_num'] = self.zh(data['like_num'])
  1002. info['desc'] = jo['Official']['desc'] + " " + jo['Official']['title']
  1003. info.update(get_up_videoNum.result())
  1004. self.up_info[mid] = info
  1005. self.get_up_info_event.set()
  1006. return info
  1007. def get_vod_relation(self, query):
  1008. url = f'https://api.bilibili.com/x/web-interface/archive/relation?{query}'
  1009. jo = self._get_sth(url).json()
  1010. relation = []
  1011. if jo['code'] == 0:
  1012. jo = jo['data']
  1013. if jo['attention']:
  1014. relation.append('已关注')
  1015. else:
  1016. relation.append('未关注')
  1017. triple = []
  1018. if jo['favorite']:
  1019. triple.append('⭐')
  1020. if jo['like']:
  1021. triple.append('👍')
  1022. coin = jo.get('coin')
  1023. if coin:
  1024. triple.append('💰'*coin)
  1025. if len(triple) == 3:
  1026. relation.append('👍💰⭐')
  1027. else:
  1028. relation.extend(triple)
  1029. if jo['dislike']:
  1030. relation.append('👎')
  1031. if jo['season_fav']:
  1032. relation.append('已订阅合集')
  1033. return relation
  1034. def get_channel(self, pg, cid, order):
  1035. result = {}
  1036. if str(pg) == '1':
  1037. self.channel_offset = ''
  1038. if order == "featured":
  1039. 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'])
  1040. else:
  1041. 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'])
  1042. jo = self._get_sth(url, 'master').json()
  1043. if jo.get('code') == 0:
  1044. self.channel_offset = jo['data'].get('offset')
  1045. videos = []
  1046. vodList = jo['data']['list']
  1047. if pg == '1' and 'items' in vodList[0]:
  1048. vodList_rank = vodList[0]['items']
  1049. del (vodList[0])
  1050. vodList = vodList_rank + vodList
  1051. for vod in vodList:
  1052. if 'uri' in vod and 'bangumi' in vod['uri']:
  1053. aid = self.find_bangumi_id(vod['uri'])
  1054. else:
  1055. aid = 'av' + str(vod['id']).strip()
  1056. title = vod['name'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  1057. img = vod['cover'].strip()
  1058. remark = "▶" + str(vod['view_count'])
  1059. duration = vod.get('duration', '')
  1060. if duration:
  1061. remark = str(self.second_to_time(self.str2sec(duration))).strip() + ' ' + remark
  1062. danmaku = vod.get('danmaku', '')
  1063. like_count = vod.get('like_count', '')
  1064. follow_count = vod.get('follow_count', '')
  1065. if danmaku:
  1066. remark += " 💬" + self.zh(danmaku)
  1067. elif like_count:
  1068. remark += " 👍" + str(like_count)
  1069. elif follow_count:
  1070. remark += " ❤" + str(follow_count)
  1071. videos.append({
  1072. "vod_id": aid,
  1073. "vod_name": title,
  1074. "vod_pic": self.format_img(img),
  1075. "vod_remarks": remark
  1076. })
  1077. result['list'] = videos
  1078. result['page'] = pg
  1079. result['pagecount'] = 9999
  1080. result['limit'] = 99
  1081. result['total'] = 999999
  1082. return result
  1083. def get_follow(self, pg, sort):
  1084. result = {}
  1085. if sort == "最常访问":
  1086. url = 'https://api.bilibili.com/x/relation/followings?vmid={0}&pn={1}&ps=10&order=desc&order_type=attention' .format(self.userid, pg)
  1087. elif sort == "最近关注":
  1088. url = 'https://api.bilibili.com/x/relation/followings?vmid={0}&pn={1}&ps=10&order=desc&order_type='.format(self.userid, pg)
  1089. elif sort == "正在直播":
  1090. url = 'https://api.live.bilibili.com/xlive/web-ucenter/v1/xfetter/GetWebList?page={0}&page_size=10'.format(pg)
  1091. elif sort == "最近访问":
  1092. url = 'https://api.bilibili.com/x/v2/history?pn={0}&ps=15'.format(pg)
  1093. elif sort == "特别关注":
  1094. url = 'https://api.bilibili.com/x/relation/tag?mid={0}&tagid=-10&pn={1}&ps=10'.format(self.userid, pg)
  1095. elif sort == "悄悄关注":
  1096. url = 'https://api.bilibili.com/x/relation/whispers?pn={0}&ps=10'.format(pg)
  1097. else:
  1098. url = 'https://api.bilibili.com/x/relation/followers?vmid={0}&pn={1}&ps=10&order=desc&order_type=attention'.format(self.userid, pg)
  1099. jo = self._get_sth(url).json()
  1100. if jo['code'] != 0:
  1101. return result
  1102. if sort == "特别关注" or sort == "最近访问":
  1103. vodList = jo['data']
  1104. elif sort == "正在直播":
  1105. vodList = jo['data']['rooms']
  1106. else:
  1107. vodList = jo['data']['list']
  1108. if int(pg) == 1:
  1109. self.recently_up_list = []
  1110. follow = []
  1111. for f in vodList:
  1112. remark = ''
  1113. if sort == "最近访问":
  1114. mid = 'up' + str(f['owner']['mid'])
  1115. if mid in self.recently_up_list:
  1116. continue
  1117. self.recently_up_list.append(mid)
  1118. title = str(f['owner']['name']).strip()
  1119. img = str(f['owner']['face']).strip()
  1120. elif sort == "正在直播":
  1121. mid = str(f['room_id'])
  1122. title = f['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;", '"')
  1123. img = f['cover_from_user'].strip()
  1124. remark = f['uname'].strip()
  1125. else:
  1126. mid = 'up' + str(f['mid'])
  1127. title = str(f['uname']).strip()
  1128. img = str(f['face']).strip()
  1129. if 'special' in f and f['special'] == 1:
  1130. remark = '特别关注'
  1131. follow.append({
  1132. "vod_id": mid,
  1133. "vod_name": title,
  1134. "vod_pic": self.format_img(img),
  1135. "vod_remarks": remark
  1136. })
  1137. result['list'] = follow
  1138. result['page'] = pg
  1139. result['pagecount'] = 9999
  1140. result['limit'] = 99
  1141. result['total'] = 999999
  1142. return result
  1143. homeVideoContent_result = {}
  1144. def homeVideoContent(self):
  1145. if not self.homeVideoContent_result:
  1146. videos = self.get_found(rid='0', tid='all', pg=1)['list'][0:int(self.userConfig['maxHomeVideoContent'])]
  1147. self.homeVideoContent_result['list'] = videos
  1148. return self.homeVideoContent_result
  1149. def categoryContent(self, tid, pg, filter, extend):
  1150. self.stop_heartbeat()
  1151. if tid == "推荐":
  1152. if 'tid' in extend:
  1153. tid = extend['tid']
  1154. if tid.isdigit():
  1155. tid = int(tid)
  1156. if tid > 10000:
  1157. tid -= 10000
  1158. return self.get_timeline(tid=tid, pg=pg)
  1159. rid = tid
  1160. tid = 'all'
  1161. return self.get_found(tid=tid, rid=rid, pg=pg)
  1162. rid = '0'
  1163. return self.get_found(tid=tid, rid=rid, pg=pg)
  1164. elif tid == "影视":
  1165. tid = '1'
  1166. order = '热门'
  1167. season_status = '-1'
  1168. if 'tid' in extend:
  1169. tid = extend['tid']
  1170. if 'order' in extend:
  1171. order = extend['order']
  1172. if 'season_status' in extend:
  1173. if order == '热门':
  1174. order = '2'
  1175. season_status = extend['season_status']
  1176. return self.get_bangumi(tid, pg, order, season_status)
  1177. elif tid == "动态":
  1178. mid = '0'
  1179. order = 'pubdate'
  1180. if 'mid' in extend:
  1181. mid = extend['mid']
  1182. if 'order' in extend:
  1183. order = extend['order']
  1184. if mid == '0' and not self.userid or mid == '登录':
  1185. return self.get_Login_qrcode(pg)
  1186. return self.get_dynamic(pg=pg, mid=mid, order=order)
  1187. elif tid == '频道':
  1188. order = 'hot'
  1189. cid = random.choice(self.userConfig['channel_list'])
  1190. cid = cid['v']
  1191. if 'order' in extend:
  1192. order = extend['order']
  1193. if 'cid' in extend:
  1194. cid = extend['cid']
  1195. return self.get_channel(pg=pg, cid=cid, order=order)
  1196. elif tid == '直播':
  1197. tid = "热门"
  1198. area_id = '0'
  1199. if 'tid' in extend:
  1200. tid = extend['tid']
  1201. if '_' in tid:
  1202. tids = tid.split('_')
  1203. tid = tids[0]
  1204. area_id = tids[1]
  1205. return self.get_live(pg=pg, parent_area_id=tid, area_id=area_id)
  1206. elif tid == "登录":
  1207. return self.get_Login_qrcode(pg)
  1208. elif tid == "关注":
  1209. sort = "最常访问"
  1210. if 'sort' in extend:
  1211. sort = extend['sort']
  1212. return self.get_follow(pg, sort)
  1213. elif tid == "收藏":
  1214. mlid = str(self.userConfig['favMode'])
  1215. if 'mlid' in extend:
  1216. mlid = extend['mlid']
  1217. fav_config = self.config["filter"].get('收藏')
  1218. if mlid in ['1', '2']:
  1219. return self.get_bangumi(tid=mlid, pg=pg, order='追番剧', season_status='')
  1220. elif mlid == '0' and fav_config:
  1221. for i in fav_config:
  1222. if i['key'] == 'mlid':
  1223. if len(i['value']) > 1:
  1224. mlid = i['value'][2]['v']
  1225. break
  1226. order = 'mtime'
  1227. if 'order' in extend:
  1228. order = extend['order']
  1229. return self.get_fav_detail(pg=pg, mlid=mlid, order=order)
  1230. elif tid == '历史':
  1231. type = 'all'
  1232. if 'type' in extend:
  1233. type = extend['type']
  1234. if type == 'UP主':
  1235. return self.get_follow(pg=pg, sort='最近访问')
  1236. return self.get_history(type=type, pg=pg)
  1237. elif tid.endswith('_getbangumiseasons'):
  1238. if int(pg) == 1:
  1239. return {'list': self.detailContent_args.get('seasons', [])}
  1240. elif tid.endswith('_getupvideos'):
  1241. mid, order, clicklink = tid.split('_')
  1242. return self.get_up_videos(pg=pg, mid=mid, order=order)
  1243. elif tid.endswith('_clicklink'):
  1244. keyword = tid.replace('_clicklink', '')
  1245. duration_diff = '0'
  1246. if 'duration' in extend:
  1247. duration_diff = extend['duration']
  1248. return self.get_search_content(key=keyword, pg=pg, duration_diff=duration_diff, order='', type='video', ps=self.userConfig['page_size'])
  1249. else:
  1250. duration_diff = '0'
  1251. if 'duration' in extend:
  1252. duration_diff = extend['duration']
  1253. type = 'video'
  1254. if 'type' in extend:
  1255. type = extend['type']
  1256. order = 'totalrank'
  1257. if 'order' in extend:
  1258. order = extend['order']
  1259. keyword = str(self.search_key)
  1260. search_config = self.config["filter"].get('搜索')
  1261. if not keyword and search_config:
  1262. for i in search_config:
  1263. if i['key'] == 'keyword':
  1264. if len(i['value']) > 0:
  1265. keyword = i['value'][0]['v']
  1266. break
  1267. if 'keyword' in extend:
  1268. keyword = extend['keyword']
  1269. return self.get_search_content(key=keyword, pg=pg, duration_diff=duration_diff, order=order, type=type, ps=self.userConfig['page_size'])
  1270. def get_search_content(self, key, pg, duration_diff, order, type, ps):
  1271. value = None
  1272. if not str(pg).isdigit():
  1273. value = pg
  1274. pg = 1
  1275. query = self.encrypt_wbi(keyword=key, page=pg, duration=duration_diff, order=order, search_type=type, page_size=ps)[0]
  1276. url = f'https://api.bilibili.com/x/web-interface/wbi/search/type?{query}'
  1277. jo = self._get_sth(url, 'fake').json()
  1278. result = {}
  1279. if jo.get('code') == 0 and 'result' in jo['data']:
  1280. videos = []
  1281. vodList = jo['data'].get('result')
  1282. if vodList and type == 'live':
  1283. vodList = vodList.get('live_room')
  1284. if not vodList:
  1285. return result
  1286. for vod in vodList:
  1287. if type != vod['type']:
  1288. continue
  1289. title = ''
  1290. if type == 'bili_user':
  1291. aid = 'up' + str(vod['mid']).strip()
  1292. img = vod['upic'].strip()
  1293. remark = '👥' + self.zh(vod['fans']) + " 🎬" + self.zh(vod['videos'])
  1294. title = vod['uname']
  1295. elif type == 'live':
  1296. aid = str(vod['roomid']).strip()
  1297. img = vod['cover'].strip()
  1298. remark = '👁' + self.zh(vod['online']) + ' 🆙' + vod['uname']
  1299. elif 'media' in type:
  1300. aid = str(vod['season_id']).strip()
  1301. if self.detailContent_args:
  1302. seasons = self.detailContent_args.get('seasons')
  1303. if seasons:
  1304. bangumi_seasons_id = []
  1305. for ss in self.detailContent_args['seasons']:
  1306. bangumi_seasons_id.append(ss['vod_id'])
  1307. if aid + 'ss' in bangumi_seasons_id:
  1308. continue
  1309. aid = 'ss' + aid
  1310. img = vod['cover'].strip()
  1311. remark = str(vod['index_show']).strip().replace('更新至', '🆕')
  1312. else:
  1313. aid = 'av' + str(vod['aid']).strip()
  1314. img = vod['pic'].strip()
  1315. remark = str(self.second_to_time(self.str2sec(vod['duration']))).strip() + " ▶" + self.zh(vod['play'])
  1316. if value == None:
  1317. remark += " 💬" + self.zh(vod['danmaku'])
  1318. if not title:
  1319. title = vod['title'].replace("<em class=\"keyword\">", "").replace("</em>", "").replace("&quot;",'"').replace('&amp;', '&')
  1320. if value:
  1321. title = value + title
  1322. videos.append({
  1323. "vod_id": aid,
  1324. "vod_name": title,
  1325. "vod_pic": self.format_img(img),
  1326. "vod_remarks": remark
  1327. })
  1328. result['list'] = videos
  1329. result['page'] = pg
  1330. result['pagecount'] = 9999
  1331. result['limit'] = 99
  1332. result['total'] = 999999
  1333. return result
  1334. def cleanSpace(self, str):
  1335. return str.replace('\n', '').replace('\t', '').replace('\r', '').replace(' ', '')
  1336. def get_normal_episodes(self, episode):
  1337. aid = episode.get('aid', '')
  1338. if not aid:
  1339. aid = self.detailContent_args['aid']
  1340. cid = episode.get('cid', '')
  1341. ep_title = episode.get('title', '')
  1342. if not ep_title:
  1343. ep_title = episode.get('part', '')
  1344. duration = episode.get('duration', '')
  1345. if not duration:
  1346. page = episode.get('page', '')
  1347. if page:
  1348. duration = page['duration']
  1349. badge = long_title = preview = parse = ''
  1350. epid = episode.get('ep_id', '')
  1351. if 'redirect_url' in episode and 'bangumi' in episode['redirect_url']:
  1352. epid = self.find_bangumi_id(episode['redirect_url'])
  1353. if epid:
  1354. if duration and str(duration).endswith('000'):
  1355. duration = int(duration / 1000)
  1356. if ep_title.isdigit():
  1357. ep_title = '第' + ep_title + self.detailContent_args['title_type']
  1358. badge = episode.get('badge', '')
  1359. if not self.session_vip.cookies and badge == '会员' and self.userConfig['bangumi_vip_parse'] or badge == '付费' and self.userConfig['bangumi_pay_parse']:
  1360. parse = '1'
  1361. if self.session_vip.cookies and self.userConfig['hide_bangumi_vip_badge']:
  1362. badge = badge.replace('会员', '')
  1363. if self.userConfig['hide_bangumi_preview'] and badge == '预告':
  1364. badge = badge.replace('预告', '')
  1365. preview = '1'
  1366. if badge:
  1367. badge = '【' + badge + '】'
  1368. long_title = episode.get('long_title', '')
  1369. if not badge and long_title:
  1370. long_title = ' ' + long_title
  1371. title = ep_title + badge + long_title
  1372. title = title.replace("#", "﹟").replace("$", "﹩")
  1373. url = f"{title}${aid}_{cid}_{epid}_{duration}_"
  1374. fromep = self.detailContent_args.get('fromep', '')
  1375. if fromep == 'ep' + str(epid):
  1376. self.detailContent_args['fromep'] = url
  1377. replyList = self.detailContent_args.get('Reply')
  1378. if fromep == 'ep' + str(epid) or not fromep and replyList == None:
  1379. self.detailContent_args['Reply'] = ''
  1380. if self.userConfig['show_vod_hot_reply']:
  1381. self.get_vod_hot_reply_event.clear()
  1382. self.pool.submit(self.get_vod_hot_reply, aid)
  1383. ssid = self.detailContent_args.get('ssid', '')
  1384. if ssid:
  1385. if preview:
  1386. return url, ''
  1387. if parse:
  1388. self.detailContent_args['parse'] = 1
  1389. if long_title:
  1390. long_title = '【解析】' + long_title
  1391. ep_title += long_title
  1392. parseurl = f"{ep_title}${aid}_{cid}_{epid}_{duration}_{parse}"
  1393. if fromep == 'ep' + str(epid):
  1394. self.detailContent_args['fromep'] += '#' + parseurl
  1395. else:
  1396. parseurl = url
  1397. return url, parseurl
  1398. else:
  1399. return url
  1400. def get_ugc_season(self, section, sections_len):
  1401. if sections_len > 1:
  1402. sec_title = self.detailContent_args['season_title'] + ' ' + section['title']
  1403. else:
  1404. sec_title = self.detailContent_args['season_title']
  1405. sec_title = sec_title.replace("#", "﹟").replace("$", "﹩")
  1406. episodes = section.get('episodes')
  1407. playUrl = '#'.join(map(self.get_normal_episodes, episodes))
  1408. result = (sec_title, playUrl)
  1409. return result
  1410. get_vod_hot_reply_event = threading.Event()
  1411. def get_vod_hot_reply(self, oid):
  1412. query = self.encrypt_wbi(type=1, ps=30, oid=str(oid))[0]
  1413. url = f'http://api.bilibili.com/x/v2/reply/wbi/main?{query}'
  1414. jRoot = self._get_sth(url, 'fake').json()
  1415. if jRoot['code'] == 0:
  1416. replies = jRoot['data'].get('replies')
  1417. top_replies = jRoot['data'].get('top_replies')
  1418. if replies and top_replies:
  1419. replies = top_replies + replies
  1420. if replies:
  1421. up_mid = jRoot['data']['upper']['mid']
  1422. ReplyList = []
  1423. Reply_jump = []
  1424. for r in replies:
  1425. rpid = r['rpid']
  1426. sex = r['member']['sex']
  1427. if sex and sex == '女':
  1428. sex = '👧'
  1429. else:
  1430. sex = '👦'
  1431. name = sex + r['member']['uname'] + ':'
  1432. mid = r['mid']
  1433. if mid == up_mid:
  1434. name = '🆙' + name
  1435. like = '👍' + self.zh(r['like'])
  1436. message = r['content']['message']
  1437. if '/note-app/' in message:
  1438. continue
  1439. content = like + ' ' + name + message
  1440. content = content.replace("#", "﹟").replace("$", "﹩")
  1441. content += '$' + str(oid) + '_' + str(rpid) + '_notplay_reply'
  1442. ReplyList.append(content)
  1443. jump_url = r['content'].get('jump_url',{})
  1444. for key, value in jump_url.items():
  1445. if not value.get('app_url_schema') and not value.get('pc_url'):
  1446. if key.startswith('https://www.bilibili.com/'):
  1447. key = str(key).split('?')[0].split('/')
  1448. while key[-1] == '':
  1449. key.pop(-1)
  1450. key = key[-1]
  1451. if key.startswith('https://b23.tv/') or key.startswith('BV') or key.startswith('ep') or key.startswith('ss'):
  1452. title = str(value['title']).replace("#", "﹟").replace("$", "﹩")
  1453. vod = {'vod_id': str(key), 'vod_name': '评论:' + title}
  1454. if not vod in Reply_jump:
  1455. Reply_jump.append(vod)
  1456. title = '快搜:' + str(key) +' ' + title
  1457. content = title + '$ '
  1458. ReplyList.append(content)
  1459. self.detailContent_args['Reply'] = '#'.join(ReplyList)
  1460. self.detailContent_args['Reply_jump'] = Reply_jump
  1461. self.get_vod_hot_reply_event.set()
  1462. detailContent_args = {}
  1463. def detailContent(self, array):
  1464. self.stop_heartbeat()
  1465. aid = array[0]
  1466. if aid.startswith('list'):
  1467. return self.series_detailContent(aid)
  1468. self.detailContent_args = {}
  1469. id = mlid = urlargs = ''
  1470. self.get_vod_hot_reply_event.set()
  1471. if aid.startswith('setting'):
  1472. aid = aid.split('_')
  1473. if aid[1] == 'tab&filter':
  1474. return self.setting_tab_filter_detailContent()
  1475. elif aid[1] == 'liveExtra':
  1476. return self.setting_liveExtra_detailContent()
  1477. elif aid[1] == 'login':
  1478. key = aid[2]
  1479. return self.setting_login_detailContent(key)
  1480. elif aid.startswith('av') or aid.startswith('BV'):
  1481. for i in aid.split('_'):
  1482. if i.startswith('av'):
  1483. id = i.replace('av', '', 1)
  1484. query = self.encrypt_wbi(aid=id)[0]
  1485. elif i.startswith('BV'):
  1486. id = i
  1487. query = self.encrypt_wbi(bvid=id)[0]
  1488. elif i.startswith('mlid'):
  1489. mlid = i.replace('mlid', '', 1)
  1490. #获取热门评论
  1491. if self.userConfig['show_vod_hot_reply']:
  1492. self.detailContent_args['Reply'] = ''
  1493. self.get_vod_hot_reply_event.clear()
  1494. self.pool.submit(self.get_vod_hot_reply, id)
  1495. elif 'up' in aid:
  1496. return self.up_detailContent(array)
  1497. elif 'ss' in aid or 'ep' in aid:
  1498. return self.ysContent(array)
  1499. elif aid.isdigit():
  1500. return self.live_detailContent(array)
  1501. relation = self.pool.submit(self.get_vod_relation, query)
  1502. url = f'https://api.bilibili.com/x/web-interface/wbi/view/detail?{query}'
  1503. jRoot = self._get_sth(url, 'fake').json()
  1504. if jRoot['code'] != 0:
  1505. return {}
  1506. jo = jRoot['data']['View']
  1507. redirect_url = jo.get('redirect_url', '')
  1508. if 'bangumi' in redirect_url:
  1509. array[0] = self.find_bangumi_id(redirect_url)
  1510. return self.ysContent(array)
  1511. self.detailContent_args['mid'] = up_mid = str(jo['owner']['mid'])
  1512. self.detailContent_args['aid'] = aid = jo.get('aid')
  1513. up_info = self.pool.submit(self.get_up_info, mid=up_mid, data=jRoot['data'].get('Card'))
  1514. #相关合集
  1515. ugc_season = jo.get('ugc_season')
  1516. if ugc_season:
  1517. self.detailContent_args['season_title'] = ugc_season['title']
  1518. sections = ugc_season['sections']
  1519. sections_len = len(sections)
  1520. ugc_season_task = []
  1521. for section in sections:
  1522. t = self.pool.submit(self.get_ugc_season, section, sections_len)
  1523. ugc_season_task.append(t)
  1524. #相关推荐
  1525. jo_Related = jRoot['data'].get('Related')
  1526. #正片
  1527. pages = jo['pages']
  1528. title = jo['title'].replace("<em class=\"keyword\">", "").replace("</em>", "")
  1529. pic = jo['pic']
  1530. desc = jo['desc'].strip()
  1531. typeName = jo['tname']
  1532. date = time.strftime("%Y%m%d", time.localtime(jo['pubdate'])) # 投稿时间本地年月日表示
  1533. stat = jo['stat']
  1534. # 演员项展示视频状态,包括以下内容:
  1535. remark = []
  1536. remark.append('▶' + self.zh(stat['view']))
  1537. remark.append('💬' + self.zh(stat['danmaku']))
  1538. remark.append('👍' + self.zh(stat['like']))
  1539. remark.append('💰' + self.zh(stat['coin']))
  1540. remark.append('⭐' + self.zh(stat['favorite']))
  1541. _is_stein_gate = jo['rights'].get('is_stein_gate', 0)
  1542. vod = {
  1543. "vod_id": 'av' + str(aid),
  1544. "vod_name": title,
  1545. "vod_pic": pic,
  1546. "type_name": typeName,
  1547. "vod_year": date,
  1548. "vod_content": desc
  1549. }
  1550. vod['vod_remarks'] = " ".join(remark)
  1551. vod_tags = ', '.join(sorted(map(lambda x: '[a=cr:{"id": "' + x['tag_name'].replace('"', '\\"') + '_clicklink","name":"' + x['tag_name'].replace('"', '\\"') + '"}/]' + x['tag_name'] + '[/a]', jRoot['data'].get('Tags', [])), key=len))
  1552. vod['vod_content'] = vod_tags + ' \n' + desc
  1553. self.userConfig['show_vod_hot_reply'] = True
  1554. secondP = []
  1555. if self.userid:
  1556. #做点什么
  1557. follow = '➕关注$1_notplay_follow'
  1558. unfollow = '➖取关$2_notplay_follow'
  1559. like = '👍点赞$1_notplay_like'
  1560. unlike = '👍🏻取消点赞$2_notplay_like'
  1561. coin1 = '👍💰投币$1_notplay_coin'
  1562. coin2 = '👍💰💰$2_notplay_coin'
  1563. triple = '👍💰⭐三连$notplay_triple'
  1564. secondPList = [follow, triple, like, coin1, coin2, unfollow, unlike]
  1565. if mlid:
  1566. favdel = f"☆取消收藏${mlid}_del_notplay_fav"
  1567. secondPList.append(favdel)
  1568. for fav in self.userConfig.get("fav_list", []):
  1569. folder = fav['n'].replace("#", "﹟").replace("$", "﹩")
  1570. ids = fav['v']
  1571. fav = '⭐{}${}_add_notplay_fav'.format(folder, ids)
  1572. secondPList.append(fav)
  1573. secondP = ['#'.join(secondPList)]
  1574. AllPt = []
  1575. AllPu = []
  1576. if pages:
  1577. AllPt = ['视频分集']
  1578. if _is_stein_gate:
  1579. AllPt = ['互动视频【快搜继续】']
  1580. AllPu = ['#'.join(self.pool.map(self.get_normal_episodes, pages))]
  1581. if secondP:
  1582. AllPt.append('做点什么')
  1583. AllPu.extend(secondP)
  1584. if self.userConfig['show_vod_hot_reply']:
  1585. self.get_vod_hot_reply_event.wait()
  1586. replyList = self.detailContent_args.get('Reply', '')
  1587. if replyList:
  1588. AllPt.append('热门评论')
  1589. AllPu.extend([replyList])
  1590. if jo_Related:
  1591. AllPt.append('相关推荐')
  1592. AllPu.append('#'.join(self.pool.map(self.get_normal_episodes, jo_Related)))
  1593. if ugc_season:
  1594. for t in as_completed(ugc_season_task):
  1595. AllPt.append(t.result()[0])
  1596. AllPu.append(t.result()[1])
  1597. vod['vod_play_from'] = "$$$".join(AllPt)
  1598. vod['vod_play_url'] = "$$$".join(AllPu)
  1599. #视频关系
  1600. up_info = up_info.result()
  1601. vod['vod_director'] = '🆙 ' + up_info['crname'] + ' 👥 ' + up_info['fans'] + ' ' + ' '.join(relation.result())
  1602. result = {
  1603. 'list': [
  1604. vod
  1605. ]
  1606. }
  1607. return result
  1608. def series_detailContent(self, array):
  1609. mid, type, sid = array.replace('list_', '').split('_')
  1610. pg = 1
  1611. ps = 99
  1612. vod = {"vod_id": array, "vod_play_from": "B站"}
  1613. urlL = []
  1614. while True:
  1615. if type == 'season':
  1616. 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)
  1617. else:
  1618. url = 'https://api.bilibili.com/x/series/archives?mid=%s&series_id=%s&pn=%s&ps=%s' % (mid, sid, pg, ps)
  1619. jo = self._get_sth(url, 'fake').json()
  1620. data = jo.get('data')
  1621. if not vod.get("vod_name"):
  1622. if data.get('meta'):
  1623. vod["vod_name"] = data['meta']['name']
  1624. vod["vod_pic"] = data['meta']['cover']
  1625. vod["vod_content"] = data['meta']['description']
  1626. else:
  1627. vod["vod_name"] = data['archives'][0]['title']
  1628. playUrl = '#'.join(map(self.get_normal_episodes, data.get('archives')))
  1629. urlL.append(playUrl)
  1630. total = data['page']['total']
  1631. if (ps * pg) >= total:
  1632. break
  1633. pg += 1
  1634. vod['vod_play_url'] = '#'.join(urlL)
  1635. up_info = self.up_info[mid]
  1636. vod['vod_director'] = '🆙 ' + up_info['name'] + " " + up_info['following']
  1637. result = {
  1638. 'list': [
  1639. vod
  1640. ]
  1641. }
  1642. return result
  1643. def up_detailContent(self, array):
  1644. self.detailContent_args['mid'] = mid = array[0].replace('up', '')
  1645. up_info = self.pool.submit(self.get_up_info, mid)
  1646. first = '是否关注$ '
  1647. follow = '关注$1_notplay_follow'
  1648. unfollow = '取消关注$2_notplay_follow'
  1649. qqfollow = '悄悄关注$3_notplay_follow'
  1650. spfollow = '特别关注$-10_notplay_special_follow'
  1651. unspfollow = '取消特别关注$0_notplay_special_follow'
  1652. Space = ' $_'
  1653. doWhat = [follow, spfollow, qqfollow, Space, Space, Space, unfollow, unspfollow]
  1654. doWhat = '#'.join(doWhat)
  1655. up_info = up_info.result()
  1656. vod = {
  1657. "vod_id": 'up' + str(mid),
  1658. "vod_name": up_info['name'] + " 个人主页",
  1659. "vod_pic": up_info['face'],
  1660. "vod_director": '🆙 ' + up_info['name'] + " " + up_info['following'] + ' UID:' + str(mid),
  1661. "vod_content": up_info['desc'],
  1662. 'vod_play_from': '关注TA$$$动态标签筛选查看视频投稿',
  1663. 'vod_play_url': doWhat
  1664. }
  1665. remark = "👥 " + up_info['fans'] + " 🎬 " + up_info['vod_count'] + " 👍 " + up_info['like_num']
  1666. vod["vod_remarks"] = remark
  1667. tabfilter = self.config['filter'].get('动态')
  1668. if not tabfilter:
  1669. tabfilter = self.config['filter'].get('UP', [])
  1670. vod["vod_actor"] = ' '.join(map(lambda x: '[a=cr:{"id": "' + str(mid) + '_' + x['v'] +'_getupvideos","name": "' + up_info['name'].replace('"', '\\"') + ' ' + x['n'] + '"}/]' + x['n'] + '[/a]', tabfilter[-1]['value']))
  1671. result = {
  1672. 'list': [
  1673. vod
  1674. ]
  1675. }
  1676. return result
  1677. def setting_login_detailContent(self, key):
  1678. cookie_dic_tmp = self.cookie_dic_tmp.get(key, '')
  1679. message = ''
  1680. if not cookie_dic_tmp:
  1681. message = self.get_cookies(key)
  1682. if message:
  1683. message = f"【{message}】通过手机客户端扫码确认登录后点击相应按钮设置账号"
  1684. else:
  1685. message = '【已扫码并确认登录】请点击相应按钮设置当前获取的账号为:'
  1686. vod = {
  1687. "vod_name": "登录与设置",
  1688. "vod_content": '通过手机客户端扫码并确认登录后,点击相应按钮设置cookie,设置后不需要管嗅探结果,直接返回二维码页面刷新,查看是否显示已登录,已登录即可重新打开APP以加载全部标签',
  1689. }
  1690. vod_play_from = ['登录$$$退出登录']
  1691. vod_play_url = []
  1692. first = message + '$ '
  1693. login = '设置为主账号,动态收藏关注等内容源于此$' + str(key) + '_master_login_setting'
  1694. login_vip = '设置为备用的VIP账号,仅用于播放会员番剧$' + str(key) + '_vip_login_setting'
  1695. vod_play_url.append('#'.join([first, login, login_vip]))
  1696. second = '点击相应按钮退出账号>>>$ '
  1697. logout = '退出主账号$master_logout_setting'
  1698. logout_vip = '退出备用的VIP账号$vip_logout_setting'
  1699. vod_play_url.append('#'.join([second, logout, logout_vip]))
  1700. cate_lis = [{
  1701. 'f': '主页站点推荐栏',
  1702. 'c': 'maxHomeVideoContent',
  1703. 'd': {
  1704. '3': '3图',
  1705. '4': '4图',
  1706. '5': '5图',
  1707. '6': '6图',
  1708. '8': '8图',
  1709. '9': '9图',
  1710. '10': '10图',
  1711. '20': '20图',
  1712. }
  1713. },{
  1714. 'f': '视频画质',
  1715. 'c': 'vodDefaultQn',
  1716. 'd': self.vod_qn_id
  1717. },{
  1718. 'f': '视频编码',
  1719. 'c': 'vodDefaultCodec',
  1720. 'd': self.vod_codec_id
  1721. },{
  1722. 'f': '音频码率',
  1723. 'c': 'vodDefaultAudio',
  1724. 'd': self.vod_audio_id
  1725. },{
  1726. 'f': '收藏默认显示',
  1727. 'c': 'favMode',
  1728. 'd': {
  1729. '0': '默认收藏夹',
  1730. '1': '追番',
  1731. '2': '追剧',
  1732. }
  1733. },{
  1734. 'f': '上传播放进度',
  1735. 'c': 'heartbeatInterval',
  1736. 'd': {
  1737. '0': '关',
  1738. '15': '开',
  1739. }
  1740. },{
  1741. 'f': '直播筛选细化',
  1742. 'c': 'showLiveFilterTag',
  1743. 'd': {
  1744. '0': '关',
  1745. '1': '开',
  1746. }
  1747. }]
  1748. for cate in cate_lis:
  1749. vod_play_from.append(cate['f'])
  1750. defaultConfig = cate['d'][str(int(self.userConfig[cate['c']]))]
  1751. if 'vodDefaultAudio' == cate['c']:
  1752. defaultConfig = str(defaultConfig).replace('000', 'k')
  1753. url = ['当前:' + defaultConfig + '$ ']
  1754. for id, name in cate['d'].items():
  1755. if 'vodDefaultAudio' == cate['c']:
  1756. name = str(name).replace('000', 'k')
  1757. url.append(name + '$' + str(id) + '_' + cate['c'] + '_setting')
  1758. vod_play_url.append('#'.join(url))
  1759. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1760. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1761. result = {
  1762. 'list': [
  1763. vod
  1764. ]
  1765. }
  1766. return result
  1767. def setting_tab_filter_detailContent(self):
  1768. vod = {
  1769. "vod_name": "标签与筛选",
  1770. "vod_content": '依次点击各标签,同一标签第一次点击为添加,第二次删除,可以返回到二维码页后重进本页查看预览,最后点击保存,未选择的将追加到末尾,如果未保存就重启app,将丢失未保存的配置',
  1771. }
  1772. vod_play_from = []
  1773. vod_play_url = []
  1774. cate_lis = [
  1775. {'n': 'cateManual', 'v': '标签'},
  1776. {'n': 'tuijianLis', 'v': '推荐[分区]'},
  1777. {'n': 'rankingLis', 'v': '推荐[排行榜]'},
  1778. {'n': 'cateManualLive', 'v': '直播'},
  1779. ]
  1780. for cate in cate_lis:
  1781. _List = cate['n']
  1782. vod_play_from.append(cate['v'])
  1783. List_tmp = self.userConfig.get(str(_List) + '_tmp', [])
  1784. status = ''
  1785. if List_tmp:
  1786. status = '【未保存】'
  1787. else:
  1788. List_tmp = self.userConfig.get(_List, [])
  1789. if not List_tmp:
  1790. List_tmp = self.defaultConfig.get(_List)
  1791. if List_tmp and type(List_tmp[0]) == dict:
  1792. List_tmp = list(map(lambda x:x['n'], List_tmp))
  1793. url = ['当前: ' + ','.join(List_tmp) + '$ ', f"{status}点击这里保存$_{_List}_save_setting", f"点击这里恢复默认并保存$_{_List}_clear_setting"]
  1794. defaultConfig = self.defaultConfig[_List].copy()
  1795. if _List == 'cateManualLive':
  1796. extra_live_filter = self.userConfig.get('cateManualLiveExtra', [])
  1797. defaultConfig.extend(extra_live_filter.copy())
  1798. for name in defaultConfig:
  1799. value = str(name)
  1800. if type(name) == dict:
  1801. value = name['n'] + '@@@' + name['v'].replace('_', '@@@')
  1802. name = name['n']
  1803. url.append(f"{name}${value}_{_List}_setting")
  1804. vod_play_url.append('#'.join(url))
  1805. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1806. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1807. result = {
  1808. 'list': [
  1809. vod
  1810. ]
  1811. }
  1812. return result
  1813. def setting_liveExtra_detailContent(self):
  1814. vod = {
  1815. "vod_name": "查看直播细化标签",
  1816. "vod_content": '点击想要添加的标签,同一标签第一次点击为添加,第二次删除,完成后在[标签与筛选]页继续操作,以添加到直播筛选分区列中',
  1817. }
  1818. vod_play_from = ['已添加']
  1819. cateManualLiveExtra = self.userConfig.get('cateManualLiveExtra', [])
  1820. vod_play_url = ['点击相应标签(只)可以删除$ #清空$clear_liveFilter_setting']
  1821. for name in cateManualLiveExtra:
  1822. value = name['v']
  1823. name = name['n']
  1824. vod_play_url.append(name + '$' + 'del_' + name + '_' + value + '_liveFilter_setting')
  1825. vod_play_url = ['#'.join(vod_play_url)]
  1826. cateLive = self.userConfig.get('cateLive', {})
  1827. for parent, parent_dic in cateLive.items():
  1828. area_dic = parent_dic['value']['value']
  1829. if len(area_dic) == 1:
  1830. continue
  1831. vod_play_from.append(parent)
  1832. url = []
  1833. for area in area_dic:
  1834. name = str(area['n']).replace('_', '-').replace("#", "﹟").replace("$", "﹩")
  1835. id = str(area['v']).replace('_', '@@@').replace("#", "﹟").replace("$", "﹩")
  1836. url.append(name + '$add_' + name + '_' + id + '_liveFilter_setting')
  1837. vod_play_url.append('#'.join(url))
  1838. vod['vod_play_from'] = '$$$'.join(vod_play_from)
  1839. vod['vod_play_url'] = '$$$'.join(vod_play_url)
  1840. result = {
  1841. 'list': [
  1842. vod
  1843. ]
  1844. }
  1845. return result
  1846. def get_all_season(self, season):
  1847. season_id = str(season['season_id'])
  1848. season_title = season['season_title']
  1849. if season_id == self.detailContent_args['ssid']:
  1850. self.detailContent_args['s_title'] = season_title
  1851. pic = season['cover']
  1852. remark = season['new_ep']['index_show']
  1853. result = {
  1854. "vod_id": season_id + 'ss',
  1855. "vod_name": '系列:' + season_title,
  1856. "vod_pic": self.format_img(pic),
  1857. "vod_remarks": remark}
  1858. return result
  1859. def get_bangumi_section(self, section):
  1860. sec_title = section['title'].replace("#", "﹟").replace("$", "﹩")
  1861. sec_type = section['type']
  1862. if sec_type in [1, 2] and len(section['episode_ids']) == 0:
  1863. episodes = section['episodes']
  1864. playUrl = '#'.join(map(lambda x: self.get_normal_episodes(x)[0], episodes))
  1865. return (sec_title, playUrl)
  1866. def ysContent(self, array):
  1867. aid = array[0]
  1868. if 'ep' in aid:
  1869. self.detailContent_args['fromep'] = aid
  1870. aid = 'ep_id=' + aid.replace('ep', '')
  1871. elif 'ss' in aid:
  1872. aid = 'season_id=' + aid.replace('ss', '')
  1873. url = "https://api.bilibili.com/pgc/view/web/season?{0}".format(aid)
  1874. jo = self._get_sth(url, 'fake').json().get('result', {})
  1875. self.detailContent_args['ssid'] = str(jo['season_id'])
  1876. title = jo['title']
  1877. self.detailContent_args['s_title'] = jo['season_title']
  1878. self.detailContent_args['title_type'] = '集'
  1879. if jo['type'] in [1, 4]:
  1880. self.detailContent_args['title_type'] = '话'
  1881. #添加系列到搜索
  1882. seasons = jo.get('seasons')
  1883. if len(seasons) == 1:
  1884. self.detailContent_args['s_title'] = seasons[0]['season_title']
  1885. seasons = 0
  1886. else:
  1887. self.detailContent_args['seasons'] = list(self.pool.map(self.get_all_season, seasons))
  1888. #获取正片
  1889. episodes = jo.get('episodes')
  1890. #获取花絮
  1891. section_task = []
  1892. for s in jo.get('section', []):
  1893. if s:
  1894. t = self.pool.submit(self.get_bangumi_section, s)
  1895. section_task.append(t)
  1896. pic = jo['cover']
  1897. typeName = jo['share_sub_title']
  1898. date = jo['publish']['pub_time'][0:4]
  1899. dec = jo['evaluate']
  1900. remark = jo['new_ep']['desc']
  1901. stat = jo['stat']
  1902. # 演员和导演框展示视频状态,包括以下内容:
  1903. status = "▶" + self.zh(stat['views']) + " ❤" + self.zh(stat['favorites'])
  1904. vod = {
  1905. "vod_id": 'ss' + self.detailContent_args['ssid'],
  1906. "vod_name": title,
  1907. "vod_pic": pic,
  1908. "type_name": typeName,
  1909. "vod_year": date,
  1910. "vod_actor": status,
  1911. "vod_content": dec
  1912. }
  1913. if seasons:
  1914. remark += ' [a=cr:{"id": "_getbangumiseasons","name": "' + title.replace('"', '\\"') + '"}/]更多系列[/a]'
  1915. seasons = 0
  1916. if 'rating' in jo:
  1917. remark = str(jo['rating']['score']) + '分 ' + remark
  1918. self.userConfig['show_vod_hot_reply'] = True
  1919. vod["vod_remarks"] = remark
  1920. ZhuiPf = []
  1921. ZhuiPu = []
  1922. if self.userid:
  1923. ZhuiPf = ['追番剧']
  1924. ZhuiPu = '❤追番剧$add_notplay_zhui#💔取消追番剧$del_notplay_zhui'
  1925. ZhuiPu = [ZhuiPu]
  1926. if seasons:
  1927. ZhuiPf.append('更多系列')
  1928. ZhuiPu.append('更多系列在快速搜索中查看$ #')
  1929. FirstPf = []
  1930. FirstPu = []
  1931. PreviewPf = []
  1932. PreviewPu = []
  1933. ParsePf = []
  1934. ParsePu = []
  1935. if episodes:
  1936. for x, y in self.pool.map(self.get_normal_episodes, episodes):
  1937. if y:
  1938. FirstPu.append(x)
  1939. ParsePu.append(y)
  1940. else:
  1941. PreviewPu.append(x)
  1942. if FirstPu:
  1943. FirstPf = [self.detailContent_args['s_title']]
  1944. FirstPu = ['#'.join(FirstPu)]
  1945. if PreviewPu:
  1946. PreviewPf = ['预告']
  1947. PreviewPu = ['#'.join(PreviewPu)]
  1948. if not self.detailContent_args.get('parse'):
  1949. ParsePu = []
  1950. if ParsePu:
  1951. ParsePf = [str(self.detailContent_args['s_title']) + '【解析】']
  1952. ParsePu = ['#'.join(ParsePu)]
  1953. fromL = ParsePf + FirstPf + PreviewPf
  1954. urlL = ParsePu + FirstPu + PreviewPu
  1955. for t in as_completed(section_task):
  1956. s = t.result()
  1957. if s:
  1958. if s[0] == '预告':
  1959. PreviewPu = ['#'.join(s[1])]
  1960. else:
  1961. fromL.append(s[0])
  1962. urlL.append(s[1])
  1963. fromep = self.detailContent_args.get('fromep', '')
  1964. if fromep:
  1965. fromL = ['B站'] + fromL
  1966. urlL = [fromep] + urlL
  1967. if self.userConfig['show_vod_hot_reply']:
  1968. self.get_vod_hot_reply_event.wait()
  1969. ReplyPu = self.detailContent_args.get('Reply', '')
  1970. if ReplyPu:
  1971. ZhuiPf.append('热门评论')
  1972. ZhuiPu.append(ReplyPu)
  1973. fromL.insert(1, '$$$'.join(ZhuiPf))
  1974. urlL.insert(1, '$$$'.join(ZhuiPu))
  1975. vod['vod_play_from'] = '$$$'.join(fromL)
  1976. vod['vod_play_url'] = '$$$'.join(urlL)
  1977. result = {
  1978. 'list': [
  1979. vod
  1980. ]
  1981. }
  1982. return result
  1983. def get_live_api2_playurl(self, room_id):
  1984. playFrom = []
  1985. playUrl = []
  1986. 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)
  1987. jo = self._get_sth(url, 'vip').json()
  1988. if jo['code'] == 0:
  1989. playurl_info = jo['data'].get('playurl_info', '')
  1990. if playurl_info:
  1991. stream = playurl_info['playurl']['stream']
  1992. liveDic = {
  1993. 'codec': {'avc': '0', 'hevc': '1'},
  1994. 'format': {'flv': '0', 'ts': '1', 'fmp4': '2'},
  1995. }
  1996. liveDic['qn'] = dict(self.pool.map(lambda x:(x['qn'], x['desc']), playurl_info['playurl']['g_qn_desc']))
  1997. vodList = []
  1998. for i in stream:
  1999. vodList.extend(i['format'])
  2000. api2_playUrl = {}
  2001. for v in vodList:
  2002. format = str(v.get('format_name'))
  2003. for c in v['codec']:
  2004. codec = str(c.get('codec_name'))
  2005. accept_qn = c.get('accept_qn')
  2006. for qn in accept_qn:
  2007. url = format + '_' + codec + f"$live_{room_id}_" + str(qn) + '_' + liveDic['format'][format] + '_' + liveDic['codec'][codec]
  2008. if not api2_playUrl.get(liveDic['qn'][qn]):
  2009. api2_playUrl[liveDic['qn'][qn]] = []
  2010. api2_playUrl[liveDic['qn'][qn]].append(url)
  2011. for key, value in api2_playUrl.items():
  2012. playFrom.append(key)
  2013. playUrl.append('#'.join(value))
  2014. result = {'From': playFrom, 'url': playUrl}
  2015. return result
  2016. def live_detailContent(self, array):
  2017. room_id = array[0]
  2018. get_live_api2_playurl = self.pool.submit(self.get_live_api2_playurl, room_id)
  2019. url = "https://api.live.bilibili.com/room/v1/Room/get_info?room_id=" + str(room_id)
  2020. jRoot = self._get_sth(url, 'fake').json()
  2021. result = {}
  2022. if jRoot.get('code') == 0:
  2023. jo = jRoot['data']
  2024. self.detailContent_args['mid'] = mid = str(jo["uid"])
  2025. up_info = self.pool.submit(self.get_up_info, mid)
  2026. title = jo['title'].replace("<em class=\"keyword\">", "").replace("</em>", "")
  2027. pic = jo.get("user_cover")
  2028. desc = jo.get('description')
  2029. typeName = jo.get('parent_area_name') + '--' + jo.get('area_name')
  2030. live_status = jo.get('live_status', '')
  2031. if live_status:
  2032. live_status = "开播时间:" + jo.get('live_time').replace('-', '.')
  2033. else:
  2034. live_status = "未开播"
  2035. vod = {
  2036. "vod_id": room_id,
  2037. "vod_name": title,
  2038. "vod_pic": pic,
  2039. "type_name": typeName,
  2040. "vod_content": desc,
  2041. }
  2042. remark = "房间号:" + room_id + " " + live_status
  2043. vod["vod_remarks"] = remark
  2044. secondPFrom = ''
  2045. secondP = ''
  2046. if self.userid:
  2047. secondPFrom = '关注Ta'
  2048. first = '是否关注$ '
  2049. follow = '➕关注$1_notplay_follow'
  2050. unfollow = '➖取关$2_notplay_follow'
  2051. secondPList = [first, follow, unfollow]
  2052. secondP = '#'.join(secondPList)
  2053. playFrom = get_live_api2_playurl.result().get('From', [])
  2054. playUrl = get_live_api2_playurl.result().get('url', [])
  2055. if secondPFrom:
  2056. playFrom.insert(1, secondPFrom)
  2057. playUrl.insert(1, secondP)
  2058. vod['vod_play_from'] = '$$$'.join(playFrom)
  2059. vod['vod_play_url'] = '$$$'.join(playUrl)
  2060. up_info = up_info.result()
  2061. vod["vod_director"] = '🆙 ' + up_info['crname'] + " 👥 " + self.zh(jo.get('attention')) + ' ' + up_info['following']
  2062. result['list'] = [vod]
  2063. return result
  2064. def searchContent(self, key, quick):
  2065. return self.searchContentPage(key, quick, '1')
  2066. search_key = ''
  2067. def searchContentPage(self, key, quick, pg):
  2068. if not self.session_fake.cookies:
  2069. self.pool.submit(self.getFakeCookie, True)
  2070. for t in self.task_pool:
  2071. t.cancel()
  2072. if int(pg) > 1:
  2073. return self.get_search_content(key = key, pg = pg, duration_diff = 0, order = '', type = 'video', ps = self.userConfig['page_size'])
  2074. self.task_pool = []
  2075. self.search_key = key
  2076. mid = self.detailContent_args.get('mid', '')
  2077. if quick and mid:
  2078. get_up_videos = self.pool.submit(self.get_up_videos, mid, 1, 'quicksearch')
  2079. types = {'video': '','media_bangumi': '番剧: ', 'media_ft': '影视: ', 'bili_user': '用户: ', 'live': '直播: '}
  2080. for type, value in types.items():
  2081. t = self.pool.submit(self.get_search_content, key = key, pg = value, duration_diff = 0, order = '', type = type, ps = self.userConfig['page_size'])
  2082. self.task_pool.append(t)
  2083. result = {}
  2084. vodList = []
  2085. for t in as_completed(self.task_pool):
  2086. res = t.result().get('list', [])
  2087. vodList.extend(res)
  2088. self.task_pool.remove(t)
  2089. if len(vodList):
  2090. result['list'] = vodList
  2091. result['page'] = pg
  2092. result['pagecount'] = 9999
  2093. result['limit'] = 99
  2094. result['total'] = 999999
  2095. return result
  2096. stop_heartbeat_event = threading.Event()
  2097. def stop_heartbeat(self):
  2098. try:
  2099. for t in self.task_pool:
  2100. t.cancel()
  2101. finally:
  2102. self.stop_heartbeat_event.set()
  2103. def start_heartbeat(self, aid, cid, ssid, epid, duration):
  2104. query = self.encrypt_wbi(aid=aid, cid=cid)[0]
  2105. url = f'https://api.bilibili.com/x/player/wbi/v2?{query}'
  2106. data = self._get_sth(url).json().get('data',{})
  2107. heartbeatInterval = int(self.userConfig['heartbeatInterval'])
  2108. if not self.userid or not heartbeatInterval:
  2109. return
  2110. played_time = 0
  2111. duration = int(duration)
  2112. if int(data.get('last_play_cid', 0)) == int(cid):
  2113. last_play_time = int(data.get('last_play_time'))
  2114. if last_play_time > 0:
  2115. played_time = int(last_play_time / 1000)
  2116. heartbeat_times = int((duration - played_time) / heartbeatInterval) + 1
  2117. url = 'https://api.bilibili.com/x/click-interface/web/heartbeat'
  2118. data = {'aid': str(aid), 'cid': str(cid), 'csrf': str(self.csrf)}
  2119. if ssid:
  2120. data['sid'] = str(ssid)
  2121. data['epid'] = str(epid)
  2122. data['type'] = '4'
  2123. heartbeat_count = 0
  2124. self.stop_heartbeat_event.clear()
  2125. while True:
  2126. if heartbeat_count == heartbeatInterval or self.stop_heartbeat_event.is_set():
  2127. played_time += heartbeat_count
  2128. heartbeat_count = 0
  2129. if not heartbeat_count:
  2130. heartbeat_times -= 1
  2131. if not heartbeat_times:
  2132. #播完为-1
  2133. played_time = -1
  2134. self.stop_heartbeat_event.set()
  2135. data['played_time'] = str(played_time)
  2136. data = self.encrypt_wbi(**data)[1]
  2137. self.pool.submit(self._post_sth, url=url, data=data)
  2138. if self.stop_heartbeat_event.is_set():
  2139. break
  2140. time.sleep(1)
  2141. heartbeat_count += 1
  2142. wbi_key = {}
  2143. def get_wbiKey(self, wts):
  2144. r = self.fetch("https://api.bilibili.com/x/web-interface/nav", headers=self.header)
  2145. wbi_img_url = r.json()['data']['wbi_img']['img_url']
  2146. wbi_sub_url = r.json()['data']['wbi_img']['sub_url']
  2147. 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,
  2148. 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,
  2149. 11, 36, 20, 34, 44, 52]
  2150. ae = wbi_img_url.split("/")[-1].split(".")[0] + wbi_sub_url.split("/")[-1].split(".")[0]
  2151. le = reduce(lambda s, i: s + ae[i], oe, "")[:32]
  2152. self.wbi_key = {
  2153. "key": le,
  2154. "wts": wts
  2155. }
  2156. def encrypt_wbi(self, **params):
  2157. wts = round(time.time())
  2158. if not self.wbi_key or abs(wts - self.wbi_key['wts']) < 120:
  2159. self.get_wbiKey(wts)
  2160. params["wts"] = wts
  2161. params["dm_img_list"] = []
  2162. dm_rand = ['QQ','Qg','Qw','RA','RQ','Rg']
  2163. params["dm_img_str"] = random.choice(dm_rand)
  2164. params["dm_cover_img_str"] = random.choice(dm_rand)
  2165. params = dict(sorted(params.items()))
  2166. params = {k : ''.join(filter(lambda chr: chr not in "!'()*", str(v))) for k, v in params.items()}
  2167. Ae = urlencode(params)
  2168. w_rid = hashlib.md5((Ae + self.wbi_key['key']).encode(encoding='utf-8')).hexdigest()
  2169. params['w_rid'] = w_rid
  2170. return [Ae + "&w_rid=" + w_rid, params]
  2171. def _get_sth(self, url, _type='master', **kwargs):
  2172. if _type == 'vip' and self.session_vip.cookies:
  2173. rsp = self.session_vip.get(url, headers=self.header, **kwargs)
  2174. elif _type == 'fake':
  2175. if not self.session_fake.cookies:
  2176. self.getFakeCookie_event.wait()
  2177. rsp = self.session_fake.get(url, headers=self.header, **kwargs)
  2178. else:
  2179. rsp = self.session_master.get(url, headers=self.header, **kwargs)
  2180. return rsp
  2181. def _post_sth(self, url, data):
  2182. return self.session_master.post(url, headers=self.header, data=data)
  2183. def post_live_history(self, room_id):
  2184. data = {'room_id': str(room_id), 'platform': 'pc', 'csrf': str(self.csrf)}
  2185. url = 'https://api.live.bilibili.com/xlive/web-room/v1/index/roomEntryAction'
  2186. self._post_sth(url=url, data=data)
  2187. def do_notplay(self, ids):
  2188. aid = self.detailContent_args.get('aid')
  2189. mid = self.detailContent_args.get('mid')
  2190. ssid = self.detailContent_args.get('ssid')
  2191. data = {'csrf': str(self.csrf)}
  2192. url = ''
  2193. if 'follow' in ids:
  2194. if 'special' in ids:
  2195. data.update({'fids': str(mid), 'tagids': str(ids[0])})
  2196. url = 'https://api.bilibili.com/x/relation/tags/addUsers'
  2197. else:
  2198. data.update({'fid': str(mid), 'act': str(ids[0])})
  2199. url = 'https://api.bilibili.com/x/relation/modify'
  2200. elif 'zhui' in ids:
  2201. data.update({'season_id': str(ssid)})
  2202. url = 'https://api.bilibili.com/pgc/web/follow/' + str(ids[0])
  2203. elif 'like' in ids:
  2204. data.update({'aid': str(aid), 'like': str(ids[0])})
  2205. url = 'https://api.bilibili.com/x/web-interface/archive/like'
  2206. elif 'coin' in ids:
  2207. data.update({'aid': str(aid), 'multiply': str(ids[0]), 'select_like': '1'})
  2208. url = 'https://api.bilibili.com/x/web-interface/coin/add'
  2209. elif 'fav' in ids:
  2210. data.update({'rid': str(aid), 'type': '2'})
  2211. data[ids[1] + '_media_ids'] = str(ids[0])
  2212. url = 'https://api.bilibili.com/x/v3/fav/resource/deal'
  2213. elif 'triple' in ids:
  2214. data.update({'aid': str(aid)})
  2215. url = 'https://api.bilibili.com/x/web-interface/archive/like/triple'
  2216. elif 'reply' in ids:
  2217. data.update({'oid': str(ids[0]), 'rpid': str(ids[1]), 'type': '1', 'action': '1'})
  2218. url = 'http://api.bilibili.com/x/v2/reply/action'
  2219. self._post_sth(url=url, data=data)
  2220. self.fetch(url='http://127.0.0.1:9978/action?do=refresh&type=detail')
  2221. def get_cid(self, aid, cid):
  2222. url = "https://api.bilibili.com/x/web-interface/view?aid=%s&cid=%s" % str(aid, cid)
  2223. jo = self._get_sth(url).json().get('data', {})
  2224. if not cid:
  2225. cid = jo['cid']
  2226. dur = jo['duration']
  2227. epid = ''
  2228. if 'redirect_url' in jo and 'bangumi' in jo['redirect_url']:
  2229. epid = self.find_bangumi_id(jo['redirect_url'])
  2230. return cid, dur, epid
  2231. cookie_dic_tmp = {}
  2232. def get_cookies(self, key):
  2233. url = 'https://passport.bilibili.com/x/passport-login/web/qrcode/poll?qrcode_key=' + key
  2234. jo = self._get_sth(url, 'fake').json()
  2235. if jo['code'] == 0:
  2236. message = jo['data']['message']
  2237. if not message:
  2238. self.cookie_dic_tmp[key] = dict(self.session_fake.cookies)
  2239. self.pool.submit(self.getFakeCookie)
  2240. return message
  2241. return '网络错误'
  2242. def set_cookie(self, key, _type):
  2243. cookie_dic_tmp = self.cookie_dic_tmp.get(key, '')
  2244. if not cookie_dic_tmp:
  2245. message = self.get_cookies(key)
  2246. if message:
  2247. return
  2248. users = self.userConfig.get('users', {})
  2249. users[_type] = {'cookies_dic': self.cookie_dic_tmp.get(key, {})}
  2250. self.userConfig.update({'users': users})
  2251. self.getCookie(_type)
  2252. self.dump_config()
  2253. def unset_cookie(self, _type):
  2254. if _type == 'vip':
  2255. self.session_vip.cookies.clear()
  2256. else:
  2257. self.session_master.cookies = self.session_fake.cookies
  2258. self.userid = self.csrf = ''
  2259. if _type in self.userConfig.get('users', {}):
  2260. self.userConfig['users'].pop(_type)
  2261. self.dump_config()
  2262. def set_normal_default(self, id, type):
  2263. self.userConfig[type] = str(id)
  2264. self.dump_config()
  2265. def set_normal_cateManual(self, name, _List, action):
  2266. List_tmp = self.userConfig.get(str(_List) + '_tmp')
  2267. if not List_tmp:
  2268. List_tmp = self.userConfig[str(_List) + '_tmp'] = []
  2269. if action == 'save':
  2270. for _item in self.defaultConfig[_List]:
  2271. if not _item in List_tmp.copy():
  2272. self.userConfig[str(_List) + '_tmp'].append(_item)
  2273. self.userConfig[_List] = self.userConfig[str(_List) + '_tmp'].copy()
  2274. self.userConfig.pop(_List + '_tmp')
  2275. self.dump_config()
  2276. elif action == 'clear':
  2277. self.userConfig[_List] = self.defaultConfig[_List].copy()
  2278. self.userConfig.pop(str(_List) + '_tmp')
  2279. self.dump_config()
  2280. else:
  2281. if _List == 'cateManualLive':
  2282. name = name.split('@@@')
  2283. if len(name) == 3:
  2284. name[1] += '_' + str(name[2])
  2285. name = {'n': name[0], 'v': str(name[1])}
  2286. if name in List_tmp:
  2287. self.userConfig[str(_List) + '_tmp'].remove(name)
  2288. else:
  2289. self.userConfig[str(_List) + '_tmp'].append(name)
  2290. def add_cateManualLiveExtra(self, action, name, id):
  2291. _Extra = self.userConfig.get('cateManualLiveExtra', [])
  2292. if not _Extra:
  2293. _Extra = self.userConfig['cateManualLiveExtra'] = []
  2294. if action == 'clear':
  2295. for _ext in _Extra:
  2296. _ext['v'] = _ext['v'].replace('@@@', '_')
  2297. if _ext in self.userConfig.get('cateManualLive', []):
  2298. self.userConfig['cateManualLive'].remove(_ext)
  2299. if _ext in self.userConfig.get('cateManualLive_tmp', []):
  2300. self.userConfig['cateManualLive_tmp'].remove(_ext)
  2301. self.userConfig.pop('cateManualLiveExtra')
  2302. elif id in list(map(lambda x:x['v'], self.userConfig.get('cateManualLiveExtra', []))):
  2303. area_dict = {'n': name, 'v': id}
  2304. self.userConfig['cateManualLiveExtra'].remove(area_dict)
  2305. area_dict['v'] = id.replace('@@@', '_')
  2306. if area_dict in self.userConfig.get('cateManualLive', []):
  2307. self.userConfig['cateManualLive'].remove(area_dict)
  2308. if area_dict in self.userConfig.get('cateManualLive_tmp', []):
  2309. self.userConfig['cateManualLive_tmp'].remove(area_dict)
  2310. else:
  2311. area_dict = {'n': name, 'v': id}
  2312. self.userConfig['cateManualLiveExtra'].append(area_dict)
  2313. self.dump_config()
  2314. vod_qn_id = {
  2315. '127': "8K",
  2316. '126': "杜比视界",
  2317. '125': "HDR",
  2318. '120': "4K",
  2319. '116': "1080P60帧",
  2320. '112': "1080P+",
  2321. '80': "1080P",
  2322. '64': "720P",
  2323. }
  2324. vod_codec_id = {
  2325. '7': 'avc',
  2326. '12': 'hevc',
  2327. '13': 'av1',
  2328. }
  2329. vod_audio_id = {
  2330. '30280': '192000',
  2331. '30232': '132000',
  2332. '30216': '64000',
  2333. }
  2334. def _testUrl(self, url):
  2335. status = head(url, headers=self.header).status_code
  2336. if status == 200:
  2337. return url
  2338. def get_fastesUrl(self, ja):
  2339. url = ja.get('baseUrl', ja.get('url', ''))
  2340. baseUrl = ja.get('backup_url', [])
  2341. baseUrl.insert(0, url)
  2342. task_pool = []
  2343. for l in baseUrl:
  2344. t = self.pool.submit(self._testUrl, l)
  2345. task_pool.append(t)
  2346. for t in as_completed(task_pool):
  2347. l = t.result()
  2348. if l:
  2349. url = l
  2350. break
  2351. return url
  2352. def get_dash_media(self, media):
  2353. qnid = str(media.get('id'))
  2354. codecid = media.get('codecid', '')
  2355. media_codecs = media.get('codecs')
  2356. media_bandwidth = media.get('bandwidth')
  2357. media_startWithSAP = media.get('startWithSap')
  2358. media_mimeType = media.get('mimeType')
  2359. media_BaseURL = self.get_fastesUrl(media).replace('&', '&amp;')
  2360. media_SegmentBase_indexRange = media['SegmentBase'].get('indexRange')
  2361. media_SegmentBase_Initialization = media['SegmentBase'].get('Initialization')
  2362. mediaType = media_mimeType.split('/')[0]
  2363. media_typeParams = ''
  2364. if mediaType == 'video':
  2365. media_frameRate = media.get('frameRate')
  2366. media_sar = media.get('sar')
  2367. media_width = media.get('width')
  2368. media_height = media.get('height')
  2369. media_typeParams = f"height='{media_height}' width='{media_width}' frameRate='{media_frameRate}' sar='{media_sar}'"
  2370. elif mediaType == 'audio':
  2371. audioSamplingRate = self.vod_audio_id.get(qnid, '192000')
  2372. media_typeParams = f"numChannels='2' sampleRate='{audioSamplingRate}'"
  2373. qnid += '_' + str(codecid)
  2374. result = f"""
  2375. <Representation id="{qnid}" bandwidth="{media_bandwidth}" codecs="{media_codecs}" mimeType="{media_mimeType}" {media_typeParams} startWithSAP="{media_startWithSAP}">
  2376. <BaseURL>{media_BaseURL}</BaseURL>
  2377. <SegmentBase indexRange="{media_SegmentBase_indexRange}">
  2378. <Initialization range="{media_SegmentBase_Initialization}"/>
  2379. </SegmentBase>
  2380. </Representation>"""
  2381. return result
  2382. def get_dash_media_list(self, media_lis, qn=''):
  2383. if not media_lis:
  2384. return ""
  2385. mediaType = media_lis[0]['mimeType'].split('/')[0]
  2386. if mediaType == 'video':
  2387. preferQn = str(qn)
  2388. preferCodec = str(self.userConfig['vodDefaultCodec'])
  2389. elif mediaType == 'audio':
  2390. preferQn = str(self.userConfig['vodDefaultAudio'])
  2391. preferCodec = '0'
  2392. else:
  2393. return
  2394. media_available = {}
  2395. for media in media_lis:
  2396. if mediaType == 'audio' and not media_available:
  2397. media_available = media
  2398. if str(media['id']) == preferQn:
  2399. if mediaType == 'audio':
  2400. media_available = media
  2401. break
  2402. if not media_available:
  2403. media_available = media
  2404. if mediaType == 'video' and str(media['id']) == preferCodec:
  2405. media_available = media
  2406. break
  2407. result = f"""
  2408. <AdaptationSet>
  2409. <ContentComponent contentType="{mediaType}"/>{self.get_dash_media(media_available)}
  2410. </AdaptationSet>"""
  2411. return result
  2412. def get_dash(self, ja, qn):
  2413. duration = ja.get('duration')
  2414. minBufferTime = ja.get('minBufferTime')
  2415. video_list = self.pool.submit(self.get_dash_media_list, ja.get('video'), qn)
  2416. audio_list = self.pool.submit(self.get_dash_media_list, ja.get('audio'))
  2417. 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">
  2418. <Period duration="PT{duration}S" start="PT0S">{video_list.result()}{audio_list.result()}
  2419. </Period>
  2420. </MPD>"""
  2421. return mpd
  2422. def miao(self, m):
  2423. m = str(m).partition('.')[2] #取小数部分
  2424. if len(m)==0:m = '000' #补齐三位小数
  2425. if len(m)==1:m = m + '00'
  2426. if len(m)==2:m = m + '0'
  2427. return m #返回标准三位的毫秒数
  2428. def down_sub(self, url):
  2429. data = self._get_sth(url, 'fake').json()['body']
  2430. srt = ''
  2431. i=1
  2432. for d in data:
  2433. f = round(d['from'],3) # 开始时间 (round(n,3)四舍五入为三位小数)
  2434. t = round(d['to'],3) # 结束时间
  2435. c = d['content'] # 字幕内容
  2436. ff = time.strftime("%H:%M:%S",time.gmtime(f)) + ',' + self.miao(f) # 开始时间,秒数转 时:分:秒 格式,加逗号、毫秒修正为三位
  2437. tt = time.strftime("%H:%M:%S",time.gmtime(t)) + ',' + self.miao(t) # 结束时间,处理方式同上
  2438. srt += str(i) + '\n' + ff + ' ' + '-->' + ' ' + tt + '\n' + c + '\n\n' # 格式化为Srt字幕
  2439. i += 1
  2440. return srt
  2441. localProxyUrl = 'http://127.0.0.1:UndCover/proxy?do=py&siteType=3&siteKey=py_bilibili&type='
  2442. def get_subs(self, aid, cid):
  2443. result = []
  2444. query = self.encrypt_wbi(aid=aid, cid=cid)[0]
  2445. url = f'https://api.bilibili.com/x/player/wbi/v2?{query}'
  2446. jRoot = self._get_sth(url, 'master').json()
  2447. if jRoot['code'] == 0:
  2448. for sub in jRoot['data']['subtitle'].get('subtitles', []):
  2449. lanDoc = str(sub.get('lan_doc', ''))
  2450. lanUrl = sub.get('subtitle_url')
  2451. if lanUrl.startswith('//'):
  2452. lanUrl = 'https:' + lanUrl
  2453. lanUrl = quote(lanUrl)
  2454. result.append(
  2455. {
  2456. "url": f"{self.localProxyUrl}subtitle&url={lanUrl}",
  2457. "name": lanDoc,
  2458. "format": "application/x-subrip"
  2459. }
  2460. )
  2461. if result:
  2462. result.insert(0,
  2463. {
  2464. "url": "",
  2465. "name": " ",
  2466. "format": "application/x-subrip"
  2467. }
  2468. )
  2469. return result
  2470. def playerContent(self, flag, id, vipFlags):
  2471. self.stop_heartbeat()
  2472. result = {'playUrl': '', 'url': ''}
  2473. ids = id.split("_")
  2474. if 'live' == ids[0]:
  2475. return self.live_playerContent(flag, id, vipFlags)
  2476. if len(ids) < 2:
  2477. return result
  2478. aid = ids[0]
  2479. cid = ids[1]
  2480. if 'setting' in ids:
  2481. if 'liveFilter' in ids:
  2482. id = ids[2]
  2483. self.add_cateManualLiveExtra(aid, cid, id)
  2484. elif cid in ['cateManual', 'cateManualLive', 'tuijianLis', 'rankingLis']:
  2485. action = ids[2]
  2486. self.set_normal_cateManual(aid, cid, action)
  2487. elif 'login' in ids:
  2488. self.set_cookie(aid, cid)
  2489. elif 'logout' in ids:
  2490. self.unset_cookie(aid)
  2491. else:
  2492. self.set_normal_default(aid, cid)
  2493. return result
  2494. elif 'notplay' in ids:
  2495. self.pool.submit(self.do_notplay, ids)
  2496. return result
  2497. aid, cid, epid, dur, parse = id.split("_")
  2498. ssid = ''
  2499. if not cid or not dur:
  2500. cid, dur, epid = self.get_cid(aid, cid)
  2501. result["danmaku"] = 'https://api.bilibili.com/x/v1/dm/list.so?oid=' + str(cid)
  2502. vodDefaultQn = self.userConfig['vodDefaultQn']
  2503. query = self.encrypt_wbi(avid=aid, cid=cid, qn=vodDefaultQn, fnval=4048, fnver=0, fourk=1)[0]
  2504. url = f'https://api.bilibili.com/x/player/wbi/playurl?{query}'
  2505. if epid:
  2506. if parse:
  2507. url = 'https://www.bilibili.com/bangumi/play/ep' + str(epid)
  2508. result["url"] = url
  2509. result["flag"] = 'bilibili'
  2510. result["parse"] = '1'
  2511. result['jx'] = '1'
  2512. result["header"] = str({"User-Agent": self.header["User-Agent"]})
  2513. return result
  2514. url = 'https://api.bilibili.com/pgc/player/web/v2/playurl?aid={}&cid={}&qn={}&fnval=4048&fnver=0&fourk=1'.format(aid, cid, vodDefaultQn)
  2515. jRoot = self._get_sth(url, 'vip').json()
  2516. if jRoot['code'] == 0:
  2517. if 'data' in jRoot:
  2518. jo = jRoot['data']
  2519. elif 'result' in jRoot:
  2520. jo = jRoot['result']
  2521. if 'video_info' in jo:
  2522. jr = jo['view_info']['report']
  2523. ssid = jr['season_id']
  2524. epid = jr['ep_id']
  2525. jo = jo['video_info']
  2526. else:
  2527. return result
  2528. else:
  2529. return result
  2530. get_subs = self.pool.submit(self.get_subs, aid, cid)
  2531. formats = dict(map(lambda x:(x['quality'], x['new_description']), jo['support_formats']))
  2532. playUrl = []
  2533. ja = jo.get('dash')
  2534. if ja:
  2535. self.playerContent_mpd = ja
  2536. result["format"] = 'application/dash+xml'
  2537. for video in ja['video']:
  2538. id = video['id']
  2539. desc = formats[id]
  2540. if not desc in playUrl:
  2541. url = f'{self.localProxyUrl}dash&aid={aid}&cid={cid}&epid={epid}&qn={id}'
  2542. if id == int(vodDefaultQn):
  2543. playUrl = [desc, url] + playUrl
  2544. else:
  2545. playUrl.extend([desc, url])
  2546. else:
  2547. if 'durls' in jo:
  2548. for durl in jo['durls']:
  2549. desc = formats[durl['quality']]
  2550. if durl['quality'] == int(vodDefaultQn):
  2551. url = self.get_fastesUrl(durl['durl'][0])
  2552. playUrl = [desc, url] + playUrl
  2553. else:
  2554. url = durl['durl'][0]['url']
  2555. playUrl.extend([desc, url])
  2556. else:
  2557. playUrl = self.get_fastesUrl(jo['durl'][0])
  2558. result["url"] = playUrl
  2559. result["parse"] = '0'
  2560. result["contentType"] = ''
  2561. result["header"] = self.header
  2562. result["subs"] = get_subs.result()
  2563. #回传播放记录
  2564. heartbeat = self.pool.submit(self.start_heartbeat, aid, cid, ssid, epid, dur)
  2565. self.task_pool.append(heartbeat)
  2566. return result
  2567. def live_playerContent(self, flag, id, vipFlags):
  2568. api, room_id, qn, format, codec = id.split("_")
  2569. # 回传观看直播记录
  2570. if self.userid and int(self.userConfig['heartbeatInterval']) > 0:
  2571. self.pool.submit(self.post_live_history, room_id)
  2572. 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)
  2573. jo = self._get_sth(url, 'vip').json()
  2574. result = {'playUrl': '', 'url': ''}
  2575. if jo['code'] == 0:
  2576. try:
  2577. playurl = jo['data']['playurl_info'].get('playurl')
  2578. codec = playurl['stream'][0]['format'][0]['codec'][0]
  2579. except:
  2580. return result
  2581. base_url = str(codec['base_url'])
  2582. host = str(codec['url_info'][0]['host'])
  2583. extra = str(codec['url_info'][0]['extra'])
  2584. playurl = host + base_url + extra
  2585. result["url"] = playurl
  2586. if ".flv" in playurl:
  2587. result["contentType"] = 'video/x-flv'
  2588. else:
  2589. result["contentType"] = ''
  2590. else:
  2591. return result
  2592. result["parse"] = '0'
  2593. result["header"] = {
  2594. "Referer": "https://live.bilibili.com",
  2595. "User-Agent": self.header["User-Agent"]
  2596. }
  2597. return result
  2598. def localProxy(self, param):
  2599. action = {
  2600. 'url': '',
  2601. 'header': '',
  2602. 'param': '',
  2603. 'type': 'string',
  2604. 'after': ''
  2605. }
  2606. if param['type'] == 'subtitle':
  2607. content = self.down_sub(param['url'])
  2608. return [200, "application/octet-stream", action, content]
  2609. if param['type'] == 'dash':
  2610. mpd = self.get_dash(self.playerContent_mpd, param['qn'])
  2611. return [200, "application/octet-stream", action, mpd]
  2612. return [200, "video/MP2T", action, ""]
  2613. config = {
  2614. "player": {},
  2615. "filter": {
  2616. "关注": [{"key": "sort", "name": "分类",
  2617. "value": [{"n": "正在直播", "v": "正在直播"}, {"n": "最常访问", "v": "最常访问"},
  2618. {"n": "最近关注", "v": "最近关注"}, {"n": "特别关注", "v": "特别关注"},
  2619. {"n": "悄悄关注", "v": "悄悄关注"}, {"n": "我的粉丝", "v": "我的粉丝"}]}],
  2620. "动态": [{"key": "order", "name": "投稿排序",
  2621. "value": [{"n": "最新发布", "v": "pubdate"}, {"n": "最多播放", "v": "click"},
  2622. {"n": "最多收藏", "v": "stow"}, {"n": "最早发布", "v": "oldest"}, {"n": "合集和列表", "v": "series"}]}, ],
  2623. "影视": [{"key": "tid", "name": "分类",
  2624. "value": [{"n": "番剧", "v": "1"}, {"n": "国创", "v": "4"}, {"n": "电影", "v": "2"},
  2625. {"n": "电视剧", "v": "5"}, {"n": "纪录片", "v": "3"}, {"n": "综艺", "v": "7"}]},
  2626. {"key": "order", "name": "排序",
  2627. "value": [{"n": "热门", "v": "热门"}, {"n": "播放数量", "v": "2"}, {"n": "更新时间", "v": "0"},
  2628. {"n": "最高评分", "v": "4"}, {"n": "弹幕数量", "v": "1"}, {"n": "追看人数", "v": "3"},
  2629. {"n": "开播时间", "v": "5"}, {"n": "上映时间", "v": "6"}]},
  2630. {"key": "season_status", "name": "付费",
  2631. "value": [{"n": "全部", "v": "-1"}, {"n": "免费", "v": "1"},
  2632. {"n": "付费", "v": "2%2C6"}, {"n": "大会员", "v": "4%2C6"}]}],
  2633. "频道": [{"key": "order", "name": "排序",
  2634. "value": [{"n": "近期热门", "v": "hot"}, {"n": "月播放量", "v": "view"},
  2635. {"n": "最新投稿", "v": "new"}, {"n": "频道精选", "v": "featured"}, ]}, ],
  2636. "收藏": [{"key": "order", "name": "排序",
  2637. "value": [{"n": "收藏时间", "v": "mtime"}, {"n": "播放量", "v": "view"},
  2638. {"n": "投稿时间", "v": "pubtime"}]}, ],
  2639. "历史": [{"key": "type", "name": "分类",
  2640. "value": [{"n": "全部", "v": "all"}, {"n": "视频", "v": "archive"}, {"n": "直播", "v": "live"}, {"n": "UP主", "v": "UP主"}, {"n": "稍后再看", "v": "稍后再看"}]}, ],
  2641. "搜索": [{"key": "type", "name": "类型",
  2642. "value": [{"n": "视频", "v": "video"}, {"n": "番剧", "v": "media_bangumi"}, {"n": "影视", "v": "media_ft"},
  2643. {"n": "直播", "v": "live"}, {"n": "用户", "v": "bili_user"}]},
  2644. {"key": "order", "name": "视频排序",
  2645. "value": [{"n": "综合排序", "v": "totalrank"}, {"n": "最多点击", "v": "click"}, {"n": "最新发布", "v": "pubdate"},
  2646. {"n": "最多收藏", "v": "stow"}, {"n": "最多弹幕", "v": "dm"}]},
  2647. {"key": "duration", "name": "视频时长",
  2648. "value": [{"n": "全部", "v": "0"}, {"n": "60分钟以上", "v": "4"}, {"n": "30~60分钟", "v": "3"},
  2649. {"n": "5~30分钟", "v": "2"}, {"n": "5分钟以下", "v": "1"}]}],
  2650. }
  2651. }
  2652. header = {
  2653. 'Origin': 'https://www.bilibili.com',
  2654. 'Referer': 'https://www.bilibili.com',
  2655. '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'
  2656. }