This repository has been archived by the owner on Feb 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
192 lines (171 loc) · 5.65 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
package main
import (
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/robfig/cron/v3"
"github.com/spf13/viper"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"schrodinger-box/internal/api"
"schrodinger-box/internal/callback"
"schrodinger-box/internal/external"
"schrodinger-box/internal/middleware"
"schrodinger-box/internal/model"
)
var startTime time.Time
func main() {
startTime = time.Now()
gin.ForceConsoleColor()
viper.SetConfigName("schrodinger-box.yaml")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
if home, err := os.UserHomeDir(); err == nil {
viper.AddConfigPath(home)
}
viper.AddConfigPath("/etc")
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// set debug mode for gin
if viper.GetBool("debug") {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
// load essential interfaces (Telegram bot API, database)
// database
db, err := gorm.Open(mysql.Open(viper.GetString("database")), &gorm.Config{})
if err != nil {
panic("Fail to connect to DB: " + err.Error())
} else {
debugPrint("Database connected")
}
if viper.GetBool("debug") {
db = db.Debug()
}
tables := []interface{}{
model.Token{},
model.User{},
model.Event{},
model.EventSignup{},
model.Notification{},
model.NotificationBatch{},
model.NotificationSubscription{},
model.SMSVerification{},
model.File{},
}
if err := db.AutoMigrate(tables...); err != nil {
panic("Failed to migrate tables: " + err.Error())
} else {
debugPrint("Database migrated")
}
router := gin.Default()
router.LoadHTMLGlob("templates/*")
router.Use(gin.Recovery())
router.Use(middleware.OptionsMiddleware)
router.Use(middleware.DatabaseMiddleware(db))
router.Static("/assets", "./assets")
// router group dealing with all API calls from front end
apiRouter := router.Group(viper.GetString("apiRoot"))
apiRouter.Use(middleware.APIMiddleware)
{
apiRouter.GET("/uptime", uptime)
apiRouter.POST("/token", api.TokenCreate)
apiRouter.GET("/token", api.TokenGet)
userRouter := apiRouter.Group("/user")
userRouter.Use(middleware.TokenMiddleware())
{
userRouter.GET("", api.UserGetSelf)
userRouter.POST("", api.UserCreate)
userRouter.PATCH("", api.UserUpdate)
userRouter.DELETE("", api.UserDelete)
userRouter.GET("/:id", api.UserGet)
}
eventRouter := apiRouter.Group("/event")
eventRouter.Use(middleware.TokenMiddleware())
{
eventRouter.POST("", api.EventCreate)
eventRouter.GET("/:id", api.EventGet)
eventRouter.DELETE("/:id", api.EventDelete)
}
apiRouter.GET("/events", middleware.TokenMiddleware(), api.EventsGet)
eventSignupRouter := apiRouter.Group("/event_signup")
eventSignupRouter.Use(middleware.TokenMiddleware())
{
eventSignupRouter.POST("", api.EventSignupCreate)
eventSignupRouter.PATCH("", api.EventSignupUpdate)
eventSignupRouter.DELETE("/:id", api.EventSignupDelete)
}
fileRouter := apiRouter.Group("/file")
fileRouter.Use(middleware.TokenMiddleware())
{
fileRouter.POST("", api.FileCreate)
fileRouter.PATCH("", api.FileUpdate)
fileRouter.DELETE("/:id", api.FileDelete)
}
apiRouter.GET("/files", middleware.TokenMiddleware(), api.FilesGet)
apiRouter.POST("/sms_bind/:number", middleware.TokenMiddleware(), api.UserSMSBind)
apiRouter.DELETE("/sms_bind/:number", middleware.TokenMiddleware(), api.UserSMSUnbind)
}
callbackRouter := router.Group("/callback")
{
callbackRouter.GET("/openid/:tokenId", callback.HandleOpenidCallback)
callbackRouter.GET("/unsub", callback.HandleUnsub)
}
enabledServices := viper.GetStringSlice("external.enable")
c := cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
if _, err := c.AddFunc(viper.GetString("external.notification.cron"), func() { external.NotificationCron(db) }); err != nil {
panic("Unable to start cron for Notification - " + err.Error())
}
for _, enabledService := range enabledServices {
switch enabledService {
case "telegram":
// authorize using bot API Key
bot, err := tgbotapi.NewBotAPI(viper.GetString("external.telegram.key"))
if err != nil {
panic("Failed to connect to Telegram bot API: " + err.Error())
} else {
bot.Debug = viper.GetBool("debug")
debugPrint("Authorized on account %s", bot.Self.UserName)
}
// telegram updates handler
go external.TelegramLoop(db, bot)
// telegram event scheduler
if _, err := c.AddFunc(viper.GetString("external.telegram.cron"), func() { external.TelegramCron(db, bot) }); err != nil {
panic("Unable to start cron for Telegram - " + err.Error())
}
case "email":
if _, err := c.AddFunc(viper.GetString("external.email.cron"), func() { external.EmailCron(db) }); err != nil {
panic("Unable to start cron for Email - " + err.Error())
}
case "sms":
if _, err := c.AddFunc(viper.GetString("external.sms.cron"), func() { external.SmsCron(db) }); err != nil {
panic("Unable to start cron for SMS - " + err.Error())
}
default:
// do nothing for unknown service
}
}
c.Start()
router.Run(viper.GetString("listen"))
}
func uptime(ctx *gin.Context) {
ctx.String(http.StatusOK, "{\"meta\":{\"uptime\": \""+fmt.Sprintf("%s", time.Since(startTime))+"\"}}")
}
// this function prints a line of debug information to the default IO writer
// debugging status and DefaultWriter are inherited from gin
func debugPrint(format string, values ...interface{}) {
if gin.IsDebugging() {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Fprintf(gin.DefaultWriter, "[Schrodinger's Box] "+format, values...)
}
}