py_bilibili_tvbox0222.py 117 KB

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