-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
430 lines (375 loc) · 14.1 KB
/
main.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package main
import (
"flag"
"log"
"net/http"
"os"
"regexp"
"strconv"
"time"
database "github.com/ad/go-githublistener/db"
ghapi "github.com/ad/go-githublistener/ghapi"
telegram "github.com/ad/go-githublistener/telegram"
dlog "github.com/amoghe/distillog"
sql "github.com/lazada/sqle"
cron "github.com/robfig/cron/v3"
tgbotapi "gopkg.in/telegram-bot-api.v4"
)
const version = "0.0.4"
var (
err error
bot *tgbotapi.BotAPI
db *sql.DB
client *ghapi.Client
clientID string
clientSecret string
httpPort int
httpRedirectURI string
telegramToken string
telegramProxyHost string
telegramProxyPort string
telegramProxyUser string
telegramProxyPassword string
telegramDebug bool
checkReposEvery string
checkCommitsEvery string
)
func main() {
dlog.Infof("Started version %s", version)
flag.StringVar(&clientID, "client_id", lookupEnvOrString("GO_GITHUB_LISTENER_CLIENT_ID", clientID), "github client id")
flag.StringVar(&clientSecret, "client_secret", lookupEnvOrString("GO_GITHUB_LISTENER_CLIENT_SECRET", clientSecret), "github client secret")
flag.IntVar(&httpPort, "http_port", lookupEnvOrInt("GO_GITHUB_LISTENER_PORT", 8080), "bot http port")
flag.StringVar(&httpRedirectURI, "http_redirect_uri", lookupEnvOrString("GO_GITHUB_LISTENER_HTTP_REDIRECT_URI", "http://localhost:8080/oauth/redirect"), "http redirect uri")
flag.StringVar(&telegramToken, "telegram_token", lookupEnvOrString("GO_GITHUB_LISTENER_TELEGRAM_TOKEN", telegramToken), "telegramToken")
flag.StringVar(&telegramProxyHost, "telegram_proxy_host", lookupEnvOrString("GO_GITHUB_LISTENER_TELEGRAM_PROXY_HOST", telegramProxyHost), "telegramProxyHost")
flag.StringVar(&telegramProxyPort, "telegram_proxy_port", lookupEnvOrString("GO_GITHUB_LISTENER_TELEGRAM_PROXY_PORT", telegramProxyPort), "telegramProxyPort")
flag.StringVar(&telegramProxyUser, "telegram_proxy_user", lookupEnvOrString("GO_GITHUB_LISTENER_TELEGRAM_PROXY_USER", telegramProxyUser), "telegramProxyUser")
flag.StringVar(&telegramProxyPassword, "telegram_proxy_password", lookupEnvOrString("GO_GITHUB_LISTENER_TELEGRAM_PROXY_PASSWORD", telegramProxyPassword), "telegramProxyPassword")
flag.BoolVar(&telegramDebug, "telegram_debug", lookupEnvOrBool("GO_GITHUB_LISTENER_TELEGRAM_DEBUG", telegramDebug), "telegramDebug")
flag.StringVar(&checkReposEvery, "check_repos_every", lookupEnvOrString("GO_GITHUB_LISTENER_CHECK_REPOS_EVERY", "*/15 * * * *"), "run cron job for check repos every")
flag.StringVar(&checkCommitsEvery, "check_commits_every", lookupEnvOrString("GO_GITHUB_LISTENER_CHECK_COMMITS_EVERY", "* * * * *"), "run cron job for check commits every")
flag.Parse()
log.SetFlags(0)
client = ghapi.NewClient(clientID, clientSecret)
// Init DB
db, err = database.InitDB()
if err != nil {
log.Fatalf("failed to open database: %v", err)
return
}
defer func() { _ = db.Close() }()
// Init telegram
bot, err = telegram.InitTelegram(telegramToken, telegramProxyHost, telegramProxyPort, telegramProxyUser, telegramProxyPassword, telegramDebug)
if err != nil {
log.Fatalf("fail on telegram login: %v", err)
}
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Fatalf("[INIT] [Failed to init Telegram updates chan: %v]", err)
}
go processTelegramMessages(updates)
http.HandleFunc("/oauth/redirect", func(w http.ResponseWriter, r *http.Request) {
// dlog.Debugf("parse query: %#v", r)
err12 := r.ParseForm()
if err12 != nil {
dlog.Errorf("could not parse query: %v", err12)
w.WriteHeader(http.StatusBadRequest)
}
code := r.FormValue("code")
token, err13 := client.GetGithubUserAccessToken(code)
if err13 != nil {
dlog.Errorln(err13)
w.WriteHeader(http.StatusInternalServerError)
return
}
//w.Header().Set("Location", "/user?access_token="+t.AccessToken)
w.Header().Set("Location", "https://t.me/"+bot.Self.UserName+"?start="+token)
w.WriteHeader(http.StatusFound)
})
dlog.Debugf("Listening on port %d", httpPort)
cron := cron.New()
_, err = cron.AddFunc(checkCommitsEvery, func() {
// ctx, cancel := context.WithTimeout(context.Background(), time.Duration(cronDisableTimeout)*time.Second)
// defer cancel()
dlog.Debugln("started check commits cron job")
if usersRepos, err14 := database.GetUserRepos(db); err14 != nil {
dlog.Errorln(err14)
} else if len(usersRepos) > 0 {
for _, item := range usersRepos {
telegramUserID, err15 := strconv.ParseInt(item.TelegramUserID, 10, 64)
if err15 != nil {
dlog.Errorln(err15)
continue
}
// dlog.Infof("ITEM in: %#v %s", item, item.UpdatedAt.String())
go func(item *database.UsersReposResult) {
commits, err16 := client.GetGithubUserRepoCommits(item)
if err16 != nil {
dlog.Errorln(err16)
if err16.Error() == "repo not found" {
if errDeleteRepo := database.DeleteRepoUserLinkDB(db, &database.GithubUser{ID: item.UserID}, &database.GithubRepo{ID: item.RepoID}); err == nil {
dlog.Infof("%s %s %d", item.RepoName, "removed for", item.UserID)
msg := tgbotapi.NewMessage(telegramUserID, "repo "+item.RepoName+" not found, removed")
_, err9 := bot.Send(msg)
if err9 != nil {
dlog.Errorln(err9)
}
} else {
dlog.Errorln(errDeleteRepo)
}
}
return
}
if len(commits) > 0 {
// dlog.Debugf("ITEM in: %#v %s", item, item.UpdatedAt.String())
// dlog.Infof("%#v", commits)
for _, commit := range commits {
if commit.Commit.Author.Date.After(item.UpdatedAt) {
item.UpdatedAt = commit.Commit.Author.Date
}
if commit.Commit.Committer.Date.After(item.UpdatedAt) {
item.UpdatedAt = commit.Commit.Committer.Date
}
msg := tgbotapi.NewMessage(telegramUserID, "")
msg.ParseMode = "Markdown"
msg.DisableWebPagePreview = true
msg.Text += "[" + item.RepoName + "](https://github.com/" + item.RepoName + ") was updated by [" + commit.Commit.Author.Name + "](https://github.com/" + commit.Commit.Author.Name + ") with new commit([" + commit.SHA + "](" + commit.HTMLUrl + ")):\n" + commit.Commit.Message
_, err17 := bot.Send(msg)
if err17 != nil {
dlog.Errorln(err17)
}
}
// dlog.Debugf("ITEM out: %#v %s", item, item.UpdatedAt.String())
err18 := database.UpdateUserRepoLink(db, item)
if err18 != nil {
dlog.Errorln(err18)
}
}
}(item)
}
}
})
if err != nil {
dlog.Errorf("wrong cronjob params: %s", err)
}
_, err2 := cron.AddFunc(checkReposEvery, func() {
dlog.Debugln("started check repos cron job")
if users, err14 := database.GetUsers(db); err14 != nil {
dlog.Errorln(err14)
} else if len(users) > 0 {
for _, ghuser := range users {
if repos, err6 := client.GetGithubUserRepos(ghuser.Token, ghuser.UserName); err6 == nil {
for _, repo := range repos {
ghrepo := &database.GithubRepo{
Name: repo.Name,
RepoName: repo.FullName,
}
if dbrepo, err7 := database.AddRepoIfNotExist(db, ghrepo); err7 != nil && err7.Error() != database.AlreadyExists {
dlog.Errorln(err7)
} else if err8 := database.AddRepoLinkIfNotExist(db, ghuser, dbrepo, repo.UpdatedAt); err8 != nil && err8.Error() != database.AlreadyExists {
dlog.Errorln(err8)
}
}
} else {
dlog.Errorln(err6)
}
}
}
})
if err2 != nil {
dlog.Errorf("wrong cronjob params: %s", err2)
}
cron.Start()
defer cron.Stop()
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(httpPort), nil))
}
func processTelegramMessages(updates tgbotapi.UpdatesChannel) {
for update := range updates {
if update.Message == nil { // ignore any non-Message Updates
continue
}
dlog.Infof("%s [%d] %s", update.Message.From.UserName, update.Message.From.ID, update.Message.Text)
message := database.TelegramMessage{
UserID: update.Message.From.ID,
UserName: update.Message.From.UserName,
Message: update.Message.Text,
Date: time.Unix(int64(update.Message.Date), 0),
}
err2 := database.StoreTelegramMessage(db, message)
if err2 != nil {
dlog.Errorf("%s", err2)
}
if update.Message.IsCommand() {
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
switch update.Message.Command() {
case "start", "startgroup", "repos":
ghuser := &database.GithubUser{
TelegramUserID: strconv.Itoa(update.Message.From.ID),
}
if update.Message.Command() != "repos" && update.Message.CommandArguments() != "" {
if user, err3 := client.GetGithubUser(update.Message.CommandArguments()); err3 == nil {
if user.Name != "" {
msg.Text = "Hi, " + user.Name
} else {
msg.Text = "Hi, " + user.UserName
}
ghuser.Name = user.Name
ghuser.UserName = user.UserName
ghuser.Token = update.Message.CommandArguments()
dbuser, err4 := database.AddUserIfNotExist(db, ghuser)
if err4 != nil && err4.Error() != database.AlreadyExists {
msg.Text += "\nError on save your token, try /start again\n" + err4.Error()
_, err5 := bot.Send(msg)
if err5 != nil {
dlog.Errorln(err5)
}
continue
}
ghuser.ID = dbuser.ID
}
} else {
if user, err20 := database.GetGithubUserFromDB(db, ghuser.TelegramUserID); err20 == nil {
ghuser.ID = user.ID
ghuser.Name = user.Name
ghuser.UserName = user.UserName
ghuser.Token = user.Token
}
}
if ghuser.ID != 0 {
if repos, err6 := client.GetGithubUserRepos(ghuser.Token, ghuser.UserName); err6 == nil {
msg2 := tgbotapi.NewMessage(update.Message.Chat.ID, "You are watching:\n")
for _, repo := range repos {
msg2.Text += "[" + repo.FullName + "](https://github.com/" + repo.FullName + ") updated at:" + repo.UpdatedAt.Format("2006-01-02 15:04:05") + "\n"
ghrepo := &database.GithubRepo{
Name: repo.Name,
RepoName: repo.FullName,
}
if dbrepo, err7 := database.AddRepoIfNotExist(db, ghrepo); err7 != nil && err7.Error() != database.AlreadyExists {
dlog.Errorln(err7)
} else if err8 := database.AddRepoLinkIfNotExist(db, ghuser, dbrepo, repo.UpdatedAt); err8 != nil && err8.Error() != database.AlreadyExists {
dlog.Errorln(err8)
}
}
msg2.ParseMode = "Markdown"
msg2.DisableWebPagePreview = true
_, err9 := bot.Send(msg2)
if err9 != nil {
dlog.Errorln(err9)
}
continue
} else {
dlog.Errorln(err6)
}
}
text := `[Click here to authorize bot in github](https://github.com/login/oauth/authorize?client_id=` + clientID + `&redirect_uri=` + httpRedirectURI + `), and then press START again`
msg.ParseMode = "Markdown"
msg.Text = text
msg.DisableWebPagePreview = true
case "me":
if user, err10 := database.GetGithubUserFromDB(db, strconv.Itoa(update.Message.From.ID)); err10 == nil {
if user.Name != "" {
msg.Text = "Hi, " + user.Name
} else {
msg.Text = "Hi, " + user.UserName
}
} else {
msg.Text = "type /start\n"
msg.Text += err10.Error()
}
case "delete":
if checkRepoName(update.Message.CommandArguments()) {
if ghuser, err10 := database.GetGithubUserFromDB(db, strconv.Itoa(update.Message.From.ID)); err10 == nil {
if ghrepo, errGetRepo := database.GetGithubRepoByNameFromDB(db, update.Message.CommandArguments()); errGetRepo == nil {
if errDeleteRepo := database.DeleteRepoUserLinkDB(db, ghuser, ghrepo); err == nil {
dlog.Infof("%s %s %s", ghuser.Name, "removed", ghrepo.RepoName)
msg.Text = ghrepo.RepoName + " removed, uncheck Watching in Github interface"
} else {
msg.Text += errDeleteRepo.Error()
}
} else {
msg.Text = errGetRepo.Error()
}
} else {
msg.Text = "type /start\n"
msg.Text += err10.Error()
}
} else {
msg.Text = "wrong repo format, try username/reponame instead"
}
case "add":
if checkRepoName(update.Message.CommandArguments()) {
if ghuser, err10 := database.GetGithubUserFromDB(db, strconv.Itoa(update.Message.From.ID)); err10 == nil {
if ghrepo, errCheckRepo := database.GetGithubRepoByNameFromDB(db, update.Message.CommandArguments()); errCheckRepo == nil {
if err8 := database.AddRepoLinkIfNotExist(db, ghuser, ghrepo, time.Now()); err8 != nil && err8.Error() != database.AlreadyExists {
dlog.Errorln(err8)
} else {
msg.Text = ghrepo.RepoName + " added"
}
} else {
if repo, errGetRepo := client.GetGithubRepo(ghuser.Token, update.Message.CommandArguments()); errGetRepo == nil {
ghrepo := &database.GithubRepo{
Name: repo.Name,
RepoName: repo.FullName,
}
if dbrepo, err7 := database.AddRepoIfNotExist(db, ghrepo); err7 != nil && err7.Error() != database.AlreadyExists {
dlog.Errorln(err7)
} else if err8 := database.AddRepoLinkIfNotExist(db, ghuser, dbrepo, repo.UpdatedAt); err8 != nil && err8.Error() != database.AlreadyExists {
dlog.Errorln(err8)
} else {
msg.Text = ghrepo.RepoName + " added"
}
} else {
msg.Text = ghrepo.RepoName + " not found"
}
}
} else {
msg.Text = "type /start\n"
msg.Text += err10.Error()
}
} else {
msg.Text = "wrong repo format, try username/reponame instead"
}
case "help":
msg.Text = "type /start"
default:
msg.Text = "I don't know that command"
}
msg.ReplyToMessageID = update.Message.MessageID
_, err11 := bot.Send(msg)
if err11 != nil {
dlog.Errorln(err11)
}
}
}
}
func checkRepoName(s string) bool {
re := regexp.MustCompile(`^([\w,\-,\_]+)\/([\w,\-,\_]+)$`)
return re.Match([]byte(s))
}
func lookupEnvOrString(key string, defaultVal string) string {
if val, ok := os.LookupEnv(key); ok {
return val
}
return defaultVal
}
func lookupEnvOrInt(key string, defaultVal int) int {
if val, ok := os.LookupEnv(key); ok {
if x, err := strconv.Atoi(val); err == nil {
return x
}
}
return defaultVal
}
func lookupEnvOrBool(key string, defaultVal bool) bool {
if val, ok := os.LookupEnv(key); ok {
if val == "true" {
return true
}
if val == "false" {
return false
}
}
return defaultVal
}