Skip to content

Commit

Permalink
fix: #26 #27
Browse files Browse the repository at this point in the history
  • Loading branch information
ForgQi committed May 29, 2022
1 parent 51200eb commit 6d4c6f0
Show file tree
Hide file tree
Showing 10 changed files with 271 additions and 329 deletions.
389 changes: 161 additions & 228 deletions src-tauri/Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ build = "src/build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies]
tauri-build = { version = "1.0.0-rc.9", features = [] }
tauri-build = { version = "1.0.0-rc.12", features = [] }

[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.0-rc.11", features = ["api-all"] }
tauri = { version = "1.0.0-rc.14", features = ["api-all"] }
reqwest = { version = "0.11", features = ["json",] }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
thiserror = "1.0"
serde_yaml = "0.8"
biliup = { version = "0.1.7" }
biliup = { version = "0.1.8" }
futures = "0.3.17"
bytes = "1.1.0"

Expand Down
38 changes: 27 additions & 11 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,39 @@ use std::pin::Pin;
use std::task::Poll;
use futures::{FutureExt, Stream};
use std::future::Future;
use std::rc::Rc;
use reqwest::Body;
use bytes::{Buf, Bytes};
use tauri::Window;
use tauri::{App, Window};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::mpsc::Sender;
use std::sync::{Arc};
use tokio::sync::Mutex;

pub mod error;

#[derive(Default)]
pub struct Credential {
pub credential: Mutex<Option<Arc<(LoginInfo, Client)>>>
}

impl Credential {
pub async fn get_credential(&self) -> error::Result<Arc<(LoginInfo, Client)>> {
let mut guard = self.credential.lock().await;
if guard.is_none() {
let client = Client::new();
let login_info = client
.login_by_cookies(std::fs::File::open(cookie_file()?)?)
.await?;
let arc = Arc::new((login_info, client));
*guard = Some(arc.clone());
Ok(arc.clone())
} else {
Ok(guard.as_ref().unwrap().clone())
}
}
}

pub fn config_file() -> error::Result<PathBuf> {
Ok(config_path()?.join("config.yaml"))
}
Expand All @@ -29,7 +54,7 @@ pub fn config_path() -> error::Result<PathBuf> {
if !config_dir.exists() {
std::fs::create_dir(&config_dir)?;
}
println!("{config_dir:?}");
println!("config_path: {config_dir:?}");
Ok(config_dir)
}

Expand All @@ -43,14 +68,6 @@ pub async fn login_by_password(username: &str, password: &str) -> anyhow::Result
Ok(())
}

pub async fn login_by_cookies() -> anyhow::Result<(LoginInfo, Client)> {
let client = Client::new();
let login_info = client
.login_by_cookies(std::fs::File::open(cookie_file()?)?)
.await?;
Ok((login_info, client))
}

pub fn encode_hex(bytes: &[u16]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for &b in bytes {
Expand Down Expand Up @@ -114,6 +131,5 @@ impl From<Progressbar> for Body {
mod test {
#[test]
fn test_hex() {

}
}
65 changes: 25 additions & 40 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,15 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Poll;
use std::time::Instant;

use anyhow::{anyhow, bail, Context};
use biliup::{Account, Config, line, User, VideoFile};
use biliup::client::{Client, LoginInfo};
use biliup::video::{BiliBili, Studio, Video};
use bytes::Buf;
use futures::future::abortable;
use futures::stream::Abortable;
use tauri::{Manager, Window};

// use app::video::{BiliBili, Client, LoginInfo, Studio, Video};
use app::{config_file, cookie_file, encode_hex, login_by_cookies};
use tauri::{Manager, State, Window};
use app::{config_file, cookie_file, Credential, encode_hex};
use app::error;
use app::error::Result;
use futures::StreamExt;
Expand Down Expand Up @@ -59,14 +56,12 @@ fn login(username: &str, password: &str, remember_me: bool) -> Result<String> {
}
}
}
// println!("body = {:?}", client);
Ok("登录成功".into())
}

