-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.go
271 lines (229 loc) · 7.25 KB
/
telegram.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
// ErrUserNotAllowed is returned when a user is not allowed to send commands to the bot.
var ErrUserNotAllowed = errors.New("user was not whitelisted")
// TelegramProvider is a Telegram bot that provides audio files to the podcast feed.
type TelegramProvider struct {
api *tgbotapi.BotAPI
mediaServiceURL *url.URL
allowedUsers map[int]struct{}
}
// NewTelegramProvider creates a new TelegramProvider instance.
func NewTelegramProvider(token, apiEndpoint, mediaServiceURL string) (*TelegramProvider, error) {
if apiEndpoint == "" {
apiEndpoint = tgbotapi.APIEndpoint
}
if !strings.HasSuffix(apiEndpoint, "/bot%s/%s") {
apiEndpoint += "/bot%s/%s"
}
api, err := tgbotapi.NewBotAPIWithAPIEndpoint(token, apiEndpoint)
if err != nil {
return nil, fmt.Errorf("failed to initialize telegram api: %w", err)
}
p := &TelegramProvider{
api: api,
}
if mediaServiceURL != "" {
u, err := url.Parse(mediaServiceURL)
if err != nil {
return nil, fmt.Errorf("malformed media service URL %s: %w", mediaServiceURL, err)
}
p.mediaServiceURL = u
}
return p, nil
}
// WhitelistUser allows a user to send commands to the bot.
func (tg *TelegramProvider) WhitelistUser(id int) {
log.Printf("allowing user with id %d to send commands to bot", id)
if tg.allowedUsers != nil {
tg.allowedUsers[id] = struct{}{}
return
}
tg.allowedUsers = map[int]struct{}{
id: {},
}
}
// Name returns the name of the provider.
func (tg *TelegramProvider) Name() string {
return "Telegram"
}
// HandleRequest handles an incoming request from Telegram.
func (tg *TelegramProvider) HandleRequest(w http.ResponseWriter, req *http.Request) audioSource {
msg := &tgbotapi.Message{}
if err := json.NewDecoder(req.Body).Decode(&struct {
Message *tgbotapi.Message `json:"message"`
}{msg}); err != nil {
log.Printf("failed to unmarshal telegram message: %s", err)
tg.sendResponse(msg, "Could not add this item: Telegram sent nonsense", true)
w.WriteHeader(http.StatusNoContent)
return nil
}
w.WriteHeader(http.StatusNoContent)
switch src, err := tg.HandleMessage(msg); err {
case ErrUserNotAllowed, ErrNoAudio:
return nil
case nil:
return src
default:
tg.sendResponse(msg, "Could not add this item: "+err.Error(), true)
return nil
}
}
// HandleMessage handles an incoming message from Telegram.
func (tg *TelegramProvider) HandleMessage(msg *tgbotapi.Message) (*TelegramMessage, error) {
if tg.allowedUsers != nil {
if _, ok := tg.allowedUsers[msg.From.ID]; !ok {
return nil, ErrUserNotAllowed
}
}
if msg.Audio == nil {
return nil, ErrNoAudio
}
u, err := tg.api.GetFileDirectURL(msg.Audio.FileID)
if err != nil {
log.Printf("failed to fetch telegram audio url: %s", err)
return nil, fmt.Errorf("failed to fetch file URL: %w", err)
}
if tg.mediaServiceURL != nil {
u1, err := url.Parse(u)
if err != nil {
return nil, fmt.Errorf("telegram api returned malformed download url %s: %w", u, err)
}
u1.Scheme = tg.mediaServiceURL.Scheme
u1.Host = tg.mediaServiceURL.Host
u = u1.String()
}
var sender string
switch {
case msg.ForwardFromChat != nil:
sender = msg.ForwardFromChat.Title
case msg.ForwardFrom != nil:
sender = msg.ForwardFrom.UserName
default:
sender = msg.From.UserName
}
if msg.Caption == "" {
msg.Caption = fmt.Sprintf("Audio from %s submitted on %s", sender, time.Unix(int64(msg.Date), 0).Format("Jan, 02 15:04 MST"))
}
if msg.Audio.Performer == "" {
msg.Audio.Performer = sender
}
if msg.Audio.Title == "" {
msg.Audio.Title = msg.Caption
}
var linkURL string
switch {
case msg.ForwardFromChat != nil:
if chatID := strconv.FormatInt(msg.ForwardFromChat.ID, 10); len(chatID) > 4 {
linkURL = path.Join("https://t.me/c", chatID[4:], strconv.Itoa(msg.MessageID))
} else {
log.Println("unexpected telegram chat ID:", msg.Chat.ID)
}
case msg.Chat.IsChannel():
linkURL = path.Join("https://t.me", msg.Chat.UserName, strconv.Itoa(msg.MessageID))
case msg.Chat.IsSuperGroup():
if chatID := strconv.FormatInt(msg.Chat.ID, 10); len(chatID) > 4 {
linkURL = path.Join("https://t.me/c", chatID[4:], strconv.Itoa(msg.MessageID))
} else {
log.Println("unexpected telegram chat ID:", msg.Chat.ID)
}
}
return &TelegramMessage{
Audio: msg.Audio,
Description: msg.Caption,
Link: linkURL,
FileURL: u,
}, nil
}
// Updates listens for incoming messages from Telegram and returns them as a channel.
func (tg *TelegramProvider) Updates(ctx context.Context) (<-chan *TelegramMessage, error) {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := tg.api.GetUpdatesChan(u)
if err != nil {
return nil, fmt.Errorf("failed to subscribe to updates: %w", err)
}
res := make(chan *TelegramMessage, 10)
go func() {
defer close(res)
for {
select {
case upd := <-updates:
switch src, err := tg.HandleMessage(upd.Message); err {
case ErrUserNotAllowed:
log.Printf("UNAUTHORIZED message from user %s (id:%d)", upd.Message.From.UserName, upd.Message.From.ID)
case ErrNoAudio:
log.Printf("incoming message from user %s (id:%d)", upd.Message.From.UserName, upd.Message.From.ID)
tg.HandleCommand(upd.Message)
case nil:
res <- src
tg.sendResponse(upd.Message, fmt.Sprintf(`Will add "%s" to your feed`, src.Audio.Title), true)
default:
log.Printf("failed to handle Telegram update: %s", err)
tg.sendResponse(upd.Message, "Could not add this item: "+err.Error(), true)
}
case <-ctx.Done():
log.Println("context cancelled, shutting down Telegram provider")
return
}
}
}()
return res, nil
}
// HandleCommand handles an incoming command from Telegram.
func (tg *TelegramProvider) HandleCommand(msg *tgbotapi.Message) {
switch strings.ToLower(msg.Text) {
case "/start", "/help":
tg.sendResponse(msg, "Hello, I'm LaterCast bot! Just forward me audio files and I will add them to your feed.", false)
case "/status":
tg.sendResponse(msg, "Up and running!", false)
default:
tg.sendResponse(msg, "Unknown command, send /help", false)
}
}
func (tg *TelegramProvider) sendResponse(msg *tgbotapi.Message, text string, quoteSrc bool) {
resp := tgbotapi.NewMessage(msg.Chat.ID, text)
if quoteSrc {
resp.ReplyToMessageID = msg.MessageID
}
if _, err := tg.api.Send(resp); err != nil {
log.Printf("failed to send response: %s", err)
}
}
// TelegramMessage represents a Telegram message with an audio file.
type TelegramMessage struct {
Audio *tgbotapi.Audio
Description string
Link string
FileURL string
}
// Metadata returns the metadata for the Telegram message.
func (tg *TelegramMessage) Metadata(ctx context.Context) (Metadata, error) {
return Metadata{
Type: TelegramItem,
OriginalURL: tg.Link,
Title: tg.Audio.Title,
Author: tg.Audio.Performer,
Description: tg.Description,
Duration: time.Duration(tg.Audio.Duration) * time.Second,
MIMEType: tg.Audio.MimeType,
ContentLength: int64(tg.Audio.FileSize),
}, nil
}
// DownloadURL returns the download URL for the Telegram message.
func (tg *TelegramMessage) DownloadURL(context.Context) (string, error) {
return tg.FileURL, nil
}