87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
import { ACCESS_TOKEN, SERVER_URL, ROOM_ID } from "./conf.js";
|
|
|
|
try {
|
|
var last_ts = Number(Deno.readTextFileSync("last_ts"));
|
|
} catch (error) {
|
|
var last_ts = 0;
|
|
}
|
|
|
|
|
|
async function fetchMatrix(url, options = {}) {
|
|
options.headers ||= {};
|
|
options.headers.Authorization ||= `Bearer ${ACCESS_TOKEN}`;
|
|
url = SERVER_URL + url;
|
|
do {
|
|
console.debug("fetch", url);
|
|
try {
|
|
var res = await fetch(url, options);
|
|
if (res.ok) break;
|
|
console.warn("status:", res.status);
|
|
if (res.status == 429) {
|
|
var {retry_after_ms} = await res.json();
|
|
}
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
await new Promise(r => setTimeout(r, retry_after_ms || 60000));
|
|
} while (true)
|
|
if (!res.ok) throw new Error(`HTTP ${res.status} ${await res.text()}`);
|
|
return res;
|
|
}
|
|
|
|
async function checkNotifications() {
|
|
var new_notifications = [];
|
|
var next_token;
|
|
var limit = 5;
|
|
|
|
l: do {
|
|
var data = await fetchMatrix(`/_matrix/client/v3/notifications?limit=${limit}${next_token ? `&from=${next_token}` : ''}`).then(res => res.json());
|
|
for (let n of data.notifications) {
|
|
if (n.ts <= last_ts) break l;
|
|
new_notifications.unshift(n);
|
|
}
|
|
next_token = data.next_token;
|
|
limit = 50;
|
|
} while (next_token !== null)
|
|
|
|
console.debug("new notifications:", new_notifications);
|
|
if (!new_notifications.length) return;
|
|
for (let n of new_notifications) {
|
|
try {
|
|
await addNotificationToRoom(n);
|
|
last_ts = n.ts;
|
|
Deno.writeTextFileSync("last_ts", String(last_ts));
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
async function addNotificationToRoom(notification) {
|
|
var text = `https://matrix.to/#/${encodeURIComponent(notification.room_id)}/${encodeURIComponent(notification.event.event_id)} ${new Date(notification.ts).toLocaleString()}`;
|
|
await fetchMatrix(`/_matrix/client/v3/rooms/${encodeURIComponent(ROOM_ID)}/send/m.room.message/${Math.random()}`, {
|
|
method: "PUT",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
},
|
|
body: JSON.stringify({
|
|
msgtype: "m.text",
|
|
format: "org.matrix.custom.html",
|
|
body: text,
|
|
formatted_body: `<p>${text}</p>\n<pre><code class=\"language-json\">${JSON.stringify(notification.event, null, '\t')}\n</code></pre>\n`
|
|
})
|
|
});
|
|
}
|
|
|
|
|
|
|
|
|
|
while (true) {
|
|
try {
|
|
await checkNotifications();
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
await new Promise(r => setTimeout(r, 10000));
|
|
} |