File size: 2,002 Bytes
1830215
 
 
 
aa300d8
1830215
 
 
 
 
 
 
 
 
 
 
836ff0c
 
2fa5701
aa300d8
 
49b198e
 
1830215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d498c7c
 
 
1830215
adb2908
836ff0c
 
 
2fa5701
836ff0c
aa300d8
 
49b198e
 
 
 
 
 
 
 
1830215
 
 
 
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
// 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
}