-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.go
344 lines (304 loc) · 9.33 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
package main
import (
"embed"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/fiatjaf/go-cliche"
"github.com/fiatjaf/go-lnurl"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
"github.com/kelseyhightower/envconfig"
_ "github.com/lib/pq"
"github.com/msingleton/amplitude-go"
cmap "github.com/orcaman/concurrent-map"
"github.com/rs/cors"
"github.com/rs/zerolog"
"gopkg.in/redis.v5"
)
type Settings struct {
ServiceId string `envconfig:"SERVICE_ID" default:"lntxbot"`
ServiceURL string `envconfig:"SERVICE_URL" required:"true"`
Host string `envconfig:"HOST" default:"0.0.0.0"`
Port string `envconfig:"PORT" required:"true"`
TorProxyURL *url.URL `envconfig:"TOR_PROXY_URL"`
TelegramBotToken string `envconfig:"TELEGRAM_BOT_TOKEN" required:"true"`
PostgresURL string `envconfig:"DATABASE_URL" required:"true"`
RedisURL string `envconfig:"REDIS_URL" required:"true"`
ClicheJARPath string `envconfig:"CLICHE_JAR_PATH"`
ClicheBinaryPath string `envconfig:"CLICHE_BINARY_PATH"`
ClicheDataDir string `envconfig:"CLICHE_DATADIR" required:"true"`
// account in the database named '@'
ProxyAccount int `envconfig:"PROXY_ACCOUNT" required:"true"`
AdminAccount int `envconfig:"ADMIN_ACCOUNT"`
AmplitudeKey string `envconfig:"AMPLITUDE_KEY"`
InvoiceTimeout time.Duration `envconfig:"INVOICE_TIMEOUT" default:"480h"`
PayConfirmTimeout time.Duration `envconfig:"PAY_CONFIRM_TIMEOUT" default:"10m"`
GiveAwayTimeout time.Duration `envconfig:"GIVE_AWAY_TIMEOUT" default:"5h"`
HiddenMessageTimeout time.Duration `envconfig:"HIDDEN_MESSAGE_TIMEOUT" default:"72h"`
CoinflipDailyQuota int `envconfig:"COINFLIP_DAILY_QUOTA" default:"5"` // times each user can join a coinflip
CoinflipAvgDays int `envconfig:"COINFLIP_AVG_DAYS" default:"7"` // days we'll consider for the average
GiveflipDailyQuota int `envconfig:"GIVEFLIP_DAILY_QUOTA" default:"5"`
GiveflipAvgDays int `envconfig:"GIVEFLIP_AVG_DAYS" default:"7"`
GiveawayDailyQuota int `envconfig:"GIVEAWAY_DAILY_QUOTA" default:"5"`
GiveawayAvgDays int `envconfig:"GIVEAWAY_AVG_DAYS" default:"7"`
Banned map[int]bool `envconfig:"BANNED"`
Usage string
}
var (
s Settings
pg *sqlx.DB
ln *cliche.Control
rds *redis.Client
bot *tgbotapi.BotAPI
amp *amplitude.Client
log = zerolog.New(os.Stderr).Output(zerolog.ConsoleWriter{Out: PluginLogger{}})
router = mux.NewRouter()
waitingPaymentSuccesses = cmap.New() // make(map[string][]chan string)
bundle t.Bundle
)
//go:embed templates
var templates embed.FS
var tmpl = template.Must(template.ParseFS(templates, "templates/*"))
//go:embed static
var static embed.FS
func main() {
err := envconfig.Process("", &s)
if err != nil {
log.Fatal().Err(err).Msg("couldn't process envconfig.")
}
// increase default lnurl client timeout because people are using tor unfortunately
lnurl.Client = &http.Client{Timeout: 25 * time.Second}
lnurl.TorClient = &http.Client{
Timeout: 50 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyURL(s.TorProxyURL),
},
}
// setup logger
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log = log.With().Timestamp().Logger()
// http client
http.DefaultClient.CheckRedirect = func(r *http.Request, via []*http.Request) error {
return fmt.Errorf("target '%s' has returned a redirect", r.URL)
}
// translations and templates
bundle, err = createLocalizerBundle()
if err != nil {
log.Fatal().Err(err).Msg("error initializing localization")
}
// seed the random generator
rand.Seed(time.Now().UnixNano())
// setup cliche
// setupCliche()
// go handleClicheEvents()
// go clicheCheckingRoutine()
// postgres connection
pg, err = sqlx.Connect("postgres", s.PostgresURL)
if err != nil {
log.Fatal().Err(err).Msg("couldn't connect to postgres")
}
// redis connection
rurl, _ := url.Parse(s.RedisURL)
pw, _ := rurl.User.Password()
rds = redis.NewClient(&redis.Options{
Addr: rurl.Host,
Password: pw,
})
if err := rds.Ping().Err(); err != nil {
log.Fatal().Err(err).Str("url", s.RedisURL).
Msg("failed to connect to redis")
}
// amplitude client
if s.AmplitudeKey != "" {
amp = amplitude.New(s.AmplitudeKey)
}
// setup commands
setupCommands()
// create telegram bot
bot, err = tgbotapi.NewBotAPI(s.TelegramBotToken)
if err != nil {
log.Fatal().Err(err).Msg("")
}
log.Info().Str("username", bot.Self.UserName).Msg("telegram bot authorized")
// setup telegram webhook
go func() {
time.Sleep(1 * time.Second)
// set webhook
_, err = bot.SetWebhook(tgbotapi.NewWebhook(s.ServiceURL + "/" + bot.Token))
if err != nil {
log.Fatal().Err(err).Msg("failed to set webhook")
}
// bot.Debug = true
_, err := bot.GetWebhookInfo()
if err != nil {
log.Fatal().Err(err).Msg("failed to get webhook info")
}
}()
// routines
// routineCtx := context.WithValue(context.Background(), "origin", "routine")
// go startKicking()
// go sats4adsCleanupRoutine()
// go lnurlBalanceCheckRoutine()
// go checkAllOutgoingPayments(routineCtx)
// go checkAllIncomingPayments(routineCtx)
// routes
//
// telegram webhooks
router.Path("/" + bot.Token).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bytes, _ := ioutil.ReadAll(r.Body)
var update tgbotapi.Update
json.Unmarshal(bytes, &update)
handle(update)
})
// lndhub-compatible routes
// registerAPIMethods()
// register webserver routes
// serveQRCodes()
// serveTempAssets()
// serveLNURL()
// serveLNURLBalanceNotify()
// servePages()
// router.Path("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, "https://t.me/lntxbot", http.StatusTemporaryRedirect)
// })
// random assets
// router.PathPrefix("/static/").Handler(http.FileServer(http.FS(static)))
// start http server
srv := &http.Server{
Handler: cors.Default().Handler(router),
Addr: s.Host + ":" + s.Port,
WriteTimeout: 300 * time.Second,
ReadTimeout: 300 * time.Second,
}
if err := srv.ListenAndServe(); err != nil {
log.Error().Err(err).Msg("error serving http")
}
}
func createLocalizerBundle() (t.Bundle, error) {
// bundle stores a set of messages
bundle = t.NewBundle("en")
// template functions
bundle.AddFunc("s", func(iquantity interface{}) string {
switch quantity := iquantity.(type) {
case int64:
if quantity != 1 {
return "s"
}
case int:
if quantity != 1 {
return "s"
}
case float64:
if quantity != 1 {
return "s"
}
}
return ""
})
bundle.AddFunc("dollar", func(isat interface{}) string {
switch sat := isat.(type) {
case int64:
return getDollarPrice(sat * 1000)
case int:
return getDollarPrice(int64(sat) * 1000)
case float64:
return getDollarPrice(int64(sat * 1000))
default:
return "~"
}
})
bundle.AddFunc("msatToSat", func(imsat interface{}) float64 {
switch msat := imsat.(type) {
case int64:
return float64(msat) / 1000
case int:
return float64(msat) / 1000
case float64:
return msat / 1000
default:
return 0
}
})
bundle.AddFunc("escapehtml", escapeHTML)
bundle.AddFunc("nodeLink", nodeLink)
bundle.AddFunc("nodeAlias", getNodeAlias)
bundle.AddFunc("channelLink", channelLink)
bundle.AddFunc("nodeAliasLink", nodeAliasLink)
bundle.AddFunc("makeLinks", makeLinks)
bundle.AddFunc("json", func(v interface{}) string {
j, _ := json.MarshalIndent(v, "", " ")
return string(j)
})
bundle.AddFunc("time", func(t time.Time) string {
return t.Format("2 Jan 2006 at 3:04PM")
})
bundle.AddFunc("timeSmall", func(t time.Time) string {
return t.Format("2 Jan 15:04")
})
bundle.AddFunc("paddedSatoshis", func(amount float64) string {
if amount > 99999 {
return fmt.Sprintf("%7.15g", amount)
}
if amount < -9999 {
return fmt.Sprintf("%7.15g", amount)
}
return fmt.Sprintf("%7.15g", amount)
})
bundle.AddFunc("lower", strings.ToLower)
bundle.AddFunc("roman", roman)
bundle.AddFunc("letter", func(i int) string { return string([]rune{rune(i) + 97}) })
bundle.AddFunc("add", func(a, b int) int { return a + b })
bundle.AddFunc("menuItem", func(sats interface{}, rawItem string, showSats bool) string {
var satShow string
switch s := sats.(type) {
case int:
satShow = strconv.Itoa(s) + " sat"
case int64:
satShow = strconv.FormatInt(s, 10) + " sat"
case float64:
satShow = fmt.Sprintf("%.3g sat", s)
}
if _, ok := menuItems[rawItem]; ok {
if showSats {
return rawItem + " (" + satShow + ")"
} else {
return rawItem
}
}
return satShow
})
bundle.AddFunc("messageLink", telegramMessageLink)
err := bundle.AddLanguage("en", t.EN)
if err != nil {
return bundle, err
}
err = bundle.AddLanguage("ru", t.RU)
if err != nil {
return bundle, err
}
err = bundle.AddLanguage("de", t.DE)
if err != nil {
return bundle, err
}
err = bundle.AddLanguage("es", t.ES)
if err != nil {
return bundle, err
}
// print an annoying message if keys are missing from translations
for lang, missing := range bundle.Check() {
log.Debug().Str("lang", lang).Interface("keys", missing).
Msg("missing translation")
}
return bundle, nil
}