tgf / internal /db /database.go
Mohammad Shahid
.
adb2908
// In file: internal/db/database.go
package db
import (
"TelegramCloud/tgf/config"
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
)
var (
Client *mongo.Client
Links *mongo.Collection
Users *mongo.Collection
OTPs *mongo.Collection
Files *mongo.Collection
// User management instance
UserMgr *UserManager
// User bot management instance
UserBotMgr *UserBotManager
)
// InitDatabase initializes the MongoDB connection.
func InitDatabase(log *zap.Logger) error {
if config.ValueOf.DB_URI == "" {
log.Warn("DB_URI is not set. Proactive link refreshing will be disabled.")
return nil // Not a fatal error, the feature is just disabled.
}
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI(config.ValueOf.DB_URI).SetServerAPIOptions(serverAPI)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, opts)
if err != nil {
return err
}
// Ping the server to verify connection
if err := client.Ping(ctx, nil); err != nil {
return err
}
// Console log to confirm database connection
log.Sugar().Info("✅ Successfully connected to MongoDB database!")
Client = client
database := client.Database("tgf_dev") // Use a consistent database name
Links = database.Collection("links")
Users = database.Collection("users")
OTPs = database.Collection("otps")
Files = database.Collection("files")
// Initialize UserManager
UserMgr = NewUserManager(database, log)
// Initialize UserBotManager with encryption key from config
encryptionKey := config.ValueOf.BotEncryptionKey
if encryptionKey == "" {
encryptionKey = "default-encryption-key-change-me" // Fallback key
log.Warn("BotEncryptionKey not set in config, using default key")
}
UserBotMgr = NewUserBotManager(database, log, encryptionKey)
log.Info("MongoDB connection established successfully.")
return nil
}