py_bilibili02222.py 117 KB

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