feat: 保留 DramaBox 登录,只有手动退出才清除
This commit is contained in:
@@ -85,6 +85,11 @@ def login_account(body: AccountBody):
|
|||||||
return call(lambda: db_login.apply_account(body.language, body.user))
|
return call(lambda: db_login.apply_account(body.language, body.user))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/resume")
|
||||||
|
def resume():
|
||||||
|
return call(db_login.resume)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/me")
|
@router.post("/me")
|
||||||
def me(body: TokenBody):
|
def me(body: TokenBody):
|
||||||
return call(lambda: db_login.current(body.token))
|
return call(lambda: db_login.current(body.token))
|
||||||
|
|||||||
@@ -64,6 +64,11 @@ def login_device():
|
|||||||
return call(hd_login.enter)
|
return call(hd_login.enter)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/resume")
|
||||||
|
def resume():
|
||||||
|
return call(hd_login.resume)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/me")
|
@router.post("/me")
|
||||||
def me(body: TokenBody):
|
def me(body: TokenBody):
|
||||||
return call(lambda: hd_login.current(body.token))
|
return call(lambda: hd_login.current(body.token))
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
|
import secrets
|
||||||
|
|
||||||
from server.services.dramabox.client import client
|
from server.services.dramabox.client import client
|
||||||
from server.services.dramabox.locales import DEFAULT_LANGUAGE, public_list
|
from server.services.dramabox.locales import DEFAULT_LANGUAGE, public_list, resolve
|
||||||
|
|
||||||
|
|
||||||
def languages() -> list[dict]:
|
def languages() -> list[dict]:
|
||||||
@@ -16,7 +18,13 @@ def apply_account(language: str, user: dict) -> dict:
|
|||||||
web_token = str(user.get("token") or "").strip()
|
web_token = str(user.get("token") or "").strip()
|
||||||
if not web_token or not _logged_in(user.get("isLogin")):
|
if not web_token or not _logged_in(user.get("isLogin")):
|
||||||
raise RuntimeError("还没有登录成功")
|
raise RuntimeError("还没有登录成功")
|
||||||
locale = client.enter(language or client.language or DEFAULT_LANGUAGE)["profile"]
|
try:
|
||||||
|
locale = resolve(language or client.language or DEFAULT_LANGUAGE)
|
||||||
|
except RuntimeError:
|
||||||
|
locale = resolve(DEFAULT_LANGUAGE)
|
||||||
|
if not client.token:
|
||||||
|
client.token = secrets.token_hex(16)
|
||||||
|
client.language = locale["id"]
|
||||||
client.web_token = web_token
|
client.web_token = web_token
|
||||||
profile = _account_profile(locale, user)
|
profile = _account_profile(locale, user)
|
||||||
client.profile = profile
|
client.profile = profile
|
||||||
@@ -69,6 +77,12 @@ def _number(value) -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def resume() -> dict:
|
||||||
|
if not client.token or not client.profile:
|
||||||
|
raise RuntimeError("还没有登录")
|
||||||
|
return {"token": client.token, "profile": client.profile}
|
||||||
|
|
||||||
|
|
||||||
def current(token: str) -> dict:
|
def current(token: str) -> dict:
|
||||||
token = (token or "").strip()
|
token = (token or "").strip()
|
||||||
if not token:
|
if not token:
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ def enter() -> dict:
|
|||||||
return {"token": client.token, "profile": profile}
|
return {"token": client.token, "profile": profile}
|
||||||
|
|
||||||
|
|
||||||
|
def resume() -> dict:
|
||||||
|
if not client.token or not client.profile:
|
||||||
|
raise RuntimeError("还没有登录")
|
||||||
|
return {"token": client.token, "profile": client.profile}
|
||||||
|
|
||||||
|
|
||||||
def current(token: str) -> dict:
|
def current(token: str) -> dict:
|
||||||
token = (token or "").strip()
|
token = (token or "").strip()
|
||||||
if not token:
|
if not token:
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
fn main() {
|
fn main() {
|
||||||
tauri_build::try_build(
|
tauri_build::try_build(
|
||||||
tauri_build::Attributes::new().app_manifest(
|
tauri_build::Attributes::new().app_manifest(
|
||||||
tauri_build::AppManifest::new().commands(&["dramabox_login"]),
|
tauri_build::AppManifest::new().commands(&["dramabox_login", "dramabox_clear_login"]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.expect("failed to run tauri-build");
|
.expect("failed to run tauri-build");
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"core:default",
|
"core:default",
|
||||||
"core:window:allow-destroy",
|
"core:window:allow-destroy",
|
||||||
"opener:default",
|
"opener:default",
|
||||||
"allow-dramabox-login"
|
"allow-dramabox-login",
|
||||||
|
"allow-dramabox-clear-login"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,5 +11,5 @@
|
|||||||
"http://localhost:*/*"
|
"http://localhost:*/*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"permissions": ["allow-dramabox-login"]
|
"permissions": ["allow-dramabox-login", "allow-dramabox-clear-login"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-dramabox-clear-login"
|
||||||
|
description = "Enables the dramabox_clear_login command without any pre-configured scope."
|
||||||
|
commands.allow = ["dramabox_clear_login"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-dramabox-clear-login"
|
||||||
|
description = "Denies the dramabox_clear_login command without any pre-configured scope."
|
||||||
|
commands.deny = ["dramabox_clear_login"]
|
||||||
+204
-28
@@ -230,18 +230,6 @@ const DRAMABOX_LOGIN_SCRIPT: &str = r#"
|
|||||||
lastMark = "";
|
lastMark = "";
|
||||||
stableSince = 0;
|
stableSince = 0;
|
||||||
}
|
}
|
||||||
function readAccount() {
|
|
||||||
try {
|
|
||||||
var raw = localStorage.getItem("dz_seo_user_info");
|
|
||||||
if (!raw) return;
|
|
||||||
var user = JSON.parse(raw);
|
|
||||||
var flag = user && user.isLogin;
|
|
||||||
var loggedIn = user && user.token && (flag === true || flag === 1 || flag === "1" || String(flag).toLowerCase() === "true");
|
|
||||||
if (!loggedIn) return;
|
|
||||||
if (location.hash.indexOf("raptd=") !== -1) return;
|
|
||||||
location.hash = "raptd=" + encodeURIComponent(raw);
|
|
||||||
} catch (err) {}
|
|
||||||
}
|
|
||||||
function onUserCenter() {
|
function onUserCenter() {
|
||||||
var path = location.pathname.replace(/\/+$/, "") || "/";
|
var path = location.pathname.replace(/\/+$/, "") || "/";
|
||||||
return path === "/uc" || /\/uc$/.test(path);
|
return path === "/uc" || /\/uc$/.test(path);
|
||||||
@@ -296,7 +284,28 @@ const DRAMABOX_LOGIN_SCRIPT: &str = r#"
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
function ensureConfirmBar() {
|
||||||
|
if (document.getElementById("rapt-logged-in")) return;
|
||||||
|
var bar = document.createElement("div");
|
||||||
|
bar.id = "rapt-logged-in";
|
||||||
|
bar.style.cssText = "position:fixed;left:0;right:0;bottom:0;z-index:2147483647;display:flex;justify-content:flex-end;gap:12px;padding:10px 16px;background:#2b2b2b;border-top:1px solid rgba(255,255,255,.08);";
|
||||||
|
var button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.textContent = "已登录";
|
||||||
|
button.style.cssText = "height:34px;min-width:120px;padding:0 16px;border:0;border-radius:6px;background:#3c3c3c;color:#f2f2f2;cursor:pointer;";
|
||||||
|
button.addEventListener("click", function () {
|
||||||
|
try { sessionStorage.setItem("rapt_confirm_login", "1"); } catch (err) {}
|
||||||
|
location.reload();
|
||||||
|
});
|
||||||
|
bar.appendChild(button);
|
||||||
|
(document.body || document.documentElement).appendChild(bar);
|
||||||
|
}
|
||||||
function openChoices() {
|
function openChoices() {
|
||||||
|
ensureConfirmBar();
|
||||||
|
if (!document.querySelector('[class*="toLogin"]') && idNode()) {
|
||||||
|
opened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (choicesOpen()) {
|
if (choicesOpen()) {
|
||||||
opened = true;
|
opened = true;
|
||||||
return;
|
return;
|
||||||
@@ -331,15 +340,93 @@ const DRAMABOX_LOGIN_SCRIPT: &str = r#"
|
|||||||
stableSince = 0;
|
stableSince = 0;
|
||||||
clickNode(target);
|
clickNode(target);
|
||||||
}
|
}
|
||||||
readAccount();
|
|
||||||
openChoices();
|
openChoices();
|
||||||
setInterval(function () {
|
setInterval(openChoices, 400);
|
||||||
readAccount();
|
|
||||||
openChoices();
|
|
||||||
}, 400);
|
|
||||||
})();
|
})();
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
const DRAMABOX_ACCOUNT_SCRIPT: &str = r#"(function () {
|
||||||
|
function displayedName() {
|
||||||
|
if (document.querySelector('[class*="toLogin"]')) return "";
|
||||||
|
var idNode = document.querySelector('[class*="userId"]');
|
||||||
|
var name = idNode && idNode.previousElementSibling;
|
||||||
|
return name ? String(name.textContent || "").trim() : "";
|
||||||
|
}
|
||||||
|
function match(user, displayed, confirmed) {
|
||||||
|
if (!user || typeof user !== "object" || !user.token) return null;
|
||||||
|
var flag = user.isLogin;
|
||||||
|
var kind = String(user.loginType || "").toLowerCase();
|
||||||
|
var loggedIn = flag === true || flag === 1 || flag === "1" || String(flag).toLowerCase() === "true";
|
||||||
|
var oauth = kind === "google" || kind === "facebook" || kind === "apple";
|
||||||
|
var storedName = String(user.nickname || user.name || user.userName || "").trim();
|
||||||
|
var samePerson = Boolean(displayed) && storedName === displayed;
|
||||||
|
var confirmedLogin = confirmed && Boolean(displayed);
|
||||||
|
if (!loggedIn && !oauth && !samePerson && !confirmedLogin) return null;
|
||||||
|
user.isLogin = true;
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
function parse(raw, displayed, confirmed) {
|
||||||
|
if (!raw) return null;
|
||||||
|
try {
|
||||||
|
var value = JSON.parse(raw);
|
||||||
|
return match(value, displayed, confirmed) || match(value.userInfo, displayed, confirmed) || match(value.user, displayed, confirmed) || match(value.data, displayed, confirmed);
|
||||||
|
} catch (err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function scan(store, displayed, confirmed) {
|
||||||
|
var direct = parse(store.getItem("dz_seo_user_info"), displayed, confirmed);
|
||||||
|
if (direct) return direct;
|
||||||
|
for (var i = 0; i < store.length; i++) {
|
||||||
|
var key = store.key(i) || "";
|
||||||
|
if (key.indexOf("user_info") === -1 && key.indexOf("userInfo") === -1) continue;
|
||||||
|
var found = parse(store.getItem(key), displayed, confirmed);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
var displayed = displayedName();
|
||||||
|
var confirmed = false;
|
||||||
|
try { confirmed = sessionStorage.getItem("rapt_confirm_login") === "1"; } catch (err) {}
|
||||||
|
var found = null;
|
||||||
|
try {
|
||||||
|
found = scan(localStorage, displayed, confirmed) || scan(sessionStorage, displayed, confirmed);
|
||||||
|
} catch (err) {}
|
||||||
|
if (!found) {
|
||||||
|
var parts = String(document.cookie || "").split(";");
|
||||||
|
for (var i = 0; i < parts.length; i++) {
|
||||||
|
var part = parts[i].replace(/^\s+/, "");
|
||||||
|
var key = "dz_seo_user_info=";
|
||||||
|
if (part.indexOf(key) !== 0) continue;
|
||||||
|
var value = part.slice(key.length);
|
||||||
|
try { value = decodeURIComponent(value); } catch (err) {}
|
||||||
|
found = parse(value, displayed, confirmed);
|
||||||
|
if (found) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (found && confirmed) {
|
||||||
|
try { sessionStorage.removeItem("rapt_confirm_login"); } catch (err) {}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
})()"#;
|
||||||
|
|
||||||
|
fn dramabox_webview_dir() -> PathBuf {
|
||||||
|
app_root().join("cache").join("dramabox").join("webview")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discard_dramabox_browser() {
|
||||||
|
let dir = dramabox_webview_dir();
|
||||||
|
for _ in 0..10 {
|
||||||
|
if !dir.exists() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if std::fs::remove_dir_all(&dir).is_ok() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn dramabox_login_url(language: &str) -> Result<String, String> {
|
fn dramabox_login_url(language: &str) -> Result<String, String> {
|
||||||
let lang = language.trim();
|
let lang = language.trim();
|
||||||
let allowed = [
|
let allowed = [
|
||||||
@@ -396,10 +483,16 @@ fn logged_in_account(value: &serde_json::Value) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn account_from_url(url: &Url) -> Option<serde_json::Value> {
|
fn account_from_script(result: &str) -> Option<serde_json::Value> {
|
||||||
let fragment = url.fragment()?;
|
let text = result.trim();
|
||||||
let encoded = fragment.split_once("raptd=")?.1;
|
if text.is_empty() || text == "null" {
|
||||||
let value: serde_json::Value = serde_json::from_str(encoded).ok()?;
|
return None;
|
||||||
|
}
|
||||||
|
let value: serde_json::Value = serde_json::from_str(text).ok()?;
|
||||||
|
let value = match value.as_str() {
|
||||||
|
Some(inner) => serde_json::from_str(inner).unwrap_or(value),
|
||||||
|
None => value,
|
||||||
|
};
|
||||||
if logged_in_account(&value) {
|
if logged_in_account(&value) {
|
||||||
Some(value)
|
Some(value)
|
||||||
} else {
|
} else {
|
||||||
@@ -407,10 +500,53 @@ fn account_from_url(url: &Url) -> Option<serde_json::Value> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_login_window(app: &AppHandle, url: Url) -> Result<(), String> {
|
fn read_login_account(window: &tauri::WebviewWindow) -> Option<serde_json::Value> {
|
||||||
if let Some(existing) = app.get_webview_window(DRAMABOX_LOGIN_LABEL) {
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
let _ = existing.close();
|
let started = window.with_webview(move |webview| {
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe {
|
||||||
|
use webview2_com::ExecuteScriptCompletedHandler;
|
||||||
|
use windows_core::HSTRING;
|
||||||
|
let Ok(core) = webview.controller().CoreWebView2() else {
|
||||||
|
let _ = tx.send(String::new());
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let script = HSTRING::from(DRAMABOX_ACCOUNT_SCRIPT);
|
||||||
|
let callback = tx.clone();
|
||||||
|
let handler = ExecuteScriptCompletedHandler::create(Box::new(move |_, result| {
|
||||||
|
let _ = callback.send(result);
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
if core.ExecuteScript(&script, &handler).is_err() {
|
||||||
|
let _ = tx.send(String::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
let _ = webview;
|
||||||
|
let _ = tx.send(String::new());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if started.is_err() {
|
||||||
|
return None;
|
||||||
}
|
}
|
||||||
|
let result = rx.recv_timeout(Duration::from_secs(3)).unwrap_or_default();
|
||||||
|
account_from_script(&result)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_login_windows(app: &AppHandle) {
|
||||||
|
if let Some(current) = app.get_webview_window(DRAMABOX_LOGIN_LABEL) {
|
||||||
|
let _ = current.close();
|
||||||
|
}
|
||||||
|
for (label, window) in app.webview_windows() {
|
||||||
|
if label.starts_with("dramabox-popup-") {
|
||||||
|
let _ = window.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_login_window(app: &AppHandle, url: Url) -> Result<(), String> {
|
||||||
|
close_login_windows(app);
|
||||||
let popup_app = app.clone();
|
let popup_app = app.clone();
|
||||||
let window = WebviewWindowBuilder::new(app, DRAMABOX_LOGIN_LABEL, WebviewUrl::External(url))
|
let window = WebviewWindowBuilder::new(app, DRAMABOX_LOGIN_LABEL, WebviewUrl::External(url))
|
||||||
.title("DramaBox 登录")
|
.title("DramaBox 登录")
|
||||||
@@ -418,6 +554,7 @@ fn open_login_window(app: &AppHandle, url: Url) -> Result<(), String> {
|
|||||||
.center()
|
.center()
|
||||||
.background_color(tauri::window::Color(54, 54, 54, 255))
|
.background_color(tauri::window::Color(54, 54, 54, 255))
|
||||||
.user_agent(DRAMABOX_UA)
|
.user_agent(DRAMABOX_UA)
|
||||||
|
.data_directory(dramabox_webview_dir())
|
||||||
.on_new_window(move |next_url, features| open_oauth_popup(&popup_app, next_url, features))
|
.on_new_window(move |next_url, features| open_oauth_popup(&popup_app, next_url, features))
|
||||||
.on_page_load(|webview, payload| {
|
.on_page_load(|webview, payload| {
|
||||||
if payload.event() == tauri::webview::PageLoadEvent::Finished {
|
if payload.event() == tauri::webview::PageLoadEvent::Finished {
|
||||||
@@ -434,6 +571,18 @@ fn open_login_window(app: &AppHandle, url: Url) -> Result<(), String> {
|
|||||||
async fn dramabox_login(app: AppHandle, language: String) -> Result<serde_json::Value, String> {
|
async fn dramabox_login(app: AppHandle, language: String) -> Result<serde_json::Value, String> {
|
||||||
let page = dramabox_login_url(&language)?;
|
let page = dramabox_login_url(&language)?;
|
||||||
let url = Url::parse(&page).map_err(|err| err.to_string())?;
|
let url = Url::parse(&page).map_err(|err| err.to_string())?;
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
let opener = app.clone();
|
||||||
|
app.run_on_main_thread(move || {
|
||||||
|
close_login_windows(&opener);
|
||||||
|
let _ = tx.send(());
|
||||||
|
})
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
tauri::async_runtime::spawn_blocking(move || rx.recv())
|
||||||
|
.await
|
||||||
|
.map_err(|err| err.to_string())?
|
||||||
|
.map_err(|_| "登录窗口没有打开".to_string())?;
|
||||||
|
|
||||||
let (tx, rx) = std::sync::mpsc::channel();
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
let opener = app.clone();
|
let opener = app.clone();
|
||||||
app.run_on_main_thread(move || {
|
app.run_on_main_thread(move || {
|
||||||
@@ -459,9 +608,15 @@ async fn dramabox_login(app: AppHandle, language: String) -> Result<serde_json::
|
|||||||
let Some(current) = watcher.get_webview_window(DRAMABOX_LOGIN_LABEL) else {
|
let Some(current) = watcher.get_webview_window(DRAMABOX_LOGIN_LABEL) else {
|
||||||
return Err("登录已取消".to_string());
|
return Err("登录已取消".to_string());
|
||||||
};
|
};
|
||||||
if let Ok(location) = current.url() {
|
let mut windows = vec![current];
|
||||||
if let Some(account) = account_from_url(&location) {
|
for (label, popup) in watcher.webview_windows() {
|
||||||
let _ = current.close();
|
if label.starts_with("dramabox-popup-") {
|
||||||
|
windows.push(popup);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for window in windows {
|
||||||
|
if let Some(account) = read_login_account(&window) {
|
||||||
|
close_login_windows(&watcher);
|
||||||
return Ok(account);
|
return Ok(account);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -471,6 +626,27 @@ async fn dramabox_login(app: AppHandle, language: String) -> Result<serde_json::
|
|||||||
.map_err(|err| err.to_string())?
|
.map_err(|err| err.to_string())?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn dramabox_clear_login(app: AppHandle) -> Result<(), String> {
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
let opener = app.clone();
|
||||||
|
app.run_on_main_thread(move || {
|
||||||
|
close_login_windows(&opener);
|
||||||
|
let _ = tx.send(());
|
||||||
|
})
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
tauri::async_runtime::spawn_blocking(move || rx.recv())
|
||||||
|
.await
|
||||||
|
.map_err(|err| err.to_string())?
|
||||||
|
.map_err(|_| "没有清掉登录凭据".to_string())?;
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
discard_dramabox_browser();
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn boot(handle: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String> {
|
fn boot(handle: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String> {
|
||||||
let root = app_root();
|
let root = app_root();
|
||||||
let mut last_error = "后台启动超时".to_string();
|
let mut last_error = "后台启动超时".to_string();
|
||||||
@@ -507,7 +683,7 @@ pub fn run() {
|
|||||||
prepare_webview_runtime(&root);
|
prepare_webview_runtime(&root);
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.plugin(tauri_plugin_opener::init())
|
.plugin(tauri_plugin_opener::init())
|
||||||
.invoke_handler(tauri::generate_handler![dramabox_login])
|
.invoke_handler(tauri::generate_handler![dramabox_login, dramabox_clear_login])
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
app.manage(Backend {
|
app.manage(Backend {
|
||||||
child: Mutex::new(None),
|
child: Mutex::new(None),
|
||||||
|
|||||||
+79
-16
@@ -34,6 +34,7 @@ interface Profile {
|
|||||||
language?: string;
|
language?: string;
|
||||||
native?: string;
|
native?: string;
|
||||||
locale?: string;
|
locale?: string;
|
||||||
|
loginType?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Device {
|
interface Device {
|
||||||
@@ -118,6 +119,7 @@ const busy = ref(false);
|
|||||||
const error = ref("");
|
const error = ref("");
|
||||||
const token = ref("");
|
const token = ref("");
|
||||||
const profile = ref<Profile | null>(null);
|
const profile = ref<Profile | null>(null);
|
||||||
|
const dramaboxLoggedIn = computed(() => profile.value?.has_login === "1");
|
||||||
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
|
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
|
||||||
const playing = ref<{ id: string | number; title: string; image: string } | null>(null);
|
const playing = ref<{ id: string | number; title: string; image: string } | null>(null);
|
||||||
const progressCount = ref(0);
|
const progressCount = ref(0);
|
||||||
@@ -199,6 +201,22 @@ function tokenKey() {
|
|||||||
return "rapt-token";
|
return "rapt-token";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readSavedToken() {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(tokenKey()) || "";
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeSavedToken(value: string) {
|
||||||
|
localStorage.setItem(tokenKey(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function forgetSavedToken() {
|
||||||
|
localStorage.removeItem(tokenKey());
|
||||||
|
}
|
||||||
|
|
||||||
async function loadDramaboxLanguages() {
|
async function loadDramaboxLanguages() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/dramabox/languages");
|
const response = await fetch("/api/dramabox/languages");
|
||||||
@@ -284,10 +302,19 @@ const accountFields = computed(() => {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
if (platform.value === "dramabox") {
|
if (platform.value === "dramabox") {
|
||||||
|
if (profile.value?.has_login === "1") {
|
||||||
|
return [
|
||||||
|
{ key: "nickname" as const, label: "昵称" },
|
||||||
|
{ key: "email" as const, label: "邮箱" },
|
||||||
|
{ key: "id" as const, label: "用户 ID" },
|
||||||
|
{ key: "loginType" as const, label: "登录方式" },
|
||||||
|
{ key: "country" as const, label: "国家" },
|
||||||
|
{ key: "language" as const, label: "语言" },
|
||||||
|
];
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
{ key: "country" as const, label: "国家" },
|
{ key: "country" as const, label: "国家" },
|
||||||
{ key: "language" as const, label: "语言" },
|
{ key: "language" as const, label: "语言" },
|
||||||
{ key: "id" as const, label: "代码" },
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
return [
|
return [
|
||||||
@@ -563,6 +590,13 @@ function saveAccount(info: Profile) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function profileText(key: keyof Profile) {
|
function profileText(key: keyof Profile) {
|
||||||
|
if (key === "loginType") {
|
||||||
|
const kind = String(profile.value?.loginType || "").trim().toLowerCase();
|
||||||
|
if (kind === "google") return "Google";
|
||||||
|
if (kind === "facebook") return "Facebook";
|
||||||
|
if (kind === "apple") return "Apple";
|
||||||
|
return kind ? String(profile.value?.loginType) : "—";
|
||||||
|
}
|
||||||
const value = profile.value?.[key];
|
const value = profile.value?.[key];
|
||||||
if (value === undefined || value === null || value === "") return "—";
|
if (value === undefined || value === null || value === "") return "—";
|
||||||
return String(value);
|
return String(value);
|
||||||
@@ -650,7 +684,7 @@ async function loginHuangdou() {
|
|||||||
}
|
}
|
||||||
token.value = payload.token;
|
token.value = payload.token;
|
||||||
profile.value = payload.profile;
|
profile.value = payload.profile;
|
||||||
sessionStorage.setItem(tokenKey(), payload.token);
|
writeSavedToken(payload.token);
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
startLive();
|
startLive();
|
||||||
} catch (exc) {
|
} catch (exc) {
|
||||||
@@ -689,7 +723,7 @@ async function loginDramaboxAccount() {
|
|||||||
}
|
}
|
||||||
token.value = payload.token;
|
token.value = payload.token;
|
||||||
profile.value = payload.profile;
|
profile.value = payload.profile;
|
||||||
sessionStorage.setItem(tokenKey(), payload.token);
|
writeSavedToken(payload.token);
|
||||||
if (!inside) {
|
if (!inside) {
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
startLive();
|
startLive();
|
||||||
@@ -720,7 +754,7 @@ async function loginDramabox() {
|
|||||||
}
|
}
|
||||||
token.value = payload.token;
|
token.value = payload.token;
|
||||||
profile.value = payload.profile;
|
profile.value = payload.profile;
|
||||||
sessionStorage.setItem(tokenKey(), payload.token);
|
writeSavedToken(payload.token);
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
startLive();
|
startLive();
|
||||||
} catch (exc) {
|
} catch (exc) {
|
||||||
@@ -773,7 +807,7 @@ async function login() {
|
|||||||
}
|
}
|
||||||
token.value = payload.token;
|
token.value = payload.token;
|
||||||
profile.value = payload.profile;
|
profile.value = payload.profile;
|
||||||
sessionStorage.setItem(tokenKey(), payload.token);
|
writeSavedToken(payload.token);
|
||||||
rememberSessionDevice(payload.device);
|
rememberSessionDevice(payload.device);
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
startLive();
|
startLive();
|
||||||
@@ -833,22 +867,32 @@ function stopLive() {
|
|||||||
|
|
||||||
async function logout() {
|
async function logout() {
|
||||||
const current = token.value;
|
const current = token.value;
|
||||||
|
const clearSite = platform.value === "dramabox";
|
||||||
stopLive();
|
stopLive();
|
||||||
token.value = "";
|
token.value = "";
|
||||||
profile.value = null;
|
profile.value = null;
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
sessionStorage.removeItem(tokenKey());
|
forgetSavedToken();
|
||||||
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
||||||
if (!current) return;
|
|
||||||
try {
|
try {
|
||||||
await fetch(isolated.value ? `${apiBase.value}/logout` : "/api/logout", {
|
if (current) {
|
||||||
method: "POST",
|
await fetch(isolated.value ? `${apiBase.value}/logout` : "/api/logout", {
|
||||||
headers: { "Content-Type": "application/json" },
|
method: "POST",
|
||||||
body: JSON.stringify({ token: current }),
|
headers: { "Content-Type": "application/json" },
|
||||||
});
|
body: JSON.stringify({ token: current }),
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 本地登录态已经清掉
|
// 本地登录态已经清掉
|
||||||
}
|
}
|
||||||
|
if (clearSite && inTauri()) {
|
||||||
|
try {
|
||||||
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
|
await invoke("dramabox_clear_login");
|
||||||
|
} catch {
|
||||||
|
// 程序里的登录凭据已经清掉
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const closeAsk = ref(false);
|
const closeAsk = ref(false);
|
||||||
@@ -909,7 +953,21 @@ onMounted(async () => {
|
|||||||
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
||||||
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
||||||
if (platform.value === "dramabox") await loadDramaboxLanguages();
|
if (platform.value === "dramabox") await loadDramaboxLanguages();
|
||||||
const saved = sessionStorage.getItem(tokenKey());
|
let saved = readSavedToken();
|
||||||
|
if (!saved && isolated.value) {
|
||||||
|
try {
|
||||||
|
const resume = await fetch(`${apiBase.value}/resume`, { method: "POST" });
|
||||||
|
if (resume.ok) {
|
||||||
|
const payload = await resume.json();
|
||||||
|
if (typeof payload.token === "string" && payload.token) {
|
||||||
|
saved = payload.token;
|
||||||
|
writeSavedToken(saved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 没有可恢复的登录
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!saved) return;
|
if (!saved) return;
|
||||||
const response = await fetch(isolated.value ? `${apiBase.value}/me` : "/api/me", {
|
const response = await fetch(isolated.value ? `${apiBase.value}/me` : "/api/me", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -917,7 +975,8 @@ onMounted(async () => {
|
|||||||
body: JSON.stringify({ token: saved, device: sessionDevice() }),
|
body: JSON.stringify({ token: saved, device: sessionDevice() }),
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
sessionStorage.removeItem(tokenKey());
|
const payload = await response.json().catch(() => ({}));
|
||||||
|
if (payload.detail === "登录已失效") forgetSavedToken();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
@@ -1046,8 +1105,11 @@ onUnmounted(stopLive);
|
|||||||
</div>
|
</div>
|
||||||
<div class="profile-block">
|
<div class="profile-block">
|
||||||
<div class="profile-block-title">
|
<div class="profile-block-title">
|
||||||
账号
|
<span>账号</span>
|
||||||
<n-button v-if="platform === 'dramabox'" size="tiny" secondary :loading="accountBusy" @click="loginDramaboxAccount">登录</n-button>
|
<span v-if="platform === 'dramabox'" class="profile-title-actions">
|
||||||
|
<n-tag size="small" :bordered="false" :type="dramaboxLoggedIn ? 'success' : 'default'">{{ dramaboxLoggedIn ? "已登录" : "未登录" }}</n-tag>
|
||||||
|
<n-button v-if="!dramaboxLoggedIn" size="tiny" secondary :loading="accountBusy" @click="loginDramaboxAccount">登录</n-button>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<n-alert v-if="profileError" class="hint" type="error" :show-icon="false">{{ profileError }}</n-alert>
|
<n-alert v-if="profileError" class="hint" type="error" :show-icon="false">{{ profileError }}</n-alert>
|
||||||
<div v-for="item in accountFields" :key="item.key" class="profile-row">
|
<div v-for="item in accountFields" :key="item.key" class="profile-row">
|
||||||
@@ -1325,6 +1387,7 @@ html { color-scheme: dark; }
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
color: rgba(255, 255, 255, 0.45);
|
color: rgba(255, 255, 255, 0.45);
|
||||||
}
|
}
|
||||||
|
.profile-title-actions { display: flex; align-items: center; gap: 8px; }
|
||||||
.profile-row { display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 8px 16px; }
|
.profile-row { display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 8px 16px; }
|
||||||
.profile-row-label { width: 72px; flex: none; color: rgba(255, 255, 255, 0.72); }
|
.profile-row-label { width: 72px; flex: none; color: rgba(255, 255, 255, 0.72); }
|
||||||
.profile-row-value {
|
.profile-row-value {
|
||||||
|
|||||||
Reference in New Issue
Block a user