Merge pull request #2622 from ludovic111/feat/launcher-console
🤖 Agent: launcher-features-1: base main, merge-tree clean against main, CI verify + launcher green; queued.
This commit is contained in:
@@ -153,6 +153,26 @@ Show or set the extra arguments the game starts with (for example --server-threa
|
||||
|
||||
MCP: `game_args`.
|
||||
|
||||
## `horizon-launcher share-log`
|
||||
|
||||
Upload an instance's latest.log to mclo.gs (a paste service for Minecraft logs) and print its link, for a bug report: only when the player asks. The home folder, the user name and the account names are taken out first; the link expires after 90 days unread.
|
||||
|
||||
horizon-launcher share-log
|
||||
|
||||
- `--instance`: The instance (default: the selected one)
|
||||
|
||||
MCP: `share_log`, only when the player asks.
|
||||
|
||||
## `horizon-launcher unshare-log`
|
||||
|
||||
Delete a log shared with share-log: the "<id>:<token>" it printed.
|
||||
|
||||
horizon-launcher unshare-log <SHARED>
|
||||
|
||||
- `SHARED`
|
||||
|
||||
MCP: `unshare_log`, needs `confirm: true`.
|
||||
|
||||
## `horizon-launcher logs`
|
||||
|
||||
Print the end of the game's log (logs/latest.log in the game folder), or its newest crash report.
|
||||
|
||||
@@ -100,6 +100,13 @@ The opening, then Play ([clip](docs/opening.webm)):
|
||||
pack into the selected instance. A data pack is pointed at the world rows, and the Packs section
|
||||
and the world rows keep taking their own drops. A note in the corner says what happened.
|
||||
`horizon-launcher instance import <file>`.
|
||||
- **Console**: Home's Console shows the game's output of this run as it comes: a search (every
|
||||
word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings
|
||||
and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste
|
||||
service for Minecraft logs, only after the player confirms; the home folder, the user name and
|
||||
the account names are taken out first (`horizon_launcher::game_log`), and **Delete it** removes
|
||||
the paste. `horizon-launcher share-log [--instance]` and `unshare-log <id:token>`;
|
||||
`HORIZON_LAUNCHER_PASTE_URL` points it at a test server.
|
||||
- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played,
|
||||
size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does
|
||||
(`<date>_<time>_<folder>.zip`); **Copy** puts "<name> (1)" beside it; **Delete** moves it to the
|
||||
|
||||
@@ -564,6 +564,16 @@ enum Cmd {
|
||||
#[arg(allow_hyphen_values = true)]
|
||||
args: Option<String>,
|
||||
},
|
||||
/// Upload an instance's latest.log to mclo.gs (a paste service for Minecraft logs) and print
|
||||
/// its link, for a bug report: only when the player asks. The home folder, the user name and
|
||||
/// the account names are taken out first; the link expires after 90 days unread
|
||||
ShareLog {
|
||||
/// The instance (default: the selected one)
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
/// Delete a log shared with share-log: the "<id>:<token>" it printed
|
||||
UnshareLog { shared: String },
|
||||
/// Print the end of the game's log (logs/latest.log in the game folder), or its newest crash
|
||||
/// report
|
||||
Logs {
|
||||
@@ -1056,6 +1066,41 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
println!("Game arguments: {line}");
|
||||
}
|
||||
}
|
||||
Cmd::ShareLog { instance } => {
|
||||
use horizon_launcher::game_log;
|
||||
let i = match instance {
|
||||
Some(name) => instances::find(&name)?,
|
||||
None => instances::selected(),
|
||||
};
|
||||
let path = i.home.join("logs/latest.log");
|
||||
let text =
|
||||
std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let names = game_log::names(&[&i.home, &backend::game_home()]);
|
||||
let text = game_log::private(&text, dirs::home_dir().as_deref(), &names);
|
||||
let shared = game_log::share(&text)?;
|
||||
if as_json {
|
||||
json(serde_json::json!({
|
||||
"url": shared.url, "delete": format!("{}:{}", shared.id, shared.token),
|
||||
}));
|
||||
} else {
|
||||
println!("{}", shared.url);
|
||||
println!(
|
||||
"Delete it: horizon-launcher unshare-log {}:{}",
|
||||
shared.id, shared.token
|
||||
);
|
||||
}
|
||||
}
|
||||
Cmd::UnshareLog { shared } => {
|
||||
let (id, token) = shared
|
||||
.split_once(':')
|
||||
.ok_or("Give the \"<id>:<token>\" share-log printed.")?;
|
||||
horizon_launcher::game_log::unshare(&horizon_launcher::game_log::Shared {
|
||||
url: String::new(),
|
||||
id: id.into(),
|
||||
token: token.into(),
|
||||
})?;
|
||||
println!("Deleted the shared log {id}.");
|
||||
}
|
||||
Cmd::Logs { lines, crash } => {
|
||||
let (path, text) = backend::read_logs(lines, crash)?;
|
||||
if as_json {
|
||||
|
||||
@@ -31,6 +31,7 @@ pub const DESTRUCTIVE: &[&str] = &[
|
||||
"screenshots delete",
|
||||
"packs remove",
|
||||
"worlds datapack-remove",
|
||||
"unshare-log",
|
||||
];
|
||||
|
||||
/// Commands that send something or reach other people: only when the player asks.
|
||||
@@ -40,6 +41,7 @@ pub const OPEN_WORLD: &[&str] = &[
|
||||
"data bug",
|
||||
"data benchmark",
|
||||
"servers create",
|
||||
"share-log",
|
||||
];
|
||||
|
||||
/// A generated tool: its name, the CLI words it runs and the clap command behind them.
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
//! Home's Console: the game's output of this run as it comes, with a search, Follow (keep the
|
||||
//! newest line in view), Copy, and Share log (`horizon_launcher::game_log`): an upload to mclo.gs
|
||||
//! that happens only after the player confirms, without their home folder or names.
|
||||
use super::servers_page::Field;
|
||||
use super::*;
|
||||
use gpui::{ClipboardItem, ScrollHandle};
|
||||
use horizon_launcher::game_log::{self, Shared};
|
||||
|
||||
pub(super) struct Console {
|
||||
open: bool,
|
||||
follow: bool,
|
||||
scroll: ScrollHandle,
|
||||
/// Lines and search at the last draw: a change means scroll down when following.
|
||||
seen: (usize, String),
|
||||
confirm_share: bool,
|
||||
sharing: bool,
|
||||
shared: Option<Result<Shared, String>>,
|
||||
}
|
||||
|
||||
impl Default for Console {
|
||||
fn default() -> Self {
|
||||
Console {
|
||||
open: std::env::var("HORIZON_LAUNCHER_CONSOLE").is_ok(),
|
||||
follow: true,
|
||||
scroll: ScrollHandle::new(),
|
||||
seen: (0, String::new()),
|
||||
confirm_share: false,
|
||||
sharing: false,
|
||||
shared: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
/// What Share log sends: this run's lines, else the selected instance's latest.log.
|
||||
fn log_to_share(&self) -> Result<(String, Vec<std::path::PathBuf>), String> {
|
||||
let home = self
|
||||
.client_home
|
||||
.clone()
|
||||
.or_else(|| self.selected_instance().map(|i| i.home.clone()))
|
||||
.unwrap_or_else(backend::game_home);
|
||||
let text = match self.prepare_log.is_empty() {
|
||||
false => {
|
||||
self.prepare_log
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
+ "\n"
|
||||
}
|
||||
true => {
|
||||
let path = home.join("logs/latest.log");
|
||||
std::fs::read_to_string(&path).map_err(|_| "There is no log to share yet.")?
|
||||
}
|
||||
};
|
||||
Ok((text, vec![home, backend::game_home()]))
|
||||
}
|
||||
|
||||
fn share_log(&mut self, cx: &mut Context<Self>) {
|
||||
let shared = match self.log_to_share() {
|
||||
Ok(log) => log,
|
||||
Err(e) => {
|
||||
self.console.shared = Some(Err(e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.console.confirm_share = false;
|
||||
self.console.sharing = true;
|
||||
let task = cx.background_executor().spawn(async move {
|
||||
let (text, homes) = shared;
|
||||
let homes: Vec<&std::path::Path> = homes.iter().map(|h| h.as_path()).collect();
|
||||
let names = game_log::names(&homes);
|
||||
game_log::share(&game_log::private(
|
||||
&text,
|
||||
dirs::home_dir().as_deref(),
|
||||
&names,
|
||||
))
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let done = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.console.sharing = false;
|
||||
this.console.shared = Some(done);
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn unshare_log(&mut self, cx: &mut Context<Self>) {
|
||||
let Some(Ok(shared)) = self.console.shared.clone() else {
|
||||
return;
|
||||
};
|
||||
self.console.sharing = true;
|
||||
let task = cx
|
||||
.background_executor()
|
||||
.spawn(async move { game_log::unshare(&shared) });
|
||||
cx.spawn(async move |this, cx| {
|
||||
let done = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.console.sharing = false;
|
||||
this.console.shared = match done {
|
||||
Ok(()) => None,
|
||||
Err(e) => Some(Err(e)),
|
||||
};
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Home's Console section, once the game has said something (or is running).
|
||||
pub(super) fn console_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
|
||||
let t = self.theme;
|
||||
if self.prepare_log.is_empty() && self.client.is_none() {
|
||||
return None;
|
||||
}
|
||||
let open = self.console.open;
|
||||
let toggle = button(
|
||||
"console-toggle",
|
||||
if open { "Hide" } else { "Show" },
|
||||
Kind::Ghost,
|
||||
&t,
|
||||
)
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.console.open = !this.console.open;
|
||||
cx.notify();
|
||||
}));
|
||||
let count = self.prepare_log.len();
|
||||
let header = div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.child(section_title("Console", "terminal", &t))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(10.))
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child(match self.client {
|
||||
Some(_) => format!("{count} lines, the game is running"),
|
||||
None => format!("{count} lines from the last run"),
|
||||
}),
|
||||
)
|
||||
.child(toggle),
|
||||
);
|
||||
let mut section = div().flex().flex_col().gap(px(10.)).child(header);
|
||||
if !open {
|
||||
return Some(section);
|
||||
}
|
||||
let search = self.servers.value(Field::ConsoleSearch).trim().to_string();
|
||||
let lines: Vec<String> = self
|
||||
.prepare_log
|
||||
.iter()
|
||||
.filter(|l| game_log::matches(l, &search))
|
||||
.cloned()
|
||||
.collect();
|
||||
let now = (count, search);
|
||||
if self.console.follow && now != self.console.seen {
|
||||
self.console.scroll.scroll_to_bottom();
|
||||
}
|
||||
self.console.seen = now;
|
||||
let follow = div()
|
||||
.id("console-follow")
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(8.))
|
||||
.cursor_pointer()
|
||||
.child(switch("console-follow-switch", self.console.follow, &t))
|
||||
.child(text(theme::LABEL).text_color(t.ink_soft).child("Follow"))
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.console.follow = !this.console.follow;
|
||||
this.console.seen.0 = usize::MAX;
|
||||
cx.notify();
|
||||
}));
|
||||
let copied = lines.join("\n");
|
||||
let tools = div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap(px(10.))
|
||||
.child(self.field(Field::ConsoleSearch, "Search the log", 260., cx))
|
||||
.child(follow)
|
||||
.child(div().flex_1())
|
||||
.child(
|
||||
button("console-copy", "Copy", Kind::Ghost, &t).on_click(cx.listener(
|
||||
move |this, _: &ClickEvent, _, cx| {
|
||||
copy_to_clipboard(cx, ClipboardItem::new_string(copied.clone()));
|
||||
this.console.shared = None;
|
||||
cx.notify();
|
||||
},
|
||||
)),
|
||||
)
|
||||
.child({
|
||||
let b = button("console-share", "Share log…", Kind::Ghost, &t);
|
||||
match self.console.sharing {
|
||||
true => disabled(b),
|
||||
false => b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.console.confirm_share = true;
|
||||
cx.notify();
|
||||
})),
|
||||
}
|
||||
})
|
||||
.child({
|
||||
let logs = self
|
||||
.client_home
|
||||
.clone()
|
||||
.or_else(|| self.selected_instance().map(|i| i.home.clone()))
|
||||
.unwrap_or_else(backend::game_home)
|
||||
.join("logs");
|
||||
button("console-folder", "Open logs folder", Kind::Ghost, &t).on_click(
|
||||
move |_, _, cx| {
|
||||
let _ = std::fs::create_dir_all(&logs);
|
||||
cx.open_with_system(&logs);
|
||||
},
|
||||
)
|
||||
});
|
||||
section = section.child(tools);
|
||||
if self.console.confirm_share {
|
||||
section = section.child(
|
||||
plate(&t)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(12.))
|
||||
.px(px(14.))
|
||||
.py(px(10.))
|
||||
.child(div().flex_1().min_w_0().child(
|
||||
text(theme::CAPTION).text_color(t.ink_soft).child(
|
||||
"Upload this log to mclo.gs, a paste service for Minecraft logs? \
|
||||
Anyone with the link can read it, until it is deleted or unread \
|
||||
for 90 days. Your home folder, user name and account names are \
|
||||
taken out first.",
|
||||
),
|
||||
))
|
||||
.child(
|
||||
button("console-share-no", "Cancel", Kind::Ghost, &t).on_click(
|
||||
cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.console.confirm_share = false;
|
||||
cx.notify();
|
||||
}),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
button("console-share-yes", "Upload", Kind::Secondary, &t).on_click(
|
||||
cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.share_log(cx);
|
||||
cx.notify();
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
match &self.console.shared {
|
||||
_ if self.console.sharing => {
|
||||
section = section.child(text(theme::CAPTION).text_color(t.muted).child("Sending…"))
|
||||
}
|
||||
Some(Ok(shared)) => {
|
||||
let (url, open_url) = (shared.url.clone(), shared.url.clone());
|
||||
section = section.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(10.))
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.ink_soft)
|
||||
.child(format!("Shared: {url}")),
|
||||
)
|
||||
.child(
|
||||
button("console-link-copy", "Copy link", Kind::Ghost, &t).on_click(
|
||||
move |_, _, cx| {
|
||||
copy_to_clipboard(cx, ClipboardItem::new_string(url.clone()))
|
||||
},
|
||||
),
|
||||
)
|
||||
.child(
|
||||
button("console-link-open", "Open", Kind::Ghost, &t)
|
||||
.on_click(move |_, _, cx| cx.open_url(&open_url)),
|
||||
)
|
||||
.child(
|
||||
button("console-unshare", "Delete it", Kind::Ghost, &t).on_click(
|
||||
cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.unshare_log(cx);
|
||||
cx.notify();
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Some(Err(e)) => section = section.child(notice(e.clone(), &t)),
|
||||
None => {}
|
||||
}
|
||||
let shown = lines.len().saturating_sub(LOG_LINES);
|
||||
let body = div()
|
||||
.id("console-lines")
|
||||
.track_scroll(&self.console.scroll)
|
||||
.h(px(320.))
|
||||
.overflow_y_scroll()
|
||||
.p(px(10.))
|
||||
.border_2()
|
||||
.border_color(t.outline)
|
||||
.bg(t.well)
|
||||
.font_family(theme::MONO)
|
||||
.text_size(px(12.))
|
||||
.children(lines.into_iter().skip(shown).map(|line| {
|
||||
let color = if line.contains("/ERROR]") || line.contains("ERROR:") {
|
||||
t.danger
|
||||
} else if line.contains("/WARN]") {
|
||||
t.warn
|
||||
} else {
|
||||
t.ink_soft
|
||||
};
|
||||
div().text_color(color).child(line)
|
||||
}));
|
||||
Some(section.child(body))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! The game's log as the console shows it, and sharing it.
|
||||
//!
|
||||
//! Sharing uploads the log to mclo.gs, and only when the player asks (a click, or `logs share`).
|
||||
//! mclo.gs is a paste service made for Minecraft logs by Aternos: no account, links expire after
|
||||
//! 90 days unread, and the uploader gets a token that deletes the paste. Before anything leaves
|
||||
//! the computer, [`private`] takes out the player's home folder, their user name and their
|
||||
//! account names.
|
||||
use std::path::Path;
|
||||
|
||||
/// mclo.gs's API; `HORIZON_LAUNCHER_PASTE_URL` points it elsewhere for tests.
|
||||
const API: &str = "https://api.mclo.gs/1";
|
||||
const PASTE_ENV: &str = "HORIZON_LAUNCHER_PASTE_URL";
|
||||
/// mclo.gs keeps at most 25,000 lines and 10 MiB: the end of a longer log is sent.
|
||||
const MAX_LINES: usize = 25_000;
|
||||
const MAX_BYTES: usize = 10 << 20;
|
||||
|
||||
fn api() -> String {
|
||||
std::env::var(PASTE_ENV)
|
||||
.ok()
|
||||
.filter(|u| !u.is_empty())
|
||||
.unwrap_or_else(|| API.into())
|
||||
}
|
||||
|
||||
/// Whether a console line matches the search: every word, in any case.
|
||||
pub fn matches(line: &str, search: &str) -> bool {
|
||||
let line = line.to_lowercase();
|
||||
search
|
||||
.split_whitespace()
|
||||
.all(|w| line.contains(&w.to_lowercase()))
|
||||
}
|
||||
|
||||
/// The names to take out of a log: the account names, the offline player name kept in each
|
||||
/// game folder (`horizon-player.txt`), and the computer's user name.
|
||||
pub fn names(homes: &[&Path]) -> Vec<String> {
|
||||
let mut names: Vec<String> = crate::account::Accounts::load()
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|a| a.name)
|
||||
.collect();
|
||||
for home in homes {
|
||||
if let Ok(name) = std::fs::read_to_string(home.join("horizon-player.txt")) {
|
||||
names.push(name.trim().to_string());
|
||||
}
|
||||
}
|
||||
for var in ["USER", "USERNAME"] {
|
||||
if let Ok(user) = std::env::var(var) {
|
||||
names.push(user);
|
||||
}
|
||||
}
|
||||
if let Some(user) =
|
||||
dirs::home_dir().and_then(|h| h.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
{
|
||||
names.push(user);
|
||||
}
|
||||
names.retain(|n| n.chars().count() >= 3);
|
||||
names.sort_by_key(|n| std::cmp::Reverse(n.len()));
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
/// The log without the home folder (`~` instead, with either slash) and without `names` (each
|
||||
/// becomes `<player>`), as whole words in any case.
|
||||
pub fn private(text: &str, home: Option<&Path>, names: &[String]) -> String {
|
||||
let mut out = text.to_string();
|
||||
if let Some(home) = home
|
||||
.map(|h| h.to_string_lossy().into_owned())
|
||||
.filter(|h| h.len() > 1)
|
||||
{
|
||||
out = out.replace(&home, "~");
|
||||
out = out.replace(&home.replace('\\', "/"), "~");
|
||||
out = out.replace(&home.replace('/', "\\"), "~");
|
||||
}
|
||||
for name in names {
|
||||
out = replace_word(&out, name, "<player>");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Replaces `word` (any case) where it isn't part of a longer name.
|
||||
fn replace_word(text: &str, word: &str, with: &str) -> String {
|
||||
let lower = text.to_lowercase();
|
||||
let find = word.to_lowercase();
|
||||
if find.is_empty() || lower.len() != text.len() {
|
||||
// A case change that moves bytes (rare scripts): exact matches only.
|
||||
return text.replace(word, with);
|
||||
}
|
||||
let part = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut at = 0;
|
||||
while let Some(i) = lower[at..].find(&find).map(|i| i + at) {
|
||||
let end = i + find.len();
|
||||
if part(text[..i].chars().next_back()) || part(text[end..].chars().next()) {
|
||||
out.push_str(&text[at..end]);
|
||||
} else {
|
||||
out.push_str(&text[at..i]);
|
||||
out.push_str(with);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
out.push_str(&text[at..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The end of the log that fits what mclo.gs keeps.
|
||||
pub fn fit(text: &str) -> &str {
|
||||
let mut start = 0;
|
||||
let lines: Vec<usize> = text.match_indices('\n').map(|(i, _)| i + 1).collect();
|
||||
if lines.len() > MAX_LINES {
|
||||
start = lines[lines.len() - MAX_LINES - 1];
|
||||
}
|
||||
while text.len() - start > MAX_BYTES {
|
||||
start = text[start..]
|
||||
.find('\n')
|
||||
.map_or(text.len(), |i| start + i + 1);
|
||||
}
|
||||
&text[start..]
|
||||
}
|
||||
|
||||
/// A shared log: its page, and what deletes it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Shared {
|
||||
pub url: String,
|
||||
pub id: String,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
/// Uploads `text` (already [`private`]) and returns its link.
|
||||
pub fn share(text: &str) -> Result<Shared, String> {
|
||||
let body = serde_json::json!({ "content": fit(text), "source": "Horizon launcher" });
|
||||
let answer: serde_json::Value = ureq::post(&format!("{}/log", api()))
|
||||
.send_json(body)
|
||||
.map_err(|e| format!("mclo.gs didn't take the log: {e}"))?
|
||||
.into_json()
|
||||
.map_err(|e| format!("mclo.gs answered something unexpected: {e}"))?;
|
||||
let field = |k: &str| answer[k].as_str().map(str::to_string);
|
||||
match (
|
||||
answer["success"].as_bool(),
|
||||
field("url"),
|
||||
field("id"),
|
||||
field("token"),
|
||||
) {
|
||||
(Some(true), Some(url), Some(id), Some(token)) => Ok(Shared { url, id, token }),
|
||||
_ => Err(format!(
|
||||
"mclo.gs didn't take the log: {}",
|
||||
field("error").unwrap_or_else(|| "no reason given".into())
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes a log shared from here.
|
||||
pub fn unshare(shared: &Shared) -> Result<(), String> {
|
||||
ureq::delete(&format!("{}/log/{}", api(), shared.id))
|
||||
.set("Authorization", &format!("Bearer {}", shared.token))
|
||||
.call()
|
||||
.map_err(|e| format!("mclo.gs didn't delete it: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "game_log/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,114 @@
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
|
||||
#[test]
|
||||
fn search_matches_every_word_in_any_case() {
|
||||
assert!(matches(
|
||||
"[12:00:01] [Render thread/WARN]: Missing texture",
|
||||
"warn texture"
|
||||
));
|
||||
assert!(!matches("[12:00:01] [Render thread/INFO]: Loaded", "warn"));
|
||||
assert!(matches("anything", " "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shared_log_has_no_home_folder_or_names() {
|
||||
let log = "Loading /Users/ludovicmarie/Library/Application Support/horizon/options.txt\n\
|
||||
C:\\Users\\ludovicmarie\\AppData\\horizon too\n\
|
||||
Ludo47 joined the game\n\
|
||||
<ludo47> hi, Ludo470 is someone else\n\
|
||||
user LUDOVICMARIE on ludovicmarie-mac\n";
|
||||
let names = vec!["ludovicmarie".to_string(), "Ludo47".to_string()];
|
||||
let out = private(log, Some(Path::new("/Users/ludovicmarie")), &names);
|
||||
assert_eq!(
|
||||
out,
|
||||
"Loading ~/Library/Application Support/horizon/options.txt\n\
|
||||
C:~\\AppData\\horizon too\n\
|
||||
<player> joined the game\n\
|
||||
<<player>> hi, Ludo470 is someone else\n\
|
||||
user <player> on <player>-mac\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_log_sends_its_end() {
|
||||
let log: String = (0..30_000).map(|i| format!("line {i}\n")).collect();
|
||||
let sent = fit(&log);
|
||||
assert_eq!(sent.lines().count(), MAX_LINES);
|
||||
assert!(sent.starts_with("line 5000\n") && sent.ends_with("line 29999\n"));
|
||||
assert_eq!(fit("short\n"), "short\n");
|
||||
}
|
||||
|
||||
/// A one-request HTTP server that answers `body` and hands back what it was sent.
|
||||
fn stub(body: &'static str) -> (String, std::thread::JoinHandle<String>) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let served = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut head = String::new();
|
||||
let mut length = 0;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {
|
||||
length = n.trim().parse().unwrap();
|
||||
}
|
||||
head.push_str(&line);
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut sent = vec![0; length];
|
||||
reader.read_exact(&mut sent).unwrap();
|
||||
let reply = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
reader.get_mut().write_all(reply.as_bytes()).unwrap();
|
||||
head + &String::from_utf8(sent).unwrap()
|
||||
});
|
||||
(url, served)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shares_and_deletes_through_the_paste_api() {
|
||||
let (url, served) =
|
||||
stub(r#"{"success":true,"id":"Ab12","url":"https://mclo.gs/Ab12","token":"t0k"}"#);
|
||||
std::env::set_var(PASTE_ENV, &url);
|
||||
let shared = share("[main/INFO]: hello\n").unwrap();
|
||||
assert_eq!(
|
||||
shared,
|
||||
Shared {
|
||||
url: "https://mclo.gs/Ab12".into(),
|
||||
id: "Ab12".into(),
|
||||
token: "t0k".into()
|
||||
}
|
||||
);
|
||||
let request = served.join().unwrap();
|
||||
assert!(request.starts_with("POST /log "), "{request}");
|
||||
assert!(
|
||||
request.ends_with(r#"{"content":"[main/INFO]: hello\n","source":"Horizon launcher"}"#),
|
||||
"{request}"
|
||||
);
|
||||
|
||||
let (url, served) = stub(r#"{"success":true}"#);
|
||||
std::env::set_var(PASTE_ENV, &url);
|
||||
unshare(&shared).unwrap();
|
||||
let request = served.join().unwrap();
|
||||
assert!(request.starts_with("DELETE /log/Ab12 "), "{request}");
|
||||
assert!(
|
||||
request
|
||||
.to_ascii_lowercase()
|
||||
.contains("authorization: bearer t0k"),
|
||||
"{request}"
|
||||
);
|
||||
|
||||
let (url, _served) = stub(r#"{"success":false,"error":"Required field 'content' not found."}"#);
|
||||
std::env::set_var(PASTE_ENV, &url);
|
||||
assert_eq!(
|
||||
share("").unwrap_err(),
|
||||
"mclo.gs didn't take the log: Required field 'content' not found."
|
||||
);
|
||||
std::env::remove_var(PASTE_ENV);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod desktop_seams;
|
||||
pub mod export;
|
||||
#[cfg(unix)]
|
||||
pub mod game_app;
|
||||
pub mod game_log;
|
||||
pub mod heads;
|
||||
pub mod import;
|
||||
pub mod instances;
|
||||
|
||||
@@ -10,6 +10,7 @@ mod cli;
|
||||
mod cli_tools;
|
||||
mod collection;
|
||||
mod console;
|
||||
mod console_page;
|
||||
mod cull;
|
||||
mod datapacks_page;
|
||||
mod export_page;
|
||||
@@ -245,6 +246,7 @@ struct Launcher {
|
||||
world_packs: datapacks_page::WorldPacks,
|
||||
export: Option<export_page::ExportPanel>,
|
||||
importing: import_page::Importing,
|
||||
console: console_page::Console,
|
||||
/// The name the game made up for an offline player (`horizon-player.txt`), for the top bar.
|
||||
offline_name: Option<String>,
|
||||
/// The player's servers, for the sidebar until the Servers page has read them.
|
||||
@@ -411,6 +413,7 @@ impl Launcher {
|
||||
world_packs: datapacks_page::WorldPacks::default(),
|
||||
export: None,
|
||||
importing: Default::default(),
|
||||
console: Default::default(),
|
||||
offline_name: offline_name(),
|
||||
side_servers: horizon_launcher::servers::list(),
|
||||
art: art::Art::default(),
|
||||
@@ -2229,6 +2232,9 @@ impl Launcher {
|
||||
page = page.child(notice(e, &t));
|
||||
}
|
||||
page = page.child(rows);
|
||||
if let Some(console) = self.console_section(cx) {
|
||||
page = page.child(console);
|
||||
}
|
||||
if let Some(worlds) = self.worlds_section(cx) {
|
||||
page = page.child(worlds);
|
||||
}
|
||||
|
||||
@@ -38,10 +38,12 @@ pub(super) enum Field {
|
||||
/// Home's Multiplayer section's (`multiplayer_page.rs`).
|
||||
ServerName,
|
||||
ServerAddress,
|
||||
/// Home's Console's search (`console_page.rs`).
|
||||
ConsoleSearch,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
const ALL: [Field; 13] = [
|
||||
const ALL: [Field; 14] = [
|
||||
Field::Name,
|
||||
Field::Seed,
|
||||
Field::Players,
|
||||
@@ -55,6 +57,7 @@ impl Field {
|
||||
Field::InstanceGroup,
|
||||
Field::ServerName,
|
||||
Field::ServerAddress,
|
||||
Field::ConsoleSearch,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1031,7 +1034,7 @@ impl Launcher {
|
||||
Field::Port => self.save_port(),
|
||||
Field::Token => self.save_token(),
|
||||
Field::Email => self.invite_friend(),
|
||||
Field::InstanceName | Field::InstanceGroup => {}
|
||||
Field::InstanceName | Field::InstanceGroup | Field::ConsoleSearch => {}
|
||||
Field::ServerName | Field::ServerAddress => self.add_server(),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user