-
Notifications
You must be signed in to change notification settings - Fork 2
/
unsubscribe.ts
73 lines (64 loc) · 2.24 KB
/
unsubscribe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import * as DB from '../db'
import Ctx from '../ctx'
import { Markup } from 'telegraf'
import { manageSubsButton } from './app'
const directUnsubscription = async (ctx: Ctx, url: string): Promise<boolean> => {
console.log(`Unsubscribing ${ctx.chat.id} from ${url}`)
try {
const id = await DB.subscriptions.updateInactiveByUrl(ctx.chat.id, url)
const extra = Markup
.inlineKeyboard([
Markup.button.callback('Resubscribe', `resubscribe:${id}`)
])
await ctx.reply(`Unsubscribed`, extra) // TODO: Show name and url
return true
} catch(err) {
return false
}
}
const handleUnsubscriptionReply = async (ctx: Ctx): Promise<boolean> => {
try {
if ("reply_to_message" in ctx.message) {
const reply = ctx.message.reply_to_message
const subscription_id = await DB.unsubscriptions.lookup(reply.chat.id, reply.message_id)
await DB.subscriptions.updateInactiveDirect(subscription_id)
const info = await DB.subscriptions.info(subscription_id)
const extra = Markup
.inlineKeyboard([
Markup.button.callback('Resubscribe', `enable_subscription:${subscription_id}`, false)
])
await ctx.replyWithHTML(`Unsubscribed from <b><a href="${info.url}">${info.title}</a></b>`, extra)
return true
} else {
return false
}
} catch(err) {
return false
}
}
const help = `Reply “/unsubscribe” to an article, or tap the button below`
export const handleUnsubscribe = async (ctx: Ctx) => {
if ("reply_to_message" !in ctx.message) {
const ok = await handleUnsubscriptionReply(ctx)
// ignore if reply message is invalid
return
}
var urls = []
if ("entities" in ctx.message) {
urls = ctx.message.entities?.filter(entity => entity.type == 'url')
}
if (urls.length == 0) {
await ctx.replyWithHTML(help, await manageSubsButton(ctx))
return
}
if ("text" in ctx.message) {
const text = ctx.message.text
const found = urls.slice(0, 1)
.map(entity => text.substr(entity.offset, entity.length))
.map(url => directUnsubscription(ctx, url))
.filter(async token => await token)
if (found.length == 0) {
await ctx.replyWithHTML(`Could not unsubscribe. ` + help, await manageSubsButton(ctx))
}
}
}