-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2376 lines (2056 loc) · 67.9 KB
/
Copy pathmain.go
File metadata and controls
2376 lines (2056 loc) · 67.9 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"database/sql"
"encoding/json" // Temporarily added for migration
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"net/url"
"os" // Permanently added for environment variable access
"sort"
"strconv"
"strings"
"time"
"context" // New import for context
"crypto/rand" // New import for secure token generation
"encoding/base64" // New import for encoding tokens
"net/mail" // New import for email address parsing
"net/smtp" // New import for sending emails
"github.com/gorilla/sessions" // New import for sessions
"github.com/jung-kurt/gofpdf"
_ "github.com/lib/pq" // PostgreSQL driver
"golang.org/x/crypto/bcrypt"
)
type Series struct {
ID int
Title string
Year string
IMDBID string
EpisodesWatched int
TotalEpisodes int
Status string
Progress int
CoverURL string `db:"cover_url"`
UserID int // Foreign key to users table
Rating int // 1-5 stars
}
type Comment struct {
ID int
UserID int
Username string // For displaying who commented
Initial string // For avatar
IMDBID string
Content string
CreatedAt time.Time
}
// OldSeries struct for JSON migration
type OldSeries struct {
ID int `json:"id"`
Title string `json:"title"`
Year string `json:"year"`
IMDBID string `json:"imdb_id"`
EpisodesWatched int `json:"episodes_watched"`
TotalEpisodes int `json:"total_episodes"`
Status string `json:"status"`
Progress int `json:"progress"`
CoverURL string `json:"CoverURL"`
User string `json:"user"`
}
type User struct {
ID int
Username string
PasswordHash string
Email string
CreatedAt time.Time
IsAdmin bool // New field for admin status
AvatarURL string // Persistent avatar selection
}
type OMDbResponse struct {
Title string `json:"Title"`
Year string `json:"Year"`
TotalSeasons string `json:"totalSeasons"`
IMDBID string `json:"imdbID"`
Response string `json:"Response"`
Error string `json:"Error"`
Poster string `json:"Poster"`
}
type SearchResult struct {
Search []SearchItem `json:"Search"`
Response string `json:"Response"`
Error string `json:"Error"`
TotalResults string `json:"totalResults"`
}
type SearchItem struct {
Title string `json:"Title"`
Year string `json:"Year"`
IMDBID string `json:"imdbID"`
Type string `json:"Type"`
Poster string `json:"Poster"`
}
type UserWithAvatar struct {
ID int
Username string
Initial string
}
type UserStatsData struct {
UserID int
User string
EpisodesWatched int
EpisodesTotal int
Progress int
Completed int
WatchTimeHours int
Rank int
}
type PageData struct {
SeriesList []Series
SearchResults []SearchItem
SearchQuery string
ErrorMessage string
SuccessMessage string
APIAvailable bool
TotalSeries int
TotalWatched int
TotalEpisodes int
WatchTimeHours int
Rank int
SortBy string
Order string
UserStats []UserStatsData
User *User // Current logged-in user object
CurrentUser UserWithAvatar // Current user info
Users []UserWithAvatar // All users for switcher
FullUsers []User // Detailed list for admin
CurrentUserID int
// Social Features
ViewedUser *User // User whose list is being viewed
IsMutual map[string]bool // map[IMDBID]true for shared series
ActiveSeries *Series // For detail page
Comments []Comment // Comments for the active series
}
// Define a type for context keys to avoid collisions
type contextKey string
const (
dbPath = "data/series.db" // Updated path for Docker volume persistence
dataFile = "series.json" // Needed for migration
sessionName = "series-tracker-session"
userSessionKey = "userID"
userContextKey contextKey = "user" // Key to store User in request context
// PostgreSQL specific constants (default values - will be overwritten by environment variables)
defaultDBHost = "localhost"
defaultDBPort = "5432"
defaultDBUser = "user"
defaultDBPassword = "password"
defaultDBName = "seriestracker"
defaultSSLMode = "disable" // For local/Docker testing; use "require" or "verify-full" in production
)
var (
apiKey = os.Getenv("OMDB_API_KEY") // Load API Key from environment variable
)
var (
templates *template.Template
db *sql.DB // Global database connection
sessionStore *sessions.CookieStore // Session store
httpClient = &http.Client{
Timeout: 15 * time.Second,
}
)
func initDB() {
var err error
dbHostEnv := os.Getenv("DB_HOST")
if dbHostEnv == "" {
dbHostEnv = defaultDBHost
}
dbPortEnv := os.Getenv("DB_PORT")
if dbPortEnv == "" {
dbPortEnv = defaultDBPort
}
dbUserEnv := os.Getenv("DB_USER")
if dbUserEnv == "" {
dbUserEnv = defaultDBUser
}
dbPasswordEnv := os.Getenv("DB_PASSWORD")
if dbPasswordEnv == "" {
dbPasswordEnv = defaultDBPassword
}
dbNameEnv := os.Getenv("DB_NAME")
if dbNameEnv == "" {
dbNameEnv = defaultDBName
}
dbSSLModeEnv := os.Getenv("DB_SSLMODE")
if dbSSLModeEnv == "" {
dbSSLModeEnv = defaultSSLMode
}
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
dbHostEnv, dbPortEnv, dbUserEnv, dbPasswordEnv, dbNameEnv, dbSSLModeEnv)
db, err = sql.Open("postgres", connStr)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
// Ping the database to ensure connection is established
err = db.Ping()
if err != nil {
log.Fatalf("Failed to connect to the database: %v", err)
}
// Create users table
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
email VARCHAR(255) UNIQUE,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
reset_token TEXT,
reset_token_expires_at TIMESTAMPTZ,
is_admin BOOLEAN DEFAULT FALSE,
avatar_url TEXT
);
`)
if err != nil {
log.Fatalf("Failed to create users table: %v", err)
}
// Migrate existing database for avatar_url
_, _ = db.Exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar_url TEXT")
// Create series table
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS series (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
title VARCHAR(255) NOT NULL,
year VARCHAR(20),
imdb_id VARCHAR(20) NOT NULL,
episodes_watched INTEGER DEFAULT 0,
total_episodes INTEGER DEFAULT 0,
status VARCHAR(50) DEFAULT 'Watching',
cover_url TEXT,
UNIQUE (user_id, imdb_id), -- Ensure unique series per user
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
`)
if err != nil {
log.Fatalf("Failed to create series table: %v", err)
}
// Migrate existing database for rating
_, _ = db.Exec("ALTER TABLE series ADD COLUMN IF NOT EXISTS rating INTEGER DEFAULT 0")
// Create comments table
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS comments (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
imdb_id VARCHAR(20) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
`)
if err != nil {
log.Fatalf("Failed to create comments table: %v", err)
}
// Migrate existing database if necessary (increase year column length)
_, _ = db.Exec("ALTER TABLE series ALTER COLUMN year TYPE VARCHAR(20)")
// Perform migration if series.json exists and series table is empty
err = migrateSeriesJSONtoDB()
if err != nil {
log.Printf("Migration from series.json failed: %v. Continuing without migration.", err)
}
log.Println("Database initialized successfully.")
}
func main() {
// Initialize database
initDB()
defer db.Close()
// --- MODULE LOAD GUIDANCE ---
// If you encounter "module not found" or similar errors when running this application,
// it's likely that Go dependencies haven't been downloaded or synchronized.
// Please ensure you run the following commands in the project's root directory:
//
// go mod tidy
// go mod download
//
// After running these commands, try starting the application again.
// ----------------------------
// Initialize session store
sessionSecret := os.Getenv("SESSION_SECRET")
if sessionSecret == "" {
log.Fatal("SESSION_SECRET environment variable not set. This is required for secure session management.")
}
sessionStore = sessions.NewCookieStore([]byte(sessionSecret))
sessionStore.Options = &sessions.Options{
HttpOnly: true,
Secure: false, // Set to true in production with HTTPS
SameSite: http.SameSiteLaxMode,
}
// Prüfe API-Key zu Start
if apiKey == "" {
apiKey = "fbd55d5e" // Fallback to default key if environment variable is not set
log.Printf("⚠️ WARNUNG: OMDB_API_KEY Umgebungsvariable nicht gesetzt. Nutze Standard-Key.")
}
if apiKey == "dein_api_key_hier" || apiKey == "demo" {
log.Printf("⚠️ WARNUNG: Bitte trage einen gültigen OMDb API-Key in die OMDB_API_KEY Umgebungsvariable ein.")
}
// Templates laden
funcMap := template.FuncMap{
"div": func(a, b int) int {
if b == 0 {
return 0
}
return a / b
},
"percent": func(a, b int) int {
if b == 0 {
return 0
}
return (a * 100) / b
},
"seq": func(start, end int) []int {
var res []int
for i := start; i <= end; i++ {
res = append(res, i)
}
return res
},
}
templates = template.Must(template.New("").Funcs(funcMap).ParseGlob("templates/*.html"))
// HTTP Routes (protected)
http.Handle("/", authMiddleware(http.HandlerFunc(indexHandler)))
http.Handle("/mylist", authMiddleware(http.HandlerFunc(myListHandler)))
http.Handle("/add", authMiddleware(http.HandlerFunc(addHandler)))
http.Handle("/update", authMiddleware(http.HandlerFunc(updateHandler)))
http.Handle("/delete", authMiddleware(http.HandlerFunc(deleteHandler)))
http.Handle("/search", authMiddleware(http.HandlerFunc(searchHandler)))
http.Handle("/api/series", authMiddleware(http.HandlerFunc(apiSeriesHandler)))
http.Handle("/pdf", authMiddleware(http.HandlerFunc(pdfHandler)))
http.Handle("/stats", authMiddleware(http.HandlerFunc(statsHandler)))
http.Handle("/admin", authMiddleware(adminMiddleware(http.HandlerFunc(adminHandler))))
http.Handle("/admin/add-user", authMiddleware(adminMiddleware(http.HandlerFunc(adminAddUserHandler))))
http.Handle("/admin/reset-password", authMiddleware(adminMiddleware(http.HandlerFunc(adminResetPasswordHandler))))
http.Handle("/admin/delete-user", authMiddleware(adminMiddleware(http.HandlerFunc(adminDeleteUserHandler))))
http.Handle("/explore", authMiddleware(http.HandlerFunc(exploreHandler)))
http.Handle("/update-rating", authMiddleware(http.HandlerFunc(updateRatingHandler)))
http.Handle("/add-comment", authMiddleware(http.HandlerFunc(addCommentHandler)))
http.Handle("/series", authMiddleware(http.HandlerFunc(seriesDetailHandler)))
// New Authentication Routes (unprotected)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/register", registerHandler)
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/forgot-password", forgotPasswordHandler)
http.HandleFunc("/reset-password", resetPasswordHandler)
// Statische Dateien
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Automatisch freien Port finden
port := findAvailablePort()
if port == 0 {
port = 8081
}
fmt.Printf("🚀 Serien-Tracker Web-Oberfläche läuft auf http://localhost:%d\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil))
}
func findAvailablePort() int {
for port := 8081; port <= 8090; port++ {
addr := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", addr)
if err == nil {
listener.Close()
return port
}
}
return 0
}
// authMiddleware checks for an authenticated user in the session and adds the user object to the request context.
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := sessionStore.Get(r, sessionName)
if err != nil {
log.Printf("Error getting session: %v", err)
// Continue without a user if session is problematic
next.ServeHTTP(w, r)
return
}
userID, ok := session.Values[userSessionKey].(int)
if !ok || userID == 0 {
// No user in session, or invalid userID
next.ServeHTTP(w, r)
return
}
user, err := getUserByID(userID)
if err != nil {
log.Printf("Error getting user from DB for ID %d: %v", userID, err)
// User might have been deleted, clear session and continue
session.Values[userSessionKey] = nil
session.Save(r, w)
next.ServeHTTP(w, r)
return
}
if user == nil {
// User not found, clear session
session.Values[userSessionKey] = nil
session.Save(r, w)
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), userContextKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// getUserFromContext retrieves the User object from the request context.
func getUserFromContext(ctx context.Context) *User {
user, ok := ctx.Value(userContextKey).(*User)
if !ok {
return nil
}
return user
}
// adminMiddleware checks if the authenticated user has admin privileges.
func adminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUserFromContext(r.Context())
if user == nil || !user.IsAdmin {
http.Error(w, "Zugriff verweigert: Nur für Administratoren.", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// getUsers returns all registered users from the database.
func getUsers() ([]User, error) {
rows, err := db.Query("SELECT id, username, email, created_at, is_admin FROM users")
if err != nil {
return nil, fmt.Errorf("failed to query users: %w", err)
}
defer rows.Close()
var users []User
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Username, &u.Email, &u.CreatedAt, &u.IsAdmin); err != nil {
log.Printf("Error scanning user: %v", err)
continue
}
users = append(users, u)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating over users: %w", err)
}
return users, nil
}
// getUserByName retrieves a user by their username.
func getUserByName(username string) (*User, error) {
var user User
err := db.QueryRow("SELECT id, username, password_hash, email, created_at, is_admin FROM users WHERE username = $1", username).
Scan(&user.ID, &user.Username, &user.PasswordHash, &user.Email, &user.CreatedAt, &user.IsAdmin)
if err == sql.ErrNoRows {
return nil, nil // User not found
}
if err != nil {
return nil, fmt.Errorf("failed to query user by name: %w", err)
}
return &user, nil
}
// getUserByID retrieves a user by their ID.
func getUserByID(id int) (*User, error) {
var user User
err := db.QueryRow("SELECT id, username, password_hash, email, created_at, is_admin FROM users WHERE id = $1", id).
Scan(&user.ID, &user.Username, &user.PasswordHash, &user.Email, &user.CreatedAt, &user.IsAdmin)
if err == sql.ErrNoRows {
return nil, nil // User not found
}
if err != nil {
return nil, fmt.Errorf("failed to query user by ID: %w", err)
}
return &user, nil
}
func getUserWithAvatar(u User) UserWithAvatar {
initial := "U"
if len(u.Username) > 0 {
initial = strings.ToUpper(string(u.Username[0]))
}
return UserWithAvatar{
ID: u.ID,
Username: u.Username,
Initial: initial,
}
}
func getUserInfos(users []User) []UserWithAvatar {
infos := make([]UserWithAvatar, len(users))
for i, u := range users {
infos[i] = getUserWithAvatar(u)
}
return infos
}
// The following functions are removed:
// loadSeries()
// saveSeries()
// getUsers()
// getCurrentUser()
// getAllSeriesForUser retrieves all series for a given user ID from the database.
func getAllSeriesForUser(userID int) ([]Series, error) {
rows, err := db.Query("SELECT id, title, year, imdb_id, episodes_watched, total_episodes, status, cover_url, rating FROM series WHERE user_id = $1", userID)
if err != nil {
return nil, fmt.Errorf("failed to query series for user %d: %w", userID, err)
}
defer rows.Close()
var seriesList []Series
for rows.Next() {
var s Series
if err := rows.Scan(&s.ID, &s.Title, &s.Year, &s.IMDBID, &s.EpisodesWatched, &s.TotalEpisodes, &s.Status, &s.CoverURL, &s.Rating); err != nil {
log.Printf("Error scanning series: %v", err)
continue
}
s.UserID = userID // Set UserID for consistency
if s.TotalEpisodes > 0 {
s.Progress = (s.EpisodesWatched * 100) / s.TotalEpisodes
}
seriesList = append(seriesList, s)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating over series: %w", err)
}
return seriesList, nil
}
// addSeriesToDB inserts a new series into the database.
func addSeriesToDB(series Series) error {
stmt := `INSERT INTO series (user_id, title, year, imdb_id, episodes_watched, total_episodes, status, cover_url, rating) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`
var newID int
err := db.QueryRow(stmt,
series.UserID, series.Title, series.Year, series.IMDBID, series.EpisodesWatched, series.TotalEpisodes, series.Status, series.CoverURL, series.Rating,
).Scan(&newID)
if err != nil {
return fmt.Errorf("failed to insert series into database: %w", err)
}
// The newID is captured but not used directly, as the function returns error.
// If the calling context needs the ID, the function signature would need to change.
return nil
}
// updateSeriesInDB updates an existing series in the database.
func updateSeriesInDB(series Series) error {
res, err := db.Exec(
"UPDATE series SET episodes_watched = $1, total_episodes = $2, status = $3, cover_url = $4 WHERE id = $5 AND user_id = $6",
series.EpisodesWatched, series.TotalEpisodes, series.Status, series.CoverURL, series.ID, series.UserID,
)
if err != nil {
return fmt.Errorf("failed to update series in database: %w", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("failed to get rows affected during update: %w", err)
}
if rowsAffected == 0 {
return fmt.Errorf("no series found with ID %d for user %d to update", series.ID, series.UserID)
}
return nil
}
// deleteSeriesFromDB deletes a series from the database.
func deleteSeriesFromDB(seriesID int, userID int) error {
res, err := db.Exec("DELETE FROM series WHERE id = $1 AND user_id = $2", seriesID, userID)
if err != nil {
return fmt.Errorf("failed to delete series from database: %w", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("failed to get rows affected during delete: %w", err)
}
if rowsAffected == 0 {
return fmt.Errorf("no series found with ID %d for user %d to delete", seriesID, userID)
}
return nil
}
// Sortierfunktion
func sortSeries(series []Series, sortBy, order string) {
switch sortBy {
case "title":
if order == "desc" {
sort.Slice(series, func(i, j int) bool {
return series[i].Title > series[j].Title
})
} else {
sort.Slice(series, func(i, j int) bool {
return series[i].Title < series[j].Title
})
}
case "progress":
if order == "desc" {
sort.Slice(series, func(i, j int) bool {
// Höherer Fortschritt zuerst
if series[i].Progress != series[j].Progress {
return series[i].Progress > series[j].Progress
}
// Bei gleichem Fortschritt: nach Titel sortieren
return series[i].Title < series[j].Title
})
} else {
sort.Slice(series, func(i, j int) bool {
// Niedriger Fortschritt zuerst
if series[i].Progress != series[j].Progress {
return series[i].Progress < series[j].Progress
}
return series[i].Title < series[j].Title
})
}
case "watched":
if order == "desc" {
sort.Slice(series, func(i, j int) bool {
if series[i].EpisodesWatched != series[j].EpisodesWatched {
return series[i].EpisodesWatched > series[j].EpisodesWatched
}
return series[i].Title < series[j].Title
})
} else {
sort.Slice(series, func(i, j int) bool {
if series[i].EpisodesWatched != series[j].EpisodesWatched {
return series[i].EpisodesWatched < series[j].EpisodesWatched
}
return series[i].Title < series[j].Title
})
}
default:
sort.Slice(series, func(i, j int) bool {
return series[i].Title < series[j].Title
})
}
}
// HTTP Handler
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
user := getUserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
seriesList, err := getAllSeriesForUser(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching series: %v", err), http.StatusInternalServerError)
return
}
totalSeries, totalCompleted, err := calculateStats(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error calculating stats: %v", err), http.StatusInternalServerError)
return
}
apiAvailable := testAPIConnection()
// Get all users for the profile switcher
allUsers, err := getUsers()
if err != nil {
log.Printf("Error getting all users: %v", err)
allUsers = []User{} // Fallback to empty list
}
data := PageData{
SeriesList: seriesList,
APIAvailable: apiAvailable,
TotalSeries: totalSeries,
TotalWatched: totalCompleted,
User: user,
CurrentUser: getUserWithAvatar(*user),
Users: getUserInfos(allUsers),
CurrentUserID: user.ID,
}
err = templates.ExecuteTemplate(w, "index.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func pdfHandler(w http.ResponseWriter, r *http.Request) {
user := getUserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
seriesList, err := getAllSeriesForUser(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching series for PDF: %v", err), http.StatusInternalServerError)
return
}
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.SetFont("Helvetica", "", 12)
utf8 := pdf.UnicodeTranslatorFromDescriptor("")
pdf.AddPage()
pdf.SetFont("Helvetica", "B", 20)
pdf.Cell(0, 10, utf8(fmt.Sprintf("Meine Serienliste (%s)", user.Username)))
pdf.Ln(15)
countOnPage := 0
for _, s := range seriesList {
if countOnPage == 4 {
pdf.AddPage()
pdf.SetFont("Helvetica", "B", 20)
pdf.Cell(0, 10, utf8(fmt.Sprintf("Meine Serienliste (%s) (Fortsetzung)", user.Username)))
pdf.Ln(15)
countOnPage = 0
}
imgWidth := 40.0
startY := pdf.GetY()
var imgHeight float64 = 0
if s.CoverURL != "" && s.CoverURL != "N/A" {
resp, err := httpClient.Get(s.CoverURL)
if err == nil {
func() {
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return
}
imgName := fmt.Sprintf("cover_%d_%d", user.ID, s.ID) // Unique name per user and series
info := pdf.RegisterImageOptionsReader(
imgName,
gofpdf.ImageOptions{
ImageType: "JPG",
ReadDpi: true,
},
bytes.NewReader(data),
)
if info != nil && info.Width() > 0 {
imgHeight = info.Height() * imgWidth / info.Width()
pdf.ImageOptions(
imgName,
10, startY,
imgWidth, 0,
false,
gofpdf.ImageOptions{
ImageType: "JPG",
ReadDpi: true,
},
0,
"",
)
}
}()
}
}
if imgHeight == 0 {
imgHeight = 20
}
textX := 10 + imgWidth + 6
pdf.SetXY(textX, startY)
pdf.SetFont("Helvetica", "B", 14)
pdf.CellFormat(0, 7, utf8(fmt.Sprintf("%s (%s)", s.Title, s.Year)), "", 0, "L", false, 0, "")
pdf.Ln(8)
pdf.SetX(textX)
pdf.SetFont("Helvetica", "", 12)
pdf.MultiCell(0, 6,
utf8(fmt.Sprintf("Status: %s – %d/%d Episoden",
s.Status, s.EpisodesWatched, s.TotalEpisodes)),
"", "L", false,
)
endY := pdf.GetY()
finalY := startY + imgHeight
if endY > finalY {
finalY = endY
}
pdf.SetY(finalY + 10)
pdf.Line(10, pdf.GetY(), 200, pdf.GetY())
pdf.Ln(8)
countOnPage++
}
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=mylist_%s.pdf", user.Username))
err = pdf.Output(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// myListHandler für die Poster-Ansicht
func myListHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
user := getUserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
seriesList, err := getAllSeriesForUser(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching series: %v", err), http.StatusInternalServerError)
return
}
apiAvailable := testAPIConnection()
sortParam := r.URL.Query().Get("sort")
var sortBy, order string
switch sortParam {
case "title":
sortBy = "title"
order = "asc"
case "title_desc":
sortBy = "title"
order = "desc"
case "progress_asc":
sortBy = "progress"
order = "asc"
case "progress_desc":
sortBy = "progress"
order = "desc"
default:
sortBy = "title"
order = "asc"
}
sortSeries(seriesList, sortBy, order)
totalSeries, totalCompleted, err := calculateStats(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error calculating stats: %v", err), http.StatusInternalServerError)
return
}
// Get all users for the profile switcher
allUsers, err := getUsers()
if err != nil {
log.Printf("Error getting all users: %v", err)
allUsers = []User{} // Fallback to empty list
}
data := PageData{
SeriesList: seriesList,
APIAvailable: apiAvailable,
TotalSeries: totalSeries,
TotalWatched: totalCompleted, // Note: totalWatched is now totalCompleted
SortBy: sortBy,
Order: order,
User: user,
CurrentUser: getUserWithAvatar(*user),
Users: getUserInfos(allUsers),
CurrentUserID: user.ID,
}
err = templates.ExecuteTemplate(w, "mylist.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func addHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
user := getUserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
identifier := r.FormValue("identifier")
if identifier == "" {
http.Redirect(w, r, "/", http.StatusSeeOther) // Redirect back to index with an error might be better
return
}
omdbSeries, err := fetchIMDBData(identifier)
if err != nil {
seriesList, _ := getAllSeriesForUser(user.ID) // Fetch current user's series to display
totalSeries, totalCompleted, _ := calculateStats(user.ID)
allUsers, _ := getUsers()
data := PageData{
SeriesList: seriesList,
ErrorMessage: fmt.Sprintf("Fehler beim Hinzufügen: %v", err),
APIAvailable: testAPIConnection(),
TotalSeries: totalSeries,
TotalWatched: totalCompleted,
User: user,
CurrentUser: getUserWithAvatar(*user),
Users: getUserInfos(allUsers),
CurrentUserID: user.ID,
}
templates.ExecuteTemplate(w, "index.html", data)
return
}
totalEpisodes := 0
if omdbSeries.TotalSeasons != "" {
if seasons, err := strconv.Atoi(omdbSeries.TotalSeasons); err == nil {
totalEpisodes = seasons * 10
}
}
// Check if series already exists for this user
existingSeries, err := getAllSeriesForUser(user.ID)
if err != nil {
http.Error(w, fmt.Sprintf("Error checking existing series: %v", err), http.StatusInternalServerError)
return
}
for _, s := range existingSeries {
if s.IMDBID == omdbSeries.IMDBID {
seriesList, _ := getAllSeriesForUser(user.ID)
totalSeries, totalCompleted, _ := calculateStats(user.ID)
allUsers, _ := getUsers()
data := PageData{
SeriesList: seriesList,
ErrorMessage: "Serie ist bereits in deiner Bibliothek",
APIAvailable: testAPIConnection(),
TotalSeries: totalSeries,
TotalWatched: totalCompleted,
User: user,
CurrentUser: getUserWithAvatar(*user),
Users: getUserInfos(allUsers),
CurrentUserID: user.ID,
}
templates.ExecuteTemplate(w, "index.html", data)
return
}
}
newSeries := Series{
Title: omdbSeries.Title,
Year: omdbSeries.Year,
IMDBID: omdbSeries.IMDBID,