cli login works and hello-world spacetime module

This commit is contained in:
Sebastian Moser
2026-03-14 15:33:27 +01:00
parent d9e0e81e61
commit f1f53e3857
28 changed files with 1054 additions and 278 deletions

View File

@@ -18,10 +18,11 @@ reqwest = { version = "0.13.2", features = ["blocking", "json"] }
serde = "1.0.228"
serde_json = "1.0.149"
rusqlite = { version = "0.31", features = ["bundled"], optional = true }
dioxus = { version = "0.7.1", features = ["router", "fullstack", "web", "desktop", "mobile", "server", "ssr"], optional = true }
[features]
default = ["target-os"]
target-os = [ "clap", "mize/target-os", "rustyscript", "rusqlite" ]
target-os = [ "clap", "mize/target-os", "rustyscript", "rusqlite", "dioxus" ]
target-wasm = [ "mize/target-wasm" ]
clap = ["dep:clap"]

View File

@@ -0,0 +1,9 @@
use dioxus::prelude::*;
pub fn main() -> Element {
rsx! {
div {
h1 { "my dashbaord" }
}
}
}

View File

@@ -10,6 +10,8 @@ use mize::{mize_err, mize_part, Mize, MizeError, MizePart, MizeResult};
use crate::cli::CliPart;
use crate::habitica::Habitica;
mod dashboard;
#[mize_part]
#[derive(Default)]
pub struct C2vi {
@@ -40,7 +42,9 @@ impl C2vi {
}
pub fn c2vi(mize: &mut Mize) -> MizeResult<()> {
let storage_path = mize.get_config("c2vi.local_storage_path")?.to_string();
//let storage_path = mize.get_config("c2vi.local_storage_path")?.as_
let storage_path = "/home/me/work/app-data/ppc";
println!("storage_path: {}", storage_path);
let db_path = std::path::PathBuf::from(&storage_path).join("data.db");
let conn = Connection::open(&db_path)
.map_err(|e| mize_err!("Failed to open C2vi database at {:?}: {}", db_path, e))?;
@@ -84,6 +88,10 @@ fn setup_tables(conn: &Connection) -> MizeResult<()> {
}
fn register_subcommands(cli: &mut CliPart) {
cli.subcommand(
Command::new("c2vi-dash").about("Run the c2vi dashboard gui"),
|_matches, mut mize| Ok(dioxus::launch(dashboard::main)),
);
cli.subcommand(
Command::new("bed").about("Command to run when c2vi goes to bed"),
|_matches, mut mize| {
@@ -184,10 +192,7 @@ fn register_subcommands(cli: &mut CliPart) {
.map_err(|e| mize_err!("DB error: {}", e))?;
let rows = stmt
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
))
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})
.map_err(|e| mize_err!("DB error: {}", e))?;
for row in rows {
@@ -206,15 +211,17 @@ fn register_subcommands(cli: &mut CliPart) {
|matches, mut mize| {
let id = matches.get_one::<String>("id").unwrap();
let mut hab = mize.get_part_native::<Habitica>("habitica")?;
let data = hab.api_request(
reqwest::Method::GET,
format!("tasks/{}", id),
json!({}),
)?;
let data = hab.api_request(reqwest::Method::GET, format!("tasks/{}", id), json!({}))?;
if let Some(history) = data.get("history") {
println!("{}", serde_json::to_string_pretty(history).unwrap_or_default());
println!(
"{}",
serde_json::to_string_pretty(history).unwrap_or_default()
);
} else {
println!("{}", serde_json::to_string_pretty(&data).unwrap_or_default());
println!(
"{}",
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
Ok(())
},
@@ -250,9 +257,7 @@ fn get_or_create_log(conn: &Connection, date: &str) -> MizeResult<Value> {
let mut stmt = conn
.prepare("SELECT data FROM habitica_log WHERE date = ?1")
.map_err(|e| mize_err!("DB error: {}", e))?;
let result: Option<String> = stmt
.query_row(params![date], |row| row.get(0))
.ok();
let result: Option<String> = stmt.query_row(params![date], |row| row.get(0)).ok();
match result {
Some(data_str) => {
serde_json::from_str(&data_str).map_err(|e| mize_err!("JSON parse error: {}", e))
@@ -394,7 +399,10 @@ fn save_habitica_logs(mize: &mut Mize) -> MizeResult<()> {
if save_for_yesterday {
let existing_todos = data["todos_done"].as_array().unwrap();
let todo_id = todo["id"].as_str().unwrap_or("");
if existing_todos.iter().any(|t| t["id"].as_str() == Some(todo_id)) {
if existing_todos
.iter()
.any(|t| t["id"].as_str() == Some(todo_id))
{
continue;
}
}
@@ -419,10 +427,7 @@ fn save_habitica_logs(mize: &mut Mize) -> MizeResult<()> {
// If saving for yesterday but todo was completed today, also record it
if save_for_yesterday && date_completed == today_str {
println!("todo-done: {}", todo["text"].as_str().unwrap_or(""));
data["todos_done"]
.as_array_mut()
.unwrap()
.push(todo_entry);
data["todos_done"].as_array_mut().unwrap().push(todo_entry);
}
}
}
@@ -441,7 +446,9 @@ fn skip_habitica_todo(mize: &mut Mize, num: usize) -> MizeResult<()> {
hab.get_tasks("todos")?
};
let arr = todos.as_array().ok_or_else(|| mize_err!("Expected array of todos"))?;
let arr = todos
.as_array()
.ok_or_else(|| mize_err!("Expected array of todos"))?;
// Delete and log each skipped todo
for i in 0..num {
@@ -517,10 +524,8 @@ se 21:40
read
bed 22:10";
let tmp_file = std::env::temp_dir().join(format!(
"habitica-tasks-{}.md",
Utc::now().timestamp()
));
let tmp_file =
std::env::temp_dir().join(format!("habitica-tasks-{}.md", Utc::now().timestamp()));
std::fs::write(&tmp_file, initial_content)
.map_err(|e| mize_err!("Failed to write temp file: {}", e))?;
@@ -531,8 +536,8 @@ bed 22:10";
.map_err(|e| mize_err!("Failed to run nvim: {}", e))?;
// Read back and parse
let list_str =
std::fs::read_to_string(&tmp_file).map_err(|e| mize_err!("Failed to read temp file: {}", e))?;
let list_str = std::fs::read_to_string(&tmp_file)
.map_err(|e| mize_err!("Failed to read temp file: {}", e))?;
let _ = std::fs::remove_file(&tmp_file);
let tasks: Vec<&str> = list_str
@@ -577,17 +582,18 @@ fn dump_habitica_logs(mize: &mut Mize) -> MizeResult<()> {
.map_err(|e| mize_err!("DB error: {}", e))?;
let rows = stmt
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
))
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})
.map_err(|e| mize_err!("DB error: {}", e))?;
for row in rows {
let (date, data_str) = row.map_err(|e| mize_err!("DB error: {}", e))?;
let data: Value =
serde_json::from_str(&data_str).unwrap_or(json!({"parse_error": data_str}));
println!("{}: {}", date, serde_json::to_string_pretty(&data).unwrap_or_default());
println!(
"{}: {}",
date,
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
Ok(())
})

View File

@@ -2,10 +2,7 @@
"name": "@ppc/marts",
"imports": {},
"exports": {
".": "./index.ts",
"stub_deno": "./js/stub_deno.ts"
".": "./index.ts"
},
"tasks": {
"build": "deno bundle -o ./deno_dist/habitica.js ./habitica.ts && deno -A ./esbuild.config.mjs"
}
"tasks": {}
}

View File

@@ -1,2 +1,4 @@
export { task_obsidian_otask_parse } from "./task/obsidian-otask-parse";
export { c2vi_obsidian_canvas_patch } from "./c2vi/obsidian-canvas-patch";
export * from "./task/obsidian-otask-parse";
export * from "./c2vi/obsidian-canvas-patch";
export * from "./js/stub_deno";

View File

@@ -16,7 +16,7 @@ pub mod c2vi;
#[cfg(feature = "target-os")]
pub use c2vi::*;
#[cfg(feature = "target-os")]
pub mod js;
#[cfg(feature = "target-os")]
pub use js::*;
//#[cfg(feature = "target-os")]
//pub mod js;
//#[cfg(feature = "target-os")]
//pub use js::*;

View File

@@ -1,21 +1,15 @@
{
"name": "marts",
"name": "@ppc/marts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.15.1",
"dependencies": {
"@flowershow/remark-wiki-link": "^3.4.0",
"builtin-modules": "^5.0.0",
"esbuild": "^0.27.3",
"mdast": "^3.0.0",
"obsidian": "^1.12.2",
"obsidian": "^1.12.3",
"remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",

View File

@@ -1,4 +1,3 @@
import { id, i, init, InstaQLEntity } from "@instantdb/react";
import remarkParse from "remark-parse";
import remarkStringify from "remark-stringify";
import { unified } from "unified";
@@ -7,6 +6,7 @@ import { Root, Content, Heading, List, ListItem, Text } from "mdast";
import remarkFrontmatter from "remark-frontmatter";
import remarkGfm from "remark-gfm";
import wikiLinkPlugin from "@flowershow/remark-wiki-link";
import { TFile } from "obsidian";
const OTASK_PROP_NAMES = ["short", "outcome", "priority"];
const ACTION_PROP_NAMES = [];
@@ -77,7 +77,7 @@ async function full_parse() {
render_sub0_file(OTASK_LIST);
}
let OTASK_PARSE_QUEUE = [];
let OTASK_PARSE_QUEUE: any = [];
let OTASK_LIST = [];
let DBG = false;
@@ -201,130 +201,37 @@ async function replaceHeading(
}
async function otasks_from_list_item(listItem, otask_path, priority = 0) {
// the main otask this listItem is about
let otask = {
description: [],
actions: [],
path: [],
priority,
};
dbg("SystemC2: otasks_from_list_item", listItem, otask_path);
try {
// the main otask this listItem is about
let otask = {
description: [],
actions: [],
path: [],
priority,
};
dbg("SystemC2: otasks_from_list_item", listItem, otask_path);
if (!listItem.children[0].type === "paragraph") {
dbg(
"listItem[0] of a otask item is not a paragraph... the otask:",
listItem,
);
return null;
}
let longName = nodeToString(listItem.children[0]);
dbg("longName:", longName);
// check for [[anotherotask]], call otasks_from_file, return those
const match = longName.match(/\[\[([^\]]+)\]\]/);
if (match) {
const file = app.metadataCache.getFirstLinkpathDest(match[1], "");
if (file) {
const metadata = app.metadataCache.getFileCache(file);
if (metadata?.frontmatter?.tags?.includes("t/otask")) {
queue_otasks_from_file(file, otask_path);
return null;
} else {
dbg(
"SystemC2: listItem with Link to '",
match[1],
"', which is not an otask",
longName,
);
}
if (!listItem.children[0].type === "paragraph") {
dbg(
"listItem[0] of a otask item is not a paragraph... the otask:",
listItem,
);
return null;
}
}
let longName = nodeToString(listItem.children[0]);
//check for [x] and remove from name
if (longName.startsWith("[ ") || longName.startsWith("[x")) {
longName = longName.slice(4);
}
dbg("longName:", longName);
//check for "ot:" and remove from name
if (longName.startsWith("ot:")) {
longName = longName.slice(4);
}
otask.longName = longName;
otask.short = longName;
otask.path = otask_path;
let new_otask_path = [...otask_path, otask.short];
// go through sub list items
// - if it's a prop for the otask... handle that
// - if it's an "ac:" handle that
// - if it's "ot: " handle as another otask -> recursive call
// - if it's "[ ]" handle as another otask -> recursive call
// - if it's a link to a otask file... handle as another otask -> call otasks_from_file()
// - else add it as description item list to otask
if (!listItem.children || listItem.children.length < 2) {
return otask;
}
// add content as text to otask
if (otask.longName == "hosting updates") {
console.log("listItem... ", listItem.children[1]);
let hii = REMARK.stringify(listItem.children[1]);
console.log("text...", hii);
}
let content_text = REMARK.stringify(listItem.children[1]);
otask.content = content_text;
for (const subListItem of listItem.children[1].children) {
let text = nodeToString(subListItem.children[0]);
// check prop
if (check_otask_prop_from_list_item(subListItem, otask)) {
new_otask_path = [...otask_path, otask.short]; // have to redo it here, in case short changed from aprop
continue; // don't do any other processing on this sub-listItem
}
// remove "[ ]"
if (text.startsWith("[ ") || text.startsWith("[x")) {
text = text.slice(4);
}
// check ac
if (text.startsWith("ac:")) {
otask.actions = [
...otask.actions,
action_from_list_item(subListItem, new_otask_path, otask.priority),
];
continue; // don't do any other processing on this sub-listItem
}
// check ot
if (text.startsWith("ot:")) {
queue_otasks_from_list_item(subListItem, new_otask_path, otask.priority);
continue; // don't do any other processing on this sub-listItem
}
// check [ ]
if (text.startsWith("[ ] ") || text.startsWith("[x] ")) {
queue_otasks_from_list_item(subListItem, new_otask_path, otask.priority);
continue; // don't do any other processing on this sub-listItem
}
// check link to otask file
const match = text.match(/\[\[([^\]]+)\]\]/);
// check for [[anotherotask]], call otasks_from_file, return those
const match = longName.match(/\[\[([^\]]+)\]\]/);
if (match) {
const file = app.metadataCache.getFirstLinkpathDest(match[1], "");
if (file) {
const metadata = app.metadataCache.getFileCache(file);
if (metadata?.frontmatter?.tags?.includes("t/otask")) {
queue_otasks_from_file(file, new_otask_path, otask.priority);
continue;
queue_otasks_from_file(file, otask_path);
return null;
} else {
dbg(
"SystemC2: listItem with Link to '",
@@ -333,83 +240,192 @@ async function otasks_from_list_item(listItem, otask_path, priority = 0) {
longName,
);
}
}
}
//check for [x] and remove from name
if (longName.startsWith("[ ") || longName.startsWith("[x")) {
longName = longName.slice(4);
}
//check for "ot:" and remove from name
if (longName.startsWith("ot:")) {
longName = longName.slice(4);
}
otask.longName = longName;
otask.short = longName;
otask.path = otask_path;
let new_otask_path = [...otask_path, otask.short];
// go through sub list items
// - if it's a prop for the otask... handle that
// - if it's an "ac:" handle that
// - if it's "ot: " handle as another otask -> recursive call
// - if it's "[ ]" handle as another otask -> recursive call
// - if it's a link to a otask file... handle as another otask -> call otasks_from_file()
// - else add it as description item list to otask
if (!listItem.children || listItem.children.length < 2) {
return otask;
}
// add content as text to otask
if (otask.longName == "hosting updates") {
console.log("listItem... ", listItem.children[1]);
let hii = REMARK.stringify(listItem.children[1]);
console.log("text...", hii);
}
let content_text = REMARK.stringify(listItem.children[1]);
otask.content = content_text;
for (const subListItem of listItem.children[1].children) {
let text = nodeToString(subListItem.children[0]);
// check prop
if (check_otask_prop_from_list_item(subListItem, otask)) {
new_otask_path = [...otask_path, otask.short]; // have to redo it here, in case short changed from aprop
continue; // don't do any other processing on this sub-listItem
}
// remove "[ ]"
if (text.startsWith("[ ") || text.startsWith("[x")) {
text = text.slice(4);
}
// check ac
if (text.startsWith("ac:")) {
otask.actions = [
...otask.actions,
action_from_list_item(subListItem, new_otask_path, otask.priority),
];
continue; // don't do any other processing on this sub-listItem
}
// check ot
if (text.startsWith("ot:")) {
queue_otasks_from_list_item(
subListItem,
new_otask_path,
otask.priority,
);
continue; // don't do any other processing on this sub-listItem
}
// check [ ]
if (text.startsWith("[ ] ") || text.startsWith("[x] ")) {
queue_otasks_from_list_item(
subListItem,
new_otask_path,
otask.priority,
);
continue; // don't do any other processing on this sub-listItem
}
// check link to otask file
const match = text.match(/\[\[([^\]]+)\]\]/);
if (match) {
const file = app.metadataCache.getFirstLinkpathDest(match[1], "");
if (file) {
const metadata = app.metadataCache.getFileCache(file);
if (metadata?.frontmatter?.tags?.includes("t/otask")) {
queue_otasks_from_file(file, new_otask_path, otask.priority);
continue;
} else {
dbg(
"SystemC2: listItem with Link to '",
match[1],
"', which is not an otask",
longName,
);
}
continue; // don't do any other processing on this sub-listItem
}
}
// add as description
const desc = REMARK.stringify(subListItem);
otask.description.push(desc);
}
return otask;
} catch (error) {
console.log("failed to parse list item:", listItem);
}
}
async function otasks_from_file(file: TFile, otask_path, priority = 0) {
try {
dbg("SystemC2: otasks_from_file", file, otask_path);
// the main otask this file is about
let otask = {
description: [],
actions: [],
path: [],
priority,
is_file: true,
};
otask.longName = file.basename;
otask.short = otask.longName;
otask.path = otask_path;
let new_otask_path = [...otask_path, otask.short];
const content = await app.vault.read(file);
// parse listItems at the top... for props
const topListItems = getListItemsBeforeFirstHeading(content);
for (const topListItem of topListItems) {
const text = nodeToString(topListItem);
// check for prop
if (check_otask_prop_from_list_item(topListItem, otask)) {
new_otask_path = [...otask_path, otask.short];
continue; // don't do any other processing on this sub-listItem
}
}
// add as description
const desc = REMARK.stringify(subListItem);
otask.description.push(desc);
}
// parse all the sub sections
const SUB_COUNT = 10;
for (let sub_number = 0; sub_number < SUB_COUNT; sub_number++) {
let listItems = await getListUnderHeading(content, "sub" + sub_number);
return otask;
}
async function otasks_from_file(file: TFile, otask_path, priority = 0) {
dbg("SystemC2: otasks_from_file", file, otask_path);
// the main otask this file is about
let otask = {
description: [],
actions: [],
path: [],
priority,
is_file: true,
};
otask.longName = file.basename;
otask.short = otask.longName;
otask.path = otask_path;
let new_otask_path = [...otask_path, otask.short];
const content = await app.vault.read(file);
// parse listItems at the top... for props
const topListItems = getListItemsBeforeFirstHeading(content);
for (const topListItem of topListItems) {
const text = nodeToString(topListItem);
// check for prop
if (check_otask_prop_from_list_item(topListItem, otask)) {
new_otask_path = [...otask_path, otask.short];
continue; // don't do any other processing on this sub-listItem
}
}
// parse all the sub sections
const SUB_COUNT = 10;
for (let sub_number = 0; sub_number < SUB_COUNT; sub_number++) {
let listItems = await getListUnderHeading(content, "sub" + sub_number);
// "sub" without a number should have priority 5
if (sub_number == 5) {
listItems = listItems.concat(await getListUnderHeading(content, "sub"));
}
//dbg(`sub section ${sub_number} has items:`, listItems)
for (const listItem of listItems) {
// check if listItem is an action...
let text = nodeToString(listItem.children[0]);
if (
text.startsWith("ac:") ||
text.startsWith("[ ] ac:") ||
text.startsWith("[x] ac:")
) {
const action = action_from_list_item(listItem, otask_path);
otask.actions.push(action);
// "sub" without a number should have priority 5
if (sub_number == 5) {
listItems = listItems.concat(await getListUnderHeading(content, "sub"));
}
queue_otasks_from_list_item(
listItem,
new_otask_path,
otask.priority + sub_number,
);
}
}
//dbg(`sub section ${sub_number} has items:`, listItems)
return otask;
for (const listItem of listItems) {
// check if listItem is an action...
let text = nodeToString(listItem.children[0]);
if (
text.startsWith("ac:") ||
text.startsWith("[ ] ac:") ||
text.startsWith("[x] ac:")
) {
const action = action_from_list_item(listItem, otask_path);
otask.actions.push(action);
}
queue_otasks_from_list_item(
listItem,
new_otask_path,
otask.priority + sub_number,
);
}
}
return otask;
} catch (error) {
console.log("failed to parse file: ", file.path);
}
}
function action_from_list_item(listItem, otask_path) {