export const ntfy = () => {
class NtfyPublisher {
private serverUrl: string = "ntfy.sh";
private topic: string | null = null;
private message: string | null = null;
private file: any | null = null;
private actions: string[] = [];
private headers: Record<string, string> = {};
toServer(url: string): NtfyPublisher {
this.serverUrl = url;
return this;
}
asUser(user: string, password: string) {
const payload = btoa(`${user}:${password}`);
this.headers["Authorization"] = `Basic ${payload}`;
return this;
}
usingToken(token: string) {
this.headers["Authorization"] = `Bearer ${token}`;
return this;
}
toTopic(topic: string) {
this.topic = topic;
return this;
}
withMessage(message: string, markdown = false) {
if (this.file != null)
throw new Error(
"A file is already attached. Can't send a message and a file at once.",
);
if (this.message != null)
throw new Error(
"A message has been already set. Can't send 2 messages at once.",
);
this.message = message;
if (markdown) {
this.headers["Markdown"] = "yes";
}
return this;
}
withTitle(title: string) {
this.headers["Title"] = title;
return this;
}
withPriority(priority: "min" | "low" | "default" | "high" | "max") {
this.headers["Priority"] = priority;
return this;
}
withMinPriority() {
return this.withPriority("min");
}
withLowPriority() {
return this.withPriority("low");
}
withDefaultPriority() {
return this.withPriority("default");
}
withHighPriority() {
return this.withPriority("high");
}
withMaxPriority() {
return this.withPriority("max");
}
withTags(...tags: string[]) {
this.headers["Tags"] = tags.join(",");
return this;
}
withDelay(when: string) {
this.headers["Delay"] = when;
return this;
}
withViewAction(label: string, url: string, clear: string | null = null) {
if (this.actions.length >= 3) {
throw new Error("Max of 3 actions are allowed.");
}
this.actions.push(
`view, ${label}, ${url}${clear == null ? "" : ", clear=" + clear}`,
);
return this;
}
withBroadcastAction(
label: string,
intent: string | null = null,
extras: Record<string, string> = {},
clear: boolean | null = null,
) {
if (this.actions.length >= 3) {
throw new Error("Max of 3 actions are allowed.");
}
const segments = ["broadcast", label];
if (intent != null) {
segments.push(`intent=${intent}`);
}
if (clear != null) {
segments.push(`clear=${clear}`);
}
for (const [key, value] of Object.entries(extras)) {
segments.push(`extras.${key}=${value}`);
}
this.actions.push(segments.join(", "));