Temp commit to merge main into this branch

This commit is contained in:
Koper
2023-12-04 20:54:54 +07:00
parent ba40d28152
commit 999a3e05a4
8 changed files with 310 additions and 118 deletions

View File

@@ -1,62 +0,0 @@
import { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
type ZulipStream = {
id: number;
name: string;
topics: string[];
};
async function getTopics(stream_id: number): Promise<string[]> {
try {
const response = await axios.get(
`https://${process.env.ZULIP_REALM}/api/v1/users/me/${stream_id}/topics`,
{
auth: {
username: process.env.ZULIP_BOT_EMAIL || "?",
password: process.env.ZULIP_API_KEY || "?",
},
},
);
return response.data.topics.map((topic) => topic.name);
} catch (error) {
console.error("Error fetching topics for stream " + stream_id, error);
throw error; // Propagate the error up to be handled by the caller
}
}
async function getStreams(): Promise<ZulipStream[]> {
try {
const response = await axios.get(
`https://${process.env.ZULIP_REALM}/api/v1/streams`,
{
auth: {
username: process.env.ZULIP_BOT_EMAIL || "?",
password: process.env.ZULIP_API_KEY || "?",
},
},
);
const streams: ZulipStream[] = [];
for (const stream of response.data.streams) {
console.log("Loading topics for " + stream.name);
const topics = await getTopics(stream.stream_id);
streams.push({ id: stream.stream_id, name: stream.name, topics });
}
return streams;
} catch (error) {
console.error("Error fetching zulip streams", error);
throw error; // Propagate the error up
}
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
try {
const streams = await getStreams();
return res.status(200).json({ streams });
} catch (error) {
// Handle errors more gracefully
return res.status(500).json({ error: "Internal Server Error" });
}
};

View File

@@ -0,0 +1,44 @@
import axios from "axios";
import { URLSearchParams } from "url";
export default async function handler(req, res) {
if (req.method === "POST") {
const { stream, topic, message } = req.body;
console.log("Sending zulip message", stream, topic);
if (!stream || !topic || !message) {
return res.status(400).json({ error: "Missing required parameters" });
}
try {
// Construct URL-encoded data
const params = new URLSearchParams();
params.append("type", "stream");
params.append("to", stream);
params.append("topic", topic);
params.append("content", message);
// Send the request1
const zulipResponse = await axios.post(
`https://${process.env.ZULIP_REALM}/api/v1/messages`,
params,
{
auth: {
username: process.env.ZULIP_BOT_EMAIL || "?",
password: process.env.ZULIP_API_KEY || "?",
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
return res.status(200).json(zulipResponse.data);
} catch (error) {
return res.status(500).json({ failed: true, error: error });
}
} else {
res.setHeader("Allow", ["POST"]);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}