mirror of
https://github.com/skidoodle/ncore-stats.git
synced 2026-04-28 15:57:37 +02:00
jo lesz az
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func loadConfig() *Configuration {
|
||||
_ = godotenv.Load()
|
||||
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true, ForceColors: true})
|
||||
|
||||
cfg := &Configuration{}
|
||||
cfg.Ncore.Nick = os.Getenv("NICK")
|
||||
cfg.Ncore.Pass = os.Getenv("PASS")
|
||||
if cfg.Ncore.Nick == "" || cfg.Ncore.Pass == "" {
|
||||
logrus.Fatal("NICK and PASS environment variables are required")
|
||||
}
|
||||
|
||||
cfg.ServerPort = os.Getenv("SERVER_PORT")
|
||||
if cfg.ServerPort == "" {
|
||||
cfg.ServerPort = defaultPort
|
||||
} else if !strings.HasPrefix(cfg.ServerPort, ":") {
|
||||
cfg.ServerPort = ":" + cfg.ServerPort
|
||||
}
|
||||
|
||||
cfg.DatabasePath = os.Getenv("DATABASE_PATH")
|
||||
if cfg.DatabasePath == "" {
|
||||
cfg.DatabasePath = defaultDbFolder
|
||||
}
|
||||
|
||||
lvl, _ := logrus.ParseLevel(os.Getenv("LOG_LEVEL"))
|
||||
if lvl == 0 {
|
||||
lvl = logrus.InfoLevel
|
||||
}
|
||||
logrus.SetLevel(lvl)
|
||||
return cfg
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func initDB(cfg *Configuration) *sql.DB {
|
||||
_ = os.MkdirAll(cfg.DatabasePath, 0755)
|
||||
db, err := sql.Open("sqlite", fmt.Sprintf("%s/ncore_stats.db", cfg.DatabasePath))
|
||||
if err != nil {
|
||||
logrus.Fatalf("DB failed: %v", err)
|
||||
}
|
||||
|
||||
schemas := []string{
|
||||
`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, display_name TEXT UNIQUE, profile_id TEXT);`,
|
||||
`CREATE TABLE IF NOT EXISTS profile_history (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, timestamp DATETIME, rank INTEGER, upload TEXT, current_upload TEXT, current_download TEXT, points INTEGER, seeding_count INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE);`,
|
||||
}
|
||||
for _, s := range schemas {
|
||||
if _, err := db.Exec(s); err != nil {
|
||||
logrus.Fatalf("Schema error: %v", err)
|
||||
}
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (s *State) getLatest() ([]ProfileData, error) {
|
||||
query := `
|
||||
SELECT u.display_name, ph.timestamp, ph.rank, ph.upload, ph.current_upload, ph.current_download, ph.points, ph.seeding_count
|
||||
FROM profile_history ph
|
||||
INNER JOIN (SELECT user_id, MAX(timestamp) as ts FROM profile_history GROUP BY user_id) latest
|
||||
ON ph.user_id = latest.user_id AND ph.timestamp = latest.ts
|
||||
JOIN users u ON ph.user_id = u.id
|
||||
ORDER BY u.id ASC;`
|
||||
|
||||
rows, err := s.db.Query(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var res []ProfileData
|
||||
for rows.Next() {
|
||||
var p ProfileData
|
||||
rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount)
|
||||
res = append(res, p)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (s *State) profilesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
data, _ := s.getLatest()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func (s *State) historyHandler(w http.ResponseWriter, r *http.Request) {
|
||||
owner := r.URL.Query().Get("owner")
|
||||
rows, _ := s.db.Query(`SELECT u.display_name, ph.timestamp, ph.rank, ph.upload, ph.current_upload, ph.current_download, ph.points, ph.seeding_count FROM profile_history ph JOIN users u ON ph.user_id = u.id WHERE u.display_name = ? ORDER BY ph.timestamp ASC`, owner)
|
||||
defer rows.Close()
|
||||
|
||||
var history []ProfileData
|
||||
for rows.Next() {
|
||||
var p ProfileData
|
||||
rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount)
|
||||
history = append(history, p)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(history)
|
||||
}
|
||||
|
||||
func (s *State) historyModalHandler(w http.ResponseWriter, r *http.Request) {
|
||||
owner := r.URL.Query().Get("owner")
|
||||
fmt.Fprintf(w, `<div id="chart-data-container" data-owner="%s" x-init="renderChart('%s')"></div>`, owner, owner)
|
||||
}
|
||||
|
||||
func (s *State) rootHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
latest, _ := s.getLatest()
|
||||
tmpl, _ := template.ParseFiles("web/index.html")
|
||||
tmpl.Execute(w, struct{ Profiles []ProfileData }{latest})
|
||||
}
|
||||
@@ -2,62 +2,18 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/sirupsen/logrus"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Configuration holds application settings loaded from the environment.
|
||||
type Configuration struct {
|
||||
ServerPort string
|
||||
DatabasePath string
|
||||
LogLevel logrus.Level
|
||||
Ncore struct {
|
||||
Nick string
|
||||
Pass string
|
||||
}
|
||||
}
|
||||
|
||||
// State holds application runtime state and dependencies.
|
||||
type State struct {
|
||||
config *Configuration
|
||||
db *sql.DB
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// ProfileData represents a snapshot of a user's profile statistics.
|
||||
type ProfileData struct {
|
||||
Owner string `json:"owner"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Rank int `json:"rank"`
|
||||
Upload string `json:"upload"`
|
||||
CurrentUpload string `json:"current_upload"`
|
||||
CurrentDownload string `json:"current_download"`
|
||||
Points int `json:"points"`
|
||||
SeedingCount int `json:"seeding_count"`
|
||||
}
|
||||
|
||||
// User represents a user whose stats are being tracked.
|
||||
type User struct {
|
||||
ID int
|
||||
DisplayName string
|
||||
ProfileID string
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPort = ":3000"
|
||||
defaultDbFolder = "./data"
|
||||
@@ -65,417 +21,67 @@ const (
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
config := initializeApplication()
|
||||
|
||||
db, err := initializeDatabase(config)
|
||||
if err != nil {
|
||||
logrus.Fatalf("Database initialization failed: %v", err)
|
||||
}
|
||||
config := loadConfig()
|
||||
db := initDB(config)
|
||||
defer db.Close()
|
||||
|
||||
state := &State{
|
||||
config: config,
|
||||
db: db,
|
||||
client: &http.Client{Timeout: 30 * time.Second},
|
||||
client: &http.Client{Timeout: 45 * time.Second},
|
||||
}
|
||||
|
||||
// If a command-line flag was handled, the program should exit.
|
||||
if handleFlags(state) {
|
||||
return
|
||||
}
|
||||
|
||||
router := http.NewServeMux()
|
||||
router.HandleFunc("/api/profiles", state.profilesHandler)
|
||||
router.HandleFunc("/api/history", state.historyHandler)
|
||||
router.Handle("/", http.FileServer(http.Dir("web")))
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/profiles", state.profilesHandler)
|
||||
mux.HandleFunc("/api/history", state.historyHandler)
|
||||
mux.HandleFunc("/api/history-modal", state.historyModalHandler)
|
||||
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web"))))
|
||||
mux.HandleFunc("/", state.rootHandler)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: config.ServerPort,
|
||||
Handler: router,
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go state.profileFetcherLoop(ctx)
|
||||
go state.worker(ctx)
|
||||
|
||||
startServer(server)
|
||||
handleShutdown(server, cancel)
|
||||
}
|
||||
|
||||
// initializeApplication sets up logging and loads the application configuration.
|
||||
func initializeApplication() *Configuration {
|
||||
logrus.SetFormatter(&logrus.TextFormatter{
|
||||
FullTimestamp: true,
|
||||
TimestampFormat: time.RFC3339,
|
||||
ForceColors: true,
|
||||
})
|
||||
|
||||
config, err := loadConfiguration()
|
||||
if err != nil {
|
||||
logrus.Fatalf("Failed to load configuration: %v", err)
|
||||
}
|
||||
|
||||
logrus.SetLevel(config.LogLevel)
|
||||
logrus.Info("Application configuration loaded successfully")
|
||||
return config
|
||||
}
|
||||
|
||||
// loadConfiguration loads settings from .env files and the environment.
|
||||
func loadConfiguration() (*Configuration, error) {
|
||||
// godotenv.Load will not override existing environment variables,
|
||||
// making it safe for use in production environments like Docker.
|
||||
_ = godotenv.Load(".env.local")
|
||||
_ = godotenv.Load()
|
||||
|
||||
cfg := &Configuration{}
|
||||
|
||||
required := map[string]*string{
|
||||
"NICK": &cfg.Ncore.Nick,
|
||||
"PASS": &cfg.Ncore.Pass,
|
||||
}
|
||||
for key, ptr := range required {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return nil, fmt.Errorf("missing required environment variable: %s", key)
|
||||
go func() {
|
||||
logrus.Infof("Server active on %s", config.ServerPort)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logrus.Fatalf("Server failure: %v", err)
|
||||
}
|
||||
*ptr = value
|
||||
}
|
||||
}()
|
||||
|
||||
cfg.ServerPort = defaultPort
|
||||
if port := os.Getenv("SERVER_PORT"); port != "" {
|
||||
cfg.ServerPort = ":" + strings.TrimLeft(port, ":")
|
||||
}
|
||||
<-ctx.Done()
|
||||
logrus.Info("Shutting down gracefully...")
|
||||
|
||||
cfg.DatabasePath = defaultDbFolder
|
||||
if path := os.Getenv("DATABASE_PATH"); path != "" {
|
||||
cfg.DatabasePath = path
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logrus.Errorf("Shutdown error: %v", err)
|
||||
}
|
||||
|
||||
switch strings.ToLower(os.Getenv("LOG_LEVEL")) {
|
||||
case "debug":
|
||||
cfg.LogLevel = logrus.DebugLevel
|
||||
case "warn":
|
||||
cfg.LogLevel = logrus.WarnLevel
|
||||
case "error":
|
||||
cfg.LogLevel = logrus.ErrorLevel
|
||||
default:
|
||||
cfg.LogLevel = logrus.InfoLevel
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// initializeDatabase connects to the SQLite database and ensures tables are created.
|
||||
func initializeDatabase(config *Configuration) (*sql.DB, error) {
|
||||
dbPath := fmt.Sprintf("%s/ncore_stats.db", config.DatabasePath)
|
||||
|
||||
if err := os.MkdirAll(config.DatabasePath, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory: %w", err)
|
||||
}
|
||||
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
usersTableSQL := `CREATE TABLE IF NOT EXISTS users ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "display_name" TEXT NOT NULL UNIQUE, "profile_id" TEXT NOT NULL);`
|
||||
if _, err := db.Exec(usersTableSQL); err != nil {
|
||||
return nil, fmt.Errorf("failed to create users table: %w", err)
|
||||
}
|
||||
|
||||
profileHistoryTableSQL := `CREATE TABLE IF NOT EXISTS profile_history ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "timestamp" DATETIME NOT NULL, "rank" INTEGER, "upload" TEXT, "current_upload" TEXT, "current_download" TEXT, "points" INTEGER, "seeding_count" INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE);`
|
||||
if _, err := db.Exec(profileHistoryTableSQL); err != nil {
|
||||
return nil, fmt.Errorf("failed to create profile_history table: %w", err)
|
||||
}
|
||||
|
||||
logrus.Info("Database initialized successfully")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// handleFlags processes command-line flags and returns true if the program should exit.
|
||||
func handleFlags(s *State) bool {
|
||||
addUserFlag := flag.String("add-user", "", "Add a new user. Provide as 'DisplayName,ProfileID'")
|
||||
addUser := flag.String("add-user", "", "Format: DisplayName,ProfileID")
|
||||
flag.Parse()
|
||||
|
||||
if *addUserFlag != "" {
|
||||
parts := strings.Split(*addUserFlag, ",")
|
||||
if len(parts) != 2 {
|
||||
logrus.Fatal("Invalid format for --add-user. Use 'DisplayName,ProfileID'")
|
||||
if *addUser != "" {
|
||||
parts := strings.Split(*addUser, ",")
|
||||
if len(parts) == 2 {
|
||||
_, err := s.db.Exec("INSERT INTO users(display_name, profile_id) VALUES(?, ?)", parts[0], parts[1])
|
||||
if err != nil {
|
||||
logrus.Fatalf("Add user failed: %v", err)
|
||||
}
|
||||
logrus.Infof("User %s added", parts[0])
|
||||
}
|
||||
s.addUser(parts[0], parts[1])
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// startServer runs the HTTP server in a new goroutine.
|
||||
func startServer(server *http.Server) {
|
||||
go func() {
|
||||
logrus.Infof("Server starting on %s", server.Addr)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logrus.Fatalf("Server failed to start: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// handleShutdown waits for a termination signal and performs a graceful shutdown.
|
||||
func handleShutdown(server *http.Server, cancel context.CancelFunc) {
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||
<-sigChan
|
||||
|
||||
logrus.Info("Shutdown signal received, initiating graceful shutdown...")
|
||||
cancel() // Notify background goroutines to stop.
|
||||
|
||||
shutdownCtx, cancelTimeout := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancelTimeout()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logrus.Errorf("Server shutdown error: %v", err)
|
||||
}
|
||||
logrus.Info("Server shutdown complete")
|
||||
}
|
||||
|
||||
// profilesHandler serves the latest profile data for all tracked users.
|
||||
func (s *State) profilesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
query := `
|
||||
SELECT u.display_name, ph.timestamp, ph.rank, ph.upload, ph.current_upload, ph.current_download, ph.points, ph.seeding_count
|
||||
FROM profile_history ph
|
||||
INNER JOIN (
|
||||
SELECT user_id, MAX(timestamp) as max_ts
|
||||
FROM profile_history
|
||||
GROUP BY user_id
|
||||
) latest ON ph.user_id = latest.user_id AND ph.timestamp = latest.max_ts
|
||||
JOIN users u ON ph.user_id = u.id;
|
||||
`
|
||||
rows, err := s.db.Query(query)
|
||||
if err != nil {
|
||||
http.Error(w, "Could not read latest profiles from database", http.StatusInternalServerError)
|
||||
logrus.Errorf("Error querying latest profiles: %v", err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var latestProfiles []ProfileData
|
||||
for rows.Next() {
|
||||
var p ProfileData
|
||||
if err := rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount); err != nil {
|
||||
http.Error(w, "Could not process profile data", http.StatusInternalServerError)
|
||||
logrus.Errorf("Error scanning latest profile row: %v", err)
|
||||
return
|
||||
}
|
||||
latestProfiles = append(latestProfiles, p)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(latestProfiles); err != nil {
|
||||
logrus.Errorf("Error encoding latest profiles to JSON: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// historyHandler serves the full profile history for a single user.
|
||||
func (s *State) historyHandler(w http.ResponseWriter, r *http.Request) {
|
||||
owner := r.URL.Query().Get("owner")
|
||||
if owner == "" {
|
||||
http.Error(w, "Missing 'owner' query parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT u.display_name, ph.timestamp, ph.rank, ph.upload, ph.current_upload, ph.current_download, ph.points, ph.seeding_count
|
||||
FROM profile_history ph
|
||||
JOIN users u ON ph.user_id = u.id
|
||||
WHERE u.display_name = ?
|
||||
ORDER BY ph.timestamp ASC
|
||||
`
|
||||
rows, err := s.db.Query(query, owner)
|
||||
if err != nil {
|
||||
http.Error(w, "Could not read history from database", http.StatusInternalServerError)
|
||||
logrus.Errorf("Error querying history for %s: %v", owner, err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var userHistory []ProfileData
|
||||
for rows.Next() {
|
||||
var p ProfileData
|
||||
if err := rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount); err != nil {
|
||||
http.Error(w, "Could not process history data", http.StatusInternalServerError)
|
||||
logrus.Errorf("Error scanning history row for %s: %v", owner, err)
|
||||
return
|
||||
}
|
||||
userHistory = append(userHistory, p)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(userHistory); err != nil {
|
||||
logrus.Errorf("Error encoding history for %s to JSON: %v", err, owner)
|
||||
}
|
||||
}
|
||||
|
||||
// serveStatic returns an http.HandlerFunc that serves a static file.
|
||||
func serveStatic(fileName, contentType string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
http.ServeFile(w, r, fileName)
|
||||
}
|
||||
}
|
||||
|
||||
// profileFetcherLoop runs a background task to fetch profiles on a schedule.
|
||||
func (s *State) profileFetcherLoop(ctx context.Context) {
|
||||
logrus.Info("Starting background profile fetcher...")
|
||||
s.fetchAndLogAllProfiles() // Fetch immediately on startup.
|
||||
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.fetchAndLogAllProfiles()
|
||||
case <-ctx.Done():
|
||||
logrus.Info("Stopping background profile fetcher.")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// addUser inserts a new user into the database.
|
||||
func (s *State) addUser(displayName, profileID string) {
|
||||
stmt, err := s.db.Prepare("INSERT INTO users(display_name, profile_id) VALUES(?, ?)")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Failed to prepare statement for adding user: %v", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
if _, err = stmt.Exec(displayName, profileID); err != nil {
|
||||
logrus.Fatalf("Failed to add user %s: %v", displayName, err)
|
||||
}
|
||||
logrus.Infof("User '%s' with profile ID '%s' added successfully.", displayName, profileID)
|
||||
}
|
||||
|
||||
// getUsers retrieves all tracked users from the database.
|
||||
func (s *State) getUsers() ([]User, error) {
|
||||
rows, err := s.db.Query("SELECT id, display_name, profile_id FROM users")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error querying users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []User
|
||||
for rows.Next() {
|
||||
var u User
|
||||
if err := rows.Scan(&u.ID, &u.DisplayName, &u.ProfileID); err != nil {
|
||||
return nil, fmt.Errorf("error scanning user row: %w", err)
|
||||
}
|
||||
users = append(users, u)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// logToDB inserts a new profile data point into the history table.
|
||||
func (s *State) logToDB(profile *ProfileData, userID int) error {
|
||||
stmt, err := s.db.Prepare(`INSERT INTO profile_history(user_id, timestamp, rank, upload, current_upload, current_download, points, seeding_count) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error preparing insert statement: %w", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
if _, err = stmt.Exec(userID, profile.Timestamp, profile.Rank, profile.Upload, profile.CurrentUpload, profile.CurrentDownload, profile.Points, profile.SeedingCount); err != nil {
|
||||
return fmt.Errorf("error executing insert for %s: %w", profile.Owner, err)
|
||||
}
|
||||
logrus.Infof("Profile for %s logged successfully to database.", profile.Owner)
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchAndLogAllProfiles orchestrates the fetching and logging of all user profiles.
|
||||
func (s *State) fetchAndLogAllProfiles() {
|
||||
users, err := s.getUsers()
|
||||
if err != nil {
|
||||
logrus.Errorf("Could not get users to fetch: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(users) == 0 {
|
||||
logrus.Info("No users in database to fetch. Use the --add-user flag to add one.")
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Infof("Starting profile fetch for %d user(s).", len(users))
|
||||
for _, user := range users {
|
||||
profile, err := s.fetchProfile(user)
|
||||
if err != nil {
|
||||
logrus.Errorf("Error fetching profile for %s: %v", user.DisplayName, err)
|
||||
continue
|
||||
}
|
||||
if err := s.logToDB(profile, user.ID); err != nil {
|
||||
logrus.Errorf("Error logging profile to DB for %s: %v", user.DisplayName, err)
|
||||
}
|
||||
// Pause between requests to avoid rate-limiting.
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
logrus.Info("Profile fetch cycle complete.")
|
||||
}
|
||||
|
||||
// fetchProfile retrieves and parses the profile page for a single user.
|
||||
func (s *State) fetchProfile(user User) (*ProfileData, error) {
|
||||
profileURL := ncoreBaseURL + user.ProfileID
|
||||
req, err := http.NewRequest("GET", profileURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Cookie", fmt.Sprintf("nick=%s; pass=%s", s.config.Ncore.Nick, s.config.Ncore.Pass))
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error performing request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("received non-200 status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing profile document: %w", err)
|
||||
}
|
||||
|
||||
return parseProfileDoc(doc, user.DisplayName), nil
|
||||
}
|
||||
|
||||
// parseProfileDoc extracts data from a profile document.
|
||||
func parseProfileDoc(doc *goquery.Document, displayName string) *ProfileData {
|
||||
profile := &ProfileData{Owner: displayName, Timestamp: time.Now()}
|
||||
doc.Find(".userbox_tartalom_mini .profil_jobb_elso2").Each(func(i int, s *goquery.Selection) {
|
||||
label, value := s.Text(), s.Next().Text()
|
||||
switch label {
|
||||
case "Helyezés:":
|
||||
profile.Rank, _ = strconv.Atoi(strings.TrimSuffix(value, "."))
|
||||
case "Feltöltés:":
|
||||
profile.Upload = value
|
||||
case "Aktuális feltöltés:":
|
||||
profile.CurrentUpload = value
|
||||
case "Aktuális letöltés:":
|
||||
profile.CurrentDownload = value
|
||||
case "Pontok száma:":
|
||||
profile.Points, _ = strconv.Atoi(strings.ReplaceAll(value, " ", ""))
|
||||
}
|
||||
})
|
||||
|
||||
doc.Find(".lista_mini_fej").Each(func(i int, s *goquery.Selection) {
|
||||
text := s.Text()
|
||||
if matches := regexp.MustCompile(`\((\d+)\)`).FindStringSubmatch(text); len(matches) > 1 {
|
||||
fmt.Sscanf(matches[1], "%d", &profile.SeedingCount)
|
||||
}
|
||||
if matches := regexp.MustCompile(`le: ([\d.]+ \w+/s)`).FindStringSubmatch(text); len(matches) > 1 {
|
||||
profile.CurrentDownload = matches[1]
|
||||
}
|
||||
if matches := regexp.MustCompile(`fel: ([\d.]+ \w+/s)`).FindStringSubmatch(text); len(matches) > 1 {
|
||||
profile.CurrentUpload = matches[1]
|
||||
}
|
||||
})
|
||||
|
||||
return profile
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Configuration holds application settings.
|
||||
type Configuration struct {
|
||||
ServerPort string
|
||||
DatabasePath string
|
||||
LogLevel logrus.Level
|
||||
Ncore struct {
|
||||
Nick string
|
||||
Pass string
|
||||
}
|
||||
}
|
||||
|
||||
// ProfileData represents a snapshot of a user's profile statistics.
|
||||
type ProfileData struct {
|
||||
Owner string `json:"owner"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Rank int `json:"rank"`
|
||||
Upload string `json:"upload"`
|
||||
CurrentUpload string `json:"current_upload"`
|
||||
CurrentDownload string `json:"current_download"`
|
||||
Points int `json:"points"`
|
||||
SeedingCount int `json:"seeding_count"`
|
||||
}
|
||||
|
||||
// User represents a tracked user.
|
||||
type User struct {
|
||||
ID int
|
||||
DisplayName string
|
||||
ProfileID string
|
||||
}
|
||||
|
||||
type State struct {
|
||||
config *Configuration
|
||||
db *sql.DB
|
||||
client *http.Client
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s *State) worker(ctx context.Context) {
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
|
||||
s.scrapeAll(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.scrapeAll(ctx)
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *State) scrapeAll(ctx context.Context) {
|
||||
rows, err := s.db.Query("SELECT id, display_name, profile_id FROM users")
|
||||
if err != nil {
|
||||
logrus.Errorf("User query failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []User
|
||||
for rows.Next() {
|
||||
var u User
|
||||
rows.Scan(&u.ID, &u.DisplayName, &u.ProfileID)
|
||||
users = append(users, u)
|
||||
}
|
||||
|
||||
if len(users) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Infof("Starting concurrent scrape for %d users", len(users))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for _, u := range users {
|
||||
wg.Add(1)
|
||||
go func(user User) {
|
||||
defer wg.Done()
|
||||
|
||||
time.Sleep(time.Duration(100+(user.ID%500)) * time.Millisecond)
|
||||
|
||||
profile, err := s.fetchProfile(user)
|
||||
if err != nil {
|
||||
logrus.Errorf("[%s] Fetch failed: %v", user.DisplayName, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = s.db.Exec(`INSERT INTO profile_history(user_id, timestamp, rank, upload, current_upload, current_download, points, seeding_count) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
user.ID, profile.Timestamp, profile.Rank, profile.Upload, profile.CurrentUpload, profile.CurrentDownload, profile.Points, profile.SeedingCount)
|
||||
if err != nil {
|
||||
logrus.Errorf("[%s] DB log failed: %v", user.DisplayName, err)
|
||||
} else {
|
||||
logrus.Infof("[%s] Metrics recorded", user.DisplayName)
|
||||
}
|
||||
}(u)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
logrus.Info("Scrape cycle complete")
|
||||
}
|
||||
|
||||
func (s *State) fetchProfile(user User) (*ProfileData, error) {
|
||||
req, _ := http.NewRequest("GET", ncoreBaseURL+user.ProfileID, nil)
|
||||
req.Header.Set("Cookie", fmt.Sprintf("nick=%s; pass=%s", s.config.Ncore.Nick, s.config.Ncore.Pass))
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := &ProfileData{Owner: user.DisplayName, Timestamp: time.Now()}
|
||||
doc.Find(".userbox_tartalom_mini .profil_jobb_elso2").Each(func(i int, sel *goquery.Selection) {
|
||||
label, value := sel.Text(), sel.Next().Text()
|
||||
switch label {
|
||||
case "Helyezés:":
|
||||
p.Rank, _ = strconv.Atoi(strings.TrimSuffix(value, "."))
|
||||
case "Feltöltés:":
|
||||
p.Upload = value
|
||||
case "Pontok száma:":
|
||||
p.Points, _ = strconv.Atoi(strings.ReplaceAll(value, " ", ""))
|
||||
}
|
||||
})
|
||||
|
||||
doc.Find(".lista_mini_fej").Each(func(i int, sel *goquery.Selection) {
|
||||
text := sel.Text()
|
||||
if m := regexp.MustCompile(`\((\d+)\)`).FindStringSubmatch(text); len(m) > 1 {
|
||||
p.SeedingCount, _ = strconv.Atoi(m[1])
|
||||
}
|
||||
if m := regexp.MustCompile(`fel: ([\d.]+ \w+/s)`).FindStringSubmatch(text); len(m) > 1 {
|
||||
p.CurrentUpload = m[1]
|
||||
}
|
||||
if m := regexp.MustCompile(`le: ([\d.]+ \w+/s)`).FindStringSubmatch(text); len(m) > 1 {
|
||||
p.CurrentDownload = m[1]
|
||||
}
|
||||
})
|
||||
|
||||
return p, nil
|
||||
}
|
||||
+88
-39
@@ -2,48 +2,97 @@
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>nCore Profile Stats</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>nCore Stats</title>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
|
||||
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="preload" as="style"
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
|
||||
<style>
|
||||
[x-cloak] {
|
||||
display: none !important;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body class="p-4 sm:p-8">
|
||||
<header class="text-center mb-12">
|
||||
<h1 class="text-3xl sm:text-4xl font-semibold text-glow text-green-400 header-cursor">nCore_Profile_Stats</h1>
|
||||
</header>
|
||||
<main class="container mx-auto">
|
||||
<section class="w-full max-w-6xl mx-auto">
|
||||
<div id="loader" class="flex justify-center items-center py-20" aria-live="polite">
|
||||
<span class="text-2xl loader-text">INITIALIZING</span>
|
||||
</div>
|
||||
<div id="error-message" class="hidden text-center bg-red-900/50 border border-red-500 p-4" aria-live="polite">
|
||||
</div>
|
||||
<div id="profiles" class="hidden grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"></div>
|
||||
</section>
|
||||
</main>
|
||||
<div id="historyModal"
|
||||
class="modal-container fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-80">
|
||||
<div class="modal-panel relative w-full max-w-5xl flex flex-col bg-[#0A0F14] border border-[#30363d]"
|
||||
style="height: calc(100% - 2rem); max-height: 800px;">
|
||||
<div class="p-4 border-b border-b-gray-700 flex justify-between items-center flex-shrink-0">
|
||||
<h2 class="text-xl font-semibold">History: <span id="modal-owner-name" class="text-glow text-green-400"></span>
|
||||
</h2>
|
||||
<button id="modal-close-btn" class="action-btn px-2 py-1" aria-label="Close modal">[X]</button>
|
||||
</div>
|
||||
<div id="modal-content" class="p-4 flex-grow relative flex items-center justify-center">
|
||||
<div id="modal-loader" class="text-2xl loader-text">FETCHING DATA</div>
|
||||
<div id="modal-message" class="hidden text-2xl loader-text"></div>
|
||||
<div id="chartContainer" class="absolute inset-4 hidden"></div>
|
||||
</div>
|
||||
<body x-data="{ modalOpen: false, modalOwner: '' }" :class="modalOpen ? 'overflow-hidden' : ''" x-cloak>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>nCore Stats</h1>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<div id="profiles" class="grid">
|
||||
{{range .Profiles}}
|
||||
<article class="card">
|
||||
<div class="card-header">
|
||||
<h3>{{.Owner}}</h3>
|
||||
<span class="rank-badge">RANK #{{.Rank}}</span>
|
||||
</div>
|
||||
|
||||
<div class="stats-group">
|
||||
<div class="stat">
|
||||
<span class="stat-label">Total Upload</span>
|
||||
<span class="stat-value">{{.Upload}}</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Points</span>
|
||||
<span class="stat-value">{{.Points}}</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Up Speed</span>
|
||||
<span class="stat-value">{{if .CurrentUpload}}{{.CurrentUpload}}{{else}}0 B/s{{end}}</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Down Speed</span>
|
||||
<span class="stat-value">{{if .CurrentDownload}}{{.CurrentDownload}}{{else}}0
|
||||
B/s{{end}}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button hx-get="/api/history-modal?owner={{.Owner}}" hx-target="#modal-stats-root"
|
||||
@click="modalOpen = true; modalOwner = '{{.Owner}}'" class="btn-view">
|
||||
View History
|
||||
</button>
|
||||
</article>
|
||||
{{else}}
|
||||
<div
|
||||
style="grid-column: 1 / -1; padding: 4rem; text-align: center; color: var(--muted); border: 1px dashed var(--border-dim);">
|
||||
No profiles found. Use the CLI to add users.
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script src="script.js"></script>
|
||||
|
||||
<template x-teleport="body">
|
||||
<div x-show="modalOpen" class="modal-overlay" x-cloak @keydown.escape.window="modalOpen = false">
|
||||
<div class="modal-panel" @click.away="modalOpen = false">
|
||||
<div class="modal-header">
|
||||
<h2 x-text="'HISTORY: ' + modalOwner.toUpperCase()"></h2>
|
||||
<button @click="modalOpen = false" class="close-btn">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="2">
|
||||
<path d="M18 6L6 18M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="modal-content" class="modal-body">
|
||||
<div id="modal-stats-root" style="flex: 1; min-height: 0;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script src="/static/script.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
+147
-334
@@ -1,335 +1,148 @@
|
||||
const app = {
|
||||
config: {
|
||||
api: {
|
||||
profiles: '/api/profiles',
|
||||
historyBase: '/api/history?owner='
|
||||
},
|
||||
messages: {
|
||||
noProfiles: 'STATUS: NO_PROFILES_FOUND.',
|
||||
noHistory: 'STATUS: NO_HISTORY_FOUND.',
|
||||
fetchError: (status) => `ERR_NET_FETCH (${status})`,
|
||||
fatalError: (msg) => `FATAL: ${msg}.`
|
||||
}
|
||||
},
|
||||
dom: {},
|
||||
state: {
|
||||
historyChart: null,
|
||||
modalRequestID: 0,
|
||||
},
|
||||
init() {
|
||||
this.dom.loader = document.getElementById('loader');
|
||||
this.dom.errorMessage = document.getElementById('error-message');
|
||||
this.dom.profilesContainer = document.getElementById('profiles');
|
||||
this.dom.historyModal = document.getElementById('historyModal');
|
||||
this.dom.modalOwnerName = document.getElementById('modal-owner-name');
|
||||
this.dom.modalCloseBtn = document.getElementById('modal-close-btn');
|
||||
this.dom.modalLoader = document.getElementById('modal-loader');
|
||||
this.dom.modalMessage = document.getElementById('modal-message');
|
||||
this.dom.chartContainer = document.getElementById('chartContainer');
|
||||
this.addEventListeners();
|
||||
this.fetchProfiles();
|
||||
},
|
||||
addEventListeners() {
|
||||
this.dom.profilesContainer.addEventListener('click', (e) => {
|
||||
const button = e.target.closest('.view-history-btn');
|
||||
if (button) this.showHistory(button.dataset.owner);
|
||||
});
|
||||
this.dom.modalCloseBtn.addEventListener('click', () => this.closeModal());
|
||||
this.dom.historyModal.addEventListener('click', (e) => {
|
||||
if (e.target === this.dom.historyModal) this.closeModal();
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && this.dom.historyModal.classList.contains('visible')) {
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
this.dom.historyModal.addEventListener('keydown', (e) => this.trapFocus(e));
|
||||
},
|
||||
async fetchProfiles() {
|
||||
try {
|
||||
const response = await fetch(this.config.api.profiles);
|
||||
if (!response.ok) throw new Error(this.config.messages.fetchError(response.status));
|
||||
const profiles = await response.json();
|
||||
if (!profiles || profiles.length === 0) {
|
||||
this.showError(this.config.messages.noProfiles);
|
||||
return;
|
||||
}
|
||||
const fragment = document.createDocumentFragment();
|
||||
profiles.forEach(profile => {
|
||||
const article = document.createElement('article');
|
||||
article.className = "flex flex-col bg-opacity-20 bg-gray-700 border border-[#30363d] hover:border-gray-500 transition-colors duration-300";
|
||||
article.innerHTML = `
|
||||
|
||||
<div class="p-5 flex-grow">
|
||||
<h3 class="text-xl font-bold mb-4 text-glow text-green-400">> ${profile.owner}</h3>
|
||||
<div class="grid grid-cols-2 gap-x-4 text-sm">
|
||||
<span class="text-gray-400"># Rank</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.rank}</span>
|
||||
<span class="text-gray-400">^ Total Upload</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.upload}</span>
|
||||
<span class="text-gray-400">+ Current Upload</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.current_upload}</span>
|
||||
<span class="text-gray-400">- Current Download</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.current_download}</span>
|
||||
<span class="text-gray-400">* Points</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.points.toLocaleString()}</span>
|
||||
<span class="text-gray-400">~ Seeding</span>
|
||||
<span class="font-semibold text-green-400 text-right">${profile.seeding_count} torrents</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-5 pt-2">
|
||||
<button data-owner="${profile.owner}" class="view-history-btn action-btn w-full py-2 font-semibold">VIEW_HISTORY</button>
|
||||
</div>`;
|
||||
fragment.appendChild(article);
|
||||
});
|
||||
this.dom.profilesContainer.appendChild(fragment);
|
||||
this.dom.profilesContainer.style.display = 'grid';
|
||||
this.dom.loader.style.display = 'none';
|
||||
} catch (e) {
|
||||
this.showError(this.config.messages.fatalError(e.message));
|
||||
console.error(e);
|
||||
}
|
||||
},
|
||||
async showHistory(owner) {
|
||||
this.state.modalRequestID++;
|
||||
const currentRequestID = this.state.modalRequestID;
|
||||
this.dom.modalOwnerName.textContent = owner;
|
||||
this.dom.modalLoader.style.display = 'block';
|
||||
this.dom.chartContainer.style.display = 'none';
|
||||
this.dom.modalMessage.style.display = 'none';
|
||||
this.dom.historyModal.classList.add('visible');
|
||||
document.body.style.overflow = 'hidden';
|
||||
this.dom.modalCloseBtn.focus();
|
||||
try {
|
||||
const response = await fetch(`${this.config.api.historyBase}${encodeURIComponent(owner)}`);
|
||||
if (this.state.modalRequestID !== currentRequestID) return;
|
||||
if (!response.ok) throw new Error(this.config.messages.fetchError(response.status));
|
||||
const historyData = await response.json();
|
||||
if (this.state.modalRequestID !== currentRequestID) return;
|
||||
if (!historyData || historyData.length === 0) {
|
||||
this.showModalMessage(this.config.messages.noHistory);
|
||||
} else {
|
||||
this.dom.modalLoader.style.display = 'none';
|
||||
this.dom.chartContainer.style.display = 'block';
|
||||
this.renderChart(historyData);
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.state.modalRequestID === currentRequestID) {
|
||||
this.showModalMessage(this.config.messages.fatalError(e.message));
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
renderChart(historyData) {
|
||||
if (this.state.historyChart) {
|
||||
this.state.historyChart.destroy();
|
||||
}
|
||||
this.dom.chartContainer.innerHTML = ' <canvas tabindex="0"> </canvas>';
|
||||
const canvas = this.dom.chartContainer.querySelector('canvas');
|
||||
if (!canvas) return;
|
||||
const parseUploadValue = (value) => {
|
||||
if (typeof value !== 'string') return 0;
|
||||
const num = parseFloat(value.replace(/,/g, '').replace(/TiB|GiB|MiB/i, '').trim());
|
||||
if (isNaN(num)) return 0;
|
||||
if (value.toLowerCase().includes('gib')) return num / 1024;
|
||||
if (value.toLowerCase().includes('mib')) return num / 1024 / 1024;
|
||||
return num;
|
||||
};
|
||||
const labels = historyData.map(r => new Date(r.timestamp).toLocaleDateString('en-CA'));
|
||||
const rankData = historyData.map(r => r.rank);
|
||||
const uploadData = historyData.map(r => parseUploadValue(r.upload));
|
||||
const pointsData = historyData.map(r => r.points);
|
||||
const seedingData = historyData.map(r => r.seeding_count);
|
||||
const textColor = getComputedStyle(document.documentElement).getPropertyValue('--text-primary').trim();
|
||||
const gridColor = 'rgba(50, 50, 50, 0.5)';
|
||||
const font = {
|
||||
family: "'Fira Code', monospace"
|
||||
};
|
||||
const accentGreen = getComputedStyle(document.documentElement).getPropertyValue('--accent-green').trim();
|
||||
const accentAmber = getComputedStyle(document.documentElement).getPropertyValue('--accent-amber').trim();
|
||||
const accentCyan = getComputedStyle(document.documentElement).getPropertyValue('--accent-cyan').trim();
|
||||
const accentMagenta = getComputedStyle(document.documentElement).getPropertyValue('--accent-magenta').trim();
|
||||
this.state.historyChart = new Chart(canvas, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{
|
||||
label: 'Rank',
|
||||
data: rankData,
|
||||
borderColor: accentMagenta,
|
||||
tension: 0.2,
|
||||
yAxisID: 'yRank',
|
||||
fill: false
|
||||
}, {
|
||||
label: 'Upload (TiB)',
|
||||
data: uploadData,
|
||||
borderColor: accentGreen,
|
||||
tension: 0.2,
|
||||
yAxisID: 'yUpload',
|
||||
fill: false
|
||||
}, {
|
||||
label: 'Points',
|
||||
data: pointsData,
|
||||
borderColor: accentAmber,
|
||||
tension: 0.2,
|
||||
yAxisID: 'yPoints',
|
||||
fill: false
|
||||
}, {
|
||||
label: 'Seeding',
|
||||
data: seedingData,
|
||||
borderColor: accentCyan,
|
||||
tension: 0.2,
|
||||
yAxisID: 'ySeeding',
|
||||
fill: false
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: {
|
||||
color: gridColor,
|
||||
borderDash: [2, 4]
|
||||
},
|
||||
ticks: {
|
||||
color: textColor,
|
||||
font: font
|
||||
}
|
||||
},
|
||||
yRank: {
|
||||
type: 'linear',
|
||||
position: 'left',
|
||||
reverse: true,
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Rank',
|
||||
color: accentMagenta,
|
||||
font: font
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
ticks: {
|
||||
color: accentMagenta,
|
||||
font: font
|
||||
}
|
||||
},
|
||||
yUpload: {
|
||||
type: 'linear',
|
||||
position: 'left',
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Upload (TiB)',
|
||||
color: accentGreen,
|
||||
font: font
|
||||
},
|
||||
grid: {
|
||||
color: gridColor,
|
||||
borderDash: [2, 4]
|
||||
},
|
||||
ticks: {
|
||||
color: accentGreen,
|
||||
font: font
|
||||
},
|
||||
offset: true
|
||||
},
|
||||
yPoints: {
|
||||
type: 'linear',
|
||||
position: 'right',
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Points',
|
||||
color: accentAmber,
|
||||
font: font
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
ticks: {
|
||||
color: accentAmber,
|
||||
font: font
|
||||
}
|
||||
},
|
||||
ySeeding: {
|
||||
type: 'linear',
|
||||
position: 'right',
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Seeding',
|
||||
color: accentCyan,
|
||||
font: font
|
||||
},
|
||||
grid: {
|
||||
drawOnChartArea: false
|
||||
},
|
||||
ticks: {
|
||||
color: accentCyan,
|
||||
font: font
|
||||
},
|
||||
offset: true
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
labels: {
|
||||
color: textColor,
|
||||
font: font
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: '#000',
|
||||
titleFont: font,
|
||||
bodyFont: font,
|
||||
padding: 10,
|
||||
cornerRadius: 0,
|
||||
borderColor: textColor,
|
||||
borderWidth: 1
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
closeModal() {
|
||||
this.state.modalRequestID++;
|
||||
this.dom.historyModal.classList.remove('visible');
|
||||
document.body.style.overflow = 'auto';
|
||||
if (this.state.historyChart) {
|
||||
this.state.historyChart.destroy();
|
||||
this.state.historyChart = null;
|
||||
}
|
||||
},
|
||||
showError(message) {
|
||||
this.dom.loader.style.display = 'none';
|
||||
this.dom.errorMessage.textContent = message;
|
||||
this.dom.errorMessage.style.display = 'block';
|
||||
},
|
||||
showModalMessage(message) {
|
||||
this.dom.modalLoader.style.display = 'none';
|
||||
this.dom.chartContainer.style.display = 'none';
|
||||
this.dom.modalMessage.textContent = message;
|
||||
this.dom.modalMessage.style.display = 'block';
|
||||
},
|
||||
trapFocus(e) {
|
||||
if (e.key !== 'Tab') return;
|
||||
const focusableElements = this.dom.historyModal.querySelectorAll('button, [tabindex]:not([tabindex="-1"])');
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
if (e.shiftKey) {
|
||||
if (document.activeElement === firstElement) {
|
||||
lastElement.focus();
|
||||
e.preventDefault();
|
||||
}
|
||||
} else {
|
||||
if (document.activeElement === lastElement) {
|
||||
firstElement.focus();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
const config = {
|
||||
api: {
|
||||
history: '/api/history?owner='
|
||||
}
|
||||
};
|
||||
document.addEventListener('DOMContentLoaded', () => app.init());
|
||||
|
||||
let currentChart = null;
|
||||
|
||||
async function renderChart(owner) {
|
||||
const root = document.getElementById('modal-stats-root');
|
||||
if (!root) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${config.api.history}${encodeURIComponent(owner)}`);
|
||||
if (!response.ok) throw new Error('Network error');
|
||||
const historyData = await response.json();
|
||||
|
||||
if (!historyData || historyData.length === 0) {
|
||||
root.innerHTML = '<div class="spinner-container"><p class="stat-label">No history available.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const parseUploadValue = (value) => {
|
||||
if (typeof value !== 'string') return 0;
|
||||
const num = parseFloat(value.replace(/,/g, '').replace(/TiB|GiB|MiB/i, '').trim());
|
||||
if (isNaN(num)) return 0;
|
||||
const lowerVal = value.toLowerCase();
|
||||
if (lowerVal.includes('tib')) return num;
|
||||
if (lowerVal.includes('gib')) return num / 1024;
|
||||
if (lowerVal.includes('mib')) return num / 1024 / 1024;
|
||||
return num;
|
||||
};
|
||||
|
||||
const series = [
|
||||
{
|
||||
name: 'Upload',
|
||||
data: historyData.map(r => ({ x: new Date(r.timestamp).getTime(), y: parseUploadValue(r.upload) }))
|
||||
},
|
||||
{
|
||||
name: 'Rank',
|
||||
data: historyData.map(r => ({ x: new Date(r.timestamp).getTime(), y: r.rank }))
|
||||
},
|
||||
{
|
||||
name: 'Points',
|
||||
data: historyData.map(r => ({ x: new Date(r.timestamp).getTime(), y: r.points }))
|
||||
},
|
||||
{
|
||||
name: 'Seeding',
|
||||
data: historyData.map(r => ({ x: new Date(r.timestamp).getTime(), y: r.seeding_count }))
|
||||
}
|
||||
];
|
||||
|
||||
root.innerHTML = '<div id="chart-mount" style="height: 100%; width: 100%;"></div>';
|
||||
|
||||
const options = {
|
||||
series: series,
|
||||
chart: {
|
||||
type: 'line',
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
background: 'transparent',
|
||||
foreColor: '#888',
|
||||
fontFamily: 'Inter, system-ui, sans-serif',
|
||||
toolbar: { show: false },
|
||||
animations: { enabled: true, easing: 'easeinout', speed: 800 }
|
||||
},
|
||||
theme: { mode: 'dark' },
|
||||
colors: ['#FFFFFF', '#00FF00', '#0066FF', '#FF00FF'],
|
||||
stroke: {
|
||||
curve: 'smooth',
|
||||
width: [3, 2, 2, 2],
|
||||
dashArray: 0
|
||||
},
|
||||
grid: {
|
||||
borderColor: '#1a1a1a',
|
||||
strokeDashArray: 0,
|
||||
padding: { top: 20, bottom: 0, left: 20, right: 20 },
|
||||
xaxis: { lines: { show: true } },
|
||||
yaxis: { lines: { show: true } }
|
||||
},
|
||||
xaxis: {
|
||||
type: 'datetime',
|
||||
labels: {
|
||||
style: { fontSize: '10px', fontWeight: 600 },
|
||||
datetimeUTC: false
|
||||
},
|
||||
axisBorder: { show: false },
|
||||
axisTicks: { show: false }
|
||||
},
|
||||
yaxis: [
|
||||
{
|
||||
seriesName: 'Upload',
|
||||
labels: {
|
||||
style: { colors: '#FFF', fontSize: '10px', fontWeight: 700 },
|
||||
formatter: (v) => v != null ? v.toFixed(2) : ''
|
||||
}
|
||||
},
|
||||
{
|
||||
seriesName: 'Rank',
|
||||
opposite: true,
|
||||
reversed: true,
|
||||
labels: {
|
||||
style: { colors: '#00FF00', fontSize: '10px', fontWeight: 700 },
|
||||
formatter: (v) => v != null ? '#' + Math.round(v) : ''
|
||||
}
|
||||
},
|
||||
{
|
||||
seriesName: 'Points',
|
||||
show: false
|
||||
},
|
||||
{
|
||||
seriesName: 'Seeding',
|
||||
show: false
|
||||
}
|
||||
],
|
||||
legend: {
|
||||
position: 'bottom',
|
||||
fontSize: '14px',
|
||||
fontWeight: 600,
|
||||
markers: { width: 10, height: 10, radius: 2 },
|
||||
itemMargin: { horizontal: 15, vertical: 10 }
|
||||
},
|
||||
tooltip: {
|
||||
shared: true,
|
||||
theme: 'dark',
|
||||
x: { format: 'dd MMM yyyy HH:mm' },
|
||||
y: {
|
||||
formatter: (val, { seriesIndex }) => {
|
||||
if (val == null) return '--';
|
||||
switch (seriesIndex) {
|
||||
case 0: return val.toFixed(3) + ' TiB';
|
||||
case 1: return '#' + Math.round(val);
|
||||
default: return Math.round(val).toLocaleString();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
markers: { size: 0, hover: { size: 5 } }
|
||||
};
|
||||
|
||||
if (currentChart) currentChart.destroy();
|
||||
currentChart = new ApexCharts(document.getElementById('chart-mount'), options);
|
||||
currentChart.render();
|
||||
|
||||
} catch (e) {
|
||||
root.innerHTML = `<div class="spinner-container"><p class="stat-label" style="color: #ef4444;">Error: ${e.message}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
+257
-80
@@ -1,91 +1,268 @@
|
||||
:root {
|
||||
--bg-main: #0A0F14;
|
||||
--text-primary: #E0E0E0;
|
||||
--text-secondary: #8B949E;
|
||||
--border-color: #30363d;
|
||||
--accent-green: #28a745;
|
||||
--accent-amber: #FFB800;
|
||||
--accent-cyan: #00BFFF;
|
||||
--accent-magenta: #FF0057;
|
||||
--accent-hover: #1F2937;
|
||||
:root {
|
||||
--bg: #000000;
|
||||
--fg: #ffffff;
|
||||
--border: #ffffff;
|
||||
--border-dim: #1a1a1a;
|
||||
--muted: #666666;
|
||||
--accent: #ffffff;
|
||||
}
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body {
|
||||
background-color: var(--bg-main);
|
||||
color: var(--text-primary);
|
||||
font-family: 'Fira Code', monospace;
|
||||
overflow-x: hidden;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
|
||||
[x-cloak] {
|
||||
display: none !important;
|
||||
}
|
||||
body::before {
|
||||
content: " ";
|
||||
display: block;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
|
||||
z-index: 100;
|
||||
pointer-events: none;
|
||||
background-size: 100% 2px, 3px 100%;
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
background-color: var(--bg);
|
||||
overflow: hidden;
|
||||
}
|
||||
body::after {
|
||||
content: " ";
|
||||
display: block;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 60%, rgba(0, 0, 0, 0.8));
|
||||
z-index: 101;
|
||||
pointer-events: none;
|
||||
|
||||
body {
|
||||
color: var(--fg);
|
||||
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||
line-height: 1.4;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.text-glow {
|
||||
text-shadow: 0 0 5px rgba(0, 255, 65, 0.5);
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
width: 100%;
|
||||
padding: 2.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
}
|
||||
.header-cursor::after {
|
||||
content: '_';
|
||||
animation: blink 1s step-end infinite;
|
||||
|
||||
header {
|
||||
margin-bottom: 2.5rem;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--border-dim);
|
||||
padding-bottom: 1.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@keyframes blink {
|
||||
50% {
|
||||
opacity: 0;
|
||||
|
||||
h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.2em;
|
||||
}
|
||||
|
||||
main {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 1.25rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--bg);
|
||||
border: 1px solid var(--border-dim);
|
||||
padding: 1.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
border-color: var(--muted);
|
||||
background-color: #050505;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.card h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.rank-badge {
|
||||
font-family: monospace;
|
||||
font-size: 0.7rem;
|
||||
color: var(--muted);
|
||||
background: #111;
|
||||
padding: 3px 6px;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.stats-group {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.stat {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #111;
|
||||
padding-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.6rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.btn-view {
|
||||
margin-top: auto;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-dim);
|
||||
color: var(--fg);
|
||||
padding: 0.75rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
}
|
||||
|
||||
.btn-view:hover {
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
border-color: var(--fg);
|
||||
}
|
||||
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background-color: rgba(0, 0, 0, 0.9);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.modal-panel {
|
||||
background-color: var(--bg);
|
||||
border: 1px solid var(--border-dim);
|
||||
width: 90vw;
|
||||
max-width: 1200px;
|
||||
height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
padding: 1.25rem 2rem;
|
||||
border-bottom: 1px solid var(--border-dim);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.modal-header h2 {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.2em;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1.5rem 2rem;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
main::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
main::-webkit-scrollbar-track {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
main::-webkit-scrollbar-thumb {
|
||||
background: var(--border-dim);
|
||||
}
|
||||
|
||||
.apexcharts-canvas,
|
||||
.apexcharts-canvas *,
|
||||
.apexcharts-canvas *:focus {
|
||||
outline: none !important;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
.apexcharts-yaxis-label {
|
||||
font-weight: 700 !important;
|
||||
}
|
||||
|
||||
.apexcharts-tooltip {
|
||||
background: #000 !important;
|
||||
border: 1px solid #333 !important;
|
||||
color: #fff !important;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.action-btn {
|
||||
background-color: transparent;
|
||||
border: 1px solid var(--text-secondary);
|
||||
color: var(--text-secondary);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
.action-btn:hover {
|
||||
background-color: var(--accent-hover);
|
||||
border-color: var(--text-primary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.loader-text::after {
|
||||
content: '_';
|
||||
animation: blink 1s step-end infinite;
|
||||
}
|
||||
.modal-container {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease-in-out;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
.modal-container.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.modal-panel {
|
||||
transform: scale(0.95);
|
||||
transition: transform 0.2s ease-in-out;
|
||||
}
|
||||
.modal-container.visible .modal-panel {
|
||||
transform: scale(1);
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user