small updates, for some reason it thinks every file is modified

This commit is contained in:
2026-02-19 04:21:31 -06:00
parent 1b394a57a9
commit e829f6b405
32 changed files with 6142 additions and 6115 deletions
+2 -2
View File
@@ -1,3 +1,3 @@
backend/raster.db backend/raster.db
backend/media backend/media
backend/cache backend/cache
+202 -202
View File
@@ -1,202 +1,202 @@
Apache License Apache License
Version 2.0, January 2004 Version 2.0, January 2004
http://www.apache.org/licenses/ http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions. 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, "License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document. and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by "Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License. the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all "Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition, control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the "control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity. outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity "You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License. exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, "Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation including but not limited to software source code, documentation
source, and configuration files. source, and configuration files.
"Object" form shall mean any form resulting from mechanical "Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation, not limited to compiled object code, generated documentation,
and conversions to other media types. and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or "Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work copyright notice that is included in or attached to the work
(an example is provided in the Appendix below). (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object "Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of, separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof. the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including "Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted" the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution." designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity "Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work. subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of 2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual, this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of, copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form. Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of 3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual, this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, (except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work, use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s) Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate granted to You under this License for that Work shall terminate
as of the date such litigation is filed. as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the 4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You modifications, and in Source or Object form, provided that You
meet the following conditions: meet the following conditions:
(a) You must give any other recipients of the Work or (a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices (b) You must cause any modified files to carry prominent notices
stating that You changed the files; and stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works (c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work, attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of excluding those notices that do not pertain to any part of
the Derivative Works; and the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its (d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or, documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed that such additional attribution notices cannot be construed
as modifying the License. as modifying the License.
You may add Your own copyright statement to Your modifications and You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use, for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License. the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, 5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions. this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions. with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade 6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor, names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file. origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or 7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS, Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License. risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, 8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise, whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill, Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages. has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing 9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer, the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity, and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify, of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability. of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work. APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]" boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier same "printed page" as the copyright notice for easier
identification within third-party archives. identification within third-party archives.
Copyright 2025 wisplite Copyright 2025 wisplite
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
+1 -1
View File
@@ -18,7 +18,7 @@ func main() {
// Configure CORS middleware // Configure CORS middleware
r.Use(cors.New(cors.Config{ r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000", "http://localhost:5173"}, AllowOrigins: []string{"http://localhost:3000", "http://localhost:5173", "http://192.168.1.130:5173"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
ExposeHeaders: []string{"Content-Length"}, ExposeHeaders: []string{"Content-Length"},
+20 -20
View File
@@ -1,20 +1,20 @@
package models package models
import ( import (
"time" "time"
"gorm.io/datatypes" "gorm.io/datatypes"
) )
type Media struct { type Media struct {
ID string `gorm:"primaryKey"` ID string `gorm:"primaryKey"`
Title string `gorm:"not null"` Title string `gorm:"not null"`
Description string `gorm:"not null"` Description string `gorm:"not null"`
Tags datatypes.JSON `gorm:"type:json"` Tags datatypes.JSON `gorm:"type:json"`
AlbumID string `gorm:"not null"` AlbumID string `gorm:"not null"`
Path string `gorm:"not null"` Path string `gorm:"not null"`
Type string `gorm:"not null"` // MIME type Type string `gorm:"not null"` // MIME type
Metadata datatypes.JSON `gorm:"type:json"` // Metadata about the media. Metadata datatypes.JSON `gorm:"type:json"` // Metadata about the media.
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
+156 -156
View File
@@ -1,156 +1,156 @@
package routes package routes
import ( import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/wisplite/raster/internal/services" "github.com/wisplite/raster/internal/services"
) )
func RegisterMediaRoutes(rg *gin.RouterGroup) { func RegisterMediaRoutes(rg *gin.RouterGroup) {
media := rg.Group("/media") media := rg.Group("/media")
media.POST("/uploadMedia", func(c *gin.Context) { media.POST("/uploadMedia", func(c *gin.Context) {
file, err := c.FormFile("file") file, err := c.FormFile("file")
if err != nil { if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return return
} }
accessToken := c.GetHeader("Authorization") accessToken := c.GetHeader("Authorization")
albumID := c.PostForm("albumId") albumID := c.PostForm("albumId")
media, err := services.UploadMedia(file, albumID, accessToken) media, err := services.UploadMedia(file, albumID, accessToken)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
if err := os.MkdirAll(filepath.Dir(media.Path), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(media.Path), 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create directory"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create directory"})
return return
} }
if err := c.SaveUploadedFile(file, media.Path); err != nil { if err := c.SaveUploadedFile(file, media.Path); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return return
} }
c.JSON(http.StatusOK, gin.H{"media": media}) c.JSON(http.StatusOK, gin.H{"media": media})
}) })
media.GET("/getAllMediaInAlbum", func(c *gin.Context) { media.GET("/getAllMediaInAlbum", func(c *gin.Context) {
accessToken := c.GetHeader("Authorization") accessToken := c.GetHeader("Authorization")
albumID := c.Query("albumId") albumID := c.Query("albumId")
isPublic, err := services.IsAlbumPublic(albumID) isPublic, err := services.IsAlbumPublic(albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
if isPublic { if isPublic {
media, err := services.GetAllMediaInPublicAlbum(albumID) media, err := services.GetAllMediaInPublicAlbum(albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.JSON(http.StatusOK, gin.H{"media": media}) c.JSON(http.StatusOK, gin.H{"media": media})
return return
} else { } else {
media, err := services.GetAllMediaInAlbum(albumID, accessToken) media, err := services.GetAllMediaInAlbum(albumID, accessToken)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.JSON(http.StatusOK, gin.H{"media": media}) c.JSON(http.StatusOK, gin.H{"media": media})
} }
}) })
media.GET("/:albumId/:mediaId", func(c *gin.Context) { media.GET("/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId") albumID := c.Param("albumId")
mediaID := c.Param("mediaId") mediaID := c.Param("mediaId")
if albumID == "root" { if albumID == "root" {
albumID = "" albumID = ""
} }
isPublic, err := services.IsAlbumPublic(albumID) isPublic, err := services.IsAlbumPublic(albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
if isPublic { if isPublic {
mediaData, err := services.GetMedia(albumID, mediaID) mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.File(mediaData.Path) c.File(mediaData.Path)
return return
} }
accessToken := c.GetHeader("Authorization") accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken) userID, err := services.ValidateAccessToken(accessToken)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID) accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
if accessLevel < 0 { if accessLevel < 0 {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"}) c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return return
} }
mediaData, err := services.GetMedia(albumID, mediaID) mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.File(mediaData.Path) c.File(mediaData.Path)
}) })
media.GET("/thumb/:albumId/:mediaId", func(c *gin.Context) { media.GET("/thumb/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId") albumID := c.Param("albumId")
mediaID := c.Param("mediaId") mediaID := c.Param("mediaId")
widthStr := c.Query("width") widthStr := c.Query("width")
heightStr := c.Query("height") heightStr := c.Query("height")
width, _ := strconv.Atoi(widthStr) width, _ := strconv.Atoi(widthStr)
height, _ := strconv.Atoi(heightStr) height, _ := strconv.Atoi(heightStr)
if albumID == "root" { if albumID == "root" {
albumID = "" albumID = ""
} }
isPublic, err := services.IsAlbumPublic(albumID) isPublic, err := services.IsAlbumPublic(albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
allowed := false allowed := false
if isPublic { if isPublic {
allowed = true allowed = true
} else { } else {
accessToken := c.GetHeader("Authorization") accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken) userID, err := services.ValidateAccessToken(accessToken)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID) accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
if accessLevel >= 0 { if accessLevel >= 0 {
allowed = true allowed = true
} else { } else {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"}) c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return return
} }
} }
if allowed { if allowed {
thumbPath, err := services.GetThumbnail(albumID, mediaID, width, height) thumbPath, err := services.GetThumbnail(albumID, mediaID, width, height)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
c.File(thumbPath) c.File(thumbPath)
} }
}) })
} }
+196 -196
View File
@@ -1,196 +1,196 @@
package services package services
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"image" "image"
_ "image/jpeg" _ "image/jpeg"
_ "image/png" _ "image/png"
"mime/multipart" "mime/multipart"
"os" "os"
"path/filepath" "path/filepath"
"github.com/disintegration/imaging" "github.com/disintegration/imaging"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/exif"
"github.com/wisplite/raster/internal/db" "github.com/wisplite/raster/internal/db"
"github.com/wisplite/raster/internal/models" "github.com/wisplite/raster/internal/models"
"gorm.io/datatypes" "gorm.io/datatypes"
) )
func UploadMedia(file *multipart.FileHeader, albumID string, accessToken string) (models.Media, error) { func UploadMedia(file *multipart.FileHeader, albumID string, accessToken string) (models.Media, error) {
userID, err := ValidateAccessToken(accessToken) userID, err := ValidateAccessToken(accessToken)
if err != nil { if err != nil {
return models.Media{}, err return models.Media{}, err
} }
accessLevel, err := CheckUserAlbumAccess(userID, albumID) accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil { if err != nil {
return models.Media{}, err return models.Media{}, err
} }
if accessLevel < 1 { if accessLevel < 1 {
return models.Media{}, fmt.Errorf("user does not have permission to upload media to this album") return models.Media{}, fmt.Errorf("user does not have permission to upload media to this album")
} }
albumPath := albumID albumPath := albumID
if albumID == "" { if albumID == "" {
albumPath = "root" albumPath = "root"
} }
// Extract metadata (dimensions and file info) // Extract metadata (dimensions and file info)
var meta datatypes.JSON var meta datatypes.JSON
metadataMap := map[string]interface{}{ metadataMap := map[string]interface{}{
"originalFilename": file.Filename, "originalFilename": file.Filename,
"fileSize": file.Size, "fileSize": file.Size,
"contentType": file.Header.Get("Content-Type"), "contentType": file.Header.Get("Content-Type"),
} }
src, err := file.Open() src, err := file.Open()
if err == nil { if err == nil {
defer src.Close() defer src.Close()
cfg, format, err := image.DecodeConfig(src) cfg, format, err := image.DecodeConfig(src)
if err == nil { if err == nil {
metadataMap["width"] = cfg.Width metadataMap["width"] = cfg.Width
metadataMap["height"] = cfg.Height metadataMap["height"] = cfg.Height
metadataMap["format"] = format metadataMap["format"] = format
// Check for EXIF orientation // Check for EXIF orientation
src.Seek(0, 0) src.Seek(0, 0)
x, err := exif.Decode(src) x, err := exif.Decode(src)
if err == nil { if err == nil {
orient, err := x.Get(exif.Orientation) orient, err := x.Get(exif.Orientation)
if err == nil { if err == nil {
val, err := orient.Int(0) val, err := orient.Int(0)
if err == nil { if err == nil {
if val >= 5 && val <= 8 { if val >= 5 && val <= 8 {
metadataMap["width"] = cfg.Height metadataMap["width"] = cfg.Height
metadataMap["height"] = cfg.Width metadataMap["height"] = cfg.Width
} }
} }
} }
} }
} }
} }
b, _ := json.Marshal(metadataMap) b, _ := json.Marshal(metadataMap)
meta = datatypes.JSON(b) meta = datatypes.JSON(b)
mediaID := uuid.New().String() mediaID := uuid.New().String()
mediaPath := fmt.Sprintf("media/%s/%s.%s", albumPath, mediaID, file.Filename) mediaPath := fmt.Sprintf("media/%s/%s.%s", albumPath, mediaID, file.Filename)
media := models.Media{ media := models.Media{
ID: mediaID, ID: mediaID,
AlbumID: albumID, AlbumID: albumID,
Path: mediaPath, Path: mediaPath,
Type: file.Header.Get("Content-Type"), Type: file.Header.Get("Content-Type"),
Title: file.Filename, Title: file.Filename,
Description: "", Description: "",
Metadata: meta, Metadata: meta,
} }
result := db.GetDB().Create(&media) result := db.GetDB().Create(&media)
if result.Error != nil { if result.Error != nil {
return models.Media{}, result.Error return models.Media{}, result.Error
} }
return media, nil return media, nil
} }
func GetAllMediaInAlbum(albumID string, accessToken string) ([]models.Media, error) { func GetAllMediaInAlbum(albumID string, accessToken string) ([]models.Media, error) {
userID, err := ValidateAccessToken(accessToken) userID, err := ValidateAccessToken(accessToken)
if err != nil { if err != nil {
return []models.Media{}, err return []models.Media{}, err
} }
accessLevel, err := CheckUserAlbumAccess(userID, albumID) accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil { if err != nil {
return []models.Media{}, err return []models.Media{}, err
} }
if accessLevel < 0 { if accessLevel < 0 {
return []models.Media{}, fmt.Errorf("user does not have permission to view media in this album") return []models.Media{}, fmt.Errorf("user does not have permission to view media in this album")
} }
media := []models.Media{} media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media) result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil { if result.Error != nil {
return []models.Media{}, result.Error return []models.Media{}, result.Error
} }
return media, nil return media, nil
} }
func GetAllMediaInPublicAlbum(albumID string) ([]models.Media, error) { func GetAllMediaInPublicAlbum(albumID string) ([]models.Media, error) {
media := []models.Media{} media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media) result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil { if result.Error != nil {
return []models.Media{}, result.Error return []models.Media{}, result.Error
} }
return media, nil return media, nil
} }
func GetMedia(albumID string, mediaID string) (models.Media, error) { func GetMedia(albumID string, mediaID string) (models.Media, error) {
media := models.Media{} media := models.Media{}
result := db.GetDB().First(&media, "album_id = ? AND id = ?", albumID, mediaID) result := db.GetDB().First(&media, "album_id = ? AND id = ?", albumID, mediaID)
if result.Error != nil { if result.Error != nil {
return models.Media{}, result.Error return models.Media{}, result.Error
} }
return media, nil return media, nil
} }
func GetThumbnail(albumID string, mediaID string, width int, height int) (string, error) { func GetThumbnail(albumID string, mediaID string, width int, height int) (string, error) {
media, err := GetMedia(albumID, mediaID) media, err := GetMedia(albumID, mediaID)
if err != nil { if err != nil {
return "", err return "", err
} }
if width == 0 { if width == 0 {
width = 200 width = 200
} }
if height == 0 { if height == 0 {
height = 200 height = 200
} }
cacheDir := "cache/thumbnails" cacheDir := "cache/thumbnails"
if err := os.MkdirAll(cacheDir, 0755); err != nil { if err := os.MkdirAll(cacheDir, 0755); err != nil {
return "", err return "", err
} }
ext := filepath.Ext(media.Path) ext := filepath.Ext(media.Path)
if ext == "" { if ext == "" {
ext = ".jpg" ext = ".jpg"
} }
thumbName := fmt.Sprintf("%s_%dx%d%s", mediaID, width, height, ext) thumbName := fmt.Sprintf("%s_%dx%d%s", mediaID, width, height, ext)
thumbPath := filepath.Join(cacheDir, thumbName) thumbPath := filepath.Join(cacheDir, thumbName)
if _, err := os.Stat(thumbPath); err == nil { if _, err := os.Stat(thumbPath); err == nil {
return thumbPath, nil return thumbPath, nil
} }
srcImage, err := imaging.Open(media.Path) srcImage, err := imaging.Open(media.Path)
if err != nil { if err != nil {
return "", err return "", err
} }
f, err := os.Open(media.Path) f, err := os.Open(media.Path)
if err == nil { if err == nil {
x, err := exif.Decode(f) x, err := exif.Decode(f)
f.Close() f.Close()
if err == nil { if err == nil {
orient, err := x.Get(exif.Orientation) orient, err := x.Get(exif.Orientation)
if err == nil { if err == nil {
val, err := orient.Int(0) val, err := orient.Int(0)
if err == nil { if err == nil {
switch val { switch val {
case 3: case 3:
srcImage = imaging.Rotate180(srcImage) srcImage = imaging.Rotate180(srcImage)
case 6: case 6:
srcImage = imaging.Rotate270(srcImage) srcImage = imaging.Rotate270(srcImage)
case 8: case 8:
srcImage = imaging.Rotate90(srcImage) srcImage = imaging.Rotate90(srcImage)
} }
} }
} }
} }
} }
dstImage := imaging.Fit(srcImage, width, height, imaging.Lanczos) dstImage := imaging.Fit(srcImage, width, height, imaging.Lanczos)
err = imaging.Save(dstImage, thumbPath) err = imaging.Save(dstImage, thumbPath)
if err != nil { if err != nil {
return "", err return "", err
} }
return thumbPath, nil return thumbPath, nil
} }
+20 -20
View File
@@ -1,21 +1,21 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link <link
href="https://fonts.googleapis.com/css2?family=Red+Hat+Mono:ital,wght@0,300..700;1,300..700&family=Red+Hat+Text:ital,wght@0,300..700;1,300..700&display=swap" href="https://fonts.googleapis.com/css2?family=Red+Hat+Display:ital,wght@0,300..900;1,300..900&family=Red+Hat+Mono:ital,wght@0,300..700;1,300..700&family=Red+Hat+Text:ital,wght@0,300..700;1,300..700&display=swap"
rel="stylesheet"> rel="stylesheet">
<title>Raster</title> <title>Raster</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.jsx"></script> <script type="module" src="/src/main.jsx"></script>
</body> </body>
</html> </html>
+4122 -4112
View File
File diff suppressed because it is too large Load Diff
+34 -34
View File
@@ -1,34 +1,34 @@
{ {
"name": "frontend", "name": "frontend",
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.15", "@radix-ui/react-popover": "^1.1.15",
"@tailwindcss/vite": "^4.1.12", "@tailwindcss/vite": "^4.1.12",
"lucide-react": "^0.554.0", "lucide-react": "^0.554.0",
"react": "^19.1.1", "react": "^19.1.1",
"react-dom": "^19.1.1", "react-dom": "^19.1.1",
"react-router-dom": "^7.9.6", "react-router-dom": "^7.9.6",
"react-spinners": "^0.17.0", "react-spinners": "^0.17.0",
"tailwindcss": "^4.1.12" "tailwindcss": "^4.1.12"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.33.0", "@eslint/js": "^9.33.0",
"@types/react": "^19.1.10", "@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7", "@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0", "@vitejs/plugin-react": "^5.0.0",
"eslint": "^9.33.0", "eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20", "eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0", "globals": "^16.3.0",
"vite": "^7.1.2" "vite": "^7.1.2"
} }
} }
+54 -54
View File
@@ -1,54 +1,54 @@
import { Navigate, Routes, Route, useNavigate, useLocation } from 'react-router-dom' import { Navigate, Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import Viewer from './viewer' import Viewer from './viewer'
import Gallery from './gallery' import Gallery from './gallery'
import Login from './account/login' import Login from './account/login'
import { getServerUrl } from './hooks/getConstants' import { getServerUrl } from './hooks/getConstants'
import { useEffect } from 'react' import { useEffect } from 'react'
import CreateRootUser from './account/createRoot' import CreateRootUser from './account/createRoot'
import { AccountProvider } from './contexts/useAccount' import { AccountProvider } from './contexts/useAccount'
import { NotifierProvider } from './contexts/useNotifier' import { NotifierProvider } from './contexts/useNotifier'
function RedirectHandler() { function RedirectHandler() {
return ( return (
<div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]"> <div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]">
</div> </div>
) )
} }
function App() { function App() {
const navigate = useNavigate() const navigate = useNavigate()
const location = useLocation() const location = useLocation()
useEffect(() => { useEffect(() => {
const checkRootUser = async () => { const checkRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/rootUserExists`) const response = await fetch(`${getServerUrl()}/api/user/rootUserExists`)
const data = await response.json() const data = await response.json()
if (data.exists) { if (data.exists) {
// Only navigate to gallery if we're on the root path // Only navigate to gallery if we're on the root path
if (location.pathname === '/') { if (location.pathname === '/') {
navigate('/gallery') navigate('/gallery')
} }
} else { } else {
// Always redirect to onboarding if root user doesn't exist // Always redirect to onboarding if root user doesn't exist
if (location.pathname !== '/onboarding/createRootUser') { if (location.pathname !== '/onboarding/createRootUser') {
navigate('/onboarding/createRootUser') navigate('/onboarding/createRootUser')
} }
} }
} }
checkRootUser() checkRootUser()
}, [location.pathname, navigate]) }, [location.pathname, navigate])
return ( return (
<NotifierProvider> <NotifierProvider>
<AccountProvider> <AccountProvider>
<Routes> <Routes>
<Route path="/" element={<RedirectHandler />} /> <Route path="/" element={<RedirectHandler />} />
<Route path="/gallery/*" element={<Gallery />} /> <Route path="/gallery/*" element={<Gallery />} />
<Route path="/viewer/:albumId/:mediaId" element={<Viewer />} /> <Route path="/viewer/:albumId/:mediaId" element={<Viewer />} />
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/onboarding/createRootUser" element={<CreateRootUser />} /> <Route path="/onboarding/createRootUser" element={<CreateRootUser />} />
</Routes> </Routes>
</AccountProvider> </AccountProvider>
</NotifierProvider> </NotifierProvider>
) )
} }
export default App export default App
+83 -83
View File
@@ -1,84 +1,84 @@
import { useState } from 'react' import { useState } from 'react'
import { getServerUrl } from '../hooks/getConstants' import { getServerUrl } from '../hooks/getConstants'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier' import { useNotifier } from '../contexts/useNotifier'
export default function CreateRootUser() { export default function CreateRootUser() {
const navigate = useNavigate() const navigate = useNavigate()
const { showError, showSuccess } = useNotifier() const { showError, showSuccess } = useNotifier()
const [username, setUsername] = useState('') const [username, setUsername] = useState('')
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const handleCreateRootUser = async () => { const handleCreateRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/createUser`, { const response = await fetch(`${getServerUrl()}/api/user/createUser`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
username: username, username: username,
password: password, password: password,
}), }),
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error creating root user: " + data.error)
} else { } else {
const rootResponse = await fetch(`${getServerUrl()}/api/user/setRootUser`, { const rootResponse = await fetch(`${getServerUrl()}/api/user/setRootUser`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
username: username, username: username,
}), }),
}) })
const rootData = await rootResponse.json() const rootData = await rootResponse.json()
if (rootData.error) { if (rootData.error) {
showError(rootData.error) showError("Error setting root user: " + rootData.error)
} else { } else {
navigate('/gallery') navigate('/gallery')
showSuccess('Root user created successfully') showSuccess('Root user created successfully')
} }
} }
} }
return ( return (
<div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]"> <div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]">
<div className="flex flex-col w-full max-w-md px-8"> <div className="flex flex-col w-full max-w-md px-8">
<div className="flex flex-col gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]"> <div className="flex flex-col gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<h1 className="text-3xl font-bold text-white red-hat-mono">Create Root User</h1> <h1 className="text-3xl font-bold text-white red-hat-mono">Create Root User</h1>
<p className="text-sm text-gray-400 red-hat-text">This is the primary user account for Raster. Make sure to remember your credentials.</p> <p className="text-sm text-gray-400 red-hat-text">This is the primary user account for Raster. Make sure to remember your credentials.</p>
</div> </div>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label> <label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input <input
value={username} value={username}
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
type="text" type="text"
placeholder="Enter username" placeholder="Enter username"
className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text"
/> />
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label> <label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input <input
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
type="password" type="password"
placeholder="Enter password" placeholder="Enter password"
className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text"
/> />
</div> </div>
</div> </div>
<button className="w-full py-2.5 bg-white text-black rounded-md font-medium hover:bg-gray-200 transition-colors red-hat-mono cursor-pointer" onClick={handleCreateRootUser}> <button className="w-full py-2.5 bg-white text-black rounded-md font-medium hover:bg-gray-200 transition-colors red-hat-mono cursor-pointer" onClick={handleCreateRootUser}>
Create Create
</button> </button>
</div> </div>
</div> </div>
</div> </div>
) )
} }
+59 -59
View File
@@ -1,60 +1,60 @@
import { useState } from 'react' import { useState } from 'react'
import { useAccount } from '../contexts/useAccount' import { useAccount } from '../contexts/useAccount'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier' import { useNotifier } from '../contexts/useNotifier'
export default function Login() { export default function Login() {
const { showError } = useNotifier() const { showError } = useNotifier()
const navigate = useNavigate() const navigate = useNavigate()
const [username, setUsername] = useState('') const [username, setUsername] = useState('')
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const { login } = useAccount() const { login } = useAccount()
const handleLogin = () => { const handleLogin = () => {
login(username, password) login(username, password)
.then(() => { .then(() => {
navigate('/gallery') navigate('/gallery')
}) })
.catch((error) => { .catch((error) => {
showError(error.message) showError("Error logging in: " + error.message)
}) })
} }
return ( return (
<div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]"> <div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]">
<div className="flex flex-col w-full max-w-md px-8"> <div className="flex flex-col w-full max-w-md px-8">
<div className="flex flex-col gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]"> <div className="flex flex-col gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<h1 className="text-3xl font-bold text-white red-hat-mono">Sign In</h1> <h1 className="text-3xl font-bold text-white red-hat-mono">Sign In</h1>
<p className="text-sm text-gray-400 red-hat-text">Enter your credentials to continue</p> <p className="text-sm text-gray-400 red-hat-text">Enter your credentials to continue</p>
</div> </div>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label> <label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input <input
value={username} value={username}
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
type="text" type="text"
placeholder="Enter username" placeholder="Enter username"
className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text"
/> />
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label> <label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input <input
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
type="password" type="password"
placeholder="Enter password" placeholder="Enter password"
className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text"
/> />
</div> </div>
</div> </div>
<button className="w-full py-2.5 bg-white text-black rounded-md font-medium hover:bg-gray-200 transition-colors red-hat-mono cursor-pointer" onClick={handleLogin}> <button className="w-full py-2.5 bg-white text-black rounded-md font-medium hover:bg-gray-200 transition-colors red-hat-mono cursor-pointer" onClick={handleLogin}>
Sign In Sign In
</button> </button>
</div> </div>
</div> </div>
</div> </div>
) )
} }
+13 -13
View File
@@ -1,13 +1,13 @@
<svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2_3)"> <g clip-path="url(#clip0_2_3)">
<rect width="120" height="120" fill="#0D1B1E"/> <rect width="120" height="120" fill="#0D1B1E"/>
<rect y="60" width="60" height="60" fill="#EBF5EE"/> <rect y="60" width="60" height="60" fill="#EBF5EE"/>
<rect width="60" height="60" fill="#FF5376"/> <rect width="60" height="60" fill="#FF5376"/>
<rect x="60" y="60" width="60" height="60" fill="#9DACFF"/> <rect x="60" y="60" width="60" height="60" fill="#9DACFF"/>
</g> </g>
<defs> <defs>
<clipPath id="clip0_2_3"> <clipPath id="clip0_2_3">
<rect width="120" height="120" fill="white"/> <rect width="120" height="120" fill="white"/>
</clipPath> </clipPath>
</defs> </defs>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 450 B

After

Width:  |  Height:  |  Size: 463 B

+68 -68
View File
@@ -1,68 +1,68 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
export default function AuthImage({ src, token, alt, className, onLoad, ...props }) { export default function AuthImage({ src, token, alt, className, onLoad, ...props }) {
const [imageSrc, setImageSrc] = useState(null) const [imageSrc, setImageSrc] = useState(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState(false) const [error, setError] = useState(false)
useEffect(() => { useEffect(() => {
let objectUrl = null let objectUrl = null
let active = true let active = true
const controller = new AbortController() const controller = new AbortController()
const fetchImage = async () => { const fetchImage = async () => {
setLoading(true) setLoading(true)
setError(false) setError(false)
try { try {
const response = await fetch(src, { const response = await fetch(src, {
headers: { headers: {
'Authorization': token 'Authorization': token
}, },
signal: controller.signal signal: controller.signal
}) })
if (!response.ok) { if (!response.ok) {
throw new Error('Failed to load image') throw new Error('Failed to load image')
} }
const blob = await response.blob() const blob = await response.blob()
if (active) { if (active) {
objectUrl = URL.createObjectURL(blob) objectUrl = URL.createObjectURL(blob)
setImageSrc(objectUrl) setImageSrc(objectUrl)
setLoading(false) setLoading(false)
} }
} catch (err) { } catch (err) {
if (active) { if (active) {
console.error("Error loading image:", err) console.error("Error loading image:", err)
setError(true) setError(true)
setLoading(false) setLoading(false)
} }
} }
} }
if (src && token) { if (src && token) {
fetchImage() fetchImage()
} else { } else {
setLoading(false) setLoading(false)
} }
return () => { return () => {
active = false active = false
controller.abort() controller.abort()
if (objectUrl) { if (objectUrl) {
URL.revokeObjectURL(objectUrl) URL.revokeObjectURL(objectUrl)
} }
} }
}, [src, token]) }, [src, token])
if (loading) { if (loading) {
return <div className={`bg-gray-800 animate-pulse ${className}`} /> return <div className={`bg-gray-800 animate-pulse ${className}`} />
} }
if (error || !imageSrc) { if (error || !imageSrc) {
return <div className={`bg-gray-800 flex items-center justify-center text-gray-500 ${className}`}>Error</div> return <div className={`bg-gray-800 flex items-center justify-center text-gray-500 ${className}`}>Error</div>
} }
return <img src={imageSrc} alt={alt} className={className} onLoad={onLoad} {...props} /> return <img src={imageSrc} alt={alt} className={className} onLoad={onLoad} {...props} />
} }
+46 -46
View File
@@ -1,46 +1,46 @@
import * as Dialog from '@radix-ui/react-dialog'; import * as Dialog from '@radix-ui/react-dialog';
import { X } from 'lucide-react'; import { X } from 'lucide-react';
export default function Modal({ open, onOpenChange, trigger, title, children, isProtected = false }) { export default function Modal({ open, onOpenChange, trigger, title, children, isProtected = false }) {
return ( return (
<Dialog.Root open={open} onOpenChange={onOpenChange}> <Dialog.Root open={open} onOpenChange={onOpenChange}>
{trigger && <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>} {trigger && <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>}
<Dialog.Portal> <Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/60 z-50" /> <Dialog.Overlay className="fixed inset-0 bg-black/60 z-50" />
<Dialog.Content <Dialog.Content
onInteractOutside={(e) => { onInteractOutside={(e) => {
if (isProtected) e.preventDefault(); if (isProtected) e.preventDefault();
}} }}
onEscapeKeyDown={(e) => { onEscapeKeyDown={(e) => {
if (isProtected) { if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) { if (!window.confirm("Are you sure you want to close this?")) {
e.preventDefault(); e.preventDefault();
} }
} }
}} }}
className="fixed left-[50%] top-[50%] max-h-[85vh] w-[90vw] max-w-[450px] translate-x-[-50%] translate-y-[-50%] rounded-lg bg-[#141414] border border-[#2B2B2B] shadow-xl focus:outline-none z-50 overflow-hidden"> className="fixed left-[50%] top-[50%] max-h-[85vh] w-[90vw] max-w-[450px] translate-x-[-50%] translate-y-[-50%] rounded-lg bg-[#141414] border border-[#2B2B2B] shadow-xl focus:outline-none z-50 overflow-hidden">
<div className="flex items-center justify-between px-4 py-3 border-b border-[#2B2B2B] bg-[#1A1A1A]"> <div className="flex items-center justify-between px-4 py-3 border-b border-[#2B2B2B] bg-[#1A1A1A]">
<Dialog.Title className="text-sm font-bold text-white red-hat-text"> <Dialog.Title className="text-sm font-bold text-white red-hat-text">
{title} {title}
</Dialog.Title> </Dialog.Title>
<Dialog.Close <Dialog.Close
onClick={(e) => { onClick={(e) => {
if (isProtected) { if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) { if (!window.confirm("Are you sure you want to close this?")) {
e.preventDefault(); e.preventDefault();
} }
} }
}} }}
className="text-gray-400 hover:text-white transition-colors cursor-pointer outline-none"> className="text-gray-400 hover:text-white transition-colors cursor-pointer outline-none">
<X className="w-4 h-4" /> <X className="w-4 h-4" />
</Dialog.Close> </Dialog.Close>
</div> </div>
<div className="p-4 text-gray-300 red-hat-text"> <div className="p-4 text-gray-300 red-hat-text">
{children} {children}
</div> </div>
</Dialog.Content> </Dialog.Content>
</Dialog.Portal> </Dialog.Portal>
</Dialog.Root> </Dialog.Root>
); );
} }
+66 -66
View File
@@ -1,67 +1,67 @@
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { ChevronDown, LogIn, LogOut, UserIcon, Settings } from 'lucide-react' import { ChevronDown, LogIn, LogOut, UserIcon, Settings } from 'lucide-react'
import * as Popover from '@radix-ui/react-popover' import * as Popover from '@radix-ui/react-popover'
import { useState } from 'react'; import { useState } from 'react';
import { useAccount } from '../contexts/useAccount'; import { useAccount } from '../contexts/useAccount';
export default function NavBar({ path }) { export default function NavBar({ path }) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const { user, logout } = useAccount(); const { user, logout } = useAccount();
return ( return (
<div className="flex flex-row items-center justify-between h-[10vh] w-full px-6 py-2 border-b border-[#2B2B2B] shrink-0"> <div className="flex flex-row items-center justify-between h-[10vh] w-full px-6 py-2 border-b border-[#2B2B2B] shrink-0">
<div className="flex flex-row items-center justify-start gap-2"> <div className="flex flex-row items-center justify-start gap-2">
{path.map((item, index) => ( {path.map((item, index) => (
<div className="flex flex-row items-center justify-start gap-2 red-hat-mono"> <div className="flex flex-row items-center justify-start gap-2 text-2xl red-hat-display">
<Link to={`/${path.slice(0, index + 1).join('/')}`} key={item} className={`text-white ${index === path.length - 1 ? 'font-bold' : ''}`}> <Link to={`/${path.slice(0, index + 1).join('/')}`} key={item} className={`text-white ${index === path.length - 1 ? 'font-bold' : ''}`}>
{decodeURIComponent(item)} {decodeURIComponent(item)}
</Link> </Link>
{index !== path.length - 1 && <p className="text-white red-hat-mono">/</p>} {index !== path.length - 1 && <p className="text-white text-xl red-hat-display">/</p>}
</div> </div>
))} ))}
</div> </div>
<div className="flex flex-row items-center justify-start gap-2"> <div className="flex flex-row items-center justify-start gap-2">
<Popover.Root open={open} onOpenChange={setOpen}> <Popover.Root open={open} onOpenChange={setOpen}>
<Popover.Trigger className="flex flex-row items-center justify-start gap-0 cursor-pointer"> <Popover.Trigger className="flex flex-row items-center justify-start gap-0 cursor-pointer">
<UserIcon className="w-6 h-6 text-white cursor-pointer" /> <UserIcon className="w-6 h-6 text-white cursor-pointer" />
{/* <ChevronDown className={`w-4 h-4 text-white ${open ? 'rotate-180' : ''}`} /> */} {/* <ChevronDown className={`w-4 h-4 text-white ${open ? 'rotate-180' : ''}`} /> */}
</Popover.Trigger> </Popover.Trigger>
<Popover.Content align="end" sideOffset={8} className="w-56 z-50"> <Popover.Content align="end" sideOffset={8} className="w-56 z-50">
<div className="flex flex-col bg-[#141414] border border-[#2B2B2B] rounded-lg shadow-xl overflow-hidden"> <div className="flex flex-col bg-[#141414] border border-[#2B2B2B] rounded-lg shadow-xl overflow-hidden">
<div className="px-4 py-3 border-b border-[#2B2B2B] bg-[#1A1A1A]"> <div className="px-4 py-3 border-b border-[#2B2B2B] bg-[#1A1A1A]">
<p className="text-xs text-gray-400 mb-0.5 font-medium red-hat-mono">Signed in as</p> <p className="text-xs text-gray-400 mb-0.5 font-medium red-hat-mono">Signed in as</p>
<p className="text-sm text-white font-bold truncate red-hat-text">{user?.Username || 'Guest'}</p> <p className="text-sm text-white font-bold truncate red-hat-text">{user?.Username || 'Guest'}</p>
</div> </div>
<div className="p-1.5 flex flex-col gap-0.5"> <div className="p-1.5 flex flex-col gap-0.5">
{user ? ( {user ? (
<> <>
<button className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer"> <button className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer">
<Settings className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" /> <Settings className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" />
<span className="font-medium red-hat-text">Settings</span> <span className="font-medium red-hat-text">Settings</span>
</button> </button>
<button <button
onClick={logout} onClick={logout}
className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer" className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer"
> >
<LogOut className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" /> <LogOut className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" />
<span className="font-medium red-hat-text">Sign Out</span> <span className="font-medium red-hat-text">Sign Out</span>
</button> </button>
</> </>
) : ( ) : (
<Link <Link
to="/login" to="/login"
className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer" className="flex items-center gap-3 px-3 py-2 w-full text-left text-sm text-gray-300 hover:text-white hover:bg-[#2B2B2B] rounded-md transition-all group cursor-pointer"
> >
<LogIn className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" /> <LogIn className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" />
<span className="font-medium red-hat-text">Sign In</span> <span className="font-medium red-hat-text">Sign In</span>
</Link> </Link>
)} )}
</div> </div>
</div> </div>
</Popover.Content> </Popover.Content>
</Popover.Root> </Popover.Root>
</div> </div>
</div> </div>
) )
} }
+77 -77
View File
@@ -1,78 +1,78 @@
import { createContext, useContext, useState } from 'react' import { createContext, useContext, useState } from 'react'
import { getServerUrl } from '../hooks/getConstants' import { getServerUrl } from '../hooks/getConstants'
const AccountContext = createContext() const AccountContext = createContext()
export const AccountProvider = ({ children }) => { export const AccountProvider = ({ children }) => {
const [accessToken, setAccessToken] = useState(null) const [accessToken, setAccessToken] = useState(null)
const [user, setUser] = useState(null) const [user, setUser] = useState(null)
const login = async (username, password) => { const login = async (username, password) => {
const response = await fetch(`${getServerUrl()}/api/user/login`, { const response = await fetch(`${getServerUrl()}/api/user/login`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
throw new Error(data.error) throw new Error(data.error)
} else { } else {
setAccessToken(data.accessToken) setAccessToken(data.accessToken)
localStorage.setItem('accessToken', data.accessToken) localStorage.setItem('accessToken', data.accessToken)
fetchUserData(data.accessToken) fetchUserData(data.accessToken)
return true return true
} }
} }
const fetchUserData = async (accessToken) => { const fetchUserData = async (accessToken) => {
if (!accessToken) { if (!accessToken) {
accessToken = getAccessToken() accessToken = getAccessToken()
if (!accessToken) { if (!accessToken) {
setUser(null) setUser(null)
return false return false
} }
} }
const response = await fetch(`${getServerUrl()}/api/user/getUserData`, { const response = await fetch(`${getServerUrl()}/api/user/getUserData`, {
headers: { headers: {
'Authorization': accessToken, 'Authorization': accessToken,
}, },
}) })
const data = await response.json() const data = await response.json()
console.log(data) console.log(data)
if (data.error) { if (data.error) {
throw new Error(data.error) throw new Error(data.error)
} else { } else {
setUser(data.userData) setUser(data.userData)
return true return true
} }
} }
const logout = () => { const logout = () => {
setAccessToken(null) setAccessToken(null)
localStorage.removeItem('accessToken') localStorage.removeItem('accessToken')
location.reload() location.reload()
} }
const getAccessToken = () => { const getAccessToken = () => {
if (!accessToken && localStorage.getItem('accessToken')) { if (!accessToken && localStorage.getItem('accessToken')) {
setAccessToken(localStorage.getItem('accessToken')) setAccessToken(localStorage.getItem('accessToken'))
return localStorage.getItem('accessToken') return localStorage.getItem('accessToken')
} else if (accessToken) { } else if (accessToken) {
return accessToken return accessToken
} else { } else {
return "guest" return "guest"
} }
} }
return <AccountContext.Provider value={{ getAccessToken, logout, login, fetchUserData, user }}>{children}</AccountContext.Provider> return <AccountContext.Provider value={{ getAccessToken, logout, login, fetchUserData, user }}>{children}</AccountContext.Provider>
} }
export const useAccount = () => { export const useAccount = () => {
const context = useContext(AccountContext) const context = useContext(AccountContext)
if (!context) { if (!context) {
throw new Error('useAccount must be used within an AccountProvider') throw new Error('useAccount must be used within an AccountProvider')
} }
return context return context
} }
+125 -125
View File
@@ -1,125 +1,125 @@
import { createContext, useContext, useState, useCallback, useEffect } from 'react' import { createContext, useContext, useState, useCallback, useEffect } from 'react'
import { X, AlertCircle, CheckCircle, Info } from 'lucide-react' import { X, AlertCircle, CheckCircle, Info } from 'lucide-react'
const NotifierContext = createContext() const NotifierContext = createContext()
export const useNotifier = () => { export const useNotifier = () => {
const context = useContext(NotifierContext) const context = useContext(NotifierContext)
if (!context) { if (!context) {
throw new Error('useNotifier must be used within a NotifierProvider') throw new Error('useNotifier must be used within a NotifierProvider')
} }
return context return context
} }
export const NotifierProvider = ({ children }) => { export const NotifierProvider = ({ children }) => {
const [notifications, setNotifications] = useState([]) const [notifications, setNotifications] = useState([])
const removeNotification = useCallback((id) => { const removeNotification = useCallback((id) => {
setNotifications((prev) => prev.filter((n) => n.id !== id)) setNotifications((prev) => prev.filter((n) => n.id !== id))
}, []) }, [])
const addNotification = useCallback((message, type = 'info', duration = 5000) => { const addNotification = useCallback((message, type = 'info', duration = 5000) => {
const id = Date.now() + Math.random() const id = Date.now() + Math.random()
setNotifications((prev) => [...prev, { id, message, type, duration }]) setNotifications((prev) => [...prev, { id, message, type, duration }])
}, []) }, [])
const showError = useCallback((message, duration = 5000) => { const showError = useCallback((message, duration = 5000) => {
addNotification(message, 'error', duration) addNotification(message, 'error', duration)
}, [addNotification]) }, [addNotification])
const showSuccess = useCallback((message, duration = 3000) => { const showSuccess = useCallback((message, duration = 3000) => {
addNotification(message, 'success', duration) addNotification(message, 'success', duration)
}, [addNotification]) }, [addNotification])
const showInfo = useCallback((message, duration = 3000) => { const showInfo = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration) addNotification(message, 'info', duration)
}, [addNotification]) }, [addNotification])
const showUpdate = useCallback((message, duration = 3000) => { const showUpdate = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration) addNotification(message, 'info', duration)
}, [addNotification]) }, [addNotification])
return ( return (
<NotifierContext.Provider value={{ showError, showSuccess, showInfo, showUpdate }}> <NotifierContext.Provider value={{ showError, showSuccess, showInfo, showUpdate }}>
{children} {children}
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none"> <div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none">
{notifications.map((notification) => ( {notifications.map((notification) => (
<NotificationItem <NotificationItem
key={notification.id} key={notification.id}
notification={notification} notification={notification}
onClose={() => removeNotification(notification.id)} onClose={() => removeNotification(notification.id)}
/> />
))} ))}
</div> </div>
</NotifierContext.Provider> </NotifierContext.Provider>
) )
} }
const NotificationItem = ({ notification, onClose }) => { const NotificationItem = ({ notification, onClose }) => {
const { message, type, duration } = notification const { message, type, duration } = notification
const [isExiting, setIsExiting] = useState(false) const [isExiting, setIsExiting] = useState(false)
useEffect(() => { useEffect(() => {
if (duration > 0) { if (duration > 0) {
const timer = setTimeout(() => { const timer = setTimeout(() => {
setIsExiting(true) setIsExiting(true)
}, duration) }, duration)
return () => clearTimeout(timer) return () => clearTimeout(timer)
} }
}, [duration]) }, [duration])
useEffect(() => { useEffect(() => {
if (isExiting) { if (isExiting) {
const timer = setTimeout(() => { const timer = setTimeout(() => {
onClose() onClose()
}, 300) // Match animation duration }, 300) // Match animation duration
return () => clearTimeout(timer) return () => clearTimeout(timer)
} }
}, [isExiting, onClose]) }, [isExiting, onClose])
const getIcon = () => { const getIcon = () => {
switch (type) { switch (type) {
case 'error': case 'error':
return <AlertCircle className="w-5 h-5 text-red-500" /> return <AlertCircle className="w-5 h-5 text-red-500" />
case 'success': case 'success':
return <CheckCircle className="w-5 h-5 text-green-500" /> return <CheckCircle className="w-5 h-5 text-green-500" />
default: default:
return <Info className="w-5 h-5 text-blue-500" /> return <Info className="w-5 h-5 text-blue-500" />
} }
} }
const getBorderColor = () => { const getBorderColor = () => {
switch (type) { switch (type) {
case 'error': case 'error':
return 'border-red-500/50' return 'border-red-500/50'
case 'success': case 'success':
return 'border-green-500/50' return 'border-green-500/50'
default: default:
return 'border-[#2B2B2B]' return 'border-[#2B2B2B]'
} }
} }
return ( return (
<div <div
className={` className={`
pointer-events-auto pointer-events-auto
flex items-center gap-3 flex items-center gap-3
bg-[#141414] border ${getBorderColor()} bg-[#141414] border ${getBorderColor()}
px-4 py-3 rounded-md shadow-lg px-4 py-3 rounded-md shadow-lg
min-w-[300px] max-w-[400px] min-w-[300px] max-w-[400px]
transition-all duration-300 ease-in-out transition-all duration-300 ease-in-out
${isExiting ? 'opacity-0 translate-x-full' : 'opacity-100 translate-x-0'} ${isExiting ? 'opacity-0 translate-x-full' : 'opacity-100 translate-x-0'}
`} `}
> >
{getIcon()} {getIcon()}
<p className="text-white red-hat-text text-sm flex-1">{message}</p> <p className="text-white red-hat-text text-sm flex-1">{message}</p>
<button <button
onClick={() => setIsExiting(true)} onClick={() => setIsExiting(true)}
className="text-gray-400 hover:text-white transition-colors" className="text-gray-400 hover:text-white transition-colors"
> >
<X className="w-4 h-4" /> <X className="w-4 h-4" />
</button> </button>
</div> </div>
) )
} }
@@ -1,40 +1,40 @@
import Modal from '../../components/Modal' import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount' import { useAccount } from '../../contexts/useAccount'
import { useState } from 'react' import { useState } from 'react'
import { useNotifier } from '../../contexts/useNotifier' import { useNotifier } from '../../contexts/useNotifier'
export default function AlbumCreateModal({ open, onOpenChange, trigger, parentId }) { export default function AlbumCreateModal({ open, onOpenChange, trigger, parentId }) {
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const [title, setTitle] = useState('') const [title, setTitle] = useState('')
const [description, setDescription] = useState('') const [description, setDescription] = useState('')
const { showError } = useNotifier() const { showError } = useNotifier()
const handleCreateAlbum = async () => { const handleCreateAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/createAlbum`, { const response = await fetch(`${getServerUrl()}/api/albums/createAlbum`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': getAccessToken(), 'Authorization': getAccessToken(),
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
title: title, title: title,
description: description, description: description,
parentId: parentId parentId: parentId
}) })
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error creating album: " + data.error)
} else { } else {
onOpenChange(false) onOpenChange(false)
} }
} }
return ( return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Create Album"> <Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Create Album">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<input type="text" placeholder="Name" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" value={title} onChange={(e) => setTitle(e.target.value)} /> <input type="text" placeholder="Name" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" value={title} onChange={(e) => setTitle(e.target.value)} />
<textarea type="text" placeholder="Description" className="w-full h-[20vh] px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text resize-none" value={description} onChange={(e) => setDescription(e.target.value)} /> <textarea type="text" placeholder="Description" className="w-full h-[20vh] px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text resize-none" value={description} onChange={(e) => setDescription(e.target.value)} />
<button className="w-full py-2.5 bg-[#2B2B2B] hover:bg-[#3B3B3B] text-white rounded-md font-medium transition-colors red-hat-mono cursor-pointer mt-2" onClick={handleCreateAlbum}>Create Album</button> <button className="w-full py-2.5 bg-[#2B2B2B] hover:bg-[#3B3B3B] text-white rounded-md font-medium transition-colors red-hat-mono cursor-pointer mt-2" onClick={handleCreateAlbum}>Create Album</button>
</div> </div>
</Modal> </Modal>
) )
} }
@@ -1,59 +1,59 @@
import Modal from '../../components/Modal' import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount' import { useAccount } from '../../contexts/useAccount'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { useNotifier } from '../../contexts/useNotifier' import { useNotifier } from '../../contexts/useNotifier'
import FilePicker from './FilePicker' import FilePicker from './FilePicker'
export default function AlbumEditModal({ open, onOpenChange, trigger, id, startTitle, startDescription, currentAlbum }) { export default function AlbumEditModal({ open, onOpenChange, trigger, id, startTitle, startDescription, currentAlbum }) {
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const [title, setTitle] = useState(startTitle || '') const [title, setTitle] = useState(startTitle || '')
const [description, setDescription] = useState(startDescription || '') const [description, setDescription] = useState(startDescription || '')
const [thumbnail, setThumbnail] = useState(null) const [thumbnail, setThumbnail] = useState(null)
const { showError } = useNotifier() const { showError } = useNotifier()
const handleEditAlbum = async () => { const handleEditAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/editAlbum`, { const response = await fetch(`${getServerUrl()}/api/albums/editAlbum`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': getAccessToken(), 'Authorization': getAccessToken(),
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
id: id, id: id,
properties: { properties: {
title: title, title: title,
description: description, description: description,
thumbnail: thumbnail, thumbnail: thumbnail,
} }
}) })
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error editing album: " + data.error)
} else { } else {
onOpenChange(false) onOpenChange(false)
} }
} }
useEffect(() => { useEffect(() => {
if (open) { if (open) {
setTitle(startTitle || '') setTitle(startTitle || '')
setDescription(startDescription || '') setDescription(startDescription || '')
} }
}, [open]) }, [open])
const handleFileSelect = (file) => { const handleFileSelect = (file) => {
console.log(file) console.log(file)
setThumbnail(file.selectedAlbum.ID + '/' + file.selectedFile.ID) setThumbnail(file.selectedAlbum.ID + '/' + file.selectedFile.ID)
} }
return ( return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Edit Album"> <Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Edit Album">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<p className="text-white red-hat-mono">Name</p> <p className="text-white red-hat-mono">Name</p>
<input type="text" placeholder="Name" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" value={title} onChange={(e) => setTitle(e.target.value)} /> <input type="text" placeholder="Name" className="w-full px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text" value={title} onChange={(e) => setTitle(e.target.value)} />
<p className="text-white red-hat-mono">Description</p> <p className="text-white red-hat-mono">Description</p>
<textarea type="text" placeholder="Description" className="w-full h-[20vh] px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text resize-none" value={description} onChange={(e) => setDescription(e.target.value)} /> <textarea type="text" placeholder="Description" className="w-full h-[20vh] px-3 py-2.5 bg-[#141414] border border-[#2B2B2B] rounded-md text-white placeholder-gray-600 focus:outline-none focus:border-[#3B3B3B] transition-colors red-hat-text resize-none" value={description} onChange={(e) => setDescription(e.target.value)} />
<p className="text-white red-hat-mono">Thumbnail</p> <p className="text-white red-hat-mono">Thumbnail</p>
<FilePicker currentAlbum={currentAlbum} onFileSelect={handleFileSelect} /> <FilePicker currentAlbum={currentAlbum} onFileSelect={handleFileSelect} />
<button className="w-full py-2.5 bg-[#2B2B2B] hover:bg-[#3B3B3B] text-white rounded-md font-medium transition-colors red-hat-mono cursor-pointer mt-2" onClick={handleEditAlbum}>Save Changes</button> <button className="w-full py-2.5 bg-[#2B2B2B] hover:bg-[#3B3B3B] text-white rounded-md font-medium transition-colors red-hat-mono cursor-pointer mt-2" onClick={handleEditAlbum}>Save Changes</button>
</div> </div>
</Modal> </Modal>
) )
} }
+99 -99
View File
@@ -1,100 +1,100 @@
import { PlusIcon, EllipsisVertical } from 'lucide-react' import { PlusIcon, EllipsisVertical } from 'lucide-react'
import AlbumCreateModal from './AlbumCreateModal' import AlbumCreateModal from './AlbumCreateModal'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount' import { useAccount } from '../../contexts/useAccount'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../../contexts/useNotifier' import { useNotifier } from '../../contexts/useNotifier'
import AlbumEditModal from './AlbumEditModal' import AlbumEditModal from './AlbumEditModal'
export default function AlbumList({ currentAlbumName }) { export default function AlbumList({ currentAlbumName }) {
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [openEdit, setOpenEdit] = useState(false) const [openEdit, setOpenEdit] = useState(false)
const [editingAlbum, setEditingAlbum] = useState(null) const [editingAlbum, setEditingAlbum] = useState(null)
const [albums, setAlbums] = useState([]) const [albums, setAlbums] = useState([])
const navigate = useNavigate() const navigate = useNavigate()
const { showError } = useNotifier() const { showError } = useNotifier()
useEffect(() => { useEffect(() => {
let ignore = false; let ignore = false;
const getAlbums = async () => { const getAlbums = async () => {
console.log('Getting albums in parent', currentAlbumName) console.log('Getting albums in parent', currentAlbumName)
const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName; const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName;
try { try {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, { const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': getAccessToken(), 'Authorization': getAccessToken(),
}, },
body: JSON.stringify({ body: JSON.stringify({
parentId: parentId, parentId: parentId,
}), }),
}) })
const data = await response.json() const data = await response.json()
if (!ignore) { if (!ignore) {
if (data.error) { if (data.error) {
setAlbums([]) setAlbums([])
showError('Failed to get albums') showError('Failed to get albums')
} else { } else {
setAlbums(data) setAlbums(data)
} }
} }
} catch (error) { } catch (error) {
if (!ignore) { if (!ignore) {
setAlbums([]) setAlbums([])
showError('Failed to get albums') showError('Failed to get albums')
} }
} }
} }
if (!open && !openEdit && currentAlbumName !== null) { if (!open && !openEdit && currentAlbumName !== null) {
getAlbums() getAlbums()
} }
return () => { ignore = true; } return () => { ignore = true; }
}, [currentAlbumName, open, openEdit]) }, [currentAlbumName, open, openEdit])
return ( return (
<div className="flex flex-col items-center justify-start h-min w-full bg-[#141414]"> <div className="flex flex-col items-center justify-start h-min w-full bg-[#141414]">
<div className="flex flex-row items-center justify-between gap-2 w-full px-6 py-4"> <div className="flex flex-row items-center justify-between gap-2 w-full px-6 py-4">
<h1 className="text-xl font-bold text-white red-hat-mono">Albums</h1> <h1 className="text-xl font-bold text-white red-hat-display">Albums</h1>
<PlusIcon className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} /> <PlusIcon className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} />
</div> </div>
<div className="flex flex-row items-center justify-start gap-2 w-full px-6 flex-wrap"> <div className="flex flex-row items-center justify-start gap-2 w-full px-6 flex-wrap">
{albums.map((album) => ( {albums.map((album) => (
<div <div
key={album.ID} key={album.ID}
className="flex flex-row items-center justify-start gap-2 w-1/8 aspect-square border border-[#2B2B2B] rounded-md px-6 py-4 cursor-pointer" className="flex flex-row items-center justify-start gap-2 w-1/8 aspect-square border border-[#2B2B2B] rounded-md px-6 py-4 cursor-pointer"
onClick={() => { onClick={() => {
// Get current path and append the album's title // Get current path and append the album's title
const currentPath = window.location.pathname; const currentPath = window.location.pathname;
// Remove leading and trailing slashes, split to parts // Remove leading and trailing slashes, split to parts
const pathParts = currentPath.replace(/^\/|\/$/g, '').split('/'); const pathParts = currentPath.replace(/^\/|\/$/g, '').split('/');
// Only append if not already the last part (avoid duplicate navigation) // Only append if not already the last part (avoid duplicate navigation)
if (pathParts[pathParts.length - 1] !== album.Title) { if (pathParts[pathParts.length - 1] !== album.Title) {
navigate(`${currentPath.replace(/\/$/, '')}/${encodeURIComponent(album.Title)}`); navigate(`${currentPath.replace(/\/$/, '')}/${encodeURIComponent(album.Title)}`);
} else { } else {
navigate(currentPath); // Or optionally do nothing/navigate to self navigate(currentPath); // Or optionally do nothing/navigate to self
} }
}} }}
> >
<p className="text-white red-hat-mono">{album.Title}</p> <p className="text-white red-hat-text">{album.Title}</p>
<EllipsisVertical className="w-6 h-6 cursor-pointer" color="white" onClick={(e) => { <EllipsisVertical className="w-6 h-6 cursor-pointer" color="white" onClick={(e) => {
e.stopPropagation() e.stopPropagation()
setEditingAlbum(album) setEditingAlbum(album)
setOpenEdit(true) setOpenEdit(true)
}} /> }} />
</div> </div>
))} ))}
</div> </div>
<AlbumCreateModal open={open} onOpenChange={setOpen} parentId={currentAlbumName === 'gallery' ? '' : currentAlbumName} /> <AlbumCreateModal open={open} onOpenChange={setOpen} parentId={currentAlbumName === 'gallery' ? '' : currentAlbumName} />
{editingAlbum && ( {editingAlbum && (
<AlbumEditModal <AlbumEditModal
open={openEdit} open={openEdit}
onOpenChange={setOpenEdit} onOpenChange={setOpenEdit}
id={editingAlbum.ID} id={editingAlbum.ID}
startTitle={editingAlbum.Title} startTitle={editingAlbum.Title}
startDescription={editingAlbum.Description} startDescription={editingAlbum.Description}
currentAlbum={editingAlbum} currentAlbum={editingAlbum}
/> />
)} )}
</div> </div>
) )
} }
@@ -14,7 +14,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
const [media, setMedia] = useState(null) const [media, setMedia] = useState(null)
const [filePickerOpen, setFilePickerOpen] = useState(false) const [filePickerOpen, setFilePickerOpen] = useState(false)
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const { showError } = useNotifier() const { showError, showInfo } = useNotifier()
useEffect(() => { useEffect(() => {
const getAlbum = async () => { const getAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, { const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
@@ -28,7 +28,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error getting albums in parent: " + data.error)
} else { } else {
setAlbums(data) setAlbums(data)
} }
@@ -45,7 +45,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error getting album info: " + data.error)
} else { } else {
setSelectedAlbum(data) setSelectedAlbum(data)
} }
@@ -59,7 +59,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error getting media: " + data.error)
} else { } else {
if (data.media.length === 0) { if (data.media.length === 0) {
setMedia(null) setMedia(null)
@@ -99,7 +99,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
showError(data.error) showError("Error getting album: " + data.error)
break break
} }
+126 -122
View File
@@ -1,122 +1,126 @@
import { EllipsisVertical, Upload } from 'lucide-react' import { EllipsisVertical, Upload } from 'lucide-react'
import MediaUploadModal from './MediaUploadModal' import MediaUploadModal from './MediaUploadModal'
import AuthImage from '../../components/AuthImage' import AuthImage from '../../components/AuthImage'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount' import { useAccount } from '../../contexts/useAccount'
import { useNotifier } from '../../contexts/useNotifier' import { useNotifier } from '../../contexts/useNotifier'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
export default function MediaList({ albumId, albumName }) { export default function MediaList({ albumId, albumName }) {
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [media, setMedia] = useState([]) const [media, setMedia] = useState([])
const [aspectRatios, setAspectRatios] = useState({}) const [aspectRatios, setAspectRatios] = useState({})
const { showError } = useNotifier() const { showError, showInfo } = useNotifier()
const navigate = useNavigate() const navigate = useNavigate()
useEffect(() => { useEffect(() => {
let ignore = false; let ignore = false;
const getMedia = async () => { const accessToken = getAccessToken()
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${albumId}`, { if (!accessToken || !albumId && albumName !== 'gallery') {
method: 'GET', return // assuming state isn't loaded yet
headers: { }
'Authorization': getAccessToken(), const getMedia = async () => {
}, const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${albumId}`, {
}) method: 'GET',
const data = await response.json() headers: {
if (ignore) return 'Authorization': accessToken,
if (data.error) { },
showError(data.error) })
} else { const data = await response.json()
setMedia(data.media) if (ignore) return
} if (data.error) {
} showError("Error getting media in album: " + data.error)
getMedia() } else {
return () => { ignore = true; } setMedia(data.media)
}, [albumId]) }
}
const handleImageLoad = (id, event) => { getMedia()
const { naturalWidth, naturalHeight } = event.target return () => { ignore = true; }
if (naturalWidth && naturalHeight) { }, [albumId])
setAspectRatios(prev => ({
...prev, const handleImageLoad = (id, event) => {
[id]: naturalWidth / naturalHeight const { naturalWidth, naturalHeight } = event.target
})) if (naturalWidth && naturalHeight) {
} setAspectRatios(prev => ({
} ...prev,
[id]: naturalWidth / naturalHeight
useEffect(() => { }))
console.log(media) }
}, [media]) }
return ( useEffect(() => {
<div className="flex flex-col items-center justify-start w-full bg-[#141414]"> console.log(media)
<div className="flex flex-row items-center justify-between gap-2 w-full px-6 py-4"> }, [media])
<h1 className="text-xl font-bold text-white red-hat-mono">Media</h1>
<Upload className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} /> return (
</div> <div className="flex flex-col items-center justify-start w-full bg-[#141414]">
<MediaUploadModal <div className="flex flex-row items-center justify-between gap-2 w-full px-6 py-4">
open={open} <h1 className="text-xl font-bold text-white red-hat-display">Media</h1>
onOpenChange={setOpen} <Upload className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} />
albumId={albumId} </div>
albumName={albumName} <MediaUploadModal
/> open={open}
onOpenChange={setOpen}
{/* Media Grid */} albumId={albumId}
<div className="flex flex-wrap justify-start gap-2 w-full px-6"> albumName={albumName}
{media.length === 0 && ( />
<p className="text-gray-500 red-hat-text">No media in this album</p>
)} {/* Media Grid */}
{media.map((item) => { <div className="flex flex-wrap justify-start gap-2 w-full px-6">
let ar = 1; {media.length === 0 && (
// Try to get aspect ratio from metadata (new uploads) or fallback to loaded state (old uploads) <p className="text-gray-500 red-hat-text">No media in this album</p>
if (item.Metadata && item.Metadata.width && item.Metadata.height) { )}
ar = item.Metadata.width / item.Metadata.height; {media.map((item) => {
} else if (aspectRatios[item.ID]) { let ar = 1;
ar = aspectRatios[item.ID]; // Try to get aspect ratio from metadata (new uploads) or fallback to loaded state (old uploads)
} if (item.Metadata && item.Metadata.width && item.Metadata.height) {
ar = item.Metadata.width / item.Metadata.height;
return ( } else if (aspectRatios[item.ID]) {
<div ar = aspectRatios[item.ID];
key={item.ID} }
style={{
aspectRatio: ar, return (
flexGrow: ar, <div
flexBasis: `${220 * ar}px`, key={item.ID}
}} style={{
className="relative bg-[#1A1A1A] rounded-md overflow-hidden border border-[#2B2B2B] min-w-[100px] hover:scale-102 transition-all duration-300 cursor-pointer" aspectRatio: ar,
onClick={() => { flexGrow: ar,
navigate(`/viewer/${albumId ? albumId : 'root'}/${item.ID}`) flexBasis: `${220 * ar}px`,
}} }}
> className="relative bg-[#1A1A1A] rounded-md overflow-hidden border border-[#2B2B2B] min-w-[100px] hover:scale-102 transition-all duration-300 cursor-pointer"
<div className="absolute top-0 left-0 w-full h-full bg-gradient-to-b from-[#1A1A1A] via-transparent to-transparent flex items-start justify-start opacity-0 hover:opacity-100 transition-all duration-300"> onClick={() => {
<p className="text-white text-sm truncate max-w-[100%] p-2 red-hat-mono">{item.Title}</p> navigate(`/viewer/${albumId ? albumId : 'root'}/${item.ID}`)
<button className="text-white px-1 py-1 rounded-md absolute top-2 right-2 cursor-pointer z-50" onClick={(e) => { }}
e.stopPropagation() >
setOpen(true) <div className="absolute top-0 left-0 w-full h-full bg-gradient-to-b from-[#1A1A1A] via-transparent to-transparent flex items-start justify-start opacity-0 hover:opacity-100 transition-all duration-300">
}}> <p className="text-white text-sm truncate max-w-[90%] p-2 red-hat-text">{item.Title}</p>
<EllipsisVertical className="w-4 h-4" /> <button className="text-white px-1 py-1 rounded-md absolute top-2 right-2 cursor-pointer z-50" onClick={(e) => {
</button> e.stopPropagation()
</div> setOpen(true)
<AuthImage }}>
src={`${getServerUrl()}/api/media/thumb/${albumId ? albumId : 'root'}/${item.ID}`} <EllipsisVertical className="w-4 h-4" />
token={getAccessToken()} </button>
alt={item.Title} </div>
className="w-full h-full object-cover" <AuthImage
onLoad={(e) => handleImageLoad(item.ID, e)} src={`${getServerUrl()}/api/media/thumb/${albumId ? albumId : 'root'}/${item.ID}`}
/> token={getAccessToken()}
</div> alt={item.Title}
) className="w-full h-full object-cover"
})} onLoad={(e) => handleImageLoad(item.ID, e)}
{/* Spacer to prevent the last row from expanding to fill width if it has few items */} />
<div style={{ flexGrow: 9999, flexBasis: '50%' }}></div> </div>
</div> )
})}
<MediaUploadModal {/* Spacer to prevent the last row from expanding to fill width if it has few items */}
open={open} <div style={{ flexGrow: 9999, flexBasis: '50%' }}></div>
onOpenChange={setOpen} </div>
albumId={albumId}
albumName={albumName} <MediaUploadModal
/> open={open}
</div> onOpenChange={setOpen}
) albumId={albumId}
} albumName={albumName}
/>
</div>
)
}
@@ -1,184 +1,184 @@
import Modal from '../../components/Modal' import Modal from '../../components/Modal'
import { useAccount } from '../../contexts/useAccount' import { useAccount } from '../../contexts/useAccount'
import { useState, useRef } from 'react' import { useState, useRef } from 'react'
import { X, Upload, FileImage, FileVideo, Trash2 } from 'lucide-react' import { X, Upload, FileImage, FileVideo, Trash2 } from 'lucide-react'
import { useNotifier } from '../../contexts/useNotifier' import { useNotifier } from '../../contexts/useNotifier'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
export default function MediaUploadModal({ open, onOpenChange, trigger, albumName, albumId }) { export default function MediaUploadModal({ open, onOpenChange, trigger, albumName, albumId }) {
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const [files, setFiles] = useState([]) const [files, setFiles] = useState([])
const fileInputRef = useRef(null) const fileInputRef = useRef(null)
const { showError, showSuccess } = useNotifier() const { showError, showSuccess } = useNotifier()
const handleFileSelect = (e) => { const handleFileSelect = (e) => {
if (e.target.files) { if (e.target.files) {
const newFiles = Array.from(e.target.files).map(file => ({ const newFiles = Array.from(e.target.files).map(file => ({
file, file,
progress: 0, progress: 0,
status: 'pending', status: 'pending',
id: Math.random().toString(36).substring(7) id: Math.random().toString(36).substring(7)
})) }))
setFiles(prev => [...prev, ...newFiles]) setFiles(prev => [...prev, ...newFiles])
} }
// Reset input so the same file can be selected again if needed // Reset input so the same file can be selected again if needed
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = '' fileInputRef.current.value = ''
} }
} }
const removeFile = (id) => { const removeFile = (id) => {
setFiles(prev => prev.filter(f => f.id !== id)) setFiles(prev => prev.filter(f => f.id !== id))
} }
const handleUpload = async () => { const handleUpload = async () => {
const pendingFiles = files.filter(f => f.status === 'pending') const pendingFiles = files.filter(f => f.status === 'pending')
if (pendingFiles.length === 0) return if (pendingFiles.length === 0) return
setFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, status: 'uploading' } : f)) setFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, status: 'uploading' } : f))
const uploadFile = (fileWrapper) => { const uploadFile = (fileWrapper) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest() const xhr = new XMLHttpRequest()
const formData = new FormData() const formData = new FormData()
formData.append('file', fileWrapper.file) formData.append('file', fileWrapper.file)
formData.append('albumId', albumId) formData.append('albumId', albumId)
xhr.upload.addEventListener('progress', (event) => { xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) { if (event.lengthComputable) {
const progress = Math.round((event.loaded / event.total) * 100) const progress = Math.round((event.loaded / event.total) * 100)
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, progress } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, progress } : f))
} }
}) })
xhr.addEventListener('load', () => { xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) { if (xhr.status >= 200 && xhr.status < 300) {
try { try {
const data = JSON.parse(xhr.responseText) const data = JSON.parse(xhr.responseText)
if (data.error) { if (data.error) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(data.error) reject(data.error)
} else { } else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'completed', progress: 100 } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'completed', progress: 100 } : f))
resolve(data) resolve(data)
} }
} catch (e) { } catch (e) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(e) reject(e)
} }
} else { } else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error(xhr.statusText)) reject(new Error(xhr.statusText))
} }
}) })
xhr.addEventListener('error', () => { xhr.addEventListener('error', () => {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f)) setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error('Network Error')) reject(new Error('Network Error'))
}) })
xhr.open('POST', `${getServerUrl()}/api/media/uploadMedia`) xhr.open('POST', `${getServerUrl()}/api/media/uploadMedia`)
xhr.setRequestHeader('Authorization', getAccessToken()) xhr.setRequestHeader('Authorization', getAccessToken())
xhr.send(formData) xhr.send(formData)
}) })
} }
const results = await Promise.allSettled(pendingFiles.map(f => uploadFile(f))) const results = await Promise.allSettled(pendingFiles.map(f => uploadFile(f)))
const failedCount = results.filter(r => r.status === 'rejected').length const failedCount = results.filter(r => r.status === 'rejected').length
const successCount = results.filter(r => r.status === 'fulfilled').length const successCount = results.filter(r => r.status === 'fulfilled').length
if (failedCount > 0) { if (failedCount > 0) {
showError(`${failedCount} file(s) failed to upload`) showError(`${failedCount} file(s) failed to upload`)
} }
if (successCount > 0) { if (successCount > 0) {
showSuccess(`${successCount} file(s) uploaded successfully`) showSuccess(`${successCount} file(s) uploaded successfully`)
} }
} }
const formatFileSize = (bytes) => { const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Bytes' if (bytes === 0) return '0 Bytes'
const k = 1024 const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB'] const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k)) const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i] return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
} }
return ( return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} isProtected={true} title={`Upload to ${albumName || 'Album'}`}> <Modal open={open} onOpenChange={onOpenChange} trigger={trigger} isProtected={true} title={`Upload to ${albumName || 'Album'}`}>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
{/* File Selection Area */} {/* File Selection Area */}
<div <div
className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-[#2B2B2B] rounded-lg cursor-pointer hover:border-[#3B3B3B] transition-colors bg-[#1A1A1A]" className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-[#2B2B2B] rounded-lg cursor-pointer hover:border-[#3B3B3B] transition-colors bg-[#1A1A1A]"
onClick={() => fileInputRef.current?.click()} onClick={() => fileInputRef.current?.click()}
> >
<Upload className="w-8 h-8 text-gray-400 mb-2" /> <Upload className="w-8 h-8 text-gray-400 mb-2" />
<p className="text-gray-400 text-sm font-medium red-hat-text">Click to select files</p> <p className="text-gray-400 text-sm font-medium red-hat-text">Click to select files</p>
<p className="text-gray-600 text-xs mt-1 red-hat-text">Images and Videos</p> <p className="text-gray-600 text-xs mt-1 red-hat-text">Images and Videos</p>
<input <input
type="file" type="file"
ref={fileInputRef} ref={fileInputRef}
className="hidden" className="hidden"
multiple multiple
accept="image/*,video/*" accept="image/*,video/*"
onChange={handleFileSelect} onChange={handleFileSelect}
/> />
</div> </div>
{/* File List */} {/* File List */}
{files.length > 0 && ( {files.length > 0 && (
<div className="flex flex-col gap-2 max-h-[40vh] overflow-y-auto pr-1"> <div className="flex flex-col gap-2 max-h-[40vh] overflow-y-auto pr-1">
{files.map((fileWrapper) => ( {files.map((fileWrapper) => (
<div key={fileWrapper.id} className="flex flex-col gap-2 bg-[#1A1A1A] p-3 rounded-md border border-[#2B2B2B]"> <div key={fileWrapper.id} className="flex flex-col gap-2 bg-[#1A1A1A] p-3 rounded-md border border-[#2B2B2B]">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-3 overflow-hidden"> <div className="flex items-center gap-3 overflow-hidden">
{fileWrapper.file.type.startsWith('video') ? ( {fileWrapper.file.type.startsWith('video') ? (
<FileVideo className="w-5 h-5 text-blue-400 flex-shrink-0" /> <FileVideo className="w-5 h-5 text-blue-400 flex-shrink-0" />
) : ( ) : (
<FileImage className="w-5 h-5 text-green-400 flex-shrink-0" /> <FileImage className="w-5 h-5 text-green-400 flex-shrink-0" />
)} )}
<div className="flex flex-col overflow-hidden"> <div className="flex flex-col overflow-hidden">
<span className="text-white text-sm truncate red-hat-text" title={fileWrapper.file.name}> <span className="text-white text-sm truncate red-hat-text" title={fileWrapper.file.name}>
{fileWrapper.file.name} {fileWrapper.file.name}
</span> </span>
<span className="text-gray-500 text-xs red-hat-mono"> <span className="text-gray-500 text-xs red-hat-mono">
{formatFileSize(fileWrapper.file.size)} {formatFileSize(fileWrapper.file.size)}
</span> </span>
</div> </div>
</div> </div>
<button <button
onClick={() => removeFile(fileWrapper.id)} onClick={() => removeFile(fileWrapper.id)}
className="text-gray-500 hover:text-red-400 transition-colors p-1" className="text-gray-500 hover:text-red-400 transition-colors p-1"
disabled={fileWrapper.status === 'uploading'} disabled={fileWrapper.status === 'uploading'}
> >
<Trash2 className="w-4 h-4" /> <Trash2 className="w-4 h-4" />
</button> </button>
</div> </div>
{/* Progress Bar */} {/* Progress Bar */}
<div className="w-full h-1.5 bg-[#2B2B2B] rounded-full overflow-hidden"> <div className="w-full h-1.5 bg-[#2B2B2B] rounded-full overflow-hidden">
<div <div
className={`h-full transition-all duration-300 ${fileWrapper.status === 'completed' ? 'bg-green-500' : className={`h-full transition-all duration-300 ${fileWrapper.status === 'completed' ? 'bg-green-500' :
fileWrapper.status === 'error' ? 'bg-red-500' : 'bg-blue-500' fileWrapper.status === 'error' ? 'bg-red-500' : 'bg-blue-500'
}`} }`}
style={{ width: `${fileWrapper.progress}%` }} style={{ width: `${fileWrapper.progress}%` }}
/> />
</div> </div>
</div> </div>
))} ))}
</div> </div>
)} )}
{/* Upload Button */} {/* Upload Button */}
<button <button
className={`w-full py-2.5 bg-[#2B2B2B] text-white rounded-md font-medium transition-colors red-hat-mono ${files.length === 0 || files.every(f => f.status === 'completed') className={`w-full py-2.5 bg-[#2B2B2B] text-white rounded-md font-medium transition-colors red-hat-mono ${files.length === 0 || files.every(f => f.status === 'completed')
? 'opacity-50 cursor-not-allowed' ? 'opacity-50 cursor-not-allowed'
: 'hover:bg-[#3B3B3B] cursor-pointer' : 'hover:bg-[#3B3B3B] cursor-pointer'
}`} }`}
onClick={handleUpload} onClick={handleUpload}
disabled={files.length === 0 || files.every(f => f.status === 'completed')} disabled={files.length === 0 || files.every(f => f.status === 'completed')}
> >
{files.some(f => f.status === 'uploading') ? 'Uploading...' : 'Upload Files'} {files.some(f => f.status === 'uploading') ? 'Uploading...' : 'Upload Files'}
</button> </button>
</div> </div>
</Modal> </Modal>
) )
} }
+59 -59
View File
@@ -1,60 +1,60 @@
import NavBar from '../components/NavBar' import NavBar from '../components/NavBar'
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import { useAccount } from '../contexts/useAccount'; import { useAccount } from '../contexts/useAccount';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import AlbumList from './components/AlbumList'; import AlbumList from './components/AlbumList';
import { getServerUrl } from '../hooks/getConstants'; import { getServerUrl } from '../hooks/getConstants';
import { useNotifier } from '../contexts/useNotifier'; import { useNotifier } from '../contexts/useNotifier';
import MediaList from './components/MediaList'; import MediaList from './components/MediaList';
export default function Gallery() { export default function Gallery() {
const currentPath = useLocation().pathname; const currentPath = useLocation().pathname;
const pathList = currentPath.split('/').slice(1); const pathList = currentPath.split('/').slice(1);
const currentAlbumName = pathList[pathList.length - 1]; const currentAlbumName = pathList[pathList.length - 1];
const [currentAlbumID, setCurrentAlbumID] = useState(null); // Initialize as null to prevent premature fetching const [currentAlbumID, setCurrentAlbumID] = useState(null); // Initialize as null to prevent premature fetching
const { fetchUserData, user } = useAccount() const { fetchUserData, user } = useAccount()
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const { showError } = useNotifier() const { showError } = useNotifier()
useEffect(() => { useEffect(() => {
fetchUserData() fetchUserData()
}, []) }, [])
useEffect(() => { useEffect(() => {
const getCurrentAlbumID = async () => { const getCurrentAlbumID = async () => {
console.log("currentAlbumName", currentAlbumName) console.log("currentAlbumName", currentAlbumName)
console.log("pathList", pathList) console.log("pathList", pathList)
if (currentAlbumName === 'gallery') { if (currentAlbumName === 'gallery') {
setCurrentAlbumID(''); setCurrentAlbumID('');
return; return;
} }
const response = await fetch(`${getServerUrl()}/api/albums/getIDFromPath`, { const response = await fetch(`${getServerUrl()}/api/albums/getIDFromPath`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': getAccessToken(), 'Authorization': getAccessToken(),
}, },
body: JSON.stringify({ body: JSON.stringify({
path: decodeURIComponent(pathList.slice(1).join('/')), path: decodeURIComponent(pathList.slice(1).join('/')),
}), }),
}) })
const data = await response.json() const data = await response.json()
if (data.error) { if (data.error) {
setCurrentAlbumID("!notfound!") setCurrentAlbumID("!notfound!")
showError('Album not found') showError('Album not found')
} else { } else {
setCurrentAlbumID(data.id); setCurrentAlbumID(data.id);
} }
}; };
getCurrentAlbumID(); getCurrentAlbumID();
}, [currentPath]); }, [currentPath]);
useEffect(() => { useEffect(() => {
console.log("currentAlbumID", currentAlbumID) console.log("currentAlbumID", currentAlbumID)
}, [currentAlbumID]) }, [currentAlbumID])
return ( return (
<div className="flex flex-col items-center justify-start min-h-screen w-full bg-[#141414] pb-8"> <div className="flex flex-col items-center justify-start min-h-screen w-full bg-[#141414] pb-8">
<NavBar path={pathList} /> <NavBar path={pathList} />
<AlbumList currentAlbumName={currentAlbumID} /> <AlbumList currentAlbumName={currentAlbumID} />
<MediaList albumId={currentAlbumID} albumName={currentAlbumName} /> <MediaList albumId={currentAlbumID} albumName={currentAlbumName} />
</div> </div>
) )
} }
+2 -2
View File
@@ -1,3 +1,3 @@
export const getServerUrl = () => { export const getServerUrl = () => {
return 'http://localhost:8080'; return 'http://localhost:8080';
} }
+30 -23
View File
@@ -1,24 +1,31 @@
@import "tailwindcss"; @import "tailwindcss";
html, html,
body, body,
#root { #root {
height: 100%; height: 100%;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
.red-hat-mono { .red-hat-mono {
font-family: "Red Hat Mono", monospace; font-family: "Red Hat Mono", monospace;
font-optical-sizing: auto; font-optical-sizing: auto;
font-weight: 400; font-weight: 400;
font-style: normal; font-style: normal;
} }
.red-hat-text { .red-hat-text {
font-family: "Red Hat Text", sans-serif; font-family: "Red Hat Text", sans-serif;
font-optical-sizing: auto; font-optical-sizing: auto;
font-weight: 400; font-weight: 400;
font-style: normal; font-style: normal;
}
.red-hat-display {
font-family: "Red Hat Display", sans-serif;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
} }
+13 -13
View File
@@ -1,13 +1,13 @@
import { StrictMode } from 'react' import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom' import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx' import App from './App.jsx'
import './index.css' import './index.css'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode> <StrictMode>
<BrowserRouter> <BrowserRouter>
<App /> <App />
</BrowserRouter> </BrowserRouter>
</StrictMode>, </StrictMode>,
) )
+6 -6
View File
@@ -1,7 +1,7 @@
export default function Test() { export default function Test() {
return ( return (
<div className="flex flex-col items-center justify-center h-full w-full"> <div className="flex flex-col items-center justify-center h-full w-full">
<h1 className="text-2xl font-bold">Test</h1> <h1 className="text-2xl font-bold">Test</h1>
</div> </div>
) )
} }
+36 -36
View File
@@ -1,36 +1,36 @@
import AuthImage from '../../components/AuthImage' import AuthImage from '../../components/AuthImage'
import { getServerUrl } from '../../hooks/getConstants' import { getServerUrl } from '../../hooks/getConstants'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
export default function ImageViewer({ albumId, mediaId, token, title }) { export default function ImageViewer({ albumId, mediaId, token, title }) {
const src = `${getServerUrl()}/api/media/${albumId}/${mediaId}` const src = `${getServerUrl()}/api/media/${albumId}/${mediaId}`
const [loaded, setLoaded] = useState(false) const [loaded, setLoaded] = useState(false)
return ( return (
<div className="flex-1 flex items-center justify-center bg-black relative overflow-hidden h-full"> <div className="flex-1 flex items-center justify-center bg-black relative overflow-hidden">
<AuthImage <AuthImage
src={src} src={src}
token={token} token={token}
alt={title} alt={title}
className={`max-w-full max-h-full object-contain absolute ${loaded ? 'block' : 'hidden'}`} className={`max-w-full max-h-full object-contain absolute ${loaded ? 'block' : 'hidden'}`}
onLoad={() => { onLoad={() => {
setLoaded(true) setLoaded(true)
}} }}
/> />
{/* loading image */} {/* loading image */}
{!loaded && ( {!loaded && (
<div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center"> <div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center">
<AuthImage <AuthImage
src={`${getServerUrl()}/api/media/thumb/${albumId}/${mediaId}`} src={`${getServerUrl()}/api/media/thumb/${albumId}/${mediaId}`}
token={token} token={token}
alt={title} alt={title}
className="max-w-full max-h-full object-contain w-full h-full" className="max-w-full max-h-full object-contain w-full h-full"
/> />
<Loader2 className="w-10 h-10 text-white animate-spin absolute bottom-5 right-5" /> <Loader2 className="w-10 h-10 text-white animate-spin absolute bottom-5 right-5" />
</div> </div>
)} )}
</div> </div>
) )
} }
@@ -1,51 +1,51 @@
export default function MetadataPanel({ mediaItem }) { export default function MetadataPanel({ mediaItem, open, onOpenChange }) {
if (!mediaItem) return <div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-4 text-white">Loading...</div> if (!mediaItem) return <div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-4 text-white">Loading...</div>
return ( return (
<div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-6 text-white overflow-y-auto flex-shrink-0"> <div className={`w-full md:w-80 bg-[#1A1A1A] h-72 md:h-full border-t md:border-t-0 md:border-l border-[#2B2B2B] p-6 text-white overflow-y-auto flex-shrink-0 ${open ? 'block' : 'hidden'}`}>
<h2 className="text-xl font-bold mb-6 red-hat-mono break-words">{mediaItem.Title}</h2> <h2 className="text-xl font-bold mb-6 red-hat-display break-words">{mediaItem.Title}</h2>
<div className="space-y-6"> <div className="space-y-6">
<div className="space-y-2"> <div className="space-y-2">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">Details</h3> <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">Details</h3>
<div className="bg-[#222] rounded p-3 space-y-2 text-sm"> <div className="bg-[#222] rounded p-3 space-y-2 text-sm red-hat-mono">
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">Type</span> <span className="text-gray-500">Type</span>
<span className="text-white">{mediaItem.Type || 'Unknown'}</span> <span className="text-white">{mediaItem.Type || 'Unknown'}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">Size</span> <span className="text-gray-500">Size</span>
{/* Placeholder for size formatting if not available */} {/* Placeholder for size formatting if not available */}
<span className="text-white">{mediaItem.Metadata?.fileSize ? (mediaItem.Metadata.fileSize / 1024 / 1024).toFixed(2) + ' MB' : 'N/A'}</span> <span className="text-white">{mediaItem.Metadata?.fileSize ? (mediaItem.Metadata.fileSize / 1024 / 1024).toFixed(2) + ' MB' : 'N/A'}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">Uploaded</span> <span className="text-gray-500">Uploaded</span>
<span className="text-white">{mediaItem.CreatedAt ? new Date(mediaItem.CreatedAt).toLocaleDateString() : '-'}</span> <span className="text-white">{mediaItem.CreatedAt ? new Date(mediaItem.CreatedAt).toLocaleDateString() : '-'}</span>
</div> </div>
</div> </div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2 red-hat-mono">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">EXIF Data</h3> <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">EXIF Data</h3>
<p className="text-xs text-gray-500 italic">Metadata editing not yet implemented.</p> <p className="text-xs text-gray-500 italic">Metadata editing not yet implemented.</p>
{/* Placeholder for EXIF data */} {/* Placeholder for EXIF data */}
<div className="bg-[#222] rounded p-3 space-y-2 text-sm opacity-50"> <div className="bg-[#222] rounded p-3 space-y-2 text-sm opacity-50">
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">Camera</span> <span className="text-gray-500">Camera</span>
<span className="text-white">-</span> <span className="text-white">-</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">ISO</span> <span className="text-gray-500">ISO</span>
<span className="text-white">-</span> <span className="text-white">-</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-gray-500">Aperture</span> <span className="text-gray-500">Aperture</span>
<span className="text-white">-</span> <span className="text-white">-</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
) )
} }
+90 -84
View File
@@ -1,84 +1,90 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useParams, useLocation, useNavigate } from 'react-router-dom' import { useParams, useLocation, useNavigate } from 'react-router-dom'
import ImageViewer from './components/ImageViewer' import ImageViewer from './components/ImageViewer'
import MetadataPanel from './components/MetadataPanel' import MetadataPanel from './components/MetadataPanel'
import { useAccount } from '../contexts/useAccount' import { useAccount } from '../contexts/useAccount'
import { getServerUrl } from '../hooks/getConstants' import { getServerUrl } from '../hooks/getConstants'
import { useNotifier } from '../contexts/useNotifier' import { useNotifier } from '../contexts/useNotifier'
import { ArrowLeft } from 'lucide-react' import { ArrowLeft, PanelRightClose, PanelRightOpen } from 'lucide-react'
export default function Viewer() { export default function Viewer() {
const { albumId, mediaId } = useParams() const { albumId, mediaId } = useParams()
const location = useLocation() const location = useLocation()
const navigate = useNavigate() const navigate = useNavigate()
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const { showError } = useNotifier() const { showError } = useNotifier()
const [mediaItem, setMediaItem] = useState(location.state?.mediaItem || null) const [mediaItem, setMediaItem] = useState(location.state?.mediaItem || null)
const [metadataPanelOpen, setMetadataPanelOpen] = useState(false)
useEffect(() => {
if (mediaItem) return useEffect(() => {
if (mediaItem) return
const fetchMediaDetails = async () => {
try { const fetchMediaDetails = async () => {
// Use '' if albumId is 'root' try {
const targetAlbumId = albumId === 'root' ? '' : albumId // Use '' if albumId is 'root'
const targetAlbumId = albumId === 'root' ? '' : albumId
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${targetAlbumId}`, {
headers: { const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${targetAlbumId}`, {
'Authorization': getAccessToken() headers: {
} 'Authorization': getAccessToken()
}) }
})
const data = await response.json()
const data = await response.json()
if (data.error) {
showError(data.error) if (data.error) {
} else { showError("Error getting media details: " + data.error)
const found = data.media.find(m => m.ID === mediaId) } else {
if (found) { const found = data.media.find(m => m.ID === mediaId)
setMediaItem(found) if (found) {
} else { setMediaItem(found)
showError("Media not found") } else {
} showError("Media not found in album")
} }
} catch (err) { }
showError("Failed to fetch media details") } catch (err) {
} showError("Failed to fetch media details: " + err.message)
} }
}
fetchMediaDetails()
}, [albumId, mediaId, getAccessToken, showError, mediaItem]) fetchMediaDetails()
}, [albumId, mediaId, getAccessToken, showError, mediaItem])
const handleBack = () => {
if (window.history.state && window.history.state.idx > 0) { const handleBack = () => {
navigate(-1) if (window.history.state && window.history.state.idx > 0) {
} else { navigate(-1)
// Fallback if opened directly } else {
navigate('/gallery') // Fallback if opened directly
} navigate('/gallery')
} }
}
return (
<div className="flex flex-col h-screen w-full bg-[#141414]"> return (
<div className="flex items-center h-14 px-4 border-b border-[#2B2B2B] bg-[#141414] flex-shrink-0 gap-4"> <div className="flex flex-col h-dvh w-full bg-[#141414]">
<button onClick={handleBack} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer"> <div className="flex items-center h-14 px-4 border-b border-[#2B2B2B] bg-[#141414] flex-shrink-0 gap-4 justify-between">
<ArrowLeft size={20} /> <div className="flex items-center gap-2">
</button> <button onClick={handleBack} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
<span className="text-white font-medium truncate red-hat-mono"> <ArrowLeft size={20} />
{mediaItem ? mediaItem.Title : 'Loading...'} </button>
</span> <span className="text-white font-medium truncate red-hat-text">
</div> {mediaItem ? mediaItem.Title : 'Loading...'}
</span>
<div className="flex flex-1 overflow-hidden"> </div>
<ImageViewer <button onClick={() => setMetadataPanelOpen(!metadataPanelOpen)} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
albumId={albumId === 'root' ? '' : albumId} {metadataPanelOpen ? <PanelRightClose size={20} /> : <PanelRightOpen size={20} />}
mediaId={mediaId} </button>
token={getAccessToken()} </div>
title={mediaItem?.Title || ''}
/> <div className="flex flex-col md:flex-row flex-1 overflow-hidden">
<MetadataPanel mediaItem={mediaItem} /> <ImageViewer
</div> albumId={albumId === 'root' ? '' : albumId}
</div> mediaId={mediaId}
) token={getAccessToken()}
} title={mediaItem?.Title || ''}
/>
<MetadataPanel mediaItem={mediaItem} open={metadataPanelOpen} />
</div>
</div>
)
}