diff --git a/app/gopherbook/main.go b/app/gopherbook/main.go index 4c8ed0c..1c9cf49 100644 --- a/app/gopherbook/main.go +++ b/app/gopherbook/main.go @@ -4,8 +4,9 @@ import ( "archive/zip" "crypto/aes" "crypto/cipher" - "crypto/sha256" "crypto/rand" + "crypto/sha256" + "embed" "encoding/base64" "encoding/json" "encoding/xml" @@ -15,8 +16,8 @@ import ( "net/http" "net/url" "os" - "regexp" "path/filepath" + "regexp" "sort" "strings" "sync" @@ -26,6 +27,9 @@ import ( yzip "github.com/yeka/zip" ) +//go:embed templates/index.html +var templateFS embed.FS + // ComicInfo represents the standard ComicInfo.xml metadata type ComicInfo struct { XMLName xml.Name `xml:"ComicInfo"` @@ -36,8 +40,8 @@ type ComicInfo struct { Artist string `xml:"Artist"` Inker string `xml:"Inker"` Publisher string `xml:"Publisher"` - Genre string `xml:"Genre"` // Standard field - TagsXml string `xml:"Tags"` // User-requested field for flexibility + Genre string `xml:"Genre"` + TagsXml string `xml:"Tags"` StoryArc string `xml:"StoryArc"` Year string `xml:"Year"` Month string `xml:"Month"` @@ -46,9 +50,9 @@ type ComicInfo struct { } type User struct { - Username string `json:"username"` - PasswordHash string `json:"password_hash"` - IsAdmin bool `json:"is_admin"` // NEW + Username string `json:"username"` + PasswordHash string `json:"password_hash"` + IsAdmin bool `json:"is_admin"` } type Comic struct { @@ -67,9 +71,10 @@ type Comic struct { FileType string `json:"file_type"` Encrypted bool `json:"encrypted"` HasPassword bool `json:"has_password"` - Password string `json:"-"` // Don't expose password in JSON + Password string `json:"-"` Tags []string `json:"tags"` UploadedAt time.Time `json:"uploaded_at"` + Bookmarks []int `json:"bookmarks"` } type Session struct { @@ -84,37 +89,36 @@ type Tag struct { } var ( - users = make(map[string]User) - sessions = make(map[string]Session) - comics = make(map[string]Comic) - tags = make(map[string]Tag) - comicPasswords = make(map[string]string) - comicsMutex sync.RWMutex - sessionsMutex sync.RWMutex - tagsMutex sync.RWMutex - passwordsMutex sync.RWMutex + users = make(map[string]User) + sessions = make(map[string]Session) + comics = make(map[string]Comic) + tags = make(map[string]Tag) + comicPasswords = make(map[string]string) + comicsMutex sync.RWMutex + sessionsMutex sync.RWMutex + tagsMutex sync.RWMutex + passwordsMutex sync.RWMutex currentEncryptionKey []byte - libraryPath = "./library" - cachePath = "./cache/covers" - etcPath = "./etc" - currentUser string - registrationEnabled = true + libraryPath = "./library" + cachePath = "./cache/covers" + etcPath = "./etc" + currentUser string + registrationEnabled = true ) func main() { - // Initialize directories os.MkdirAll(filepath.Join(libraryPath, "Unorganized"), 0755) os.MkdirAll(cachePath, 0755) os.MkdirAll(etcPath, 0755) - // Load users, comics, and tags loadUsers() - // Setup routes + http.HandleFunc("/api/register", handleRegister) http.HandleFunc("/api/login", handleLogin) http.HandleFunc("/api/logout", handleLogout) http.HandleFunc("/api/comics", authMiddleware(handleComics)) http.HandleFunc("/api/upload", authMiddleware(handleUpload)) + http.HandleFunc("/api/user", authMiddleware(handleUser)) http.HandleFunc("/api/organize", authMiddleware(handleOrganize)) http.HandleFunc("/api/pages/", authMiddleware(handleComicPages)) http.HandleFunc("/api/comic/", authMiddleware(handleComicFile)) @@ -122,6 +126,7 @@ func main() { http.HandleFunc("/api/tags", authMiddleware(handleTags)) http.HandleFunc("/api/comic-tags/", authMiddleware(handleComicTags)) http.HandleFunc("/api/set-password/", authMiddleware(handleSetPassword)) + http.HandleFunc("/api/bookmark/", authMiddleware(handleBookmark)) http.HandleFunc("/api/admin/toggle-registration", authMiddleware(handleToggleRegistration)) http.HandleFunc("/api/admin/delete-comic/", authMiddleware(handleDeleteComic)) http.HandleFunc("/", serveUI) @@ -134,179 +139,179 @@ func handleRegister(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.Method != http.MethodPost { - log.Println("Register: Method not POST") http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } if !registrationEnabled { - http.Error(w, "Registration disabled", http.StatusForbidden) - return + http.Error(w, "Registration disabled", http.StatusForbidden) + return } + var req struct { Username string `json:"username"` Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - log.Printf("Register: JSON decode error: %v", err) http.Error(w, "Invalid request", http.StatusBadRequest) return } - log.Printf("Register attempt: username=%s", req.Username) - if req.Username == "" || req.Password == "" { - log.Println("Register: Empty username or password") http.Error(w, "Username and password required", http.StatusBadRequest) return } if _, exists := users[req.Username]; exists { - log.Printf("Register: User %s already exists", req.Username) http.Error(w, "User already exists", http.StatusConflict) return } hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { - log.Printf("Register: Bcrypt error: %v", err) http.Error(w, "Error creating user", http.StatusInternalServerError) return } - // Replace the user creation block (after hash generation): users[req.Username] = User{ - Username: req.Username, - PasswordHash: string(hash), - IsAdmin: len(users) == 0, // NEW: First user is admin + Username: req.Username, + PasswordHash: string(hash), + IsAdmin: len(users) == 0, } saveUsers() - if len(users) == 1 { // NEW: Init admin config - saveAdminConfig() - registrationEnabled = true + if len(users) == 1 { + saveAdminConfig() + registrationEnabled = true } - // Create per-user directories + userLibrary := filepath.Join("./library", req.Username) os.MkdirAll(filepath.Join(userLibrary, "Unorganized"), 0755) os.MkdirAll(filepath.Join("./cache/covers", req.Username), 0755) - log.Printf("Register: User %s created successfully", req.Username) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(map[string]string{"message": "User created"}) } func handleToggleRegistration(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost && r.Method != http.MethodGet { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - user := getCurrentUser(r) - if !user.IsAdmin { - http.Error(w, "Admin only", http.StatusForbidden) - return - } - if r.Method == http.MethodPost { - registrationEnabled = !registrationEnabled - saveAdminConfig() - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]bool{"enabled": registrationEnabled}) + if r.Method != http.MethodPost && r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + user := getCurrentUser(r) + if !user.IsAdmin { + http.Error(w, "Admin only", http.StatusForbidden) + return + } + if r.Method == http.MethodPost { + registrationEnabled = !registrationEnabled + saveAdminConfig() + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]bool{"enabled": registrationEnabled}) +} + +func handleUser(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + user := getCurrentUser(r) + json.NewEncoder(w).Encode(map[string]interface{}{ + "username": user.Username, + "is_admin": user.IsAdmin, + }) } func getCurrentUser(r *http.Request) User { - cookie, err := r.Cookie("session") - if err != nil { - return User{} // Empty user if no cookie - } - sessionsMutex.RLock() - session, exists := sessions[cookie.Value] - sessionsMutex.RUnlock() - if !exists { - return User{} - } - return users[session.Username] + cookie, err := r.Cookie("session") + if err != nil { + return User{} + } + sessionsMutex.RLock() + session, exists := sessions[cookie.Value] + sessionsMutex.RUnlock() + if !exists { + return User{} + } + return users[session.Username] } func handleLogin(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Type", "application/json") - if r.Method != http.MethodPost { - log.Println("Login: Method not POST") - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } - var req struct { - Username string `json:"username"` - Password string `json:"password"` - } + var req struct { + Username string `json:"username"` + Password string `json:"password"` + } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - log.Printf("Login: JSON decode error: %v", err) - http.Error(w, "Invalid request", http.StatusBadRequest) - return - } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "Invalid request", http.StatusBadRequest) + return + } - log.Printf("Login attempt: username=%s", req.Username) + user, exists := users[req.Username] + if !exists { + http.Error(w, "Invalid credentials", http.StatusUnauthorized) + return + } - user, exists := users[req.Username] - if !exists { - log.Printf("Login: User %s not found", req.Username) - http.Error(w, "Invalid credentials", http.StatusUnauthorized) - return - } + if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { + http.Error(w, "Invalid credentials", http.StatusUnauthorized) + return + } - if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { - log.Printf("Login: Password mismatch for %s", req.Username) - http.Error(w, "Invalid credentials", http.StatusUnauthorized) - return - } + token := generateToken() + sessionsMutex.Lock() + sessions[token] = Session{ + Username: req.Username, + ExpiresAt: time.Now().Add(24 * time.Hour), + } + sessionsMutex.Unlock() - token := generateToken() - sessionsMutex.Lock() - sessions[token] = Session{ - Username: req.Username, - ExpiresAt: time.Now().Add(24 * time.Hour), - } - sessionsMutex.Unlock() + currentUser = req.Username + key := deriveKey(req.Password) + libraryPath = filepath.Join("./library", currentUser) + cachePath = filepath.Join("./cache/covers", currentUser) + os.MkdirAll(filepath.Join(libraryPath, "Unorganized"), 0755) + os.MkdirAll(cachePath, 0755) - currentUser = req.Username - key := deriveKey(req.Password) - libraryPath = filepath.Join("./library", currentUser) - cachePath = filepath.Join("./cache/covers", currentUser) - os.MkdirAll(filepath.Join(libraryPath, "Unorganized"), 0755) - os.MkdirAll(cachePath, 0755) + comicsMutex.Lock() + comics = make(map[string]Comic) + comicsMutex.Unlock() + tagsMutex.Lock() + tags = make(map[string]Tag) + tagsMutex.Unlock() + passwordsMutex.Lock() + comicPasswords = make(map[string]string) + passwordsMutex.Unlock() - comicsMutex.Lock() - comics = make(map[string]Comic) - comicsMutex.Unlock() - tagsMutex.Lock() - tags = make(map[string]Tag) - tagsMutex.Unlock() - passwordsMutex.Lock() - comicPasswords = make(map[string]string) - passwordsMutex.Unlock() + loadComics() + loadTags() + loadPasswordsWithKey(key) + currentEncryptionKey = key + scanLibrary() - loadComics() - loadTags() - loadPasswordsWithKey(key) - currentEncryptionKey = key - scanLibrary() + http.SetCookie(w, &http.Cookie{ + Name: "session", + Value: token, + Expires: time.Now().Add(24 * time.Hour), + HttpOnly: true, + Path: "/", + }) - http.SetCookie(w, &http.Cookie{ - Name: "session", - Value: token, - Expires: time.Now().Add(24 * time.Hour), - HttpOnly: true, - Path: "/", - }) - - log.Printf("Login: User %s logged in successfully", req.Username) - json.NewEncoder(w).Encode(map[string]interface{}{ - "message": "Login successful", - "token": token, - "is_admin": user.IsAdmin, - }) + json.NewEncoder(w).Encode(map[string]interface{}{ + "message": "Login successful", + "token": token, + "is_admin": user.IsAdmin, + }) } func handleLogout(w http.ResponseWriter, r *http.Request) { @@ -316,7 +321,7 @@ func handleLogout(w http.ResponseWriter, r *http.Request) { delete(sessions, cookie.Value) sessionsMutex.Unlock() } - // Clear sensitive data from memory + comicsMutex.Lock() comics = make(map[string]Comic) comicsMutex.Unlock() @@ -328,7 +333,7 @@ func handleLogout(w http.ResponseWriter, r *http.Request) { passwordsMutex.Unlock() currentEncryptionKey = nil currentUser = "" - libraryPath = "./library" // Reset to default + libraryPath = "./library" cachePath = "./cache/covers" http.SetCookie(w, &http.Cookie{ @@ -356,7 +361,6 @@ func handleComics(w http.ResponseWriter, r *http.Request) { comicList = append(comicList, comic) } - // Sort by artist, then series, then number sort.Slice(comicList, func(i, j int) bool { if comicList[i].Artist != comicList[j].Artist { return comicList[i].Artist < comicList[j].Artist @@ -377,7 +381,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { return } - r.ParseMultipartForm(100 << 20) // 100 MB max + r.ParseMultipartForm(100 << 20) file, header, err := r.FormFile("file") if err != nil { @@ -389,16 +393,11 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { filename := header.Filename ext := strings.ToLower(filepath.Ext(filename)) - validExts := map[string]bool{ - ".cbz": true, - } - - if !validExts[ext] { + if ext != ".cbz" { http.Error(w, "Invalid file type", http.StatusBadRequest) return } - // Save to Unorganized initially destPath := filepath.Join(libraryPath, "Unorganized", filename) destFile, err := os.Create(destPath) if err != nil { @@ -412,16 +411,13 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { return } - // Process the comic comic := processComic(destPath, filename) - // Must lock/unlock to ensure generateCoverCache sees the comic in the map, - // especially if it finds a password and needs to persist it. comicsMutex.Lock() comics[comic.ID] = comic comicsMutex.Unlock() - generateCoverCache(&comic) // Pass reference to updated comic struct + generateCoverCache(&comic) saveComics() @@ -429,32 +425,32 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { } func handleDeleteComic(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodDelete { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - user := getCurrentUser(r) - if !user.IsAdmin { - http.Error(w, "Admin only", http.StatusForbidden) - return - } - id := strings.TrimPrefix(r.URL.Path, "/api/admin/delete-comic/") - decodedID, _ := url.QueryUnescape(id) - comicsMutex.Lock() - comic, exists := comics[decodedID] - if exists { - os.Remove(comic.FilePath) - for _, tag := range comic.Tags { - updateTagCount(tag, -1) - } - delete(comics, decodedID) - saveComics() - saveTags() - } - comicsMutex.Unlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]string{"message": "Deleted"}) + if r.Method != http.MethodDelete { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + user := getCurrentUser(r) + if !user.IsAdmin { + http.Error(w, "Admin only", http.StatusForbidden) + return + } + id := strings.TrimPrefix(r.URL.Path, "/api/admin/delete-comic/") + decodedID, _ := url.QueryUnescape(id) + comicsMutex.Lock() + comic, exists := comics[decodedID] + if exists { + os.Remove(comic.FilePath) + for _, tag := range comic.Tags { + updateTagCount(tag, -1) + } + delete(comics, decodedID) + saveComics() + saveTags() + } + comicsMutex.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]string{"message": "Deleted"}) } func handleCover(w http.ResponseWriter, r *http.Request) { @@ -476,14 +472,12 @@ func handleCover(w http.ResponseWriter, r *http.Request) { return } - // Check cache first cacheFile := filepath.Join(cachePath, comic.ID+".jpg") if _, err := os.Stat(cacheFile); err == nil { http.ServeFile(w, r, cacheFile) return } - // Generate on-the-fly if comic.FileType == ".cbz" { serveCoverFromCBZ(w, r, comic) } else { @@ -581,7 +575,6 @@ func handleComicTags(w http.ResponseWriter, r *http.Request) { return } - // Add tag if not already present found := false for _, t := range comic.Tags { if t == req.Tag { @@ -670,7 +663,6 @@ func handleSetPassword(w http.ResponseWriter, r *http.Request) { return } - // Verify password by trying to open ComicInfo.xml yr, err := yzip.OpenReader(comic.FilePath) if err != nil { http.Error(w, "Error reading comic", http.StatusInternalServerError) @@ -691,7 +683,6 @@ func handleSetPassword(w http.ResponseWriter, r *http.Request) { if readErr != nil || len(data) == 0 { break } - // Quick XML check var info ComicInfo if xml.Unmarshal(data, &info) == nil { valid = true @@ -705,7 +696,6 @@ func handleSetPassword(w http.ResponseWriter, r *http.Request) { return } - // Set and save comicsMutex.Lock() c := comics[decodedID] c.Password = req.Password @@ -718,46 +708,42 @@ func handleSetPassword(w http.ResponseWriter, r *http.Request) { passwordsMutex.Unlock() savePasswords() - // Extract metadata now that password is known comicsMutex.Lock() c = comics[decodedID] extractCBZMetadata(&c) - // Organize comic based on extracted metadata -if c.Artist != "Unknown" || c.StoryArc != "" { - inker := sanitizeFilename(c.Artist) - storyArc := sanitizeFilename(c.StoryArc) - if inker == "" { - inker = "Unknown" - } - if storyArc == "" { - storyArc = "No_StoryArc" - } - newDir := filepath.Join(libraryPath, inker, storyArc) - os.MkdirAll(newDir, 0755) - filename := filepath.Base(c.FilePath) - newPath := filepath.Join(newDir, filename) - if newPath != c.FilePath { - if err := os.Rename(c.FilePath, newPath); err == nil { - c.FilePath = newPath - } else { - log.Printf("Failed to move comic %s to %s: %v", c.ID, newPath, err) - } - } -} -// Update tags counts for newly extracted tags -tagsMutex.Lock() -for _, tag := range c.Tags { - if tagData, exists := tags[tag]; exists { - tagData.Count++ - tags[tag] = tagData - } else { - tags[tag] = Tag{Name: tag, Color: "#1f6feb", Count: 1} - } -} -tagsMutex.Unlock() -comics[decodedID] = c -comicsMutex.Unlock() + if c.Artist != "Unknown" || c.StoryArc != "" { + inker := sanitizeFilename(c.Artist) + storyArc := sanitizeFilename(c.StoryArc) + if inker == "" { + inker = "Unknown" + } + if storyArc == "" { + storyArc = "No_StoryArc" + } + newDir := filepath.Join(libraryPath, inker, storyArc) + os.MkdirAll(newDir, 0755) + filename := filepath.Base(c.FilePath) + newPath := filepath.Join(newDir, filename) + if newPath != c.FilePath { + if err := os.Rename(c.FilePath, newPath); err == nil { + c.FilePath = newPath + } + } + } + + tagsMutex.Lock() + for _, tag := range c.Tags { + if tagData, exists := tags[tag]; exists { + tagData.Count++ + tags[tag] = tagData + } else { + tags[tag] = Tag{Name: tag, Color: "#1f6feb", Count: 1} + } + } + tagsMutex.Unlock() + comics[decodedID] = c + comicsMutex.Unlock() saveComics() saveTags() @@ -766,13 +752,109 @@ comicsMutex.Unlock() json.NewEncoder(w).Encode(map[string]string{"message": "Password set successfully"}) } +func handleBookmark(w http.ResponseWriter, r *http.Request) { + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/bookmark/"), "/") + if len(parts) == 0 { + http.Error(w, "Comic ID required", http.StatusBadRequest) + return + } + + id := parts[0] + decodedID, err := url.QueryUnescape(id) + if err != nil { + decodedID = id + } + + comicsMutex.Lock() + defer comicsMutex.Unlock() + + comic, exists := comics[decodedID] + if !exists { + comic, exists = comics[id] + if !exists { + http.Error(w, "Comic not found", http.StatusNotFound) + return + } + } + + switch r.Method { + case http.MethodPost: + var req struct { + Page int `json:"page"` + } + + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "Invalid request", http.StatusBadRequest) + return + } + + if comic.Bookmarks == nil { + comic.Bookmarks = []int{} + } + + found := false + for _, p := range comic.Bookmarks { + if p == req.Page { + found = true + break + } + } + + if !found { + comic.Bookmarks = append(comic.Bookmarks, req.Page) + sort.Ints(comic.Bookmarks) + } + + comics[decodedID] = comic + saveComics() + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "message": "Bookmark added", + "bookmarks": comic.Bookmarks, + }) + + case http.MethodDelete: + if len(parts) < 2 { + http.Error(w, "Page number required", http.StatusBadRequest) + return + } + + var pageNum int + fmt.Sscanf(parts[1], "%d", &pageNum) + + if comic.Bookmarks == nil { + comic.Bookmarks = []int{} + } + + newBookmarks := []int{} + for _, p := range comic.Bookmarks { + if p != pageNum { + newBookmarks = append(newBookmarks, p) + } + } + + comic.Bookmarks = newBookmarks + comics[decodedID] = comic + saveComics() + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "message": "Bookmark removed", + "bookmarks": comic.Bookmarks, + }) + + default: + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } +} + func handleComicFile(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/comic/"), "/") id := parts[0] decodedID, err := url.QueryUnescape(id) if err != nil { - log.Printf("Error decoding ID: %v", err) decodedID = id } @@ -784,7 +866,6 @@ func handleComicFile(w http.ResponseWriter, r *http.Request) { comicsMutex.RUnlock() if !exists { - log.Printf("Comic file not found for ID: %s or %s", decodedID, id) http.Error(w, "Comic not found", http.StatusNotFound) return } @@ -809,7 +890,6 @@ func serveComicPage(w http.ResponseWriter, r *http.Request, comic Comic, pageNum yr, err := yzip.OpenReader(comic.FilePath) if err != nil { - log.Printf("Error opening CBZ with yeka/zip: %v", err) serveComicPageStandard(w, r, comic, pageIdx) return } @@ -821,7 +901,6 @@ func serveComicPage(w http.ResponseWriter, r *http.Request, comic Comic, pageNum continue } ext := strings.ToLower(filepath.Ext(f.Name)) - // Broad image format support if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".avif" || ext == ".jxl" || ext == ".jp2" || ext == ".webp" || ext == ".gif" || ext == ".bmp" { imageFiles = append(imageFiles, f) @@ -839,27 +918,24 @@ func serveComicPage(w http.ResponseWriter, r *http.Request, comic Comic, pageNum targetFile := imageFiles[pageIdx] - // Password handling if targetFile.IsEncrypted() { if comic.Password != "" { targetFile.SetPassword(comic.Password) } else { - http.Error(w, "Comic requires password (contact admin or re-open reader)", http.StatusUnauthorized) + http.Error(w, "Comic requires password", http.StatusUnauthorized) return } } rc, err := targetFile.Open() if err != nil { - log.Printf("Error opening page file: %v", err) - http.Error(w, "Error reading page - file may be encrypted", http.StatusInternalServerError) + http.Error(w, "Error reading page", http.StatusInternalServerError) return } defer rc.Close() imageData, err := io.ReadAll(rc) if err != nil { - log.Printf("Error reading image data: %v", err) http.Error(w, "Error reading page", http.StatusInternalServerError) return } @@ -886,7 +962,6 @@ func serveComicPageStandard(w http.ResponseWriter, r *http.Request, comic Comic, continue } ext := strings.ToLower(filepath.Ext(f.Name)) - // Broad image format support if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".avif" || ext == ".jxl" || ext == ".jp2" || ext == ".webp" || ext == ".gif" || ext == ".bmp" { imageFiles = append(imageFiles, f) @@ -955,7 +1030,6 @@ func extractCBZMetadataStandard(comic *Comic) { comic.Year = info.Year comic.PageCount = info.PageCount - // Extract tags from TagsXml first, then fallback to Genre tagsSource := info.TagsXml if tagsSource == "" { tagsSource = info.Genre @@ -1000,7 +1074,6 @@ func serveCoverFromCBZ(w http.ResponseWriter, r *http.Request, comic Comic) { continue } ext := strings.ToLower(filepath.Ext(f.Name)) - // FIX 2: Expanded image types for serving covers if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".avif" || ext == ".jxl" || ext == ".webp" || ext == ".bmp" || ext == ".jp2" { imageFiles = append(imageFiles, f) } @@ -1017,20 +1090,18 @@ func serveCoverFromCBZ(w http.ResponseWriter, r *http.Request, comic Comic) { coverFile := imageFiles[0] - // Password handling if coverFile.IsEncrypted() { if comic.Password != "" { coverFile.SetPassword(comic.Password) } else { - http.Error(w, "Comic requires password (contact admin or re-open reader)", http.StatusUnauthorized) + http.Error(w, "Comic requires password", http.StatusUnauthorized) return } } rc, err := coverFile.Open() if err != nil { - log.Printf("Error opening cover for ID %s: %v", comic.ID, err) - http.Error(w, "Error reading cover - file may be encrypted", http.StatusInternalServerError) + http.Error(w, "Error reading cover", http.StatusInternalServerError) return } defer rc.Close() @@ -1173,17 +1244,17 @@ func processComic(filePath, filename string) Comic { UploadedAt: time.Now(), Artist: "Unknown", Tags: []string{}, + Bookmarks: []int{}, } if comic.FileType == ".cbz" { extractCBZMetadata(&comic) - // Register extracted tags in global tags map tagsMutex.Lock() for _, tag := range comic.Tags { if _, exists := tags[tag]; !exists { tags[tag] = Tag{ Name: tag, - Color: "#1f6feb", // Default color + Color: "#1f6feb", Count: 0, } } @@ -1194,7 +1265,6 @@ func processComic(filePath, filename string) Comic { tagsMutex.Unlock() saveTags() - // Create folder structure based on Inker and StoryArc if comic.Artist != "Unknown" || comic.StoryArc != "" { inker := sanitizeFilename(comic.Artist) storyArc := sanitizeFilename(comic.StoryArc) @@ -1247,7 +1317,6 @@ func generateCoverCache(comic *Comic) { continue } ext := strings.ToLower(filepath.Ext(f.Name)) - // FIX 2: Expanded image types for cover caching if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".avif" || ext == ".jxl" || ext == ".webp" || ext == ".bmp" || ext == ".jp2" { imageFiles = append(imageFiles, f) } @@ -1263,19 +1332,16 @@ func generateCoverCache(comic *Comic) { coverFile := imageFiles[0] - // Password handling if coverFile.IsEncrypted() { if comic.Password != "" { coverFile.SetPassword(comic.Password) } else { - log.Printf("Failed to open cover file for ID %s. File encrypted or corrupted.", comic.ID) return } } rc, err := coverFile.Open() if err != nil { - log.Printf("Failed to open cover file for ID %s. File encrypted or corrupted. %v", comic.ID, err) return } defer rc.Close() @@ -1305,16 +1371,14 @@ func extractCBZMetadata(comic *Comic) { } } comic.Encrypted = isEncrypted - comic.HasPassword = false // Default until proven + comic.HasPassword = false if !isEncrypted { - // Use standard extraction if not encrypted extractCBZMetadataStandard(comic) - comic.HasPassword = true // No password needed + comic.HasPassword = true return } - // Collect unique known passwords from other comics passwordsMutex.RLock() knownPwds := make(map[string]bool) for _, pwd := range comicPasswords { @@ -1331,7 +1395,6 @@ func extractCBZMetadata(comic *Comic) { var readErr error if len(knownPwds) > 0 { - // Try known passwords for pwd := range knownPwds { f.SetPassword(pwd) rc, err := f.Open() @@ -1351,7 +1414,6 @@ func extractCBZMetadata(comic *Comic) { } if foundPwd != "" { - // Success: persist comic.Password = foundPwd comic.HasPassword = true passwordsMutex.Lock() @@ -1359,7 +1421,6 @@ func extractCBZMetadata(comic *Comic) { passwordsMutex.Unlock() savePasswords() } else if !isEncrypted { - // Fallback for non-encrypted rc, err := f.Open() if err != nil { continue @@ -1382,7 +1443,6 @@ func extractCBZMetadata(comic *Comic) { comic.Year = info.Year comic.PageCount = info.PageCount - // Extract tags from TagsXml first, then fallback to Genre tagsSource := info.TagsXml if tagsSource == "" { tagsSource = info.Genre @@ -1414,7 +1474,6 @@ func extractCBZMetadata(comic *Comic) { } func scanLibrary() { - // Create a map to track existing file paths for quick lookup comicsMutex.RLock() existingPaths := make(map[string]string) for id, comic := range comics { @@ -1437,45 +1496,39 @@ func scanLibrary() { comicsMutex.RUnlock() if exists { - // Verify cache exists for this comic comic := comics[id] cacheFile := filepath.Join(cachePath, comic.ID+".jpg") if _, err := os.Stat(cacheFile); os.IsNotExist(err) && comic.FileType == ".cbz" { - // Generate cache only if it doesn't exist comicsMutex.RLock() c := comics[id] comicsMutex.RUnlock() generateCoverCache(&c) comicsMutex.Lock() - comics[id] = c // Update with any new password found + comics[id] = c comicsMutex.Unlock() } return nil } - // Process new comic comic := processComic(path, info.Name()) comicsMutex.Lock() comics[comic.ID] = comic comicsMutex.Unlock() - // Generate cover cache for new comic comicsMutex.RLock() c := comics[comic.ID] comicsMutex.RUnlock() generateCoverCache(&c) comicsMutex.Lock() - comics[comic.ID] = c // Write back potential password found + comics[comic.ID] = c comicsMutex.Unlock() return nil }) - // Clean up comics that no longer exist comicsMutex.Lock() for id, comic := range comics { if _, err := os.Stat(comic.FilePath); os.IsNotExist(err) { - // Remove tags associated with this comic for _, tag := range comic.Tags { updateTagCount(tag, -1) } @@ -1509,27 +1562,22 @@ func authMiddleware(next http.HandlerFunc) http.HandlerFunc { } } -// Replace loadUsers(): func loadUsers() { - data, err := os.ReadFile("etc/users.json") - if err != nil { - log.Printf("Error reading users.json: %v", err) - return - } - if err := json.Unmarshal(data, &users); err != nil { - log.Printf("Error unmarshaling users: %v", err) - } + data, err := os.ReadFile("etc/users.json") + if err != nil { + return + } + if err := json.Unmarshal(data, &users); err != nil { + log.Printf("Error unmarshaling users: %v", err) + } - // Always load admin config to set registrationEnabled - adminData, err := os.ReadFile("etc/admin.json") - if err == nil && len(adminData) > 0 { - var adminConfig struct{ RegistrationEnabled bool } - if err := json.Unmarshal(adminData, &adminConfig); err == nil { - registrationEnabled = adminConfig.RegistrationEnabled - } else { - log.Printf("Error unmarshaling admin.json: %v", err) - } - } + adminData, err := os.ReadFile("etc/admin.json") + if err == nil && len(adminData) > 0 { + var adminConfig struct{ RegistrationEnabled bool } + if err := json.Unmarshal(adminData, &adminConfig); err == nil { + registrationEnabled = adminConfig.RegistrationEnabled + } + } } func saveUsers() { @@ -1537,11 +1585,10 @@ func saveUsers() { os.WriteFile("etc/users.json", data, 0644) } -// Add new function after saveUsers(): func saveAdminConfig() { - config := struct{ RegistrationEnabled bool }{RegistrationEnabled: registrationEnabled} - data, _ := json.MarshalIndent(config, "", " ") - os.WriteFile("etc/admin.json", data, 0644) + config := struct{ RegistrationEnabled bool }{RegistrationEnabled: registrationEnabled} + data, _ := json.MarshalIndent(config, "", " ") + os.WriteFile("etc/admin.json", data, 0644) } func loadTags() { @@ -1577,31 +1624,26 @@ func loadComics() { func loadPasswordsWithKey(key []byte) { data, err := os.ReadFile(filepath.Join(libraryPath, "passwords.json")) if err != nil { - log.Printf("No passwords file for user %s, starting fresh", currentUser) return } b64data := strings.TrimSpace(string(data)) encrypted, err := base64.StdEncoding.DecodeString(b64data) if err != nil { - log.Printf("Failed to decode passwords.json: %v", err) return } decrypted, err := decryptAES(encrypted, key) if err != nil { - log.Printf("Failed to decrypt passwords: %v", err) return } passwordsMutex.Lock() defer passwordsMutex.Unlock() if err := json.Unmarshal(decrypted, &comicPasswords); err != nil { - log.Printf("Failed to unmarshal passwords: %v", err) return } - // Restore Password and HasPassword in comics map comicsMutex.Lock() defer comicsMutex.Unlock() for id, pwd := range comicPasswords { @@ -1615,7 +1657,6 @@ func loadPasswordsWithKey(key []byte) { func savePasswords() { if len(currentEncryptionKey) == 0 { - log.Println("No encryption key set, skipping save") return } @@ -1623,20 +1664,16 @@ func savePasswords() { defer passwordsMutex.Unlock() data, err := json.MarshalIndent(comicPasswords, "", " ") if err != nil { - log.Printf("Failed to marshal passwords: %v", err) return } encrypted, err := encryptAES(data, currentEncryptionKey) if err != nil { - log.Printf("Failed to encrypt passwords: %v", err) return } b64 := base64.StdEncoding.EncodeToString(encrypted) - if err := os.WriteFile(filepath.Join(libraryPath, "passwords.json"), []byte(b64), 0644); err != nil { - log.Printf("Failed to write passwords.json for user %s: %v", currentUser, err) - } + os.WriteFile(filepath.Join(libraryPath, "passwords.json"), []byte(b64), 0644) } func updateTagCount(tagName string, delta int) { @@ -1659,12 +1696,9 @@ func generateToken() string { } func sanitizeFilename(filename string) string { - // Replace spaces explicitly with underscores filename = strings.ReplaceAll(filename, " ", "_") - // Replace any character that isn't alphanumeric, hyphen, or underscore with underscore reg, _ := regexp.Compile("[^a-zA-Z0-9-_]+") sanitized := reg.ReplaceAllString(filename, "_") - // Remove leading/trailing underscores sanitized = strings.Trim(sanitized, "_") if sanitized == "" { return "Unknown" @@ -1698,31 +1732,6 @@ func deriveKey(seed string) []byte { return hash[:32] } -func isPlaintext(data []byte) bool { - if len(data) < 4 { - return true - } - - if len(data) >= 4 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 { - return true - } - if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF { - return true - } - if len(data) >= 3 && data[0] == 0x47 && data[1] == 0x49 && data[2] == 0x46 { - return true - } - if len(data) >= 12 && data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 && - data[8] == 0x57 && data[9] == 0x45 && data[10] == 0x42 && data[11] == 0x50 { - return true - } - if data[0] == 0x3C { - return true - } - - return false -} - func decryptAES(data []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { @@ -1748,1581 +1757,25 @@ func encryptAES(plaintext []byte, key []byte) ([]byte, error) { return nil, err } - // Generate random IV iv := make([]byte, aes.BlockSize) if _, err := rand.Read(iv); err != nil { return nil, err } - // Create the cipher stream stream := cipher.NewCFBEncrypter(block, iv) - // Encrypt the plaintext ciphertext := make([]byte, len(plaintext)) stream.XORKeyStream(ciphertext, plaintext) - // Prepend IV to ciphertext return append(iv, ciphertext...), nil } func serveUI(w http.ResponseWriter, r *http.Request) { + data, err := templateFS.ReadFile("templates/index.html") + if err != nil { + http.Error(w, "Template not found", http.StatusInternalServerError) + return + } w.Header().Set("Content-Type", "text/html") - w.Write([]byte(getHTML())) -} - -func getHTML() string { - return ` - -
- - -