go-dette/middleware.go

100 lines
2.4 KiB
Go
Raw Permalink Normal View History

2023-01-24 00:37:27 +03:00
package main
import (
"context"
2023-09-14 01:46:42 +03:00
"errors"
2023-01-24 00:37:27 +03:00
"log"
"time"
2023-01-24 00:37:27 +03:00
"git.nefrace.ru/nefrace/nechotron"
"git.nefrace.ru/nefrace/tongo"
2023-01-24 00:37:27 +03:00
)
2023-01-24 23:17:30 +03:00
func ExecTimeLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
2023-06-16 01:06:51 +03:00
log.Printf("Executing update [%s]", u.UpdateID.String())
2023-01-24 23:17:30 +03:00
start := time.Now()
err := next(u)
t := time.Since(start)
log.Printf("Update [%s] was handled in %d microseconds", u.UpdateID.String(), t.Microseconds())
2023-01-24 23:17:30 +03:00
return err
}
}
2023-01-24 00:37:27 +03:00
func UserLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
log.Println(u.From().FirstName)
err := next(u)
return err
}
}
2023-06-18 23:39:55 +03:00
func ChatUpdate(db *tongo.Database) nechotron.Middleware {
return func(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
if u.Message == nil {
return next(u)
}
chats := tongo.NewStore[Chat](db)
config := tongo.NewStore[Config](db)
chat := u.Message.Chat
res, err := chats.GetOne(u.Ctx, tongo.E("id", chat.ID))
if err != nil {
addNewChats, err := config.GetOne(u.Ctx, tongo.E("name", "newchats"))
if err != nil {
addNewChats = &Config{
Item: tongo.NewID(),
Name: "newchats",
Value: true,
}
config.InsertOne(u.Ctx, addNewChats)
}
addNew := addNewChats.Value.(bool)
if !addNew {
return nil
}
res = &Chat{
Item: tongo.NewID(),
ID: chat.ID,
Title: chat.Title,
}
chats.InsertOne(u.Ctx, res)
}
return next(u)
}
}
}
func UserDBUpdater(db *tongo.Database) nechotron.Middleware {
return func(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
from := u.From()
2023-01-24 23:17:30 +03:00
userFrom, err := UpdateUser(u.Ctx, db, from, true)
if err != nil {
2023-09-14 01:46:42 +03:00
return errors.Join(errors.New("can't update from-user"), err)
}
2023-01-24 23:17:30 +03:00
u.Ctx = context.WithValue(u.Ctx, "userfrom", userFrom)
if u.IsMessage() && u.Message.ReplyToMessage != nil {
to := u.Message.ReplyToMessage.From
userTo, err := UpdateUser(u.Ctx, db, to, false)
if err != nil {
2023-09-14 01:46:42 +03:00
return errors.Join(errors.New("can't update to-user"), err)
2023-01-24 23:17:30 +03:00
}
u.Ctx = context.WithValue(u.Ctx, "userto", userTo)
}
2023-01-24 23:17:30 +03:00
return next(u)
}
}
}
func ErrorLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
return func(u *nechotron.Update) error {
err := next(u)
if err != nil {
u.LogError("", err, true)
}
return err
2023-01-24 00:37:27 +03:00
}
}