100 lines
2.4 KiB
Go
100 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"time"
|
|
|
|
"git.nefrace.ru/nefrace/nechotron"
|
|
"git.nefrace.ru/nefrace/tongo"
|
|
)
|
|
|
|
func ExecTimeLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
|
|
return func(u *nechotron.Update) error {
|
|
log.Printf("Executing update [%s]", u.UpdateID.String())
|
|
start := time.Now()
|
|
err := next(u)
|
|
t := time.Since(start)
|
|
log.Printf("Update [%s] was handled in %d microseconds", u.UpdateID.String(), t.Microseconds())
|
|
return err
|
|
}
|
|
}
|
|
|
|
func UserLogger(next nechotron.UpdateHandler) nechotron.UpdateHandler {
|
|
return func(u *nechotron.Update) error {
|
|
log.Println(u.From().FirstName)
|
|
err := next(u)
|
|
return err
|
|
}
|
|
}
|
|
|
|
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()
|
|
userFrom, err := UpdateUser(u.Ctx, db, from, true)
|
|
if err != nil {
|
|
return errors.Join(errors.New("can't update from-user"), err)
|
|
}
|
|
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 {
|
|
return errors.Join(errors.New("can't update to-user"), err)
|
|
}
|
|
u.Ctx = context.WithValue(u.Ctx, "userto", userTo)
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|