Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

refactor: make it better (#1167)

tribhuwanc9eaa7cf2c54
diff --git a/pipes/reddit-auto-posts/app/api/pipeline/route.ts b/pipes/reddit-auto-posts/app/api/pipeline/route.ts
index e5136ddb8..460d5e22b 100644
--- a/pipes/reddit-auto-posts/app/api/pipeline/route.ts
+++ b/pipes/reddit-auto-posts/app/api/pipeline/route.ts
@@ -1,9 +1,8 @@
"use server";
-// requestion on this route will send mail (use it only in cron)
import fs from "node:fs";
import path from "node:path";
import { DailyLog } from "@/lib/types";
-import { NextResponse } from "next/server";
+import { NextResponse, NextRequest } from "next/server";
import { pipe } from "@screenpipe/js";
import sendEmail from "@/lib/actions/send-email";
import generateDailyLog from "@/lib/actions/generate-log";
@@ -46,7 +45,7 @@ async function retry(fn: any, retries = 3, delay = 5000) {
}
}
-export async function GET() {
+export async function GET(request: NextRequest) {
try {
console.log("starting daily log pipeline");
const settingsManager = pipe.settings;
@@ -89,6 +88,8 @@ export async function GET() {
const fileContent = fs.readFileSync(pipeConfigPath, 'utf-8');
const configData = JSON.parse(fileContent);
+ const url = new URL(request.url);
+ const fromButton = url.searchParams.get("fromButton");
if (emailEnabled && !configData?.welcomeEmailSent) {
const welcomeEmail = `
@@ -162,7 +163,9 @@ export async function GET() {
);
console.log("reddit questions:", redditQuestions);
- if (emailEnabled && redditQuestions) {
+ // only send mail in those request that are made from cron jobs,
+ // cz at that time user, is not seeing the frontend of this pipe
+ if (emailEnabled && redditQuestions && !fromButton) {
try {
await sendEmail(
emailAddress!,
diff --git a/pipes/reddit-auto-posts/app/api/test-pipeline/route.ts b/pipes/reddit-auto-posts/app/api/test-pipeline/route.ts
deleted file mode 100644
index 98cc8d3f8..000000000
--- a/pipes/reddit-auto-posts/app/api/test-pipeline/route.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-"use server";
-// this route is only for getting reddit post reccomendation, explicitly by clickin the
-// `generate button` it won't send any mails
-import fs from "node:fs";
-import path from "node:path";
-import { NextResponse } from "next/server";
-import { pipe } from "@screenpipe/js";
-import sendEmail from "@/lib/actions/send-email";
-import generateRedditQuestions from "@/lib/actions/generate-reddit-question";
-
-async function retry(fn: any, retries = 3, delay = 5000) {
- for (let i = 0; i < retries; i++) {
- try {
- const result = await fn();
- if (result){
- return result;
- }
- } catch (error) {
- console.log(`Screenpipe query failed, retry, attempt: ${i + 1}`)
- if (i === retries - 1) throw error;
- await new Promise(res => setTimeout(res, delay));
- }
- }
-}
-
-export async function GET() {
- try {
- console.log("starting daily log pipeline");
- const settingsManager = pipe.settings;
- const redditSettings = await pipe.settings.getNamespaceSettings("reddit-auto-posts");
-
- if (!settingsManager) {
- return NextResponse.json(
- { error: `no setting manager found` },
- { status: 500 }
- );
- }
-
- const rawSettings = await settingsManager.getAll();
- const aiModel = rawSettings?.aiModel;
- const aiUrl = rawSettings?.aiUrl;
- const openaiApiKey = rawSettings?.openaiApiKey;
- const aiProvider = rawSettings?.aiProviderType;
- const userToken = rawSettings?.user?.token;
-
- const interval = redditSettings?.interval * 1000 || 60000;
- const emailAddress = redditSettings?.emailAddress;
- const emailPassword = redditSettings?.emailPassword;
- const customPrompt = redditSettings?.customPrompt!;
- const windowName = redditSettings?.windowName || "";
- const pageSize = redditSettings?.pageSize;
- const contentType = redditSettings?.contentType || "ocr";
- const emailEnabled = !!(emailAddress && emailPassword);
- const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();
- const logsDir = path.join(screenpipeDir, "pipes", "reddit-auto-posts", "logs");
-
- try {
- fs.mkdirSync(logsDir);
- } catch (_error) {
- console.warn("creating logs directory, probably already exists:", logsDir);
- }
-
- const now = new Date();
- const startTime = new Date(now.getTime() - interval);
- const screenData = await retry(() => pipe.queryScreenpipe({
- startTime: startTime.toISOString(),
- endTime: now.toISOString(),
- windowName: windowName,
- limit: pageSize,
- contentType: contentType,
- }));
-
- if (screenData && screenData.data && screenData.data.length > 0) {
- if (aiProvider === "screenpipe-cloud" && !userToken) {
- return NextResponse.json(
- { error: `seems like you don't have screenpipe-cloud access :(` },
- { status: 500 }
- );
- }
- const redditQuestions = await generateRedditQuestions(
- screenData.data,
- customPrompt,
- aiProvider,
- aiModel,
- aiUrl,
- openaiApiKey,
- userToken as string,
- );
- console.log("reddit questions:", redditQuestions);
-
- if (emailEnabled && redditQuestions) {
- try {
- await sendEmail(
- emailAddress!,
- emailPassword!,
- "reddit questions",
- redditQuestions
- );
- } catch(error) {
- return NextResponse.json(
- { error: `error in sending mail ${error}` },
- { status: 500 }
- );
- }
- } else {
- console.log("Failed to get reddit questions!!")
- }
-
- if (redditQuestions) {
- try {
- console.log("Sending screenpipe inbox notification");
- await pipe.inbox.send({
- title: "reddit questions",
- body: redditQuestions,
- });
- } catch(error) {
- return NextResponse.json(
- { error: `error in sending inbox notification ${error}` },
- { status: 500 }
- );
- }
- } else {
- console.log("Failed to get reddit questions!!")
- }
-
- try {
- console.log("Sending desktop notification");
- await pipe.sendDesktopNotification({
- badge: "reddit questions",
- body: "just sent you some reddit questions",
- });
- } catch (error) {
- return NextResponse.json(
- { error: `error in sending desktop notification ${error}` },
- { status: 500 }
- );
- }
- return NextResponse.json(
- { message: "pipe executed successfully", suggestedQuestions: redditQuestions },
- { status: 200 }
- );
- } else {
- return NextResponse.json(
- { message: "query is empty please wait & and try again!" },
- { status: 200 }
- );
- };
- } catch (error) {
- console.error("error in GET handler:", error);
- return NextResponse.json(
- { error: `${error}` },
- { status: 400 }
- );
- }
-}
diff --git a/pipes/reddit-auto-posts/bun.lockb b/pipes/reddit-auto-posts/bun.lockb
index cd37e0f4c..7f986ac11 100644
Binary files a/pipes/reddit-auto-posts/bun.lockb and b/pipes/reddit-auto-posts/bun.lockb differ
diff --git a/pipes/reddit-auto-posts/components/pipe.tsx b/pipes/reddit-auto-posts/components/pipe.tsx
index 340e2a966..6404956a5 100644
--- a/pipes/reddit-auto-posts/components/pipe.tsx
+++ b/pipes/reddit-auto-posts/components/pipe.tsx
@@ -1,5 +1,5 @@
"use client";
-import React, { useState } from "react";
+import React, { useState, useEffect } from "react";
import { useSettings } from "@/lib/hooks/use-settings";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -37,6 +37,9 @@ const Pipe: React.FC = () => {
const [lastLog, setLastLog] = useState<any>(null);
const [windowName, setWindowName] = useState("");
const [contentType, setContentType] = useState("");
+ const [frequency, setFrequency] = useState("");
+ const [emailTime, setEmailTime] = useState("");
+ const [hourlyRepetance, setHourlyRepetance] = useState("1");
const aiDisabled = settings.aiProviderType === "screenpipe-cloud" && !settings.user.token;
@@ -55,10 +58,22 @@ const Pipe: React.FC = () => {
- Ensure posts are well-structured, starting with a clear title, followed by a detailed body, and end with relevant subreddit recommendations.
`;
+ // little hack :D
+ useEffect(() => {
+ if (!contentType || !frequency) {
+ const timer = setTimeout(() => {
+ setContentType(settings.customSettings?.["reddit-auto-posts"]?.contentType || "all");
+ setFrequency(settings.customSettings?.["reddit-auto-posts"]?.summaryFrequency || "daily")
+ setEmailTime(settings.customSettings?.["reddit-auto-posts"]?.emailTime || "11:00")
+ }, 1000);
+ return () => clearTimeout(timer);
+ }
+ }, [settings, contentType, frequency]);
+
const testPipe = async () => {
setLoading(true);
try {
- const res = await fetch("/api/test-pipeline");
+ const res = await fetch("/api/pipeline?fromButton=true");
if (res.status === 500 || res.status === 400) {
toast({
title: "failed to intialize daily log",
@@ -92,18 +107,21 @@ const Pipe: React.FC = () => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
+ let finalFrequency = frequency;
+ if(frequency.startsWith("hourly")) {
+ finalFrequency = `hourly:${hourlyRepetance}`;
+ }
const newRedditSettings = {
interval: parseInt(formData.get("interval") as string),
pageSize: parseInt(formData.get("pageSize") as string),
- summaryFrequency: formData.get("summaryFrequency") as string,
+ summaryFrequency: finalFrequency || formData.get("summaryFrequency") as string,
emailAddress: formData.get("emailAddress") as string,
emailPassword: formData.get("emailPassword") as string,
- emailTime: (formData).get("emailTime") as string,
+ emailTime: emailTime || (formData).get("emailTime") as string,
customPrompt: formData.get("customPrompt") as string,
dailylogPrompt: formData.get("dailylogPrompt") as string,
windowName: formData.get("windowName") as string || windowName,
contentType: contentType as string,
- lastIntervalChangeTime: new Date().toISOString()
}
try {
@@ -154,24 +172,54 @@ const Pipe: React.FC = () => {
<Label htmlFor="summaryFrequency">summary frequency </Label>
<span className="text-[13px] text-muted-foreground">&nbsp;&nbsp;email frequency: &apos;daily&apos; at email time or &apos;hourly:X&apos;(e.g.
&apos;hourly:4&apos; for every 4 hrs).</span>
- <Input
- id="summaryFrequency"
+ <Select
name="summaryFrequency"
- defaultValue={settings.customSettings?.["reddit-auto-posts"]?.summaryFrequency || "daily"}
- placeholder="frequency of summary emails: 'daily' for once a day at email time, or 'hourly:X' for every X hours (e.g., 'hourly:4' for every 4 hours)"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="emailTime">email time </Label>
- <span className="text-[13px] text-muted-foreground">&nbsp;&nbsp;time to send daily summary email (used only if summary frequency is &apos;daily&apos;)</span>
- <Input
- id="emailTime"
- name="emailTime"
- type="time"
- defaultValue={settings.customSettings?.["reddit-auto-posts"]?.emailTime || "11:00"}
- placeholder="time to send daily summary email (used only if summaryFrequency is 'daily')"
- />
+ value={frequency}
+ onValueChange={(v) => { setFrequency(v)}}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="select the summary frequency type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="daily">daily</SelectItem>
+ <SelectItem value="hourly">hourly</SelectItem>
+ </SelectContent>
+ </Select>
</div>
+ {frequency === "daily" && (
+ <div className="space-y-2">
+ <Label htmlFor="emailTime">email time</Label>
+ <span className="text-[13px] text-muted-foreground">&nbsp;&nbsp;time to send daily summary email (used only if summary frequency is &apos;daily&apos;)</span>
+ <Input
+ id="emailTime"
+ name="emailTime"
+ type="time"
+ value={emailTime}
+ onChange={(e) => {
+ setEmailTime(e.target.value);
+ }}
+ placeholder="time to send daily summary email (used only if summaryFrequency is 'daily')"
+ />
+ </div>
+ )}
+ {frequency.startsWith("hourly") && (
+ <div className="space-y-2">
+ <Label htmlFor="hourlyRepetance">hourly repetance</Label>
+ <span className="text-[13px] text-muted-foreground">
+ &nbsp;&nbsp;specify the number of hours for hourly repetition (e.g., &apos;4&apos; for every 4 hours)
+ </span>
+ <Input
+ id="hourlyRepetance"
+ name="hourlyRepetance"
+ type="number"
+ min="1"
+ max="24"
+ value={hourlyRepetance}
+ placeholder="specify the number of hours for hourly repetition"
+ onChange={(e) => setHourlyRepetance(e.target.value)}
+ />
+ </div>
+ )}
<div className="space-y-2">
<Label htmlFor="emailAddress">email address </Label>
<span className="text-[13px] text-muted-foreground">&nbsp;&nbsp;email address to send the daily summary to: (eg. [email protected])</span>
@@ -216,7 +264,7 @@ const Pipe: React.FC = () => {
<span className="text-[13px] text-muted-foreground !font-normal">&nbsp;&nbsp;type of content to analyze &apos;ocr&apos;, &apos;audio&apos;, or &apos;all&apos;. &apos;ocr&apos; is recommended due to more content</span>
</Label>
<Select
- defaultValue={settings.customSettings?.["reddit-auto-posts"]?.contentType || "all"}
+ value={contentType}
onValueChange={(value) => {
setContentType(value);
}}
@@ -225,9 +273,9 @@ const Pipe: React.FC = () => {
<SelectValue placeholder="select content type" />
</SelectTrigger>
<SelectContent>
- <SelectItem value="all">all</SelectItem>
- <SelectItem value="ocr">ocr</SelectItem>
- <SelectItem value="audio">audio</SelectItem>
+ <SelectItem textValue="all" value="all">all</SelectItem>
+ <SelectItem textValue="ocr" value="ocr">ocr</SelectItem>
+ <SelectItem textValue="audio" value="audio">audio</SelectItem>
{isMacOS() && <SelectItem value="ui">ui</SelectItem>}
</SelectContent>
</Select>
diff --git a/pipes/reddit-auto-posts/package.json b/pipes/reddit-auto-posts/package.json
index 804b3f696..57ab7753d 100644
--- a/pipes/reddit-auto-posts/package.json
+++ b/pipes/reddit-auto-posts/package.json
@@ -10,12 +10,12 @@
},
"dependencies": {
"@radix-ui/react-label": "^2.1.0",
- "@radix-ui/react-select": "^2.1.1",
+ "@radix-ui/react-select": "^2.1.4",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.6",
- "@types/lodash": "^4.17.13",
- "@screenpipe/js": "1.0.0",
"@screenpipe/browser": "0.1.12",
+ "@screenpipe/js": "1.0.0",
+ "@types/lodash": "^4.17.13",
"@types/nodemailer": "^6.4.17",
"ai": "^4.0.18",
"class-variance-authority": "^0.7.1",
@@ -24,13 +24,13 @@
"lucide-react": "^0.468.0",
"next": "14.2.15",
"nodemailer": "^6.9.16",
+ "openai": "^4.76.3",
+ "react": "^18",
+ "react-dom": "^18",
"react-markdown": "^9.0.1",
"react-syntax-highlighter": "^15.5.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
- "openai": "^4.76.3",
- "react": "^18",
- "react-dom": "^18",
"tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7"
},