-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandler_group.go
More file actions
345 lines (341 loc) · 9.55 KB
/
handler_group.go
File metadata and controls
345 lines (341 loc) · 9.55 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"archive/zip"
"bytes"
"context"
"fmt"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/google/uuid"
"github.com/life4/genesis/slices"
"howett.net/plist"
"io"
"log/slog"
"regexp"
"strconv"
"strings"
"time"
)
type HandlerGroup struct {
}
type Update struct {
*models.Update
bot *bot.Bot
ctx context.Context
}
func (o Update) GetCommand() string {
return strings.Split(strings.Split(o.Message.Text[1:], "@")[0], " ")[0]
}
func (o Update) GetArgumentString() string {
arr := strings.Split(o.Message.Text, " ")
if len(arr) <= 1 {
return ""
}
return strings.Join(arr[1:], " ")
}
func (o Update) MustSendReplyMessage(text string) *models.Message {
msg, err := o.SendReplyMessage(text)
if err != nil {
panic(err)
}
return msg
}
func (o Update) SendReplyMessage(text string) (*models.Message, error) {
defer func() {
if err := recover(); err != nil {
slog.Error(fmt.Sprintf("%v", err))
}
}()
if o.Message != nil {
return o.bot.SendMessage(o.ctx, &bot.SendMessageParams{
ChatID: o.Message.Chat.ID,
Text: text,
ReplyToMessageID: o.Message.ID,
ParseMode: "HTML",
})
} else if o.CallbackQuery != nil {
return o.bot.SendMessage(o.ctx, &bot.SendMessageParams{
ChatID: o.CallbackQuery.Message.Chat.ID,
Text: text,
ParseMode: "HTML",
})
}
panic("no target to reply")
}
func (o Update) GetPayload() string {
text := ""
if o.Message.ReplyToMessage != nil {
text = o.Message.ReplyToMessage.Text
if text == "" {
text = o.Message.ReplyToMessage.Caption
}
}
if arg := o.GetArgumentString(); arg != "" {
if text != "" {
text += "\n\n"
}
text += arg
}
return text
}
func (o Update) MustGetPayload() string {
payload := o.GetPayload()
if payload == "" {
panic("cannot get payload")
}
return payload
}
func WrapHandlerGroupFunc(fun func(update *Update)) bot.HandlerFunc {
return func(ctx context.Context, botIns *bot.Bot, update *models.Update) {
u := &Update{Update: update, bot: botIns, ctx: ctx}
defer func() {
if err := recover(); err != nil {
slog.Error("recover from panic", err)
_, err = u.SendReplyMessage(fmt.Sprintf("%v", err))
if err != nil {
slog.Error("cannot send error msg: ", err)
}
}
}()
fun(u)
}
}
func NewHandlerGroup() *HandlerGroup {
return &HandlerGroup{}
}
func (o *HandlerGroup) Start(update *Update) {
payload := update.GetPayload()
if strings.HasPrefix(payload, "app_") {
o.GetApp(update)
} else if strings.HasPrefix(payload, "del_") {
o.DelApp(update)
} else {
update.MustSendReplyMessage("Send me a signed .ipa file and " +
"I will generate a link to install it on your iOS devices directly!")
}
}
func (o *HandlerGroup) DelApp(update *Update) {
appUUID := update.MustGetPayload()[4:]
session := NewSession(update.Message.Chat.ID)
app, err := slices.Find(session.Applications, func(el Application) bool {
return el.UUID == appUUID
})
if err != nil {
panic(err)
}
session.Applications = slices.Delete(session.Applications, app)
session.Save()
update.MustSendReplyMessage("Application <b>" + app.Name + "</b> has been deleted.")
}
func (o *HandlerGroup) GetApp(update *Update) {
appUUID := update.MustGetPayload()[4:]
session := NewSession(update.Message.Chat.ID)
app, err := slices.Find(session.Applications, func(el Application) bool {
return el.UUID == appUUID
})
if err != nil {
panic(err)
}
update.MustSendReplyMessage(BuildAppInfoTemplate(app))
}
func (o *HandlerGroup) List(update *Update) {
session := NewSession(update.Message.Chat.ID)
botUser, err := update.bot.GetMe(update.ctx)
if err != nil {
panic(err)
}
str, err := BuildAppListTemplate(session.Applications, botUser.Username, 1)
if err != nil {
update.MustSendReplyMessage("error building app list template: " + err.Error())
return
}
_, err = update.bot.SendMessage(update.ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: str,
ParseMode: "HTML",
DisableWebPagePreview: true,
ReplyMarkup: models.InlineKeyboardMarkup{InlineKeyboard: [][]models.InlineKeyboardButton{
{
{
Text: "Previous Page",
CallbackData: "list_previous_page",
},
{
Text: "Next Page",
CallbackData: "list_next_page",
},
},
},
},
})
if err != nil {
panic(err)
}
}
func (o *HandlerGroup) ListSwitchPage(update *Update) {
answerText := ""
defer func() {
update.bot.AnswerCallbackQuery(update.ctx, &bot.AnswerCallbackQueryParams{
CallbackQueryID: update.CallbackQuery.ID,
Text: answerText,
})
}()
currentPage, err := strconv.Atoi(regexp.MustCompile(`\(Page: (\d+)/(\d+)\)`).
FindStringSubmatch(update.CallbackQuery.Message.Text)[1])
if err != nil {
panic(err)
}
session := NewSession(update.CallbackQuery.Message.Chat.ID)
botUser, err := update.bot.GetMe(update.ctx)
if err != nil {
panic(err)
}
template := ""
switch update.CallbackQuery.Data[5:] {
case "previous_page":
t, err := BuildAppListTemplate(session.Applications, botUser.Username, currentPage-1)
if err != nil {
answerText = err.Error()
return
}
template = t
case "next_page":
t, err := BuildAppListTemplate(session.Applications, botUser.Username, currentPage+1)
if err != nil {
answerText = err.Error()
return
}
template = t
}
_, err = update.bot.EditMessageText(update.ctx, &bot.EditMessageTextParams{
ChatID: update.CallbackQuery.Message.Chat.ID,
MessageID: update.CallbackQuery.Message.ID,
Text: template,
ParseMode: "HTML",
DisableWebPagePreview: true,
ReplyMarkup: models.InlineKeyboardMarkup{InlineKeyboard: [][]models.InlineKeyboardButton{
{
{
Text: "Previous Page",
CallbackData: "list_previous_page",
},
{
Text: "Next Page",
CallbackData: "list_next_page",
},
},
},
},
})
if err != nil {
panic(err)
}
}
func (o *HandlerGroup) UploadIPA(update *Update) {
if !strings.HasSuffix(update.Update.Message.Document.FileName, ".ipa") {
update.MustSendReplyMessage("Please upload a .ipa file")
return
}
ipaFile, err := update.bot.GetFile(update.ctx, &bot.GetFileParams{FileID: update.Update.Message.Document.FileID})
if err != nil {
panic(err)
}
processingMessage := update.MustSendReplyMessage("Processing your .ipa file...")
defer update.bot.DeleteMessage(update.ctx, &bot.DeleteMessageParams{
ChatID: update.Message.Chat.ID,
MessageID: processingMessage.ID,
})
slog.Info("Begin download ipa", "filePath", ipaFile.FilePath)
ipaBytes, err := DownloadTelegramFile(ipaFile.FilePath)
if err != nil {
panic(err)
}
slog.Info("Successfully downloaded ipa, unzipping...", "filePath", ipaFile.FilePath)
r, err := zip.NewReader(bytes.NewReader(ipaBytes), int64(len(ipaBytes)))
if err != nil {
panic(err)
}
uid := uuid.New().String()
slog.Info("Successfully unzipped", "uuid-generated", uid)
application := Application{CreatedAt: time.Now(), UUID: uid}
for _, file := range r.File {
readName := ""
if strings.HasSuffix(file.Name, ".app/embedded.mobileprovision") {
readName = "mobileprovision"
}
if strings.HasSuffix(file.Name, ".app/Info.plist") {
readName = "info.plist"
}
if readName == "" {
continue
}
reader, err := file.Open()
if err != nil {
panic(err)
}
v, err := io.ReadAll(reader)
if err != nil {
panic(err)
}
slog.Info("Parsing info", "read-name", readName)
switch readName {
case "mobileprovision":
if group := regexp.MustCompile("<plist([\\s\\S]*?)</plist>").FindSubmatch(v); len(group) > 0 {
mobileprovision := string(group[0])
if g := regexp.MustCompile("<key>CreationDate</key>[\\s\\S]*?<date>(.*?)</date>").
FindStringSubmatch(mobileprovision); len(g) > 0 {
application.CertCreatedAt, _ = time.Parse(time.RFC3339, g[1])
}
if g := regexp.MustCompile("<key>ExpirationDate</key>[\\s\\S]*?<date>(.*?)</date>").
FindStringSubmatch(mobileprovision); len(g) > 0 {
application.CertExpiredAt, _ = time.Parse(time.RFC3339, g[1])
}
if g := regexp.MustCompile("<key>TeamName</key>[\\s\\S]*?<string>(.*?)</string>").
FindStringSubmatch(mobileprovision); len(g) > 0 {
application.CertOrg = g[1]
}
}
case "info.plist":
plistV := map[string]any{}
_, err = plist.Unmarshal(v, &plistV)
if err != nil {
panic(err)
}
displayName, ok := plistV["CFBundleDisplayName"].(string)
if !ok {
displayName, _ = plistV["CFBundleExecutable"].(string)
}
application.Package = plistV["CFBundleIdentifier"].(string)
application.Name = application.Package
if displayName != "" {
application.Name = displayName
}
application.Version = plistV["CFBundleShortVersionString"].(string)
}
}
slog.Info("Application info", "v", application)
slog.Info("Uploading to S3...")
ipaURL, err := UploadS3(ipaBytes, uid+"/0.ipa", "application/octet-stream")
if err != nil {
panic(err)
}
slog.Info("Successfully uploaded to S3", "ipa-url", ipaURL)
application.IPA = ipaURL
plistContent := application.BuildPlistContent()
plistURL, err := UploadS3([]byte(plistContent), uid+"/manifest.plist", "text/xml")
if err != nil {
panic(err)
}
application.Plist = plistURL
installURL, err := UploadS3([]byte(application.BuildInstallPageContent()),
uid+"/install.html", "text/html")
if err != nil {
panic(err)
}
application.InstallPage = installURL
slog.Info("Final application", "v", application)
session := NewSession(update.Message.Chat.ID)
session.Applications = append(session.Applications, application)
session.Save()
update.MustSendReplyMessage(BuildAppInfoTemplate(application))
}