#[tauri::command]
async fn login_by_cookie() -> Result<String> {
login_by_cookies().await?;
// println!("body = {:?}", client);
async fn login_by_cookie(credential: tauri::State<'_, Credential>) -> Result<String> {
credential.get_credential().await?;
Ok("登录成功".into())
}

Expand All @@ -82,7 +77,6 @@ async fn login_by_sms(code: u32, res: serde_json::Value) -> Result<String> {
#[tauri::command]
async fn send_sms(country_code: u32, phone: u64) -> Result<serde_json::Value> {
let ret = Client::new().send_sms(phone, country_code).await?;
// println!("body = {:?}", client);
Ok(ret)
}

Expand All @@ -98,14 +92,12 @@ async fn login_by_qrcode(res: serde_json::Value) -> Result<String> {
#[tauri::command]
async fn get_qrcode() -> Result<serde_json::Value> {
let qrcode = Client::new().get_qrcode().await?;
// println!("body = {:?}", client);
Ok(qrcode)
}


#[tauri::command]
async fn upload(mut video: Video, window: Window) -> Result<Video> {
let (_, client) = login_by_cookies().await?;
async fn upload(mut video: Video, window: Window, credential: tauri::State<'_, Credential>) -> Result<Video> {
let (_, client) = &*credential.get_credential().await?;

let config = load()?;
let probe = if let Some(line) = config.line {
Expand All @@ -132,7 +124,7 @@ async fn upload(mut video: Video, window: Window) -> Result<Video> {
let (tx, mut rx) = mpsc::unbounded_channel();
// let (tx, mut rx) = mpsc::channel(1);

let f_video = parcel.upload(&client, limit, |vs| {
let f_video = parcel.upload(client, limit, |vs| {
vs.map(|chunk| {
let (chunk, len) = chunk?;
let progressbar = app::Progressbar::new(chunk, tx.clone());
Expand Down Expand Up @@ -164,55 +156,47 @@ async fn upload(mut video: Video, window: Window) -> Result<Video> {
}

#[tauri::command]
async fn submit(mut studio: Studio) -> Result<serde_json::Value> {
let (login_info, _) = login_by_cookies().await?;
let ret = studio.submit(&login_info).await?;
// let bili = BiliBili::new((client, login_info));
// let mut bilibili = bili.submit(studio).await?;
async fn submit(mut studio: Studio, credential: tauri::State<'_, Credential>) -> Result<serde_json::Value> {
let (login_info, _) = &*credential.get_credential().await?;
let ret = studio.submit(login_info).await?;
Ok(ret)
}

#[tauri::command]
async fn archive_pre() -> Result<serde_json::Value> {
let (login_info, client) = login_by_cookies().await?;
let bili = BiliBili::new(&login_info, &client);
async fn archive_pre(credential: tauri::State<'_, Credential>) -> Result<serde_json::Value> {
let (login_info, client) = &*credential.get_credential().await?;
let bili = BiliBili::new(login_info, client);
Ok(bili.archive_pre().await?)
}

#[tauri::command]
async fn get_myinfo() -> Result<serde_json::Value> {
let (_, client) = login_by_cookies().await?;
async fn get_myinfo(credential: tauri::State<'_, Credential>) -> Result<serde_json::Value> {
let (_, client) = &*credential.get_credential().await?;
Ok(client.client.get("https://api.bilibili.com/x/space/myinfo").send().await?.json().await?)
}

#[tauri::command]
fn load_account() -> Result<User> {
// let file = std::fs::File::open("config.yaml")?;
// let user: User = serde_yaml::from_reader(file)?;
// println!("body = {:?}", client);
Ok(load()?.user.ok_or(error::Error::Err("账号信息不存在".into()))?)
}

#[tauri::command]
fn save(config: Config) -> Result<Config> {
let file = std::fs::File::create(config_file()?)?;
// let config: Config = serde_yaml::from_reader(file)?;
serde_yaml::to_writer(file, &config);
// println!("body = {:?}", client);
serde_yaml::to_writer(file, &config)?;
Ok(config)
}

#[tauri::command]
fn load() -> Result<Config> {
let file = std::fs::File::open(config_file()?).with_context(|| "biliup/config.yaml")?;
let config: Config = serde_yaml::from_reader(file)?;
// println!("body = {:?}", client);
Ok(config)
}

#[tauri::command]
async fn cover_up(input: Cow<'_, [u8]>) -> Result<String> {
let (login_info, client) = login_by_cookies().await?;
async fn cover_up(input: Cow<'_, [u8]>, credential: tauri::State<'_, Credential>) -> Result<String> {
let (login_info, client) = &*credential.get_credential().await?;
let bili = BiliBili::new(&login_info, &client);
let url = bili.cover_up(&input).await?;
Ok(url)
Expand All @@ -224,9 +208,9 @@ fn is_vid(input: &str) -> bool {
}

#[tauri::command]
async fn show_video(input: &str) -> Result<Studio> {
let (login_info, client) = login_by_cookies().await?;
let bili = BiliBili::new(&login_info, &client);
async fn show_video(input: &str, credential: tauri::State<'_, Credential>) -> Result<Studio> {
let (login_info, client) = &*credential.get_credential().await?;;
let bili = BiliBili::new(login_info, client);
let mut data = bili.video_data(biliup::video::Vid::from_str(input)?).await?;
let mut studio: Studio = serde_json::from_value(data["archive"].take())?;
studio.videos = data["videos"]
Expand All @@ -243,9 +227,9 @@ async fn show_video(input: &str) -> Result<Studio> {
}

#[tauri::command]
async fn edit_video(mut studio: Studio) -> Result<serde_json::Value> {
let (login_info, _) = login_by_cookies().await?;
let ret = studio.edit(&login_info).await?;
async fn edit_video(mut studio: Studio, credential: tauri::State<'_, Credential>) -> Result<serde_json::Value> {
let (login_info, _) = &*credential.get_credential().await?;
let ret = studio.edit(login_info).await?;
Ok(ret)
}

Expand All @@ -270,6 +254,7 @@ fn main() {
show_video,
edit_video
])
.manage(Credential::default())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
2 changes: 1 addition & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"package": {
"productName": "biliup-app",
"version": "0.3.1"
"version": "0.3.2"
},
"build": {
"distDir": "../public",
Expand Down
9 changes: 8 additions & 1 deletion src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import Modal from "./Modal.svelte";
import Pop from "./Pop.svelte";
import {notifyHistory} from "./common";
import {getVersion} from "@tauri-apps/api/app";
// import {overrideItemIdKeyNameBeforeInitialisingDndZones} from "svelte-dnd-action";
// overrideItemIdKeyNameBeforeInitialisingDndZones("filename");
Expand Down Expand Up @@ -70,7 +71,13 @@
<div slot="box" class="">
<h1 class="text-2xl font-bold text-center">
biliup-app
<span class="badge badge-primary">v0.3.0</span>
<span class="badge badge-primary">
{#await getVersion()}
waiting for the promise to resolve...
{:then value}
v{value}
{/await}
</span>
</h1>
<p class="mt-3">
欢迎使用,如果操作有一些疑问,可以先查看
Expand Down
8 changes: 6 additions & 2 deletions src/Login.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import {isLogin} from './store.js';
import {fade, scale} from 'svelte/transition';
import {invoke} from '@tauri-apps/api/tauri';
import {createPop} from "./common";
import {createPop, notifyHistory} from "./common";
import QrCode from "svelte-qrcode";
import {open} from "@tauri-apps/api/shell";
Expand All @@ -22,7 +22,11 @@
.then((res) => {
isLogin.set(true);
console.log(`Message: ${res}`)
}).catch((e) => createPop(e, 5000));
}).catch((e) => $notifyHistory = [...$notifyHistory, {
type: 'Error',
msg: e,
date: new Date(),
}]);
invoke('load')
.then((res) => {
username = res.user.account.username;
Expand Down
31 changes: 15 additions & 16 deletions src/Sidebar.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts">
import {currentTemplate, template} from "./store.ts";
import {currentTemplate, template, save_config} from "./store.ts";
import {fly} from 'svelte/transition';
import {flip} from 'svelte/animate';
import {invoke} from "@tauri-apps/api/tauri";
Expand Down Expand Up @@ -61,9 +61,9 @@
});
})
$template[tempName].atomicInt = 0;
let res = await invoke('load');
res.streamers = $template;
await invoke('save', {config: res});
await save_config((ret) => {
ret.streamers = $template;
})
tempName = null;
return;
}
Expand All @@ -89,9 +89,9 @@
atomicInt: 0
};
// $currentTemplate = $template[name];
let res = await invoke('load');
res.streamers = $template;
await invoke('save', {config: res});
await save_config((ret) => {
ret.streamers = $template;
})
tempName = null;
}
Expand Down Expand Up @@ -119,15 +119,14 @@
}
async function saveSettings() {
let ret = await invoke('load');
console.log(ret);
if (line === 'auto') {
ret.line = null;
} else {
ret.line = line;
}
ret.limit = limit;
await invoke('save', {config: ret});
await save_config((ret) => {
if (line === 'auto') {
ret.line = null;
} else {
ret.line = line;
}
ret.limit = limit;
})
}
let tempName: string;
Expand Down
Loading

0 comments on commit 6d4c6f0

Please sign in to comment.