File size: 4,140 Bytes
80ffd2e
 
 
 
 
 
 
644c352
 
 
80ffd2e
 
 
 
 
644c352
80ffd2e
 
 
644c352
 
 
 
 
 
 
80ffd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644c352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80ffd2e
 
 
 
 
 
644c352
 
 
 
 
 
 
 
 
 
 
 
 
 
80ffd2e
 
 
644c352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80ffd2e
 
 
 
 
 
 
 
 
 
644c352
80ffd2e
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main

import (
	"fmt"
	"log"
	"opus-api/internal/handler"
	"opus-api/internal/logger"
	"opus-api/internal/middleware"
	"opus-api/internal/model"
	"opus-api/internal/service"
	"opus-api/internal/tokenizer"
	"opus-api/internal/types"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func main() {
	// Load .env file
	if err := godotenv.Load(); err != nil {
		log.Printf("[INFO] No .env file found or error loading it: %v", err)
	} else {
		log.Printf("[INFO] .env file loaded successfully")
	}

	// Create logs directory
	if err := os.MkdirAll(types.LogDir, 0755); err != nil {
		log.Fatalf("Failed to create logs directory: %v", err)
	}

	// Cleanup old logs on startup
	if types.DebugMode {
		logger.CleanupOldLogs()
	}

	// Initialize tokenizer for token counting
	if err := tokenizer.Init(); err != nil {
		log.Printf("[WARN] Failed to initialize tokenizer: %v (will use fallback)", err)
	}

	// Initialize database
	if err := model.InitDB(); err != nil {
		log.Printf("[WARN] Failed to initialize database: %v (running without database)", err)
	} else {
		// Create default admin user
		if err := model.CreateDefaultAdmin(model.DB); err != nil {
			log.Printf("[WARN] Failed to create default admin: %v", err)
		}
	}

	// Initialize services
	var authService *service.AuthService
	var cookieService *service.CookieService
	var cookieValidator *service.CookieValidator
	var cookieRotator *service.CookieRotator

	if model.DB != nil {
		authService = service.NewAuthService(model.DB)
		cookieService = service.NewCookieService(model.DB)
		cookieValidator = service.NewCookieValidator(cookieService)
		cookieRotator = service.NewCookieRotator(cookieService, service.StrategyRoundRobin)

		// Store rotator in types for use in messages handler
		types.CookieRotatorInstance = cookieRotator
	}

	// Set Gin mode
	gin.SetMode(gin.ReleaseMode)

	// Create Gin router
	router := gin.Default()

	// Serve static files
	router.Static("/static", "./web/static")

	// Redirect root to login page or dashboard
	router.GET("/", func(c *gin.Context) {
		c.Redirect(302, "/static/index.html")
	})

	// Dashboard redirect
	router.GET("/dashboard", func(c *gin.Context) {
		c.Redirect(302, "/static/dashboard.html")
	})

	// Register API routes
	router.POST("/v1/messages", handler.HandleMessages)
	router.GET("/health", handler.HandleHealth)

	// Auth routes (only if database is available)
	if authService != nil {
		authHandler := handler.NewAuthHandler(authService)
		router.POST("/api/auth/login", authHandler.Login)
		router.POST("/api/auth/logout", authHandler.Logout)

		// Protected routes
		authGroup := router.Group("/api")
		authGroup.Use(middleware.AuthMiddleware(authService))
		{
			authGroup.GET("/auth/me", authHandler.Me)
			authGroup.PUT("/auth/password", authHandler.ChangePassword)

			// Cookie management routes
			if cookieService != nil && cookieValidator != nil {
				cookieHandler := handler.NewCookieHandler(cookieService, cookieValidator)
				authGroup.GET("/cookies", cookieHandler.ListCookies)
				authGroup.GET("/cookies/stats", cookieHandler.GetStats)
				authGroup.POST("/cookies", cookieHandler.CreateCookie)
				authGroup.GET("/cookies/:id", cookieHandler.GetCookie)
				authGroup.PUT("/cookies/:id", cookieHandler.UpdateCookie)
				authGroup.DELETE("/cookies/:id", cookieHandler.DeleteCookie)
				authGroup.POST("/cookies/:id/validate", cookieHandler.ValidateCookie)
				authGroup.POST("/cookies/validate/all", cookieHandler.ValidateAllCookies)
			}
		}
	}

	// Start server
	// Hugging Face Spaces uses port 7860
	port := 7860
	if envPort := os.Getenv("PORT"); envPort != "" {
		fmt.Sscanf(envPort, "%d", &port)
	}
	addr := fmt.Sprintf("0.0.0.0:%d", port)
	log.Printf("Server running on http://0.0.0.0:%d", port)
	log.Printf("Debug mode: %v", types.DebugMode)
	log.Printf("Log directory: %s", types.LogDir)
	log.Printf("Database connected: %v", model.DB != nil)

	if err := router.Run(addr); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}