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/media
backend/raster.db
backend/media
backend/cache
+202 -202
View File
@@ -1,202 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"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
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
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
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
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 stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 wisplite
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"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
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
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
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
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 stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 wisplite
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1 -1
View File
@@ -18,7 +18,7 @@ func main() {
// Configure CORS middleware
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"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
+20 -20
View File
@@ -1,20 +1,20 @@
package models
import (
"time"
"gorm.io/datatypes"
)
type Media struct {
ID string `gorm:"primaryKey"`
Title string `gorm:"not null"`
Description string `gorm:"not null"`
Tags datatypes.JSON `gorm:"type:json"`
AlbumID string `gorm:"not null"`
Path string `gorm:"not null"`
Type string `gorm:"not null"` // MIME type
Metadata datatypes.JSON `gorm:"type:json"` // Metadata about the media.
CreatedAt time.Time
UpdatedAt time.Time
}
package models
import (
"time"
"gorm.io/datatypes"
)
type Media struct {
ID string `gorm:"primaryKey"`
Title string `gorm:"not null"`
Description string `gorm:"not null"`
Tags datatypes.JSON `gorm:"type:json"`
AlbumID string `gorm:"not null"`
Path string `gorm:"not null"`
Type string `gorm:"not null"` // MIME type
Metadata datatypes.JSON `gorm:"type:json"` // Metadata about the media.
CreatedAt time.Time
UpdatedAt time.Time
}
+156 -156
View File
@@ -1,156 +1,156 @@
package routes
import (
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
"github.com/wisplite/raster/internal/services"
)
func RegisterMediaRoutes(rg *gin.RouterGroup) {
media := rg.Group("/media")
media.POST("/uploadMedia", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
accessToken := c.GetHeader("Authorization")
albumID := c.PostForm("albumId")
media, err := services.UploadMedia(file, albumID, accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if err := os.MkdirAll(filepath.Dir(media.Path), 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create directory"})
return
}
if err := c.SaveUploadedFile(file, media.Path); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
})
media.GET("/getAllMediaInAlbum", func(c *gin.Context) {
accessToken := c.GetHeader("Authorization")
albumID := c.Query("albumId")
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if isPublic {
media, err := services.GetAllMediaInPublicAlbum(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
return
} else {
media, err := services.GetAllMediaInAlbum(albumID, accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
}
})
media.GET("/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId")
mediaID := c.Param("mediaId")
if albumID == "root" {
albumID = ""
}
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if isPublic {
mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(mediaData.Path)
return
}
accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if accessLevel < 0 {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return
}
mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(mediaData.Path)
})
media.GET("/thumb/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId")
mediaID := c.Param("mediaId")
widthStr := c.Query("width")
heightStr := c.Query("height")
width, _ := strconv.Atoi(widthStr)
height, _ := strconv.Atoi(heightStr)
if albumID == "root" {
albumID = ""
}
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
allowed := false
if isPublic {
allowed = true
} else {
accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if accessLevel >= 0 {
allowed = true
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return
}
}
if allowed {
thumbPath, err := services.GetThumbnail(albumID, mediaID, width, height)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(thumbPath)
}
})
}
package routes
import (
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
"github.com/wisplite/raster/internal/services"
)
func RegisterMediaRoutes(rg *gin.RouterGroup) {
media := rg.Group("/media")
media.POST("/uploadMedia", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
accessToken := c.GetHeader("Authorization")
albumID := c.PostForm("albumId")
media, err := services.UploadMedia(file, albumID, accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if err := os.MkdirAll(filepath.Dir(media.Path), 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create directory"})
return
}
if err := c.SaveUploadedFile(file, media.Path); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
})
media.GET("/getAllMediaInAlbum", func(c *gin.Context) {
accessToken := c.GetHeader("Authorization")
albumID := c.Query("albumId")
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if isPublic {
media, err := services.GetAllMediaInPublicAlbum(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
return
} else {
media, err := services.GetAllMediaInAlbum(albumID, accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"media": media})
}
})
media.GET("/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId")
mediaID := c.Param("mediaId")
if albumID == "root" {
albumID = ""
}
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if isPublic {
mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(mediaData.Path)
return
}
accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if accessLevel < 0 {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return
}
mediaData, err := services.GetMedia(albumID, mediaID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(mediaData.Path)
})
media.GET("/thumb/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId")
mediaID := c.Param("mediaId")
widthStr := c.Query("width")
heightStr := c.Query("height")
width, _ := strconv.Atoi(widthStr)
height, _ := strconv.Atoi(heightStr)
if albumID == "root" {
albumID = ""
}
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
allowed := false
if isPublic {
allowed = true
} else {
accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if accessLevel >= 0 {
allowed = true
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return
}
}
if allowed {
thumbPath, err := services.GetThumbnail(albumID, mediaID, width, height)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(thumbPath)
}
})
}
+196 -196
View File
@@ -1,196 +1,196 @@
package services
import (
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"mime/multipart"
"os"
"path/filepath"
"github.com/disintegration/imaging"
"github.com/google/uuid"
"github.com/rwcarlsen/goexif/exif"
"github.com/wisplite/raster/internal/db"
"github.com/wisplite/raster/internal/models"
"gorm.io/datatypes"
)
func UploadMedia(file *multipart.FileHeader, albumID string, accessToken string) (models.Media, error) {
userID, err := ValidateAccessToken(accessToken)
if err != nil {
return models.Media{}, err
}
accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil {
return models.Media{}, err
}
if accessLevel < 1 {
return models.Media{}, fmt.Errorf("user does not have permission to upload media to this album")
}
albumPath := albumID
if albumID == "" {
albumPath = "root"
}
// Extract metadata (dimensions and file info)
var meta datatypes.JSON
metadataMap := map[string]interface{}{
"originalFilename": file.Filename,
"fileSize": file.Size,
"contentType": file.Header.Get("Content-Type"),
}
src, err := file.Open()
if err == nil {
defer src.Close()
cfg, format, err := image.DecodeConfig(src)
if err == nil {
metadataMap["width"] = cfg.Width
metadataMap["height"] = cfg.Height
metadataMap["format"] = format
// Check for EXIF orientation
src.Seek(0, 0)
x, err := exif.Decode(src)
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
if val >= 5 && val <= 8 {
metadataMap["width"] = cfg.Height
metadataMap["height"] = cfg.Width
}
}
}
}
}
}
b, _ := json.Marshal(metadataMap)
meta = datatypes.JSON(b)
mediaID := uuid.New().String()
mediaPath := fmt.Sprintf("media/%s/%s.%s", albumPath, mediaID, file.Filename)
media := models.Media{
ID: mediaID,
AlbumID: albumID,
Path: mediaPath,
Type: file.Header.Get("Content-Type"),
Title: file.Filename,
Description: "",
Metadata: meta,
}
result := db.GetDB().Create(&media)
if result.Error != nil {
return models.Media{}, result.Error
}
return media, nil
}
func GetAllMediaInAlbum(albumID string, accessToken string) ([]models.Media, error) {
userID, err := ValidateAccessToken(accessToken)
if err != nil {
return []models.Media{}, err
}
accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil {
return []models.Media{}, err
}
if accessLevel < 0 {
return []models.Media{}, fmt.Errorf("user does not have permission to view media in this album")
}
media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil {
return []models.Media{}, result.Error
}
return media, nil
}
func GetAllMediaInPublicAlbum(albumID string) ([]models.Media, error) {
media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil {
return []models.Media{}, result.Error
}
return media, nil
}
func GetMedia(albumID string, mediaID string) (models.Media, error) {
media := models.Media{}
result := db.GetDB().First(&media, "album_id = ? AND id = ?", albumID, mediaID)
if result.Error != nil {
return models.Media{}, result.Error
}
return media, nil
}
func GetThumbnail(albumID string, mediaID string, width int, height int) (string, error) {
media, err := GetMedia(albumID, mediaID)
if err != nil {
return "", err
}
if width == 0 {
width = 200
}
if height == 0 {
height = 200
}
cacheDir := "cache/thumbnails"
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return "", err
}
ext := filepath.Ext(media.Path)
if ext == "" {
ext = ".jpg"
}
thumbName := fmt.Sprintf("%s_%dx%d%s", mediaID, width, height, ext)
thumbPath := filepath.Join(cacheDir, thumbName)
if _, err := os.Stat(thumbPath); err == nil {
return thumbPath, nil
}
srcImage, err := imaging.Open(media.Path)
if err != nil {
return "", err
}
f, err := os.Open(media.Path)
if err == nil {
x, err := exif.Decode(f)
f.Close()
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
switch val {
case 3:
srcImage = imaging.Rotate180(srcImage)
case 6:
srcImage = imaging.Rotate270(srcImage)
case 8:
srcImage = imaging.Rotate90(srcImage)
}
}
}
}
}
dstImage := imaging.Fit(srcImage, width, height, imaging.Lanczos)
err = imaging.Save(dstImage, thumbPath)
if err != nil {
return "", err
}
return thumbPath, nil
}
package services
import (
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"mime/multipart"
"os"
"path/filepath"
"github.com/disintegration/imaging"
"github.com/google/uuid"
"github.com/rwcarlsen/goexif/exif"
"github.com/wisplite/raster/internal/db"
"github.com/wisplite/raster/internal/models"
"gorm.io/datatypes"
)
func UploadMedia(file *multipart.FileHeader, albumID string, accessToken string) (models.Media, error) {
userID, err := ValidateAccessToken(accessToken)
if err != nil {
return models.Media{}, err
}
accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil {
return models.Media{}, err
}
if accessLevel < 1 {
return models.Media{}, fmt.Errorf("user does not have permission to upload media to this album")
}
albumPath := albumID
if albumID == "" {
albumPath = "root"
}
// Extract metadata (dimensions and file info)
var meta datatypes.JSON
metadataMap := map[string]interface{}{
"originalFilename": file.Filename,
"fileSize": file.Size,
"contentType": file.Header.Get("Content-Type"),
}
src, err := file.Open()
if err == nil {
defer src.Close()
cfg, format, err := image.DecodeConfig(src)
if err == nil {
metadataMap["width"] = cfg.Width
metadataMap["height"] = cfg.Height
metadataMap["format"] = format
// Check for EXIF orientation
src.Seek(0, 0)
x, err := exif.Decode(src)
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
if val >= 5 && val <= 8 {
metadataMap["width"] = cfg.Height
metadataMap["height"] = cfg.Width
}
}
}
}
}
}
b, _ := json.Marshal(metadataMap)
meta = datatypes.JSON(b)
mediaID := uuid.New().String()
mediaPath := fmt.Sprintf("media/%s/%s.%s", albumPath, mediaID, file.Filename)
media := models.Media{
ID: mediaID,
AlbumID: albumID,
Path: mediaPath,
Type: file.Header.Get("Content-Type"),
Title: file.Filename,
Description: "",
Metadata: meta,
}
result := db.GetDB().Create(&media)
if result.Error != nil {
return models.Media{}, result.Error
}
return media, nil
}
func GetAllMediaInAlbum(albumID string, accessToken string) ([]models.Media, error) {
userID, err := ValidateAccessToken(accessToken)
if err != nil {
return []models.Media{}, err
}
accessLevel, err := CheckUserAlbumAccess(userID, albumID)
if err != nil {
return []models.Media{}, err
}
if accessLevel < 0 {
return []models.Media{}, fmt.Errorf("user does not have permission to view media in this album")
}
media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil {
return []models.Media{}, result.Error
}
return media, nil
}
func GetAllMediaInPublicAlbum(albumID string) ([]models.Media, error) {
media := []models.Media{}
result := db.GetDB().Where("album_id = ?", albumID).Find(&media)
if result.Error != nil {
return []models.Media{}, result.Error
}
return media, nil
}
func GetMedia(albumID string, mediaID string) (models.Media, error) {
media := models.Media{}
result := db.GetDB().First(&media, "album_id = ? AND id = ?", albumID, mediaID)
if result.Error != nil {
return models.Media{}, result.Error
}
return media, nil
}
func GetThumbnail(albumID string, mediaID string, width int, height int) (string, error) {
media, err := GetMedia(albumID, mediaID)
if err != nil {
return "", err
}
if width == 0 {
width = 200
}
if height == 0 {
height = 200
}
cacheDir := "cache/thumbnails"
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return "", err
}
ext := filepath.Ext(media.Path)
if ext == "" {
ext = ".jpg"
}
thumbName := fmt.Sprintf("%s_%dx%d%s", mediaID, width, height, ext)
thumbPath := filepath.Join(cacheDir, thumbName)
if _, err := os.Stat(thumbPath); err == nil {
return thumbPath, nil
}
srcImage, err := imaging.Open(media.Path)
if err != nil {
return "", err
}
f, err := os.Open(media.Path)
if err == nil {
x, err := exif.Decode(f)
f.Close()
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
switch val {
case 3:
srcImage = imaging.Rotate180(srcImage)
case 6:
srcImage = imaging.Rotate270(srcImage)
case 8:
srcImage = imaging.Rotate90(srcImage)
}
}
}
}
}
dstImage := imaging.Fit(srcImage, width, height, imaging.Lanczos)
err = imaging.Save(dstImage, thumbPath)
if err != nil {
return "", err
}
return thumbPath, nil
}
+20 -20
View File
@@ -1,21 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<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.gstatic.com" crossorigin>
<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"
rel="stylesheet">
<title>Raster</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<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.gstatic.com" crossorigin>
<link
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">
<title>Raster</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</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",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.15",
"@tailwindcss/vite": "^4.1.12",
"lucide-react": "^0.554.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.6",
"react-spinners": "^0.17.0",
"tailwindcss": "^4.1.12"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",
"eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"vite": "^7.1.2"
}
}
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-popover": "^1.1.15",
"@tailwindcss/vite": "^4.1.12",
"lucide-react": "^0.554.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.6",
"react-spinners": "^0.17.0",
"tailwindcss": "^4.1.12"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",
"eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"vite": "^7.1.2"
}
}
+54 -54
View File
@@ -1,54 +1,54 @@
import { Navigate, Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import Viewer from './viewer'
import Gallery from './gallery'
import Login from './account/login'
import { getServerUrl } from './hooks/getConstants'
import { useEffect } from 'react'
import CreateRootUser from './account/createRoot'
import { AccountProvider } from './contexts/useAccount'
import { NotifierProvider } from './contexts/useNotifier'
function RedirectHandler() {
return (
<div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]">
</div>
)
}
function App() {
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
const checkRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/rootUserExists`)
const data = await response.json()
if (data.exists) {
// Only navigate to gallery if we're on the root path
if (location.pathname === '/') {
navigate('/gallery')
}
} else {
// Always redirect to onboarding if root user doesn't exist
if (location.pathname !== '/onboarding/createRootUser') {
navigate('/onboarding/createRootUser')
}
}
}
checkRootUser()
}, [location.pathname, navigate])
return (
<NotifierProvider>
<AccountProvider>
<Routes>
<Route path="/" element={<RedirectHandler />} />
<Route path="/gallery/*" element={<Gallery />} />
<Route path="/viewer/:albumId/:mediaId" element={<Viewer />} />
<Route path="/login" element={<Login />} />
<Route path="/onboarding/createRootUser" element={<CreateRootUser />} />
</Routes>
</AccountProvider>
</NotifierProvider>
)
}
export default App
import { Navigate, Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import Viewer from './viewer'
import Gallery from './gallery'
import Login from './account/login'
import { getServerUrl } from './hooks/getConstants'
import { useEffect } from 'react'
import CreateRootUser from './account/createRoot'
import { AccountProvider } from './contexts/useAccount'
import { NotifierProvider } from './contexts/useNotifier'
function RedirectHandler() {
return (
<div className="flex flex-col items-center justify-center h-full w-full bg-[#141414]">
</div>
)
}
function App() {
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
const checkRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/rootUserExists`)
const data = await response.json()
if (data.exists) {
// Only navigate to gallery if we're on the root path
if (location.pathname === '/') {
navigate('/gallery')
}
} else {
// Always redirect to onboarding if root user doesn't exist
if (location.pathname !== '/onboarding/createRootUser') {
navigate('/onboarding/createRootUser')
}
}
}
checkRootUser()
}, [location.pathname, navigate])
return (
<NotifierProvider>
<AccountProvider>
<Routes>
<Route path="/" element={<RedirectHandler />} />
<Route path="/gallery/*" element={<Gallery />} />
<Route path="/viewer/:albumId/:mediaId" element={<Viewer />} />
<Route path="/login" element={<Login />} />
<Route path="/onboarding/createRootUser" element={<CreateRootUser />} />
</Routes>
</AccountProvider>
</NotifierProvider>
)
}
export default App
+83 -83
View File
@@ -1,84 +1,84 @@
import { useState } from 'react'
import { getServerUrl } from '../hooks/getConstants'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier'
export default function CreateRootUser() {
const navigate = useNavigate()
const { showError, showSuccess } = useNotifier()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const handleCreateRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
password: password,
}),
})
const data = await response.json()
if (data.error) {
showError(data.error)
} else {
const rootResponse = await fetch(`${getServerUrl()}/api/user/setRootUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
}),
})
const rootData = await rootResponse.json()
if (rootData.error) {
showError(rootData.error)
} else {
navigate('/gallery')
showSuccess('Root user created successfully')
}
}
}
return (
<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 gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2">
<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>
</div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
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"
/>
</div>
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="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"
/>
</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}>
Create
</button>
</div>
</div>
</div>
)
import { useState } from 'react'
import { getServerUrl } from '../hooks/getConstants'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier'
export default function CreateRootUser() {
const navigate = useNavigate()
const { showError, showSuccess } = useNotifier()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const handleCreateRootUser = async () => {
const response = await fetch(`${getServerUrl()}/api/user/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
password: password,
}),
})
const data = await response.json()
if (data.error) {
showError("Error creating root user: " + data.error)
} else {
const rootResponse = await fetch(`${getServerUrl()}/api/user/setRootUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
}),
})
const rootData = await rootResponse.json()
if (rootData.error) {
showError("Error setting root user: " + rootData.error)
} else {
navigate('/gallery')
showSuccess('Root user created successfully')
}
}
}
return (
<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 gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2">
<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>
</div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
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"
/>
</div>
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="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"
/>
</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}>
Create
</button>
</div>
</div>
</div>
)
}
+59 -59
View File
@@ -1,60 +1,60 @@
import { useState } from 'react'
import { useAccount } from '../contexts/useAccount'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier'
export default function Login() {
const { showError } = useNotifier()
const navigate = useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const { login } = useAccount()
const handleLogin = () => {
login(username, password)
.then(() => {
navigate('/gallery')
})
.catch((error) => {
showError(error.message)
})
}
return (
<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 gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2">
<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>
</div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
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"
/>
</div>
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="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"
/>
</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}>
Sign In
</button>
</div>
</div>
</div>
)
import { useState } from 'react'
import { useAccount } from '../contexts/useAccount'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../contexts/useNotifier'
export default function Login() {
const { showError } = useNotifier()
const navigate = useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const { login } = useAccount()
const handleLogin = () => {
login(username, password)
.then(() => {
navigate('/gallery')
})
.catch((error) => {
showError("Error logging in: " + error.message)
})
}
return (
<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 gap-8 border border-[#2B2B2B] rounded-lg p-8 bg-[#1a1a1a]">
<div className="flex flex-col gap-2">
<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>
</div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
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"
/>
</div>
<div className="flex flex-col gap-2">
<label className="text-sm text-gray-400 red-hat-mono">Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="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"
/>
</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}>
Sign In
</button>
</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">
<g clip-path="url(#clip0_2_3)">
<rect width="120" height="120" fill="#0D1B1E"/>
<rect y="60" width="60" height="60" fill="#EBF5EE"/>
<rect width="60" height="60" fill="#FF5376"/>
<rect x="60" y="60" width="60" height="60" fill="#9DACFF"/>
</g>
<defs>
<clipPath id="clip0_2_3">
<rect width="120" height="120" fill="white"/>
</clipPath>
</defs>
</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)">
<rect width="120" height="120" fill="#0D1B1E"/>
<rect y="60" width="60" height="60" fill="#EBF5EE"/>
<rect width="60" height="60" fill="#FF5376"/>
<rect x="60" y="60" width="60" height="60" fill="#9DACFF"/>
</g>
<defs>
<clipPath id="clip0_2_3">
<rect width="120" height="120" fill="white"/>
</clipPath>
</defs>
</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'
export default function AuthImage({ src, token, alt, className, onLoad, ...props }) {
const [imageSrc, setImageSrc] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
useEffect(() => {
let objectUrl = null
let active = true
const controller = new AbortController()
const fetchImage = async () => {
setLoading(true)
setError(false)
try {
const response = await fetch(src, {
headers: {
'Authorization': token
},
signal: controller.signal
})
if (!response.ok) {
throw new Error('Failed to load image')
}
const blob = await response.blob()
if (active) {
objectUrl = URL.createObjectURL(blob)
setImageSrc(objectUrl)
setLoading(false)
}
} catch (err) {
if (active) {
console.error("Error loading image:", err)
setError(true)
setLoading(false)
}
}
}
if (src && token) {
fetchImage()
} else {
setLoading(false)
}
return () => {
active = false
controller.abort()
if (objectUrl) {
URL.revokeObjectURL(objectUrl)
}
}
}, [src, token])
if (loading) {
return <div className={`bg-gray-800 animate-pulse ${className}`} />
}
if (error || !imageSrc) {
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} />
}
import { useState, useEffect } from 'react'
export default function AuthImage({ src, token, alt, className, onLoad, ...props }) {
const [imageSrc, setImageSrc] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
useEffect(() => {
let objectUrl = null
let active = true
const controller = new AbortController()
const fetchImage = async () => {
setLoading(true)
setError(false)
try {
const response = await fetch(src, {
headers: {
'Authorization': token
},
signal: controller.signal
})
if (!response.ok) {
throw new Error('Failed to load image')
}
const blob = await response.blob()
if (active) {
objectUrl = URL.createObjectURL(blob)
setImageSrc(objectUrl)
setLoading(false)
}
} catch (err) {
if (active) {
console.error("Error loading image:", err)
setError(true)
setLoading(false)
}
}
}
if (src && token) {
fetchImage()
} else {
setLoading(false)
}
return () => {
active = false
controller.abort()
if (objectUrl) {
URL.revokeObjectURL(objectUrl)
}
}
}, [src, token])
if (loading) {
return <div className={`bg-gray-800 animate-pulse ${className}`} />
}
if (error || !imageSrc) {
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} />
}
+46 -46
View File
@@ -1,46 +1,46 @@
import * as Dialog from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
export default function Modal({ open, onOpenChange, trigger, title, children, isProtected = false }) {
return (
<Dialog.Root open={open} onOpenChange={onOpenChange}>
{trigger && <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>}
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/60 z-50" />
<Dialog.Content
onInteractOutside={(e) => {
if (isProtected) e.preventDefault();
}}
onEscapeKeyDown={(e) => {
if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) {
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">
<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">
{title}
</Dialog.Title>
<Dialog.Close
onClick={(e) => {
if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) {
e.preventDefault();
}
}
}}
className="text-gray-400 hover:text-white transition-colors cursor-pointer outline-none">
<X className="w-4 h-4" />
</Dialog.Close>
</div>
<div className="p-4 text-gray-300 red-hat-text">
{children}
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}
import * as Dialog from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
export default function Modal({ open, onOpenChange, trigger, title, children, isProtected = false }) {
return (
<Dialog.Root open={open} onOpenChange={onOpenChange}>
{trigger && <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>}
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/60 z-50" />
<Dialog.Content
onInteractOutside={(e) => {
if (isProtected) e.preventDefault();
}}
onEscapeKeyDown={(e) => {
if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) {
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">
<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">
{title}
</Dialog.Title>
<Dialog.Close
onClick={(e) => {
if (isProtected) {
if (!window.confirm("Are you sure you want to close this?")) {
e.preventDefault();
}
}
}}
className="text-gray-400 hover:text-white transition-colors cursor-pointer outline-none">
<X className="w-4 h-4" />
</Dialog.Close>
</div>
<div className="p-4 text-gray-300 red-hat-text">
{children}
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}
+66 -66
View File
@@ -1,67 +1,67 @@
import { Link } from 'react-router-dom'
import { ChevronDown, LogIn, LogOut, UserIcon, Settings } from 'lucide-react'
import * as Popover from '@radix-ui/react-popover'
import { useState } from 'react';
import { useAccount } from '../contexts/useAccount';
export default function NavBar({ path }) {
const [open, setOpen] = useState(false);
const { user, logout } = useAccount();
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-start gap-2">
{path.map((item, index) => (
<div className="flex flex-row items-center justify-start gap-2 red-hat-mono">
<Link to={`/${path.slice(0, index + 1).join('/')}`} key={item} className={`text-white ${index === path.length - 1 ? 'font-bold' : ''}`}>
{decodeURIComponent(item)}
</Link>
{index !== path.length - 1 && <p className="text-white red-hat-mono">/</p>}
</div>
))}
</div>
<div className="flex flex-row items-center justify-start gap-2">
<Popover.Root open={open} onOpenChange={setOpen}>
<Popover.Trigger className="flex flex-row items-center justify-start gap-0 cursor-pointer">
<UserIcon className="w-6 h-6 text-white cursor-pointer" />
{/* <ChevronDown className={`w-4 h-4 text-white ${open ? 'rotate-180' : ''}`} /> */}
</Popover.Trigger>
<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="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-sm text-white font-bold truncate red-hat-text">{user?.Username || 'Guest'}</p>
</div>
<div className="p-1.5 flex flex-col gap-0.5">
{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">
<Settings className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" />
<span className="font-medium red-hat-text">Settings</span>
</button>
<button
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"
>
<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>
</button>
</>
) : (
<Link
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"
>
<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>
</Link>
)}
</div>
</div>
</Popover.Content>
</Popover.Root>
</div>
</div>
)
import { Link } from 'react-router-dom'
import { ChevronDown, LogIn, LogOut, UserIcon, Settings } from 'lucide-react'
import * as Popover from '@radix-ui/react-popover'
import { useState } from 'react';
import { useAccount } from '../contexts/useAccount';
export default function NavBar({ path }) {
const [open, setOpen] = useState(false);
const { user, logout } = useAccount();
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-start gap-2">
{path.map((item, index) => (
<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' : ''}`}>
{decodeURIComponent(item)}
</Link>
{index !== path.length - 1 && <p className="text-white text-xl red-hat-display">/</p>}
</div>
))}
</div>
<div className="flex flex-row items-center justify-start gap-2">
<Popover.Root open={open} onOpenChange={setOpen}>
<Popover.Trigger className="flex flex-row items-center justify-start gap-0 cursor-pointer">
<UserIcon className="w-6 h-6 text-white cursor-pointer" />
{/* <ChevronDown className={`w-4 h-4 text-white ${open ? 'rotate-180' : ''}`} /> */}
</Popover.Trigger>
<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="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-sm text-white font-bold truncate red-hat-text">{user?.Username || 'Guest'}</p>
</div>
<div className="p-1.5 flex flex-col gap-0.5">
{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">
<Settings className="w-4 h-4 text-gray-400 group-hover:text-white transition-colors" />
<span className="font-medium red-hat-text">Settings</span>
</button>
<button
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"
>
<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>
</button>
</>
) : (
<Link
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"
>
<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>
</Link>
)}
</div>
</div>
</Popover.Content>
</Popover.Root>
</div>
</div>
)
}
+77 -77
View File
@@ -1,78 +1,78 @@
import { createContext, useContext, useState } from 'react'
import { getServerUrl } from '../hooks/getConstants'
const AccountContext = createContext()
export const AccountProvider = ({ children }) => {
const [accessToken, setAccessToken] = useState(null)
const [user, setUser] = useState(null)
const login = async (username, password) => {
const response = await fetch(`${getServerUrl()}/api/user/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
const data = await response.json()
if (data.error) {
throw new Error(data.error)
} else {
setAccessToken(data.accessToken)
localStorage.setItem('accessToken', data.accessToken)
fetchUserData(data.accessToken)
return true
}
}
const fetchUserData = async (accessToken) => {
if (!accessToken) {
accessToken = getAccessToken()
if (!accessToken) {
setUser(null)
return false
}
}
const response = await fetch(`${getServerUrl()}/api/user/getUserData`, {
headers: {
'Authorization': accessToken,
},
})
const data = await response.json()
console.log(data)
if (data.error) {
throw new Error(data.error)
} else {
setUser(data.userData)
return true
}
}
const logout = () => {
setAccessToken(null)
localStorage.removeItem('accessToken')
location.reload()
}
const getAccessToken = () => {
if (!accessToken && localStorage.getItem('accessToken')) {
setAccessToken(localStorage.getItem('accessToken'))
return localStorage.getItem('accessToken')
} else if (accessToken) {
return accessToken
} else {
return "guest"
}
}
return <AccountContext.Provider value={{ getAccessToken, logout, login, fetchUserData, user }}>{children}</AccountContext.Provider>
}
export const useAccount = () => {
const context = useContext(AccountContext)
if (!context) {
throw new Error('useAccount must be used within an AccountProvider')
}
return context
import { createContext, useContext, useState } from 'react'
import { getServerUrl } from '../hooks/getConstants'
const AccountContext = createContext()
export const AccountProvider = ({ children }) => {
const [accessToken, setAccessToken] = useState(null)
const [user, setUser] = useState(null)
const login = async (username, password) => {
const response = await fetch(`${getServerUrl()}/api/user/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
const data = await response.json()
if (data.error) {
throw new Error(data.error)
} else {
setAccessToken(data.accessToken)
localStorage.setItem('accessToken', data.accessToken)
fetchUserData(data.accessToken)
return true
}
}
const fetchUserData = async (accessToken) => {
if (!accessToken) {
accessToken = getAccessToken()
if (!accessToken) {
setUser(null)
return false
}
}
const response = await fetch(`${getServerUrl()}/api/user/getUserData`, {
headers: {
'Authorization': accessToken,
},
})
const data = await response.json()
console.log(data)
if (data.error) {
throw new Error(data.error)
} else {
setUser(data.userData)
return true
}
}
const logout = () => {
setAccessToken(null)
localStorage.removeItem('accessToken')
location.reload()
}
const getAccessToken = () => {
if (!accessToken && localStorage.getItem('accessToken')) {
setAccessToken(localStorage.getItem('accessToken'))
return localStorage.getItem('accessToken')
} else if (accessToken) {
return accessToken
} else {
return "guest"
}
}
return <AccountContext.Provider value={{ getAccessToken, logout, login, fetchUserData, user }}>{children}</AccountContext.Provider>
}
export const useAccount = () => {
const context = useContext(AccountContext)
if (!context) {
throw new Error('useAccount must be used within an AccountProvider')
}
return context
}
+125 -125
View File
@@ -1,125 +1,125 @@
import { createContext, useContext, useState, useCallback, useEffect } from 'react'
import { X, AlertCircle, CheckCircle, Info } from 'lucide-react'
const NotifierContext = createContext()
export const useNotifier = () => {
const context = useContext(NotifierContext)
if (!context) {
throw new Error('useNotifier must be used within a NotifierProvider')
}
return context
}
export const NotifierProvider = ({ children }) => {
const [notifications, setNotifications] = useState([])
const removeNotification = useCallback((id) => {
setNotifications((prev) => prev.filter((n) => n.id !== id))
}, [])
const addNotification = useCallback((message, type = 'info', duration = 5000) => {
const id = Date.now() + Math.random()
setNotifications((prev) => [...prev, { id, message, type, duration }])
}, [])
const showError = useCallback((message, duration = 5000) => {
addNotification(message, 'error', duration)
}, [addNotification])
const showSuccess = useCallback((message, duration = 3000) => {
addNotification(message, 'success', duration)
}, [addNotification])
const showInfo = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration)
}, [addNotification])
const showUpdate = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration)
}, [addNotification])
return (
<NotifierContext.Provider value={{ showError, showSuccess, showInfo, showUpdate }}>
{children}
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none">
{notifications.map((notification) => (
<NotificationItem
key={notification.id}
notification={notification}
onClose={() => removeNotification(notification.id)}
/>
))}
</div>
</NotifierContext.Provider>
)
}
const NotificationItem = ({ notification, onClose }) => {
const { message, type, duration } = notification
const [isExiting, setIsExiting] = useState(false)
useEffect(() => {
if (duration > 0) {
const timer = setTimeout(() => {
setIsExiting(true)
}, duration)
return () => clearTimeout(timer)
}
}, [duration])
useEffect(() => {
if (isExiting) {
const timer = setTimeout(() => {
onClose()
}, 300) // Match animation duration
return () => clearTimeout(timer)
}
}, [isExiting, onClose])
const getIcon = () => {
switch (type) {
case 'error':
return <AlertCircle className="w-5 h-5 text-red-500" />
case 'success':
return <CheckCircle className="w-5 h-5 text-green-500" />
default:
return <Info className="w-5 h-5 text-blue-500" />
}
}
const getBorderColor = () => {
switch (type) {
case 'error':
return 'border-red-500/50'
case 'success':
return 'border-green-500/50'
default:
return 'border-[#2B2B2B]'
}
}
return (
<div
className={`
pointer-events-auto
flex items-center gap-3
bg-[#141414] border ${getBorderColor()}
px-4 py-3 rounded-md shadow-lg
min-w-[300px] max-w-[400px]
transition-all duration-300 ease-in-out
${isExiting ? 'opacity-0 translate-x-full' : 'opacity-100 translate-x-0'}
`}
>
{getIcon()}
<p className="text-white red-hat-text text-sm flex-1">{message}</p>
<button
onClick={() => setIsExiting(true)}
className="text-gray-400 hover:text-white transition-colors"
>
<X className="w-4 h-4" />
</button>
</div>
)
}
import { createContext, useContext, useState, useCallback, useEffect } from 'react'
import { X, AlertCircle, CheckCircle, Info } from 'lucide-react'
const NotifierContext = createContext()
export const useNotifier = () => {
const context = useContext(NotifierContext)
if (!context) {
throw new Error('useNotifier must be used within a NotifierProvider')
}
return context
}
export const NotifierProvider = ({ children }) => {
const [notifications, setNotifications] = useState([])
const removeNotification = useCallback((id) => {
setNotifications((prev) => prev.filter((n) => n.id !== id))
}, [])
const addNotification = useCallback((message, type = 'info', duration = 5000) => {
const id = Date.now() + Math.random()
setNotifications((prev) => [...prev, { id, message, type, duration }])
}, [])
const showError = useCallback((message, duration = 5000) => {
addNotification(message, 'error', duration)
}, [addNotification])
const showSuccess = useCallback((message, duration = 3000) => {
addNotification(message, 'success', duration)
}, [addNotification])
const showInfo = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration)
}, [addNotification])
const showUpdate = useCallback((message, duration = 3000) => {
addNotification(message, 'info', duration)
}, [addNotification])
return (
<NotifierContext.Provider value={{ showError, showSuccess, showInfo, showUpdate }}>
{children}
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 pointer-events-none">
{notifications.map((notification) => (
<NotificationItem
key={notification.id}
notification={notification}
onClose={() => removeNotification(notification.id)}
/>
))}
</div>
</NotifierContext.Provider>
)
}
const NotificationItem = ({ notification, onClose }) => {
const { message, type, duration } = notification
const [isExiting, setIsExiting] = useState(false)
useEffect(() => {
if (duration > 0) {
const timer = setTimeout(() => {
setIsExiting(true)
}, duration)
return () => clearTimeout(timer)
}
}, [duration])
useEffect(() => {
if (isExiting) {
const timer = setTimeout(() => {
onClose()
}, 300) // Match animation duration
return () => clearTimeout(timer)
}
}, [isExiting, onClose])
const getIcon = () => {
switch (type) {
case 'error':
return <AlertCircle className="w-5 h-5 text-red-500" />
case 'success':
return <CheckCircle className="w-5 h-5 text-green-500" />
default:
return <Info className="w-5 h-5 text-blue-500" />
}
}
const getBorderColor = () => {
switch (type) {
case 'error':
return 'border-red-500/50'
case 'success':
return 'border-green-500/50'
default:
return 'border-[#2B2B2B]'
}
}
return (
<div
className={`
pointer-events-auto
flex items-center gap-3
bg-[#141414] border ${getBorderColor()}
px-4 py-3 rounded-md shadow-lg
min-w-[300px] max-w-[400px]
transition-all duration-300 ease-in-out
${isExiting ? 'opacity-0 translate-x-full' : 'opacity-100 translate-x-0'}
`}
>
{getIcon()}
<p className="text-white red-hat-text text-sm flex-1">{message}</p>
<button
onClick={() => setIsExiting(true)}
className="text-gray-400 hover:text-white transition-colors"
>
<X className="w-4 h-4" />
</button>
</div>
)
}
@@ -1,40 +1,40 @@
import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useState } from 'react'
import { useNotifier } from '../../contexts/useNotifier'
export default function AlbumCreateModal({ open, onOpenChange, trigger, parentId }) {
const { getAccessToken } = useAccount()
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const { showError } = useNotifier()
const handleCreateAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/createAlbum`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: title,
description: description,
parentId: parentId
})
})
const data = await response.json()
if (data.error) {
showError(data.error)
} else {
onOpenChange(false)
}
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Create Album">
<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)} />
<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>
</div>
</Modal>
)
import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useState } from 'react'
import { useNotifier } from '../../contexts/useNotifier'
export default function AlbumCreateModal({ open, onOpenChange, trigger, parentId }) {
const { getAccessToken } = useAccount()
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const { showError } = useNotifier()
const handleCreateAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/createAlbum`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: title,
description: description,
parentId: parentId
})
})
const data = await response.json()
if (data.error) {
showError("Error creating album: " + data.error)
} else {
onOpenChange(false)
}
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Create Album">
<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)} />
<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>
</div>
</Modal>
)
}
@@ -1,59 +1,59 @@
import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useState, useEffect } from 'react'
import { useNotifier } from '../../contexts/useNotifier'
import FilePicker from './FilePicker'
export default function AlbumEditModal({ open, onOpenChange, trigger, id, startTitle, startDescription, currentAlbum }) {
const { getAccessToken } = useAccount()
const [title, setTitle] = useState(startTitle || '')
const [description, setDescription] = useState(startDescription || '')
const [thumbnail, setThumbnail] = useState(null)
const { showError } = useNotifier()
const handleEditAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/editAlbum`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: id,
properties: {
title: title,
description: description,
thumbnail: thumbnail,
}
})
})
const data = await response.json()
if (data.error) {
showError(data.error)
} else {
onOpenChange(false)
}
}
useEffect(() => {
if (open) {
setTitle(startTitle || '')
setDescription(startDescription || '')
}
}, [open])
const handleFileSelect = (file) => {
console.log(file)
setThumbnail(file.selectedAlbum.ID + '/' + file.selectedFile.ID)
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Edit Album">
<div className="flex flex-col gap-2">
<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)} />
<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)} />
<p className="text-white red-hat-mono">Thumbnail</p>
<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>
</div>
</Modal>
)
import Modal from '../../components/Modal'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useState, useEffect } from 'react'
import { useNotifier } from '../../contexts/useNotifier'
import FilePicker from './FilePicker'
export default function AlbumEditModal({ open, onOpenChange, trigger, id, startTitle, startDescription, currentAlbum }) {
const { getAccessToken } = useAccount()
const [title, setTitle] = useState(startTitle || '')
const [description, setDescription] = useState(startDescription || '')
const [thumbnail, setThumbnail] = useState(null)
const { showError } = useNotifier()
const handleEditAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/editAlbum`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: id,
properties: {
title: title,
description: description,
thumbnail: thumbnail,
}
})
})
const data = await response.json()
if (data.error) {
showError("Error editing album: " + data.error)
} else {
onOpenChange(false)
}
}
useEffect(() => {
if (open) {
setTitle(startTitle || '')
setDescription(startDescription || '')
}
}, [open])
const handleFileSelect = (file) => {
console.log(file)
setThumbnail(file.selectedAlbum.ID + '/' + file.selectedFile.ID)
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} title="Edit Album">
<div className="flex flex-col gap-2">
<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)} />
<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)} />
<p className="text-white red-hat-mono">Thumbnail</p>
<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>
</div>
</Modal>
)
}
+99 -99
View File
@@ -1,100 +1,100 @@
import { PlusIcon, EllipsisVertical } from 'lucide-react'
import AlbumCreateModal from './AlbumCreateModal'
import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../../contexts/useNotifier'
import AlbumEditModal from './AlbumEditModal'
export default function AlbumList({ currentAlbumName }) {
const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false)
const [openEdit, setOpenEdit] = useState(false)
const [editingAlbum, setEditingAlbum] = useState(null)
const [albums, setAlbums] = useState([])
const navigate = useNavigate()
const { showError } = useNotifier()
useEffect(() => {
let ignore = false;
const getAlbums = async () => {
console.log('Getting albums in parent', currentAlbumName)
const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName;
try {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
},
body: JSON.stringify({
parentId: parentId,
}),
})
const data = await response.json()
if (!ignore) {
if (data.error) {
setAlbums([])
showError('Failed to get albums')
} else {
setAlbums(data)
}
}
} catch (error) {
if (!ignore) {
setAlbums([])
showError('Failed to get albums')
}
}
}
if (!open && !openEdit && currentAlbumName !== null) {
getAlbums()
}
return () => { ignore = true; }
}, [currentAlbumName, open, openEdit])
return (
<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">
<h1 className="text-xl font-bold text-white red-hat-mono">Albums</h1>
<PlusIcon className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} />
</div>
<div className="flex flex-row items-center justify-start gap-2 w-full px-6 flex-wrap">
{albums.map((album) => (
<div
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"
onClick={() => {
// Get current path and append the album's title
const currentPath = window.location.pathname;
// Remove leading and trailing slashes, split to parts
const pathParts = currentPath.replace(/^\/|\/$/g, '').split('/');
// Only append if not already the last part (avoid duplicate navigation)
if (pathParts[pathParts.length - 1] !== album.Title) {
navigate(`${currentPath.replace(/\/$/, '')}/${encodeURIComponent(album.Title)}`);
} else {
navigate(currentPath); // Or optionally do nothing/navigate to self
}
}}
>
<p className="text-white red-hat-mono">{album.Title}</p>
<EllipsisVertical className="w-6 h-6 cursor-pointer" color="white" onClick={(e) => {
e.stopPropagation()
setEditingAlbum(album)
setOpenEdit(true)
}} />
</div>
))}
</div>
<AlbumCreateModal open={open} onOpenChange={setOpen} parentId={currentAlbumName === 'gallery' ? '' : currentAlbumName} />
{editingAlbum && (
<AlbumEditModal
open={openEdit}
onOpenChange={setOpenEdit}
id={editingAlbum.ID}
startTitle={editingAlbum.Title}
startDescription={editingAlbum.Description}
currentAlbum={editingAlbum}
/>
)}
</div>
)
import { PlusIcon, EllipsisVertical } from 'lucide-react'
import AlbumCreateModal from './AlbumCreateModal'
import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useNavigate } from 'react-router-dom'
import { useNotifier } from '../../contexts/useNotifier'
import AlbumEditModal from './AlbumEditModal'
export default function AlbumList({ currentAlbumName }) {
const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false)
const [openEdit, setOpenEdit] = useState(false)
const [editingAlbum, setEditingAlbum] = useState(null)
const [albums, setAlbums] = useState([])
const navigate = useNavigate()
const { showError } = useNotifier()
useEffect(() => {
let ignore = false;
const getAlbums = async () => {
console.log('Getting albums in parent', currentAlbumName)
const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName;
try {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
},
body: JSON.stringify({
parentId: parentId,
}),
})
const data = await response.json()
if (!ignore) {
if (data.error) {
setAlbums([])
showError('Failed to get albums')
} else {
setAlbums(data)
}
}
} catch (error) {
if (!ignore) {
setAlbums([])
showError('Failed to get albums')
}
}
}
if (!open && !openEdit && currentAlbumName !== null) {
getAlbums()
}
return () => { ignore = true; }
}, [currentAlbumName, open, openEdit])
return (
<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">
<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)} />
</div>
<div className="flex flex-row items-center justify-start gap-2 w-full px-6 flex-wrap">
{albums.map((album) => (
<div
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"
onClick={() => {
// Get current path and append the album's title
const currentPath = window.location.pathname;
// Remove leading and trailing slashes, split to parts
const pathParts = currentPath.replace(/^\/|\/$/g, '').split('/');
// Only append if not already the last part (avoid duplicate navigation)
if (pathParts[pathParts.length - 1] !== album.Title) {
navigate(`${currentPath.replace(/\/$/, '')}/${encodeURIComponent(album.Title)}`);
} else {
navigate(currentPath); // Or optionally do nothing/navigate to self
}
}}
>
<p className="text-white red-hat-text">{album.Title}</p>
<EllipsisVertical className="w-6 h-6 cursor-pointer" color="white" onClick={(e) => {
e.stopPropagation()
setEditingAlbum(album)
setOpenEdit(true)
}} />
</div>
))}
</div>
<AlbumCreateModal open={open} onOpenChange={setOpen} parentId={currentAlbumName === 'gallery' ? '' : currentAlbumName} />
{editingAlbum && (
<AlbumEditModal
open={openEdit}
onOpenChange={setOpenEdit}
id={editingAlbum.ID}
startTitle={editingAlbum.Title}
startDescription={editingAlbum.Description}
currentAlbum={editingAlbum}
/>
)}
</div>
)
}
@@ -14,7 +14,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
const [media, setMedia] = useState(null)
const [filePickerOpen, setFilePickerOpen] = useState(false)
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
const { showError, showInfo } = useNotifier()
useEffect(() => {
const getAlbum = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
@@ -28,7 +28,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
})
const data = await response.json()
if (data.error) {
showError(data.error)
showError("Error getting albums in parent: " + data.error)
} else {
setAlbums(data)
}
@@ -45,7 +45,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
})
const data = await response.json()
if (data.error) {
showError(data.error)
showError("Error getting album info: " + data.error)
} else {
setSelectedAlbum(data)
}
@@ -59,7 +59,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
})
const data = await response.json()
if (data.error) {
showError(data.error)
showError("Error getting media: " + data.error)
} else {
if (data.media.length === 0) {
setMedia(null)
@@ -99,7 +99,7 @@ export default function FilePicker({ currentAlbum, onFileSelect }) {
const data = await response.json()
if (data.error) {
showError(data.error)
showError("Error getting album: " + data.error)
break
}
+126 -122
View File
@@ -1,122 +1,126 @@
import { EllipsisVertical, Upload } from 'lucide-react'
import MediaUploadModal from './MediaUploadModal'
import AuthImage from '../../components/AuthImage'
import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useNotifier } from '../../contexts/useNotifier'
import { useNavigate } from 'react-router-dom'
export default function MediaList({ albumId, albumName }) {
const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false)
const [media, setMedia] = useState([])
const [aspectRatios, setAspectRatios] = useState({})
const { showError } = useNotifier()
const navigate = useNavigate()
useEffect(() => {
let ignore = false;
const getMedia = async () => {
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${albumId}`, {
method: 'GET',
headers: {
'Authorization': getAccessToken(),
},
})
const data = await response.json()
if (ignore) return
if (data.error) {
showError(data.error)
} else {
setMedia(data.media)
}
}
getMedia()
return () => { ignore = true; }
}, [albumId])
const handleImageLoad = (id, event) => {
const { naturalWidth, naturalHeight } = event.target
if (naturalWidth && naturalHeight) {
setAspectRatios(prev => ({
...prev,
[id]: naturalWidth / naturalHeight
}))
}
}
useEffect(() => {
console.log(media)
}, [media])
return (
<div className="flex flex-col items-center justify-start w-full bg-[#141414]">
<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">Media</h1>
<Upload className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} />
</div>
<MediaUploadModal
open={open}
onOpenChange={setOpen}
albumId={albumId}
albumName={albumName}
/>
{/* Media Grid */}
<div className="flex flex-wrap justify-start gap-2 w-full px-6">
{media.length === 0 && (
<p className="text-gray-500 red-hat-text">No media in this album</p>
)}
{media.map((item) => {
let ar = 1;
// 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;
} else if (aspectRatios[item.ID]) {
ar = aspectRatios[item.ID];
}
return (
<div
key={item.ID}
style={{
aspectRatio: ar,
flexGrow: ar,
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"
onClick={() => {
navigate(`/viewer/${albumId ? albumId : 'root'}/${item.ID}`)
}}
>
<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-[100%] p-2 red-hat-mono">{item.Title}</p>
<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)
}}>
<EllipsisVertical className="w-4 h-4" />
</button>
</div>
<AuthImage
src={`${getServerUrl()}/api/media/thumb/${albumId ? albumId : 'root'}/${item.ID}`}
token={getAccessToken()}
alt={item.Title}
className="w-full h-full object-cover"
onLoad={(e) => handleImageLoad(item.ID, e)}
/>
</div>
)
})}
{/* Spacer to prevent the last row from expanding to fill width if it has few items */}
<div style={{ flexGrow: 9999, flexBasis: '50%' }}></div>
</div>
<MediaUploadModal
open={open}
onOpenChange={setOpen}
albumId={albumId}
albumName={albumName}
/>
</div>
)
}
import { EllipsisVertical, Upload } from 'lucide-react'
import MediaUploadModal from './MediaUploadModal'
import AuthImage from '../../components/AuthImage'
import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useNotifier } from '../../contexts/useNotifier'
import { useNavigate } from 'react-router-dom'
export default function MediaList({ albumId, albumName }) {
const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false)
const [media, setMedia] = useState([])
const [aspectRatios, setAspectRatios] = useState({})
const { showError, showInfo } = useNotifier()
const navigate = useNavigate()
useEffect(() => {
let ignore = false;
const accessToken = getAccessToken()
if (!accessToken || !albumId && albumName !== 'gallery') {
return // assuming state isn't loaded yet
}
const getMedia = async () => {
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${albumId}`, {
method: 'GET',
headers: {
'Authorization': accessToken,
},
})
const data = await response.json()
if (ignore) return
if (data.error) {
showError("Error getting media in album: " + data.error)
} else {
setMedia(data.media)
}
}
getMedia()
return () => { ignore = true; }
}, [albumId])
const handleImageLoad = (id, event) => {
const { naturalWidth, naturalHeight } = event.target
if (naturalWidth && naturalHeight) {
setAspectRatios(prev => ({
...prev,
[id]: naturalWidth / naturalHeight
}))
}
}
useEffect(() => {
console.log(media)
}, [media])
return (
<div className="flex flex-col items-center justify-start w-full bg-[#141414]">
<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-display">Media</h1>
<Upload className="w-6 h-6 cursor-pointer" color="white" onClick={() => setOpen(true)} />
</div>
<MediaUploadModal
open={open}
onOpenChange={setOpen}
albumId={albumId}
albumName={albumName}
/>
{/* Media Grid */}
<div className="flex flex-wrap justify-start gap-2 w-full px-6">
{media.length === 0 && (
<p className="text-gray-500 red-hat-text">No media in this album</p>
)}
{media.map((item) => {
let ar = 1;
// 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;
} else if (aspectRatios[item.ID]) {
ar = aspectRatios[item.ID];
}
return (
<div
key={item.ID}
style={{
aspectRatio: ar,
flexGrow: ar,
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"
onClick={() => {
navigate(`/viewer/${albumId ? albumId : 'root'}/${item.ID}`)
}}
>
<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>
<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)
}}>
<EllipsisVertical className="w-4 h-4" />
</button>
</div>
<AuthImage
src={`${getServerUrl()}/api/media/thumb/${albumId ? albumId : 'root'}/${item.ID}`}
token={getAccessToken()}
alt={item.Title}
className="w-full h-full object-cover"
onLoad={(e) => handleImageLoad(item.ID, e)}
/>
</div>
)
})}
{/* Spacer to prevent the last row from expanding to fill width if it has few items */}
<div style={{ flexGrow: 9999, flexBasis: '50%' }}></div>
</div>
<MediaUploadModal
open={open}
onOpenChange={setOpen}
albumId={albumId}
albumName={albumName}
/>
</div>
)
}
@@ -1,184 +1,184 @@
import Modal from '../../components/Modal'
import { useAccount } from '../../contexts/useAccount'
import { useState, useRef } from 'react'
import { X, Upload, FileImage, FileVideo, Trash2 } from 'lucide-react'
import { useNotifier } from '../../contexts/useNotifier'
import { getServerUrl } from '../../hooks/getConstants'
export default function MediaUploadModal({ open, onOpenChange, trigger, albumName, albumId }) {
const { getAccessToken } = useAccount()
const [files, setFiles] = useState([])
const fileInputRef = useRef(null)
const { showError, showSuccess } = useNotifier()
const handleFileSelect = (e) => {
if (e.target.files) {
const newFiles = Array.from(e.target.files).map(file => ({
file,
progress: 0,
status: 'pending',
id: Math.random().toString(36).substring(7)
}))
setFiles(prev => [...prev, ...newFiles])
}
// Reset input so the same file can be selected again if needed
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
const removeFile = (id) => {
setFiles(prev => prev.filter(f => f.id !== id))
}
const handleUpload = async () => {
const pendingFiles = files.filter(f => f.status === 'pending')
if (pendingFiles.length === 0) return
setFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, status: 'uploading' } : f))
const uploadFile = (fileWrapper) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
const formData = new FormData()
formData.append('file', fileWrapper.file)
formData.append('albumId', albumId)
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const progress = Math.round((event.loaded / event.total) * 100)
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, progress } : f))
}
})
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.responseText)
if (data.error) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(data.error)
} else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'completed', progress: 100 } : f))
resolve(data)
}
} catch (e) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(e)
}
} else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error(xhr.statusText))
}
})
xhr.addEventListener('error', () => {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error('Network Error'))
})
xhr.open('POST', `${getServerUrl()}/api/media/uploadMedia`)
xhr.setRequestHeader('Authorization', getAccessToken())
xhr.send(formData)
})
}
const results = await Promise.allSettled(pendingFiles.map(f => uploadFile(f)))
const failedCount = results.filter(r => r.status === 'rejected').length
const successCount = results.filter(r => r.status === 'fulfilled').length
if (failedCount > 0) {
showError(`${failedCount} file(s) failed to upload`)
}
if (successCount > 0) {
showSuccess(`${successCount} file(s) uploaded successfully`)
}
}
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} isProtected={true} title={`Upload to ${albumName || 'Album'}`}>
<div className="flex flex-col gap-4">
{/* File Selection Area */}
<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]"
onClick={() => fileInputRef.current?.click()}
>
<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-600 text-xs mt-1 red-hat-text">Images and Videos</p>
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
accept="image/*,video/*"
onChange={handleFileSelect}
/>
</div>
{/* File List */}
{files.length > 0 && (
<div className="flex flex-col gap-2 max-h-[40vh] overflow-y-auto pr-1">
{files.map((fileWrapper) => (
<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 gap-3 overflow-hidden">
{fileWrapper.file.type.startsWith('video') ? (
<FileVideo className="w-5 h-5 text-blue-400 flex-shrink-0" />
) : (
<FileImage className="w-5 h-5 text-green-400 flex-shrink-0" />
)}
<div className="flex flex-col overflow-hidden">
<span className="text-white text-sm truncate red-hat-text" title={fileWrapper.file.name}>
{fileWrapper.file.name}
</span>
<span className="text-gray-500 text-xs red-hat-mono">
{formatFileSize(fileWrapper.file.size)}
</span>
</div>
</div>
<button
onClick={() => removeFile(fileWrapper.id)}
className="text-gray-500 hover:text-red-400 transition-colors p-1"
disabled={fileWrapper.status === 'uploading'}
>
<Trash2 className="w-4 h-4" />
</button>
</div>
{/* Progress Bar */}
<div className="w-full h-1.5 bg-[#2B2B2B] rounded-full overflow-hidden">
<div
className={`h-full transition-all duration-300 ${fileWrapper.status === 'completed' ? 'bg-green-500' :
fileWrapper.status === 'error' ? 'bg-red-500' : 'bg-blue-500'
}`}
style={{ width: `${fileWrapper.progress}%` }}
/>
</div>
</div>
))}
</div>
)}
{/* Upload 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')
? 'opacity-50 cursor-not-allowed'
: 'hover:bg-[#3B3B3B] cursor-pointer'
}`}
onClick={handleUpload}
disabled={files.length === 0 || files.every(f => f.status === 'completed')}
>
{files.some(f => f.status === 'uploading') ? 'Uploading...' : 'Upload Files'}
</button>
</div>
</Modal>
)
}
import Modal from '../../components/Modal'
import { useAccount } from '../../contexts/useAccount'
import { useState, useRef } from 'react'
import { X, Upload, FileImage, FileVideo, Trash2 } from 'lucide-react'
import { useNotifier } from '../../contexts/useNotifier'
import { getServerUrl } from '../../hooks/getConstants'
export default function MediaUploadModal({ open, onOpenChange, trigger, albumName, albumId }) {
const { getAccessToken } = useAccount()
const [files, setFiles] = useState([])
const fileInputRef = useRef(null)
const { showError, showSuccess } = useNotifier()
const handleFileSelect = (e) => {
if (e.target.files) {
const newFiles = Array.from(e.target.files).map(file => ({
file,
progress: 0,
status: 'pending',
id: Math.random().toString(36).substring(7)
}))
setFiles(prev => [...prev, ...newFiles])
}
// Reset input so the same file can be selected again if needed
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
const removeFile = (id) => {
setFiles(prev => prev.filter(f => f.id !== id))
}
const handleUpload = async () => {
const pendingFiles = files.filter(f => f.status === 'pending')
if (pendingFiles.length === 0) return
setFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, status: 'uploading' } : f))
const uploadFile = (fileWrapper) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
const formData = new FormData()
formData.append('file', fileWrapper.file)
formData.append('albumId', albumId)
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const progress = Math.round((event.loaded / event.total) * 100)
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, progress } : f))
}
})
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.responseText)
if (data.error) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(data.error)
} else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'completed', progress: 100 } : f))
resolve(data)
}
} catch (e) {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(e)
}
} else {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error(xhr.statusText))
}
})
xhr.addEventListener('error', () => {
setFiles(prev => prev.map(f => f.id === fileWrapper.id ? { ...f, status: 'error' } : f))
reject(new Error('Network Error'))
})
xhr.open('POST', `${getServerUrl()}/api/media/uploadMedia`)
xhr.setRequestHeader('Authorization', getAccessToken())
xhr.send(formData)
})
}
const results = await Promise.allSettled(pendingFiles.map(f => uploadFile(f)))
const failedCount = results.filter(r => r.status === 'rejected').length
const successCount = results.filter(r => r.status === 'fulfilled').length
if (failedCount > 0) {
showError(`${failedCount} file(s) failed to upload`)
}
if (successCount > 0) {
showSuccess(`${successCount} file(s) uploaded successfully`)
}
}
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
return (
<Modal open={open} onOpenChange={onOpenChange} trigger={trigger} isProtected={true} title={`Upload to ${albumName || 'Album'}`}>
<div className="flex flex-col gap-4">
{/* File Selection Area */}
<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]"
onClick={() => fileInputRef.current?.click()}
>
<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-600 text-xs mt-1 red-hat-text">Images and Videos</p>
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
accept="image/*,video/*"
onChange={handleFileSelect}
/>
</div>
{/* File List */}
{files.length > 0 && (
<div className="flex flex-col gap-2 max-h-[40vh] overflow-y-auto pr-1">
{files.map((fileWrapper) => (
<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 gap-3 overflow-hidden">
{fileWrapper.file.type.startsWith('video') ? (
<FileVideo className="w-5 h-5 text-blue-400 flex-shrink-0" />
) : (
<FileImage className="w-5 h-5 text-green-400 flex-shrink-0" />
)}
<div className="flex flex-col overflow-hidden">
<span className="text-white text-sm truncate red-hat-text" title={fileWrapper.file.name}>
{fileWrapper.file.name}
</span>
<span className="text-gray-500 text-xs red-hat-mono">
{formatFileSize(fileWrapper.file.size)}
</span>
</div>
</div>
<button
onClick={() => removeFile(fileWrapper.id)}
className="text-gray-500 hover:text-red-400 transition-colors p-1"
disabled={fileWrapper.status === 'uploading'}
>
<Trash2 className="w-4 h-4" />
</button>
</div>
{/* Progress Bar */}
<div className="w-full h-1.5 bg-[#2B2B2B] rounded-full overflow-hidden">
<div
className={`h-full transition-all duration-300 ${fileWrapper.status === 'completed' ? 'bg-green-500' :
fileWrapper.status === 'error' ? 'bg-red-500' : 'bg-blue-500'
}`}
style={{ width: `${fileWrapper.progress}%` }}
/>
</div>
</div>
))}
</div>
)}
{/* Upload 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')
? 'opacity-50 cursor-not-allowed'
: 'hover:bg-[#3B3B3B] cursor-pointer'
}`}
onClick={handleUpload}
disabled={files.length === 0 || files.every(f => f.status === 'completed')}
>
{files.some(f => f.status === 'uploading') ? 'Uploading...' : 'Upload Files'}
</button>
</div>
</Modal>
)
}
+59 -59
View File
@@ -1,60 +1,60 @@
import NavBar from '../components/NavBar'
import { useLocation } from 'react-router-dom';
import { useAccount } from '../contexts/useAccount';
import { useEffect, useState } from 'react';
import AlbumList from './components/AlbumList';
import { getServerUrl } from '../hooks/getConstants';
import { useNotifier } from '../contexts/useNotifier';
import MediaList from './components/MediaList';
export default function Gallery() {
const currentPath = useLocation().pathname;
const pathList = currentPath.split('/').slice(1);
const currentAlbumName = pathList[pathList.length - 1];
const [currentAlbumID, setCurrentAlbumID] = useState(null); // Initialize as null to prevent premature fetching
const { fetchUserData, user } = useAccount()
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
useEffect(() => {
fetchUserData()
}, [])
useEffect(() => {
const getCurrentAlbumID = async () => {
console.log("currentAlbumName", currentAlbumName)
console.log("pathList", pathList)
if (currentAlbumName === 'gallery') {
setCurrentAlbumID('');
return;
}
const response = await fetch(`${getServerUrl()}/api/albums/getIDFromPath`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
},
body: JSON.stringify({
path: decodeURIComponent(pathList.slice(1).join('/')),
}),
})
const data = await response.json()
if (data.error) {
setCurrentAlbumID("!notfound!")
showError('Album not found')
} else {
setCurrentAlbumID(data.id);
}
};
getCurrentAlbumID();
}, [currentPath]);
useEffect(() => {
console.log("currentAlbumID", currentAlbumID)
}, [currentAlbumID])
return (
<div className="flex flex-col items-center justify-start min-h-screen w-full bg-[#141414] pb-8">
<NavBar path={pathList} />
<AlbumList currentAlbumName={currentAlbumID} />
<MediaList albumId={currentAlbumID} albumName={currentAlbumName} />
</div>
)
import NavBar from '../components/NavBar'
import { useLocation } from 'react-router-dom';
import { useAccount } from '../contexts/useAccount';
import { useEffect, useState } from 'react';
import AlbumList from './components/AlbumList';
import { getServerUrl } from '../hooks/getConstants';
import { useNotifier } from '../contexts/useNotifier';
import MediaList from './components/MediaList';
export default function Gallery() {
const currentPath = useLocation().pathname;
const pathList = currentPath.split('/').slice(1);
const currentAlbumName = pathList[pathList.length - 1];
const [currentAlbumID, setCurrentAlbumID] = useState(null); // Initialize as null to prevent premature fetching
const { fetchUserData, user } = useAccount()
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
useEffect(() => {
fetchUserData()
}, [])
useEffect(() => {
const getCurrentAlbumID = async () => {
console.log("currentAlbumName", currentAlbumName)
console.log("pathList", pathList)
if (currentAlbumName === 'gallery') {
setCurrentAlbumID('');
return;
}
const response = await fetch(`${getServerUrl()}/api/albums/getIDFromPath`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
},
body: JSON.stringify({
path: decodeURIComponent(pathList.slice(1).join('/')),
}),
})
const data = await response.json()
if (data.error) {
setCurrentAlbumID("!notfound!")
showError('Album not found')
} else {
setCurrentAlbumID(data.id);
}
};
getCurrentAlbumID();
}, [currentPath]);
useEffect(() => {
console.log("currentAlbumID", currentAlbumID)
}, [currentAlbumID])
return (
<div className="flex flex-col items-center justify-start min-h-screen w-full bg-[#141414] pb-8">
<NavBar path={pathList} />
<AlbumList currentAlbumName={currentAlbumID} />
<MediaList albumId={currentAlbumID} albumName={currentAlbumName} />
</div>
)
}
+2 -2
View File
@@ -1,3 +1,3 @@
export const getServerUrl = () => {
return 'http://localhost:8080';
export const getServerUrl = () => {
return 'http://localhost:8080';
}
+30 -23
View File
@@ -1,24 +1,31 @@
@import "tailwindcss";
html,
body,
#root {
height: 100%;
margin: 0;
padding: 0;
}
.red-hat-mono {
font-family: "Red Hat Mono", monospace;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
}
.red-hat-text {
font-family: "Red Hat Text", sans-serif;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
@import "tailwindcss";
html,
body,
#root {
height: 100%;
margin: 0;
padding: 0;
}
.red-hat-mono {
font-family: "Red Hat Mono", monospace;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
}
.red-hat-text {
font-family: "Red Hat Text", sans-serif;
font-optical-sizing: auto;
font-weight: 400;
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 { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
)
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
)
+6 -6
View File
@@ -1,7 +1,7 @@
export default function Test() {
return (
<div className="flex flex-col items-center justify-center h-full w-full">
<h1 className="text-2xl font-bold">Test</h1>
</div>
)
export default function Test() {
return (
<div className="flex flex-col items-center justify-center h-full w-full">
<h1 className="text-2xl font-bold">Test</h1>
</div>
)
}
+36 -36
View File
@@ -1,36 +1,36 @@
import AuthImage from '../../components/AuthImage'
import { getServerUrl } from '../../hooks/getConstants'
import { useState, useEffect } from 'react'
import { Loader2 } from 'lucide-react'
export default function ImageViewer({ albumId, mediaId, token, title }) {
const src = `${getServerUrl()}/api/media/${albumId}/${mediaId}`
const [loaded, setLoaded] = useState(false)
return (
<div className="flex-1 flex items-center justify-center bg-black relative overflow-hidden h-full">
<AuthImage
src={src}
token={token}
alt={title}
className={`max-w-full max-h-full object-contain absolute ${loaded ? 'block' : 'hidden'}`}
onLoad={() => {
setLoaded(true)
}}
/>
{/* loading image */}
{!loaded && (
<div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center">
<AuthImage
src={`${getServerUrl()}/api/media/thumb/${albumId}/${mediaId}`}
token={token}
alt={title}
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" />
</div>
)}
</div>
)
}
import AuthImage from '../../components/AuthImage'
import { getServerUrl } from '../../hooks/getConstants'
import { useState, useEffect } from 'react'
import { Loader2 } from 'lucide-react'
export default function ImageViewer({ albumId, mediaId, token, title }) {
const src = `${getServerUrl()}/api/media/${albumId}/${mediaId}`
const [loaded, setLoaded] = useState(false)
return (
<div className="flex-1 flex items-center justify-center bg-black relative overflow-hidden">
<AuthImage
src={src}
token={token}
alt={title}
className={`max-w-full max-h-full object-contain absolute ${loaded ? 'block' : 'hidden'}`}
onLoad={() => {
setLoaded(true)
}}
/>
{/* loading image */}
{!loaded && (
<div className="absolute top-0 left-0 w-full h-full bg-black/50 flex items-center justify-center">
<AuthImage
src={`${getServerUrl()}/api/media/thumb/${albumId}/${mediaId}`}
token={token}
alt={title}
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" />
</div>
)}
</div>
)
}
@@ -1,51 +1,51 @@
export default function MetadataPanel({ mediaItem }) {
if (!mediaItem) return <div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-4 text-white">Loading...</div>
return (
<div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-6 text-white overflow-y-auto flex-shrink-0">
<h2 className="text-xl font-bold mb-6 red-hat-mono break-words">{mediaItem.Title}</h2>
<div className="space-y-6">
<div className="space-y-2">
<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="flex justify-between">
<span className="text-gray-500">Type</span>
<span className="text-white">{mediaItem.Type || 'Unknown'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Size</span>
{/* 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>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Uploaded</span>
<span className="text-white">{mediaItem.CreatedAt ? new Date(mediaItem.CreatedAt).toLocaleDateString() : '-'}</span>
</div>
</div>
</div>
<div className="space-y-2">
<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>
{/* Placeholder for EXIF data */}
<div className="bg-[#222] rounded p-3 space-y-2 text-sm opacity-50">
<div className="flex justify-between">
<span className="text-gray-500">Camera</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">ISO</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Aperture</span>
<span className="text-white">-</span>
</div>
</div>
</div>
</div>
</div>
)
}
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>
return (
<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-display break-words">{mediaItem.Title}</h2>
<div className="space-y-6">
<div className="space-y-2">
<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 red-hat-mono">
<div className="flex justify-between">
<span className="text-gray-500">Type</span>
<span className="text-white">{mediaItem.Type || 'Unknown'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Size</span>
{/* 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>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Uploaded</span>
<span className="text-white">{mediaItem.CreatedAt ? new Date(mediaItem.CreatedAt).toLocaleDateString() : '-'}</span>
</div>
</div>
</div>
<div className="space-y-2 red-hat-mono">
<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>
{/* Placeholder for EXIF data */}
<div className="bg-[#222] rounded p-3 space-y-2 text-sm opacity-50">
<div className="flex justify-between">
<span className="text-gray-500">Camera</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">ISO</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Aperture</span>
<span className="text-white">-</span>
</div>
</div>
</div>
</div>
</div>
)
}
+90 -84
View File
@@ -1,84 +1,90 @@
import { useEffect, useState } from 'react'
import { useParams, useLocation, useNavigate } from 'react-router-dom'
import ImageViewer from './components/ImageViewer'
import MetadataPanel from './components/MetadataPanel'
import { useAccount } from '../contexts/useAccount'
import { getServerUrl } from '../hooks/getConstants'
import { useNotifier } from '../contexts/useNotifier'
import { ArrowLeft } from 'lucide-react'
export default function Viewer() {
const { albumId, mediaId } = useParams()
const location = useLocation()
const navigate = useNavigate()
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
const [mediaItem, setMediaItem] = useState(location.state?.mediaItem || null)
useEffect(() => {
if (mediaItem) return
const fetchMediaDetails = async () => {
try {
// Use '' if albumId is 'root'
const targetAlbumId = albumId === 'root' ? '' : albumId
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${targetAlbumId}`, {
headers: {
'Authorization': getAccessToken()
}
})
const data = await response.json()
if (data.error) {
showError(data.error)
} else {
const found = data.media.find(m => m.ID === mediaId)
if (found) {
setMediaItem(found)
} else {
showError("Media not found")
}
}
} catch (err) {
showError("Failed to fetch media details")
}
}
fetchMediaDetails()
}, [albumId, mediaId, getAccessToken, showError, mediaItem])
const handleBack = () => {
if (window.history.state && window.history.state.idx > 0) {
navigate(-1)
} else {
// Fallback if opened directly
navigate('/gallery')
}
}
return (
<div className="flex flex-col h-screen w-full bg-[#141414]">
<div className="flex items-center h-14 px-4 border-b border-[#2B2B2B] bg-[#141414] flex-shrink-0 gap-4">
<button onClick={handleBack} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
<ArrowLeft size={20} />
</button>
<span className="text-white font-medium truncate red-hat-mono">
{mediaItem ? mediaItem.Title : 'Loading...'}
</span>
</div>
<div className="flex flex-1 overflow-hidden">
<ImageViewer
albumId={albumId === 'root' ? '' : albumId}
mediaId={mediaId}
token={getAccessToken()}
title={mediaItem?.Title || ''}
/>
<MetadataPanel mediaItem={mediaItem} />
</div>
</div>
)
}
import { useEffect, useState } from 'react'
import { useParams, useLocation, useNavigate } from 'react-router-dom'
import ImageViewer from './components/ImageViewer'
import MetadataPanel from './components/MetadataPanel'
import { useAccount } from '../contexts/useAccount'
import { getServerUrl } from '../hooks/getConstants'
import { useNotifier } from '../contexts/useNotifier'
import { ArrowLeft, PanelRightClose, PanelRightOpen } from 'lucide-react'
export default function Viewer() {
const { albumId, mediaId } = useParams()
const location = useLocation()
const navigate = useNavigate()
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
const [mediaItem, setMediaItem] = useState(location.state?.mediaItem || null)
const [metadataPanelOpen, setMetadataPanelOpen] = useState(false)
useEffect(() => {
if (mediaItem) return
const fetchMediaDetails = async () => {
try {
// Use '' if albumId is 'root'
const targetAlbumId = albumId === 'root' ? '' : albumId
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${targetAlbumId}`, {
headers: {
'Authorization': getAccessToken()
}
})
const data = await response.json()
if (data.error) {
showError("Error getting media details: " + data.error)
} else {
const found = data.media.find(m => m.ID === mediaId)
if (found) {
setMediaItem(found)
} else {
showError("Media not found in album")
}
}
} catch (err) {
showError("Failed to fetch media details: " + err.message)
}
}
fetchMediaDetails()
}, [albumId, mediaId, getAccessToken, showError, mediaItem])
const handleBack = () => {
if (window.history.state && window.history.state.idx > 0) {
navigate(-1)
} else {
// Fallback if opened directly
navigate('/gallery')
}
}
return (
<div className="flex flex-col h-dvh w-full bg-[#141414]">
<div className="flex items-center h-14 px-4 border-b border-[#2B2B2B] bg-[#141414] flex-shrink-0 gap-4 justify-between">
<div className="flex items-center gap-2">
<button onClick={handleBack} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
<ArrowLeft size={20} />
</button>
<span className="text-white font-medium truncate red-hat-text">
{mediaItem ? mediaItem.Title : 'Loading...'}
</span>
</div>
<button onClick={() => setMetadataPanelOpen(!metadataPanelOpen)} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
{metadataPanelOpen ? <PanelRightClose size={20} /> : <PanelRightOpen size={20} />}
</button>
</div>
<div className="flex flex-col md:flex-row flex-1 overflow-hidden">
<ImageViewer
albumId={albumId === 'root' ? '' : albumId}
mediaId={mediaId}
token={getAccessToken()}
title={mediaItem?.Title || ''}
/>
<MetadataPanel mediaItem={mediaItem} open={metadataPanelOpen} />
</div>
</div>
)
}