Skip to content

Commit

Permalink
desktop: send mpv logs through channel
Browse files Browse the repository at this point in the history
  • Loading branch information
NextFire committed Aug 18, 2024
1 parent a28eb6a commit 6f6f259
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 31 deletions.
26 changes: 21 additions & 5 deletions ui/src-tauri/src/cmds.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::env;

use async_std::path::PathBuf;
use tauri::{AppHandle, Emitter, Manager, State};
use serde::Serialize;
use tauri::{ipc::Channel, AppHandle, Manager, State};
use tauri_plugin_shell::{process::CommandEvent, ShellExt};
use tauri_plugin_store::with_store;

Expand All @@ -10,6 +11,15 @@ use crate::{
AppState, AppStore, STORE_BIN,
};

#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase", tag = "event", content = "data")]
pub enum LogEvent {
#[serde(rename_all = "camelCase")]
Stdout(String),
#[serde(rename_all = "camelCase")]
Stderr(String),
}

#[tauri::command]
pub async fn play_mpv(
app_handle: AppHandle,
Expand All @@ -18,6 +28,7 @@ pub async fn play_mpv(
inst: Option<String>,
sub: Option<String>,
title: String,
on_log: Channel<LogEvent>,
) -> tauri::Result<()> {
let mpv = state
.lock()
Expand All @@ -26,14 +37,19 @@ pub async fn play_mpv(
.get_or_insert_with(|| {
let socket = get_mpv_socket(&app_handle);
let token = get_player_token(&app_handle);
start_mpv(&app_handle, socket, token)
start_mpv(&app_handle, socket, token, on_log)
})
.clone();
add_to_mpv_playlist(&mpv, video, inst, sub, title).await;
Ok(())
}

fn start_mpv(app_handle: &AppHandle, socket: String, token: String) -> Mpv {
fn start_mpv(
app_handle: &AppHandle,
socket: String,
token: String,
on_log: Channel<LogEvent>,
) -> Mpv {
let mut mpv = app_handle.shell().command("mpv");
mpv = mpv.args([
"--idle=once",
Expand All @@ -55,12 +71,12 @@ fn start_mpv(app_handle: &AppHandle, socket: String, token: String) -> Mpv {
CommandEvent::Stdout(line) => {
let line = String::from_utf8(line).unwrap();
print!("{}", &line);
let _ = app_handle.emit("mpv-stdout", &line);
let _ = on_log.send(LogEvent::Stdout(line));
}
CommandEvent::Stderr(line) => {
let line = String::from_utf8(line).unwrap();
eprint!("{}", &line);
let _ = app_handle.emit("mpv-stderr", &line);
let _ = on_log.send(LogEvent::Stderr(line));
}
_ => {}
}
Expand Down
13 changes: 10 additions & 3 deletions ui/src-tauri/src/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,19 @@ Release Notes:
}

async fn install_update(app_handle: AppHandle, update: Update) {
let title = "Ready to Restart";
let message = "The installation was successful, do you want to restart the application now?";
let mut downloaded = 0;

update
.download_and_install(
|_, _| {},
|chunk_length, content_length| {
downloaded += chunk_length;
println!("updater: downloaded {downloaded} from {content_length:?}");
},
|| {
let title = "Ready to Restart";
let message =
"The installation was successful, do you want to restart the application now?";

app_handle
.dialog()
.message(message)
Expand Down
6 changes: 0 additions & 6 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import { Router } from "@solidjs/router";
import { isTauri } from "@tauri-apps/api/core";
import { createEffect } from "solid-js";
import { themeChange } from "theme-change";
import routes from "~solid-pages";
import Layout from "./layout/Layout";
import { registerGlobalListeners } from "./utils/tauri";

export default function App() {
if (isTauri()) {
registerGlobalListeners();
}

createEffect(() => themeChange());

return <Router root={Layout}>{routes}</Router>;
Expand Down
10 changes: 5 additions & 5 deletions ui/src/components/MpvKaraPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HiOutlineCheck, HiSolidPlayCircle } from "solid-icons/hi";
import { createSignal, Show, type JSX } from "solid-js";
import type { components } from "../utils/karaberus";
import { apiUrl, karaberus } from "../utils/karaberus-client";
import { getStore, PLAYER_TOKEN_KEY } from "../utils/tauri";
import { logChannel, PLAYER_TOKEN_KEY, tauriStore } from "../utils/tauri";

export default function MpvKaraPlayer(props: {
kara: components["schemas"]["KaraInfoDB"];
Expand All @@ -25,15 +25,15 @@ export default function MpvKaraPlayer(props: {
: undefined,
sub: props.kara.SubtitlesUploaded ? downloadEndpoint("sub") : undefined,
title: props.kara.Title,
onLog: logChannel,
});
setLoading(false);
setSuccess(true);
setTimeout(() => setSuccess(false), 1000);
};

const ensurePlayerToken = async () => {
const store = getStore();
let token = await store.get<string>(PLAYER_TOKEN_KEY);
let token = await tauriStore.get<string>(PLAYER_TOKEN_KEY);
if (!token) {
const resp = await karaberus.POST("/api/token", {
body: {
Expand All @@ -45,8 +45,8 @@ export default function MpvKaraPlayer(props: {
throw new Error(resp.error.title);
}
token = resp.data.token;
await store.set(PLAYER_TOKEN_KEY, token);
await store.save();
await tauriStore.set(PLAYER_TOKEN_KEY, token);
await tauriStore.save();
}
return token;
};
Expand Down
9 changes: 4 additions & 5 deletions ui/src/pages/settings.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { isTauri } from "@tauri-apps/api/core";
import { HiSolidTrash } from "solid-icons/hi";
import { createResource, createSignal, Index, Show } from "solid-js";
import TokenForm from "../components/TokenForm";
import { karaberus } from "../utils/karaberus-client";
import { isTauri } from "@tauri-apps/api/core";
import { getStore, PLAYER_TOKEN_KEY } from "../utils/tauri";
import { PLAYER_TOKEN_KEY, tauriStore } from "../utils/tauri";

export default function Settings() {
const [getAllTokens, { refetch: refetchTokens }] = createResource(
Expand All @@ -28,9 +28,8 @@ export default function Settings() {
};

const resetPlayerToken = async () => {
const store = getStore();
await store.delete(PLAYER_TOKEN_KEY);
await store.save();
await tauriStore.delete(PLAYER_TOKEN_KEY);
await tauriStore.save();
await Promise.all(getAllTokens()?.map((t) => deleteToken(t.id)) ?? []);
refetchTokens();
};
Expand Down
19 changes: 12 additions & 7 deletions ui/src/utils/tauri.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Channel } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import type { Platform } from "@tauri-apps/plugin-os";
import { Store } from "@tauri-apps/plugin-store";
Expand Down Expand Up @@ -31,12 +32,16 @@ export function registerGlobalListeners() {
listen<string>("mpv-stderr", (e) => console.warn(e.payload));
}

let store: Store;
export function getStore() {
if (!store) {
store = new Store(IS_TAURI_DEV_BUILD ? "store_dev.bin" : "store.bin");
}
return store;
}
export const tauriStore = new Store(
IS_TAURI_DEV_BUILD ? "store_dev.bin" : "store.bin",
);

export const PLAYER_TOKEN_KEY = "player_token";

export const logChannel = new Channel<{
event: "stdout" | "stderr";
data: string;
}>();
logChannel.onmessage = (msg) => {
console[msg.event === "stdout" ? "log" : "error"](msg.data);
};

0 comments on commit 6f6f259

Please sign in to comment.