py_bilibili_tvbox_20240409.py 118 KB

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