Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
louis030195 committed Sep 7, 2024
1 parent 87b24d3 commit 9566362
Show file tree
Hide file tree
Showing 15 changed files with 600 additions and 168 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ members = [
"screenpipe-audio",
"screenpipe-server",
"screenpipe-integrations",

]
exclude = [
"examples/apps/screenpipe-app-tauri/src-tauri",

]
resolver = "2"

Expand Down
66 changes: 60 additions & 6 deletions examples/apps/screenpipe-app-tauri/components/pipe-store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,57 @@ const PipeDialog: React.FC = () => {
const [newRepoUrl, setNewRepoUrl] = useState("");
const { pipes, loading, error, addCustomPipe } = usePipes([
// "https://github.com/different-ai/file-organizer-2000",
"https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-tagging-activity",
// "https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-tagging-activity",
]);
const [selectedPipe, setSelectedPipe] = useState<Pipe | null>(null);
const { settings, updateSettings } = useSettings();

const handleToggleEnabled = async (pipe: Pipe) => {
try {
if (!pipe.enabled) {
pipe.enabled = true;
const updatedInstalledPipes = [...settings.installedPipes, pipe];
console.log("updated installed pipes", updatedInstalledPipes);
await updateSettings({ installedPipes: updatedInstalledPipes });

toast({
title: "Enabling pipe",
description: "This may take a few moments...",
});

// Kill existing screenpipe processes
await invoke("kill_all_sreenpipes");

// Spawn new screenpipe process with the pipe
await invoke("spawn_screenpipe");

await new Promise((resolve) => setTimeout(resolve, 1000));

toast({
title: "Pipe enabled successfully",
description: "Screenpipe has been restarted with the new pipe.",
});
} else {
pipe.enabled = false;
const updatedInstalledPipes = [...settings.installedPipes, pipe];
console.log("updated installed pipes", updatedInstalledPipes);
await updateSettings({ installedPipes: updatedInstalledPipes });

toast({
title: "Pipe disabled",
description: "The pipe has been disabled.",
});
}
} catch (error) {
console.error("Failed to toggle pipe:", error);
toast({
title: "Error toggling pipe",
description: "Please try again or check the logs for more information.",
variant: "destructive",
});
}
};

const handleAddOwnPipe = async () => {
if (newRepoUrl) {
try {
Expand Down Expand Up @@ -114,10 +160,10 @@ const PipeDialog: React.FC = () => {
await updateSettings({ installedPipes: updatedInstalledPipes });

// Kill existing screenpipe processes
await invoke("kill_all_sreenpipes");
// await invoke("kill_all_sreenpipes");

// Spawn new screenpipe process with the pipe
await invoke("spawn_screenpipe");
// await invoke("spawn_screenpipe");

await new Promise((resolve) => setTimeout(resolve, 1000));

Expand Down Expand Up @@ -231,9 +277,17 @@ const PipeDialog: React.FC = () => {
<p className="mb-4">{selectedPipe.description}</p>
<div className="flex space-x-2 mb-4">
{isInstalled ? (
<Button onClick={() => handleUninstall(selectedPipe)}>
Uninstall
</Button>
<>
<Button onClick={() => handleUninstall(selectedPipe)}>
Uninstall
</Button>
<Button
onClick={() => handleToggleEnabled(selectedPipe)}
variant={selectedPipe.enabled ? "default" : "outline"}
>
{selectedPipe.enabled ? "Disable" : "Enable"}
</Button>
</>
) : (
<Button onClick={() => handleInstall(selectedPipe)}>Install</Button>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function useHealthCheck() {
// console.log("setting health", data);
setHealth(data);
} catch (error) {
console.error("Failed to fetch health status:", error);
// console.error("Failed to fetch health status:", error);
setHealth({
last_frame_timestamp: null,
last_audio_timestamp: null,
Expand Down
27 changes: 22 additions & 5 deletions examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState, useEffect } from "react";

export type Pipe = {
enabled: boolean;
name: string;
downloads: number;
version: string;
Expand Down Expand Up @@ -143,6 +144,7 @@ export const usePipes = (initialRepoUrls: string[]) => {
const [repoUrls, setRepoUrls] = useState<string[]>(initialRepoUrls);

const fetchPipeData = async (repoUrl: string): Promise<Pipe | null> => {
console.log("fetchPipeData", repoUrl);
try {
const urlParts = repoUrl.split("/");
const isSubdir = urlParts.length > 5;
Expand All @@ -151,7 +153,13 @@ export const usePipes = (initialRepoUrls: string[]) => {
const repoFullName = `${repoOwner}/${repoName}`;
const branch = isSubdir ? urlParts[6] : "main";
const subDir = isSubdir ? urlParts.slice(7).join("/") : "";

console.log("urlParts", urlParts);
console.log("isSubdir", isSubdir);
console.log("repoFullName", repoFullName);
console.log("branch", branch);
console.log("subDir", subDir);
console.log("repoOwner", repoOwner);
console.log("repoName", repoName);
console.log(`Fetching repo data for ${repoFullName}`);
const repoData = await fetchWithCache(
`https://api.github.com/repos/${repoFullName}`
Expand All @@ -168,10 +176,11 @@ export const usePipes = (initialRepoUrls: string[]) => {
branch,
subDir
);
console.log("contents", contents);
if (!contents || !Array.isArray(contents)) return null;

const jsFiles = contents.filter((file: any) =>
file.name.endsWith(".js")
const jsFiles = contents.filter(
(file: any) => file.name.endsWith(".js") || file.name.endsWith(".ts")
);
const hasJsFile = jsFiles.length > 0;
const readmeFile = contents.find(
Expand All @@ -187,17 +196,23 @@ export const usePipes = (initialRepoUrls: string[]) => {
);

const mainFile =
jsFiles.find((file: any) => file.name === "index.js") || jsFiles[0];
jsFiles.find((file: any) => file.name === "pipe.ts") || jsFiles[0];
const mainFileUrl = mainFile
? `https://raw.githubusercontent.com/${repoFullName}/${branch}/${subDir}/${mainFile.name}`
: undefined;

console.log(`Fetching latest release for ${repoFullName}`);

console.log(`Fetching pipe config for ${repoFullName}/${subDir}`);
pipeConfig = await fetchPipeConfig(repoFullName, branch, subDir);
pipeConfig = await fetchPipeConfig(repoFullName, branch, subDir).catch(
(error) => {
console.warn("Error fetching pipe config:", error);
return undefined;
}
);

return {
enabled: false,
name: subDir.split("/").pop() || repoData.name,
downloads: repoData.stargazers_count,
version: await fetchLatestRelease(repoFullName),
Expand All @@ -223,6 +238,7 @@ export const usePipes = (initialRepoUrls: string[]) => {
pipeConfig = await fetchPipeConfig(repoFullName, branch, "");

return {
enabled: false,
name: repoData.name,
downloads: repoData.stargazers_count,
version,
Expand Down Expand Up @@ -289,6 +305,7 @@ export const usePipes = (initialRepoUrls: string[]) => {

try {
const newPipe = await fetchPipeData(newRepoUrl);
console.log("newPipe", newPipe);
if (newPipe) {
// Check if a pipe with the same name already exists
if (pipes.some((pipe) => pipe.name === newPipe.name)) {
Expand Down

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// }

use serde_json::Value;
use tracing::info;

#[tauri::command]
pub fn open_screen_capture_preferences() {
Expand Down Expand Up @@ -50,9 +51,11 @@ pub fn reset_microphone_permissions() {

#[tauri::command]
pub async fn load_pipe_config(pipe_name: String) -> Result<Value, String> {
info!("Loading pipe config for {}", pipe_name);
let default_path = dirs::home_dir().unwrap().join(".screenpipe").join("pipes");

let config_path = default_path.join(pipe_name);
let config_path = default_path.join(pipe_name).join("pipe.json");
info!("Config path: {}", config_path.to_string_lossy());
let config_content = tokio::fs::read_to_string(config_path)
.await
.map_err(|e| format!("Failed to read pipe config: {}", e))?;
Expand All @@ -63,8 +66,10 @@ pub async fn load_pipe_config(pipe_name: String) -> Result<Value, String> {

#[tauri::command]
pub async fn save_pipe_config(pipe_name: String, config: Value) -> Result<(), String> {
info!("Saving pipe config for {}", pipe_name);
let default_path = dirs::home_dir().unwrap().join(".screenpipe").join("pipes");
let config_path = default_path.join(pipe_name);
let config_path = default_path.join(pipe_name).join("pipe.json");
info!("Config path: {}", config_path.to_string_lossy());
let config_content = serde_json::to_string_pretty(&config)
.map_err(|e| format!("Failed to serialize pipe config: {}", e))?;
tokio::fs::write(config_path, config_content)
Expand Down
16 changes: 13 additions & 3 deletions examples/typescript/pipe-stream-ocr-text/pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ async function writeToMarkdown(data) {

async function runOCRTracker() {
console.log("Starting OCR Tracker");
// wait 2 seocnds
await new Promise((resolve) => setTimeout(resolve, 1000));

console.log(pipe);
await pipe.loadConfig();
INTERVAL = pipe.config.interval * 1000;
console.log("INTERVAL", INTERVAL);

while (true) {
try {
Expand All @@ -43,16 +50,19 @@ async function runOCRTracker() {
} catch (error) {
console.error("Error in OCR tracking:", error);
}

await new Promise((resolve) => setTimeout(resolve, INTERVAL));
// const isEnabled = await pipe.isEnabled();
// if (!isEnabled) {
// console.log("pipe is disabled");
// break;
// }
}
}

// Self-invoking async function to run the OCR tracker
(async () => {
try {
console.log(pipe);
await pipe.loadConfig();
INTERVAL = pipe.config.interval * 1000;
await runOCRTracker();
} catch (error) {
console.error("Fatal error in OCR Tracker:", error);
Expand Down
2 changes: 2 additions & 0 deletions screenpipe-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ url = "2.4.0"
tracing = { workspace = true }
tracing-subscriber = { workspace = true }

dirs = "5.0.1"

[features]
pipes = ["dep:deno_core", "dep:deno_ast"]

Expand Down
17 changes: 14 additions & 3 deletions screenpipe-core/src/deno/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,18 +110,29 @@ const pipe = {
loadConfig: async () => {
try {
console.log("Attempting to load pipe.json");
const configContent = await ops.op_read_file("pipe.json");
const configContent = await ops.op_read_file(process.env.SCREENPIPE_DIR + "/pipes/" + globalThis.metadata.id + "/pipe.json");
console.log("pipe.json content:", configContent);
const parsedConfig = JSON.parse(configContent);
console.log("Parsed config:", parsedConfig);
pipe.config = parsedConfig; // Set the config property
return parsedConfig;

// Process the fields and set the config values
const config = {};
parsedConfig.fields.forEach(field => {
config[field.name] = field.value !== undefined ? field.value : field.default;
});

pipe.config = config; // Set the processed config
console.log("Processed config:", config);
return config;
} catch (error) {
console.error("Error loading pipe.json:", error);
pipe.config = {}; // Set an empty object if loading fails
return {};
}
},
// isEnabled: async () => {
// return ops.op_is_enabled();
// }
};

globalThis.setTimeout = (callback, delay) => {
Expand Down
Loading

0 comments on commit 9566362

Please sign in to comment.