Skip to content

Commit

Permalink
perf(balh): 新 API 获取 access_token (#1295)
Browse files Browse the repository at this point in the history
* perf(balh): 新 API 获取 access_token

* perf(balh): access_token 失效时删除

* wip: 整理代码

* chore: biliplus_login -> bilibili_login

---------

Co-authored-by: ipcjs <[email protected]>
  • Loading branch information
Howard20181 and ipcjs authored Jan 3, 2024
1 parent 76f61df commit 7bf1303
Show file tree
Hide file tree
Showing 10 changed files with 181 additions and 166 deletions.
3 changes: 3 additions & 0 deletions packages/unblock-area-limit/src/api/biliplus.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { bilibili_login } from "../feature/bili/bilibili_login";
import { balh_config } from "../feature/config";
import { Async } from "../util/async";
import { Converters, uposMap } from "../util/converters";
Expand Down Expand Up @@ -407,6 +408,8 @@ export async function fixThailandPlayUrlJson(originJson: object) {
}

let origin: OriginResult = JSON.parse(JSON.stringify(originJson))
if (origin.code === 401)
bilibili_login.clearLoginFlag()
interface LooseObject {
[key: string]: any
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { ifNotNull } from "../../util/utils"
import { balh_config, isClosed } from "../config"
import { util_page } from "../page"
import pageTemplate from './bangumi-play-page-template.html'
import { bilibili_login } from "./bilibili_login"

export function modifyGlobalValue<T = any>(
name: string,
Expand Down Expand Up @@ -117,7 +118,8 @@ async function fixThailandSeason(ep_id: string, season_id: string) {
// https://github.com/yujincheng08/BiliRoaming/issues/112
const thailandApi = new BiliBiliApi(balh_config.server_custom_th)
const origin = await thailandApi.getSeasonInfoByEpSsIdOnThailand(ep_id, season_id)

if (origin.code === 401)
bilibili_login.clearLoginFlag()
origin.result.actors = origin.result.actor.info
origin.result.is_paster_ads = 0
origin.result.jp_title = origin.result.origin_name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Strings } from '../../util/strings'
import { util_init } from '../../util/initiator'
import { util_ui_msg } from '../../util/message'
import { RegExps } from '../../util/regexps'
import { biliplus_login } from './biliplus_login';
import { bilibili_login } from './bilibili_login';
import { injectFetch, injectFetch4Mobile } from '../../feature/bili/area_limit_fetch'
import space_account_info_map from '../../feature/bili/space_account_info_map'
import * as OpenCC from 'opencc-js'
Expand Down Expand Up @@ -812,11 +812,11 @@ export const area_limit_xhr = (() => {
} else {
return Promise.reject(new AjaxException(`服务器错误: ${JSON.stringify(data)}`, data ? data.code : 0))
}
} else if (isAreaLimitForPlayUrl(data)) {
} else if (isAreaLimitForPlayUrl(data) || data.code === 401) {
util_error('>>area limit');
ui.pop({
content: `突破黑洞失败\n需要登录\n点此确定进行登录`,
onConfirm: biliplus_login.showLogin
content: `突破黑洞失败\n${data.message}\n需要登录\n点此确定进行登录`,
onConfirm: bilibili_login.showLogin
})
} else {
if (balh_config.flv_prefer_ws) {
Expand Down
152 changes: 152 additions & 0 deletions packages/unblock-area-limit/src/feature/bili/bilibili_login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { Async } from "../../util/async"
import { Converters } from "../../util/converters"
import { cookieStorage } from "../../util/cookie"
import { util_init } from "../../util/initiator"
import { _ } from "../../util/react"
import { ui } from "../../util/ui"
import { balh_config } from "../config"
import { util_page } from "../page"
import { FALSE, TRUE, r } from "../r"


function isLogin() {
return localStorage.access_key && localStorage.oauth_expires_at && Date.now() < +localStorage.oauth_expires_at
}

function clearLoginFlag() {
// 只要清除过期时间, isLogin()就会返回false
delete localStorage.oauth_expires_at
}

function showLogout() {
ui.alert('确定取消授权登出?', () => {
// 登出, 则应该清除所有授权相关的字段
delete localStorage.oauth_expires_at
delete localStorage.access_key
delete localStorage.refresh_token
})
}

function isLoginBiliBili() {
return cookieStorage['DedeUserID'] !== undefined
}
// 当前在如下情况才会弹一次登录提示框:
// 1. 第一次使用
// 2. 主站+服务器都退出登录后, 再重新登录主站
function checkLoginState() {
// 给一些状态,设置初始值
localStorage.balh_must_remind_login_v3 === undefined && (localStorage.balh_must_remind_login_v3 = TRUE)

if (isLoginBiliBili()) {
if (!localStorage.balh_old_isLoginBiliBili // 主站 不登录 => 登录
|| localStorage.balh_pre_server !== balh_config.server // 代理服务器改变了
|| localStorage.balh_must_remind_login_v3) { // 设置了"必须提醒"flag
if (!isLogin()) {
// 保证一定要交互一次, 才不提醒
localStorage.balh_must_remind_login_v3 = TRUE;
ui.pop({
content: [
_('text', `${GM_info.script.name}\n要不要考虑进行一下授权?\n\n授权后可以观看区域限定番剧的1080P\n(如果你是大会员或承包过这部番的话)\n\n你可以随时在设置中打开授权页面`)
],
onConfirm: () => {
localStorage.balh_must_remind_login_v3 = FALSE;
showLogin();
document.querySelector('#AHP_Notice')?.remove()
},
closeBtn: '不再提醒',
onClose: () => {
localStorage.balh_must_remind_login_v3 = FALSE;
}
})
}
}
}
localStorage.balh_old_isLoginBiliBili = isLoginBiliBili() ? TRUE : FALSE
localStorage.balh_pre_server = balh_config.server
}

async function showLogin() {
const balh_auth_window = window.open('about:blank')!;
balh_auth_window.document.title = 'BALH - 授权';
balh_auth_window.document.body.innerHTML = '<meta charset="UTF-8" name="viewport" content="width=device-width">正在获取授权,请稍候……';
window.balh_auth_window = balh_auth_window;

try {
const { sign, params } = Converters.generateSign({
appkey: '27eb53fc9058f8c3',
local_id: "0",
ts: (Date.now() / 1000).toFixed(0)
}, 'c2ed53a74eeefe3cf99fbd01d8c9c375')
const data1 = await (await fetch('https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code?' + params + '&sign=' + sign, {
method: 'POST'
})).json()

if (data1.code === 0 && data1.data.auth_code) {
let authCode = data1.data.auth_code
balh_auth_window.document.body.innerHTML += '<br/>正在确认…… auth_code=' + authCode;
const bili_jct = cookieStorage.get('bili_jct')
const { params } = Converters.generateSign({
auth_code: authCode,
build: "7082000",
csrf: bili_jct
}, 'c2ed53a74eeefe3cf99fbd01d8c9c375')
const data2 = await (await fetch(('https://passport.bilibili.com/x/passport-tv-login/h5/qrcode/confirm?' + params), {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})).json()

if (data2.code === 0 && data2.message === "0") {
balh_auth_window.document.body.innerHTML += '<br/>授权成功,正在获取token……';
const { sign, params } = Converters.generateSign({
appkey: '27eb53fc9058f8c3',
local_id: "0",
auth_code: authCode,
ts: (Date.now() / 1000).toFixed(0)
}, 'c2ed53a74eeefe3cf99fbd01d8c9c375')
const data3 = await (await fetch('https://passport.bilibili.com/x/passport-tv-login/qrcode/poll?' + params + '&sign=' + sign, {
method: "POST",
})).json()

const access_token = data3.data.token_info.access_token
const oauth_expires_at = (Date.now() / 1000 + data3.data.token_info.expires_in) * 1000
balh_auth_window.document.body.innerHTML += '<br/>正在保存…… access_token=' + access_token + ', 过期于 ' + new Date(oauth_expires_at).toLocaleString();
if (data3.code === 0 && data3.message === "0") {
localStorage.access_key = access_token
localStorage.refresh_token = data3.data.token_info.refresh_token
localStorage.oauth_expires_at = oauth_expires_at
balh_auth_window.document.body.innerHTML += '<br/>保存成功!3秒后关闭';
await Async.timeout(3000)
}
} else {
ui.alert(data2.message, () => {
location.href = 'https://passport.bilibili.com/login'
})
}
} else {
ui.alert('必须登录B站才能正常授权', () => {
location.href = 'https://passport.bilibili.com/login'
})
}
} catch (e: any) {
ui.alert(e.message ?? '授权出错')
} finally {
balh_auth_window.close()
}
}

util_init(() => {
if (!(util_page.player() || util_page.av())) {
checkLoginState()
}
}, util_init.PRIORITY.DEFAULT, util_init.RUN_AT.DOM_LOADED_AFTER)

export const bilibili_login = {
showLogin,
showLogout,
isLogin,
isLoginBiliBili,
clearLoginFlag,
}
144 changes: 0 additions & 144 deletions packages/unblock-area-limit/src/feature/bili/biliplus_login.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/unblock-area-limit/src/feature/bili/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export * from './biliplus_check_area_limit'
export * from './fill_season_page'
export * from './redirect_to_bangumi_or_insert_player'
export * from './area_limit_for_vue'
export * from './biliplus_login'
export * from './bilibili_login'
export * from './settings'
export * from './remove_pre_ad'
export * from './hide_adblock_tips'
Expand Down
8 changes: 4 additions & 4 deletions packages/unblock-area-limit/src/feature/bili/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { balh_config } from "../config"
import { util_page } from "../page"
import { r } from "../r"
import { util_ui_msg } from '../../util/message'
import { biliplus_login } from "./biliplus_login"
import { bilibili_login } from "./bilibili_login"
import css from './settings.scss'

const balh_feature_runPing = function () {
Expand Down Expand Up @@ -171,10 +171,10 @@ export function settings() {
switch ((event.target as any).attributes['data-sign'].value) {
default:
case 'in':
biliplus_login.showLogin();
bilibili_login.showLogin();
break;
case 'out':
biliplus_login.showLogout();
bilibili_login.showLogout();
break;
}
}
Expand Down Expand Up @@ -390,7 +390,7 @@ export function settings() {
]), _('br'),
_('a', { href: 'javascript:', 'data-sign': 'in', event: { click: onSignClick } }, [_('text', '帐号授权')]),
_('text', ' '),
_('a', { href: 'javascript:', 'data-sign': 'out', event: { click: onSignClick } }, [_('text', '取消授权')]),
bilibili_login.isLogin() ? _('a', { href: 'javascript:', 'data-sign': 'out', event: { click: onSignClick } }, [_('text', '取消授权')]) : _('span'),
_('text', '  '),
_('a', { href: 'javascript:', event: { click: function () { util_ui_msg.show(window.$(this), '如果你的帐号进行了付费,不论是大会员还是承包,\n进行授权之后将可以在解除限制时正常享有这些权益\n\n你可以随时在这里授权或取消授权\n\n不进行授权不会影响脚本的正常使用,但可能会缺失1080P', 1e4); } } }, [_('text', '(这是什么?)')]),
_('br'), _('br'),
Expand Down
Loading

0 comments on commit 7bf1303

Please sign in to comment.