82 lines
2.5 KiB
Go
82 lines
2.5 KiB
Go
package mdb
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
"ymgb/database"
|
|
|
|
"git.nix13.pw/scuroneko/extypes"
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
)
|
|
|
|
type ConsoleLogEntry struct {
|
|
Level string `bson:"level" json:"level"`
|
|
Prefix string `bson:"prefix" json:"prefix"`
|
|
Traceback string `bson:"traceback" json:"traceback"`
|
|
Message string `bson:"message" json:"message"`
|
|
Time time.Time `bson:"time" json:"time"`
|
|
TimeStamp int64 `bson:"timeStamp" json:"time_stamp"`
|
|
}
|
|
|
|
func WriteConsoleLog(db *database.Context, e ConsoleLogEntry) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
col := database.GetMongoCollection(db, "logs")
|
|
_, err := col.InsertOne(ctx, e)
|
|
return err
|
|
}
|
|
func GetConsoleLogs(db *database.Context) ([]ConsoleLogEntry, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
col := database.GetMongoCollection(db, "logs")
|
|
opts := options.Find()
|
|
opts.SetLimit(5)
|
|
opts.SetSort(bson.D{{Key: "_id", Value: 1}})
|
|
cursor, err := col.Find(ctx, bson.D{}, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func(cursor *mongo.Cursor, ctx context.Context) {
|
|
_ = cursor.Close(ctx)
|
|
}(cursor, ctx)
|
|
result := make([]ConsoleLogEntry, 0)
|
|
err = cursor.All(ctx, &result)
|
|
return result, err
|
|
}
|
|
|
|
type MessageLogEntry struct {
|
|
MessageID int `bson:"messageId" json:"message_id"`
|
|
SenderID int64 `bson:"senderId" json:"sender_id"`
|
|
ChatID int64 `bson:"chatId" json:"chat_id"`
|
|
Text string `bson:"text" json:"text"`
|
|
TimeStamp int64 `bson:"timestamp" json:"timestamp"`
|
|
}
|
|
|
|
func WriteMessageLog(db *database.Context, e *MessageLogEntry) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
col := database.GetMongoCollection(db, "msg_logs")
|
|
_, err := col.InsertOne(ctx, e)
|
|
return err
|
|
}
|
|
func GetMessageLogs(db *database.Context) (extypes.Slice[*MessageLogEntry], error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
col := database.GetMongoCollection(db, "msg_logs")
|
|
opts := options.Find()
|
|
opts.SetLimit(5)
|
|
opts.SetSort(bson.D{{Key: "_id", Value: 1}})
|
|
cursor, err := col.Find(ctx, bson.D{}, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func(cursor *mongo.Cursor, ctx context.Context) {
|
|
_ = cursor.Close(ctx)
|
|
}(cursor, ctx)
|
|
result := make(extypes.Slice[*MessageLogEntry], 0)
|
|
err = cursor.All(ctx, &result)
|
|
return result, err
|
|
}
|