From 74abc65340c35d2cb2a82fd39a54008201868de1 Mon Sep 17 00:00:00 2001 From: Evan Reichard Date: Sun, 31 Dec 2023 23:12:46 -0500 Subject: [PATCH] [refactor] remove app route builder --- api/api.go | 83 ++--- api/app-routes.go | 670 ++++++++++++++++------------------ api/auth.go | 63 ++-- api/common.go | 140 +++++++ api/ko-routes.go | 146 +++----- assets/reader/index.js | 11 + assets/style.css | 2 +- database/query.sql | 47 ++- database/query.sql.go | 139 +++++-- templates/base.html | 21 +- templates/pages/home.html | 4 +- templates/pages/login.html | 2 +- templates/pages/progress.html | 49 +++ templates/pages/settings.html | 9 +- 14 files changed, 807 insertions(+), 579 deletions(-) create mode 100644 api/common.go create mode 100644 templates/pages/progress.html diff --git a/api/api.go b/api/api.go index 850ecdb..b150d1e 100644 --- a/api/api.go +++ b/api/api.go @@ -83,51 +83,52 @@ func (api *API) registerWebAppRoutes() { api.Router.HTMLRender = *api.generateTemplates() // Static Assets (Required @ Root) - api.Router.GET("/manifest.json", api.webManifest) - api.Router.GET("/favicon.ico", api.faviconIcon) - api.Router.GET("/sw.js", api.serviceWorker) + api.Router.GET("/manifest.json", api.appWebManifest) + api.Router.GET("/favicon.ico", api.appFaviconIcon) + api.Router.GET("/sw.js", api.appServiceWorker) // Local / Offline Static Pages (No Template, No Auth) - api.Router.GET("/local", api.localDocuments) + api.Router.GET("/local", api.appLocalDocuments) // Reader (Reader Page, Document Progress, Devices) - api.Router.GET("/reader", api.documentReader) - api.Router.GET("/reader/devices", api.authWebAppMiddleware, api.getDevices) - api.Router.GET("/reader/progress/:document", api.authWebAppMiddleware, api.getDocumentProgress) + api.Router.GET("/reader", api.appDocumentReader) + api.Router.GET("/reader/devices", api.authWebAppMiddleware, api.appGetDevices) + api.Router.GET("/reader/progress/:document", api.authWebAppMiddleware, api.appGetDocumentProgress) // Web App - api.Router.GET("/", api.authWebAppMiddleware, api.createAppResourcesRoute("home")) - api.Router.GET("/activity", api.authWebAppMiddleware, api.createAppResourcesRoute("activity")) - api.Router.GET("/documents", api.authWebAppMiddleware, api.createAppResourcesRoute("documents")) - api.Router.GET("/documents/:document", api.authWebAppMiddleware, api.createAppResourcesRoute("document")) + api.Router.GET("/", api.authWebAppMiddleware, api.appGetHome) + api.Router.GET("/activity", api.authWebAppMiddleware, api.appGetActivity) + api.Router.GET("/progress", api.authWebAppMiddleware, api.appGetProgress) + api.Router.GET("/documents", api.authWebAppMiddleware, api.appGetDocuments) + api.Router.GET("/documents/:document", api.authWebAppMiddleware, api.appGetDocument) api.Router.GET("/documents/:document/cover", api.authWebAppMiddleware, api.getDocumentCover) api.Router.GET("/documents/:document/file", api.authWebAppMiddleware, api.downloadDocument) - api.Router.GET("/login", api.createAppResourcesRoute("login")) - api.Router.GET("/logout", api.authWebAppMiddleware, api.authLogout) - api.Router.GET("/register", api.createAppResourcesRoute("login", gin.H{"Register": true})) - api.Router.GET("/settings", api.authWebAppMiddleware, api.createAppResourcesRoute("settings")) - api.Router.POST("/login", api.authFormLogin) - api.Router.POST("/register", api.authFormRegister) + api.Router.GET("/login", api.appGetLogin) + api.Router.GET("/logout", api.authWebAppMiddleware, api.appAuthLogout) + api.Router.GET("/register", api.appGetRegister) + api.Router.GET("/settings", api.authWebAppMiddleware, api.appGetSettings) + api.Router.POST("/login", api.appAuthFormLogin) + api.Router.POST("/register", api.appAuthFormRegister) // Demo Mode Enabled Configuration if api.Config.DemoMode { - api.Router.POST("/documents", api.authWebAppMiddleware, api.demoModeAppError) - api.Router.POST("/documents/:document/delete", api.authWebAppMiddleware, api.demoModeAppError) - api.Router.POST("/documents/:document/edit", api.authWebAppMiddleware, api.demoModeAppError) - api.Router.POST("/documents/:document/identify", api.authWebAppMiddleware, api.demoModeAppError) - api.Router.POST("/settings", api.authWebAppMiddleware, api.demoModeAppError) + api.Router.POST("/documents", api.authWebAppMiddleware, api.appDemoModeError) + api.Router.POST("/documents/:document/delete", api.authWebAppMiddleware, api.appDemoModeError) + api.Router.POST("/documents/:document/edit", api.authWebAppMiddleware, api.appDemoModeError) + api.Router.POST("/documents/:document/identify", api.authWebAppMiddleware, api.appDemoModeError) + api.Router.POST("/settings", api.authWebAppMiddleware, api.appDemoModeError) } else { - api.Router.POST("/documents", api.authWebAppMiddleware, api.uploadNewDocument) - api.Router.POST("/documents/:document/delete", api.authWebAppMiddleware, api.deleteDocument) - api.Router.POST("/documents/:document/edit", api.authWebAppMiddleware, api.editDocument) - api.Router.POST("/documents/:document/identify", api.authWebAppMiddleware, api.identifyDocument) - api.Router.POST("/settings", api.authWebAppMiddleware, api.editSettings) + api.Router.POST("/documents", api.authWebAppMiddleware, api.appUploadNewDocument) + api.Router.POST("/documents/:document/delete", api.authWebAppMiddleware, api.appDeleteDocument) + api.Router.POST("/documents/:document/edit", api.authWebAppMiddleware, api.appEditDocument) + api.Router.POST("/documents/:document/identify", api.authWebAppMiddleware, api.appIdentifyDocument) + api.Router.POST("/settings", api.authWebAppMiddleware, api.appEditSettings) } // Search Enabled Configuration if api.Config.SearchEnabled { - api.Router.GET("/search", api.authWebAppMiddleware, api.createAppResourcesRoute("search")) - api.Router.POST("/search", api.authWebAppMiddleware, api.saveNewDocument) + api.Router.GET("/search", api.authWebAppMiddleware, api.appGetSearch) + api.Router.POST("/search", api.authWebAppMiddleware, api.appSaveNewDocument) } } @@ -136,22 +137,22 @@ func (api *API) registerKOAPIRoutes(apiGroup *gin.RouterGroup) { // KO Sync Routes (WebApp Uses - Progress & Activity) koGroup.GET("/documents/:document/file", api.authKOMiddleware, api.downloadDocument) - koGroup.GET("/syncs/progress/:document", api.authKOMiddleware, api.getProgress) - koGroup.GET("/users/auth", api.authKOMiddleware, api.authorizeUser) - koGroup.POST("/activity", api.authKOMiddleware, api.addActivities) - koGroup.POST("/syncs/activity", api.authKOMiddleware, api.checkActivitySync) - koGroup.POST("/users/create", api.createUser) - koGroup.PUT("/syncs/progress", api.authKOMiddleware, api.setProgress) + koGroup.GET("/syncs/progress/:document", api.authKOMiddleware, api.koGetProgress) + koGroup.GET("/users/auth", api.authKOMiddleware, api.koAuthorizeUser) + koGroup.POST("/activity", api.authKOMiddleware, api.koAddActivities) + koGroup.POST("/syncs/activity", api.authKOMiddleware, api.koCheckActivitySync) + koGroup.POST("/users/create", api.koCreateUser) + koGroup.PUT("/syncs/progress", api.authKOMiddleware, api.koSetProgress) // Demo Mode Enabled Configuration if api.Config.DemoMode { - koGroup.POST("/documents", api.authKOMiddleware, api.demoModeJSONError) - koGroup.POST("/syncs/documents", api.authKOMiddleware, api.demoModeJSONError) - koGroup.PUT("/documents/:document/file", api.authKOMiddleware, api.demoModeJSONError) + koGroup.POST("/documents", api.authKOMiddleware, api.koDemoModeJSONError) + koGroup.POST("/syncs/documents", api.authKOMiddleware, api.koDemoModeJSONError) + koGroup.PUT("/documents/:document/file", api.authKOMiddleware, api.koDemoModeJSONError) } else { - koGroup.POST("/documents", api.authKOMiddleware, api.addDocuments) - koGroup.POST("/syncs/documents", api.authKOMiddleware, api.checkDocumentsSync) - koGroup.PUT("/documents/:document/file", api.authKOMiddleware, api.uploadExistingDocument) + koGroup.POST("/documents", api.authKOMiddleware, api.koAddDocuments) + koGroup.POST("/syncs/documents", api.authKOMiddleware, api.koCheckDocumentsSync) + koGroup.PUT("/documents/:document/file", api.authKOMiddleware, api.koUploadExistingDocument) } } diff --git a/api/app-routes.go b/api/app-routes.go index 27058d9..8be6d11 100644 --- a/api/app-routes.go +++ b/api/app-routes.go @@ -70,309 +70,272 @@ type requestDocumentAdd struct { Source search.Source `form:"source"` } -func (api *API) webManifest(c *gin.Context) { +func (api *API) appWebManifest(c *gin.Context) { c.Header("Content-Type", "application/manifest+json") c.FileFromFS("assets/manifest.json", http.FS(api.Assets)) } -func (api *API) serviceWorker(c *gin.Context) { +func (api *API) appServiceWorker(c *gin.Context) { c.FileFromFS("assets/sw.js", http.FS(api.Assets)) } -func (api *API) faviconIcon(c *gin.Context) { +func (api *API) appFaviconIcon(c *gin.Context) { c.FileFromFS("assets/icons/favicon.ico", http.FS(api.Assets)) } -func (api *API) localDocuments(c *gin.Context) { +func (api *API) appLocalDocuments(c *gin.Context) { c.FileFromFS("assets/local/index.htm", http.FS(api.Assets)) } -func (api *API) documentReader(c *gin.Context) { +func (api *API) appDocumentReader(c *gin.Context) { c.FileFromFS("assets/reader/index.htm", http.FS(api.Assets)) } -func (api *API) createAppResourcesRoute(routeName string, args ...map[string]any) func(*gin.Context) { - // Merge Optional Template Data - var templateVarsBase = gin.H{} - if len(args) > 0 { - templateVarsBase = args[0] - } - templateVarsBase["RouteName"] = routeName - templateVarsBase["SearchEnabled"] = api.Config.SearchEnabled +func (api *API) appGetDocuments(c *gin.Context) { + templateVars := api.getBaseTemplateVars("documents", c) + userID := templateVars["User"].(string) + qParams := bindQueryParams(c, 9) - return func(c *gin.Context) { - var userID string - if rUser, _ := c.Get("AuthorizedUser"); rUser != nil { - userID = rUser.(string) - } - - // Copy Base & Update - templateVars := gin.H{} - for k, v := range templateVarsBase { - templateVars[k] = v - } - templateVars["User"] = userID - - if routeName == "documents" { - qParams := bindQueryParams(c, 9) - - var query *string - if qParams.Search != nil && *qParams.Search != "" { - search := "%" + *qParams.Search + "%" - query = &search - } - - documents, err := api.DB.Queries.GetDocumentsWithStats(api.DB.Ctx, database.GetDocumentsWithStatsParams{ - UserID: userID, - Query: query, - Offset: (*qParams.Page - 1) * *qParams.Limit, - Limit: *qParams.Limit, - }) - if err != nil { - log.Error("[createAppResourcesRoute] GetDocumentsWithStats DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsWithStats DB Error: %v", err)) - return - } - - length, err := api.DB.Queries.GetDocumentsSize(api.DB.Ctx, query) - if err != nil { - log.Error("[createAppResourcesRoute] GetDocumentsSize DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsSize DB Error: %v", err)) - return - } - - if err = api.getDocumentsWordCount(documents); err != nil { - log.Error("[createAppResourcesRoute] Unable to Get Word Counts: ", err) - } - - totalPages := int64(math.Ceil(float64(length) / float64(*qParams.Limit))) - nextPage := *qParams.Page + 1 - previousPage := *qParams.Page - 1 - - if nextPage <= totalPages { - templateVars["NextPage"] = nextPage - } - - if previousPage >= 0 { - templateVars["PreviousPage"] = previousPage - } - - templateVars["PageLimit"] = *qParams.Limit - templateVars["Data"] = documents - } else if routeName == "document" { - var rDocID requestDocumentID - if err := c.ShouldBindUri(&rDocID); err != nil { - log.Error("[createAppResourcesRoute] Invalid URI Bind") - errorPage(c, http.StatusNotFound, "Invalid document.") - return - } - - document, err := api.DB.Queries.GetDocumentWithStats(api.DB.Ctx, database.GetDocumentWithStatsParams{ - UserID: userID, - DocumentID: rDocID.DocumentID, - }) - if err != nil { - log.Error("[createAppResourcesRoute] GetDocumentWithStats DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsWithStats DB Error: %v", err)) - return - } - - templateVars["Data"] = document - templateVars["TotalTimeLeftSeconds"] = int64((100.0 - document.Percentage) * float64(document.SecondsPerPercent)) - } else if routeName == "activity" { - qParams := bindQueryParams(c, 15) - - activityFilter := database.GetActivityParams{ - UserID: userID, - Offset: (*qParams.Page - 1) * *qParams.Limit, - Limit: *qParams.Limit, - } - - if qParams.Document != nil { - activityFilter.DocFilter = true - activityFilter.DocumentID = *qParams.Document - } - - activity, err := api.DB.Queries.GetActivity(api.DB.Ctx, activityFilter) - if err != nil { - log.Error("[createAppResourcesRoute] GetActivity DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetActivity DB Error: %v", err)) - return - } - - templateVars["Data"] = activity - } else if routeName == "home" { - start := time.Now() - read_graph_data, _ := api.DB.Queries.GetDailyReadStats(api.DB.Ctx, userID) - log.Info("GetDailyReadStats Performance: ", time.Since(start)) - - start = time.Now() - database_info, _ := api.DB.Queries.GetDatabaseInfo(api.DB.Ctx, userID) - log.Info("GetDatabaseInfo Performance: ", time.Since(start)) - - streaks, _ := api.DB.Queries.GetUserStreaks(api.DB.Ctx, userID) - wpm_leaderboard, _ := api.DB.Queries.GetWPMLeaderboard(api.DB.Ctx) - - templateVars["Data"] = gin.H{ - "Streaks": streaks, - "GraphData": read_graph_data, - "DatabaseInfo": database_info, - "WPMLeaderboard": wpm_leaderboard, - } - } else if routeName == "settings" { - user, err := api.DB.Queries.GetUser(api.DB.Ctx, userID) - if err != nil { - log.Error("[createAppResourcesRoute] GetUser DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetUser DB Error: %v", err)) - return - } - - devices, err := api.DB.Queries.GetDevices(api.DB.Ctx, userID) - if err != nil { - log.Error("[createAppResourcesRoute] GetDevices DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDevices DB Error: %v", err)) - return - } - - templateVars["Data"] = gin.H{ - "Settings": gin.H{ - "TimeOffset": *user.TimeOffset, - }, - "Devices": devices, - } - } else if routeName == "search" { - var sParams searchParams - c.BindQuery(&sParams) - - // Only Handle Query - if sParams.Query != nil && sParams.Source != nil { - // Search - searchResults, err := search.SearchBook(*sParams.Query, *sParams.Source) - if err != nil { - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("Search Error: %v", err)) - return - } - - templateVars["Data"] = searchResults - templateVars["Source"] = *sParams.Source - } else if sParams.Query != nil || sParams.Source != nil { - templateVars["SearchErrorMessage"] = "Invalid Query" - } - } else if routeName == "login" { - templateVars["RegistrationEnabled"] = api.Config.RegistrationEnabled - } - c.HTML(http.StatusOK, "page/"+routeName, templateVars) - } -} - -func (api *API) getDocumentCover(c *gin.Context) { - var rDoc requestDocumentID - if err := c.ShouldBindUri(&rDoc); err != nil { - log.Error("[getDocumentCover] Invalid URI Bind") - errorPage(c, http.StatusNotFound, "Invalid cover.") - return + var query *string + if qParams.Search != nil && *qParams.Search != "" { + search := "%" + *qParams.Search + "%" + query = &search } - // Validate Document Exists in DB - document, err := api.DB.Queries.GetDocument(api.DB.Ctx, rDoc.DocumentID) - if err != nil { - log.Error("[getDocumentCover] GetDocument DB Error:", err) - errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocument DB Error: %v", err)) - return - } - - // Handle Identified Document - if document.Coverfile != nil { - if *document.Coverfile == "UNKNOWN" { - c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) - return - } - - // Derive Path - safePath := filepath.Join(api.Config.DataPath, "covers", *document.Coverfile) - - // Validate File Exists - _, err = os.Stat(safePath) - if err != nil { - log.Error("[getDocumentCover] File Should But Doesn't Exist:", err) - c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) - return - } - - c.File(safePath) - return - } - - // --- Attempt Metadata --- - - var coverDir string = filepath.Join(api.Config.DataPath, "covers") - var coverFile string = "UNKNOWN" - - // Identify Documents & Save Covers - metadataResults, err := metadata.SearchMetadata(metadata.GBOOK, metadata.MetadataInfo{ - Title: document.Title, - Author: document.Author, + documents, err := api.DB.Queries.GetDocumentsWithStats(api.DB.Ctx, database.GetDocumentsWithStatsParams{ + UserID: userID, + Query: query, + Offset: (*qParams.Page - 1) * *qParams.Limit, + Limit: *qParams.Limit, }) - - if err == nil && len(metadataResults) > 0 && metadataResults[0].ID != nil { - firstResult := metadataResults[0] - - // Save Cover - fileName, err := metadata.CacheCover(*firstResult.ID, coverDir, document.ID, false) - if err == nil { - coverFile = *fileName - } - - // Store First Metadata Result - if _, err = api.DB.Queries.AddMetadata(api.DB.Ctx, database.AddMetadataParams{ - DocumentID: document.ID, - Title: firstResult.Title, - Author: firstResult.Author, - Description: firstResult.Description, - Gbid: firstResult.ID, - Olid: nil, - Isbn10: firstResult.ISBN10, - Isbn13: firstResult.ISBN13, - }); err != nil { - log.Error("[getDocumentCover] AddMetadata DB Error:", err) - } - } - - // Upsert Document - if _, err = api.DB.Queries.UpsertDocument(api.DB.Ctx, database.UpsertDocumentParams{ - ID: document.ID, - Coverfile: &coverFile, - }); err != nil { - log.Warn("[getDocumentCover] UpsertDocument DB Error:", err) - } - - // Return Unknown Cover - if coverFile == "UNKNOWN" { - c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) + if err != nil { + log.Error("[appGetDocuments] GetDocumentsWithStats DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsWithStats DB Error: %v", err)) return } - coverFilePath := filepath.Join(coverDir, coverFile) - c.File(coverFilePath) + length, err := api.DB.Queries.GetDocumentsSize(api.DB.Ctx, query) + if err != nil { + log.Error("[appGetDocuments] GetDocumentsSize DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsSize DB Error: %v", err)) + return + } + + if err = api.getDocumentsWordCount(documents); err != nil { + log.Error("[appGetDocuments] Unable to Get Word Counts: ", err) + } + + totalPages := int64(math.Ceil(float64(length) / float64(*qParams.Limit))) + nextPage := *qParams.Page + 1 + previousPage := *qParams.Page - 1 + + if nextPage <= totalPages { + templateVars["NextPage"] = nextPage + } + + if previousPage >= 0 { + templateVars["PreviousPage"] = previousPage + } + + templateVars["PageLimit"] = *qParams.Limit + templateVars["Data"] = documents + + c.HTML(http.StatusOK, "page/documents", templateVars) } -func (api *API) getDocumentProgress(c *gin.Context) { - rUser, _ := c.Get("AuthorizedUser") +func (api *API) appGetDocument(c *gin.Context) { + templateVars := api.getBaseTemplateVars("document", c) + userID := templateVars["User"].(string) - var rDoc requestDocumentID - if err := c.ShouldBindUri(&rDoc); err != nil { - log.Error("[getDocumentProgress] Invalid URI Bind") + var rDocID requestDocumentID + if err := c.ShouldBindUri(&rDocID); err != nil { + log.Error("[appGetDocument] Invalid URI Bind") errorPage(c, http.StatusNotFound, "Invalid document.") return } - progress, err := api.DB.Queries.GetProgress(api.DB.Ctx, database.GetProgressParams{ + document, err := api.DB.Queries.GetDocumentWithStats(api.DB.Ctx, database.GetDocumentWithStatsParams{ + UserID: userID, + DocumentID: rDocID.DocumentID, + }) + if err != nil { + log.Error("[appGetDocument] GetDocumentWithStats DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentsWithStats DB Error: %v", err)) + return + } + + templateVars["Data"] = document + templateVars["TotalTimeLeftSeconds"] = int64((100.0 - document.Percentage) * float64(document.SecondsPerPercent)) + + c.HTML(http.StatusOK, "page/document", templateVars) +} + +func (api *API) appGetProgress(c *gin.Context) { + templateVars := api.getBaseTemplateVars("progress", c) + userID := templateVars["User"].(string) + qParams := bindQueryParams(c, 15) + + progressFilter := database.GetProgressParams{ + UserID: userID, + Offset: (*qParams.Page - 1) * *qParams.Limit, + Limit: *qParams.Limit, + } + + if qParams.Document != nil { + progressFilter.DocFilter = true + progressFilter.DocumentID = *qParams.Document + } + + progress, err := api.DB.Queries.GetProgress(api.DB.Ctx, progressFilter) + if err != nil { + log.Error("[appGetProgress] GetProgress DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetActivity DB Error: %v", err)) + return + } + + templateVars["Data"] = progress + + c.HTML(http.StatusOK, "page/progress", templateVars) +} + +func (api *API) appGetActivity(c *gin.Context) { + templateVars := api.getBaseTemplateVars("activity", c) + userID := templateVars["User"].(string) + qParams := bindQueryParams(c, 15) + + activityFilter := database.GetActivityParams{ + UserID: userID, + Offset: (*qParams.Page - 1) * *qParams.Limit, + Limit: *qParams.Limit, + } + + if qParams.Document != nil { + activityFilter.DocFilter = true + activityFilter.DocumentID = *qParams.Document + } + + activity, err := api.DB.Queries.GetActivity(api.DB.Ctx, activityFilter) + if err != nil { + log.Error("[appGetActivity] GetActivity DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetActivity DB Error: %v", err)) + return + } + + templateVars["Data"] = activity + + c.HTML(http.StatusOK, "page/activity", templateVars) +} + +func (api *API) appGetHome(c *gin.Context) { + templateVars := api.getBaseTemplateVars("home", c) + userID := templateVars["User"].(string) + + start := time.Now() + graphData, _ := api.DB.Queries.GetDailyReadStats(api.DB.Ctx, userID) + log.Info("GetDailyReadStats Performance: ", time.Since(start)) + + start = time.Now() + databaseInfo, _ := api.DB.Queries.GetDatabaseInfo(api.DB.Ctx, userID) + log.Info("GetDatabaseInfo Performance: ", time.Since(start)) + + streaks, _ := api.DB.Queries.GetUserStreaks(api.DB.Ctx, userID) + WPMLeaderboard, _ := api.DB.Queries.GetWPMLeaderboard(api.DB.Ctx) + + templateVars["Data"] = gin.H{ + "Streaks": streaks, + "GraphData": graphData, + "DatabaseInfo": databaseInfo, + "WPMLeaderboard": WPMLeaderboard, + } + + c.HTML(http.StatusOK, "page/home", templateVars) +} + +func (api *API) appGetSettings(c *gin.Context) { + templateVars := api.getBaseTemplateVars("settings", c) + userID := templateVars["User"].(string) + + user, err := api.DB.Queries.GetUser(api.DB.Ctx, userID) + if err != nil { + log.Error("[appGetSettings] GetUser DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetUser DB Error: %v", err)) + return + } + + devices, err := api.DB.Queries.GetDevices(api.DB.Ctx, userID) + if err != nil { + log.Error("[appGetSettings] GetDevices DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDevices DB Error: %v", err)) + return + } + + templateVars["Data"] = gin.H{ + "TimeOffset": *user.TimeOffset, + "Devices": devices, + } + + c.HTML(http.StatusOK, "page/settings", templateVars) +} + +func (api *API) appGetSearch(c *gin.Context) { + templateVars := api.getBaseTemplateVars("search", c) + + var sParams searchParams + c.BindQuery(&sParams) + + // Only Handle Query + if sParams.Query != nil && sParams.Source != nil { + // Search + searchResults, err := search.SearchBook(*sParams.Query, *sParams.Source) + if err != nil { + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("Search Error: %v", err)) + return + } + + templateVars["Data"] = searchResults + templateVars["Source"] = *sParams.Source + } else if sParams.Query != nil || sParams.Source != nil { + templateVars["SearchErrorMessage"] = "Invalid Query" + } + + c.HTML(http.StatusOK, "page/search", templateVars) +} + +func (api *API) appGetLogin(c *gin.Context) { + templateVars := api.getBaseTemplateVars("login", c) + templateVars["RegistrationEnabled"] = api.Config.RegistrationEnabled + c.HTML(http.StatusOK, "page/login", templateVars) +} + +func (api *API) appGetRegister(c *gin.Context) { + if !api.Config.RegistrationEnabled { + c.Redirect(http.StatusFound, "/login") + return + } + + templateVars := api.getBaseTemplateVars("login", c) + templateVars["RegistrationEnabled"] = api.Config.RegistrationEnabled + templateVars["Register"] = true + c.HTML(http.StatusOK, "page/login", templateVars) +} + +func (api *API) appGetDocumentProgress(c *gin.Context) { + rUser, _ := c.Get("AuthorizedUser") + + var rDoc requestDocumentID + if err := c.ShouldBindUri(&rDoc); err != nil { + log.Error("[appGetDocumentProgress] Invalid URI Bind") + errorPage(c, http.StatusNotFound, "Invalid document.") + return + } + + progress, err := api.DB.Queries.GetDocumentProgress(api.DB.Ctx, database.GetDocumentProgressParams{ DocumentID: rDoc.DocumentID, UserID: rUser.(string), }) if err != nil && err != sql.ErrNoRows { - log.Error("[getDocumentProgress] UpsertDocument DB Error:", err) + log.Error("[appGetDocumentProgress] UpsertDocument DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("UpsertDocument DB Error: %v", err)) return } @@ -382,7 +345,7 @@ func (api *API) getDocumentProgress(c *gin.Context) { DocumentID: rDoc.DocumentID, }) if err != nil { - log.Error("[getDocumentProgress] GetDocumentWithStats DB Error:", err) + log.Error("[appGetDocumentProgress] GetDocumentWithStats DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentWithStats DB Error: %v", err)) return } @@ -397,13 +360,13 @@ func (api *API) getDocumentProgress(c *gin.Context) { }) } -func (api *API) getDevices(c *gin.Context) { +func (api *API) appGetDevices(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") devices, err := api.DB.Queries.GetDevices(api.DB.Ctx, rUser.(string)) if err != nil && err != sql.ErrNoRows { - log.Error("[getDevices] GetDevices DB Error:", err) + log.Error("[appGetDevices] GetDevices DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDevices DB Error: %v", err)) return } @@ -411,10 +374,10 @@ func (api *API) getDevices(c *gin.Context) { c.JSON(http.StatusOK, devices) } -func (api *API) uploadNewDocument(c *gin.Context) { +func (api *API) appUploadNewDocument(c *gin.Context) { var rDocUpload requestDocumentUpload if err := c.ShouldBind(&rDocUpload); err != nil { - log.Error("[uploadNewDocument] Invalid Form Bind") + log.Error("[appUploadNewDocument] Invalid Form Bind") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } @@ -427,14 +390,14 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Validate Type & Derive Extension on MIME uploadedFile, err := rDocUpload.DocumentFile.Open() if err != nil { - log.Error("[uploadNewDocument] File Error: ", err) + log.Error("[appUploadNewDocument] File Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to open file.") return } fileMime, err := mimetype.DetectReader(uploadedFile) if err != nil { - log.Error("[uploadNewDocument] MIME Error") + log.Error("[appUploadNewDocument] MIME Error") errorPage(c, http.StatusInternalServerError, "Unable to detect filetype.") return } @@ -442,7 +405,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Validate Extension if !slices.Contains([]string{".epub"}, fileExtension) { - log.Error("[uploadNewDocument] Invalid FileType: ", fileExtension) + log.Error("[appUploadNewDocument] Invalid FileType: ", fileExtension) errorPage(c, http.StatusBadRequest, "Invalid filetype.") return } @@ -450,7 +413,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Create Temp File tempFile, err := os.CreateTemp("", "book") if err != nil { - log.Warn("[uploadNewDocument] Temp File Create Error: ", err) + log.Warn("[appUploadNewDocument] Temp File Create Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to create temp file.") return } @@ -460,7 +423,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Save Temp err = c.SaveUploadedFile(rDocUpload.DocumentFile, tempFile.Name()) if err != nil { - log.Error("[uploadNewDocument] File Error: ", err) + log.Error("[appUploadNewDocument] File Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to save file.") return } @@ -468,7 +431,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Get Metadata metadataInfo, err := metadata.GetMetadata(tempFile.Name()) if err != nil { - log.Warn("[uploadNewDocument] GetMetadata Error: ", err) + log.Warn("[appUploadNewDocument] GetMetadata Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to acquire file metadata.") return } @@ -476,7 +439,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Calculate Partial MD5 ID partialMD5, err := utils.CalculatePartialMD5(tempFile.Name()) if err != nil { - log.Warn("[uploadNewDocument] Partial MD5 Error: ", err) + log.Warn("[appUploadNewDocument] Partial MD5 Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to calculate partial MD5.") return } @@ -491,7 +454,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Calculate Actual MD5 fileHash, err := getFileMD5(tempFile.Name()) if err != nil { - log.Error("[uploadNewDocument] MD5 Hash Failure:", err) + log.Error("[appUploadNewDocument] MD5 Hash Failure:", err) errorPage(c, http.StatusInternalServerError, "Unable to calculate MD5.") return } @@ -499,7 +462,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Get Word Count wordCount, err := metadata.GetWordCount(tempFile.Name()) if err != nil { - log.Error("[uploadNewDocument] Word Count Failure:", err) + log.Error("[appUploadNewDocument] Word Count Failure:", err) errorPage(c, http.StatusInternalServerError, "Unable to calculate word count.") return } @@ -528,7 +491,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { safePath := filepath.Join(api.Config.DataPath, "documents", fileName) destFile, err := os.Create(safePath) if err != nil { - log.Error("[uploadNewDocument] Dest File Error:", err) + log.Error("[appUploadNewDocument] Dest File Error:", err) errorPage(c, http.StatusInternalServerError, "Unable to save file.") return } @@ -536,7 +499,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { // Copy File if _, err = io.Copy(destFile, tempFile); err != nil { - log.Error("[uploadNewDocument] Copy Temp File Error:", err) + log.Error("[appUploadNewDocument] Copy Temp File Error:", err) errorPage(c, http.StatusInternalServerError, "Unable to save file.") return } @@ -551,7 +514,7 @@ func (api *API) uploadNewDocument(c *gin.Context) { Md5: fileHash, Filepath: &fileName, }); err != nil { - log.Error("[uploadNewDocument] UpsertDocument DB Error:", err) + log.Error("[appUploadNewDocument] UpsertDocument DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("UpsertDocument DB Error: %v", err)) return } @@ -559,17 +522,17 @@ func (api *API) uploadNewDocument(c *gin.Context) { c.Redirect(http.StatusFound, fmt.Sprintf("./documents/%s", partialMD5)) } -func (api *API) editDocument(c *gin.Context) { +func (api *API) appEditDocument(c *gin.Context) { var rDocID requestDocumentID if err := c.ShouldBindUri(&rDocID); err != nil { - log.Error("[createAppResourcesRoute] Invalid URI Bind") + log.Error("[appEditDocument] Invalid URI Bind") errorPage(c, http.StatusNotFound, "Invalid document.") return } var rDocEdit requestDocumentEdit if err := c.ShouldBind(&rDocEdit); err != nil { - log.Error("[createAppResourcesRoute] Invalid Form Bind") + log.Error("[appEditDocument] Invalid Form Bind") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } @@ -583,7 +546,7 @@ func (api *API) editDocument(c *gin.Context) { rDocEdit.RemoveCover == nil && rDocEdit.CoverGBID == nil && rDocEdit.CoverFile == nil { - log.Error("[createAppResourcesRoute] Missing Form Values") + log.Error("[appEditDocument] Missing Form Values") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } @@ -597,14 +560,14 @@ func (api *API) editDocument(c *gin.Context) { // Validate Type & Derive Extension on MIME uploadedFile, err := rDocEdit.CoverFile.Open() if err != nil { - log.Error("[createAppResourcesRoute] File Error") + log.Error("[appEditDocument] File Error") errorPage(c, http.StatusInternalServerError, "Unable to open file.") return } fileMime, err := mimetype.DetectReader(uploadedFile) if err != nil { - log.Error("[createAppResourcesRoute] MIME Error") + log.Error("[appEditDocument] MIME Error") errorPage(c, http.StatusInternalServerError, "Unable to detect filetype.") return } @@ -612,7 +575,7 @@ func (api *API) editDocument(c *gin.Context) { // Validate Extension if !slices.Contains([]string{".jpg", ".png"}, fileExtension) { - log.Error("[uploadDocumentFile] Invalid FileType: ", fileExtension) + log.Error("[appEditDocument] Invalid FileType: ", fileExtension) errorPage(c, http.StatusBadRequest, "Invalid filetype.") return } @@ -624,7 +587,7 @@ func (api *API) editDocument(c *gin.Context) { // Save err = c.SaveUploadedFile(rDocEdit.CoverFile, safePath) if err != nil { - log.Error("[createAppResourcesRoute] File Error: ", err) + log.Error("[appEditDocument] File Error: ", err) errorPage(c, http.StatusInternalServerError, "Unable to save file.") return } @@ -648,7 +611,7 @@ func (api *API) editDocument(c *gin.Context) { Isbn13: api.sanitizeInput(rDocEdit.ISBN13), Coverfile: coverFileName, }); err != nil { - log.Error("[createAppResourcesRoute] UpsertDocument DB Error:", err) + log.Error("[appEditDocument] UpsertDocument DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("UpsertDocument DB Error: %v", err)) return } @@ -657,21 +620,21 @@ func (api *API) editDocument(c *gin.Context) { return } -func (api *API) deleteDocument(c *gin.Context) { +func (api *API) appDeleteDocument(c *gin.Context) { var rDocID requestDocumentID if err := c.ShouldBindUri(&rDocID); err != nil { - log.Error("[deleteDocument] Invalid URI Bind") + log.Error("[appDeleteDocument] Invalid URI Bind") errorPage(c, http.StatusNotFound, "Invalid document.") return } changed, err := api.DB.Queries.DeleteDocument(api.DB.Ctx, rDocID.DocumentID) if err != nil { - log.Error("[deleteDocument] DeleteDocument DB Error") + log.Error("[appDeleteDocument] DeleteDocument DB Error") errorPage(c, http.StatusInternalServerError, fmt.Sprintf("DeleteDocument DB Error: %v", err)) return } if changed == 0 { - log.Error("[deleteDocument] DeleteDocument DB Error") + log.Error("[appDeleteDocument] DeleteDocument DB Error") errorPage(c, http.StatusNotFound, "Invalid document.") return } @@ -679,19 +642,17 @@ func (api *API) deleteDocument(c *gin.Context) { c.Redirect(http.StatusFound, "../") } -func (api *API) identifyDocument(c *gin.Context) { - rUser, _ := c.Get("AuthorizedUser") - +func (api *API) appIdentifyDocument(c *gin.Context) { var rDocID requestDocumentID if err := c.ShouldBindUri(&rDocID); err != nil { - log.Error("[identifyDocument] Invalid URI Bind") + log.Error("[appIdentifyDocument] Invalid URI Bind") errorPage(c, http.StatusNotFound, "Invalid document.") return } var rDocIdentify requestDocumentIdentify if err := c.ShouldBind(&rDocIdentify); err != nil { - log.Error("[identifyDocument] Invalid Form Bind") + log.Error("[appIdentifyDocument] Invalid Form Bind") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } @@ -709,15 +670,14 @@ func (api *API) identifyDocument(c *gin.Context) { // Validate Values if rDocIdentify.ISBN == nil && rDocIdentify.Title == nil && rDocIdentify.Author == nil { - log.Error("[identifyDocument] Invalid Form") + log.Error("[appIdentifyDocument] Invalid Form") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } - // Template Variables - templateVars := gin.H{ - "SearchEnabled": api.Config.SearchEnabled, - } + // Get Template Variables + templateVars := api.getBaseTemplateVars("document", c) + userID := templateVars["User"].(string) // Get Metadata metadataResults, err := metadata.SearchMetadata(metadata.GBOOK, metadata.MetadataInfo{ @@ -740,21 +700,21 @@ func (api *API) identifyDocument(c *gin.Context) { Isbn10: firstResult.ISBN10, Isbn13: firstResult.ISBN13, }); err != nil { - log.Error("[identifyDocument] AddMetadata DB Error:", err) + log.Error("[appIdentifyDocument] AddMetadata DB Error:", err) } templateVars["Metadata"] = firstResult } else { - log.Warn("[identifyDocument] Metadata Error") + log.Warn("[appIdentifyDocument] Metadata Error") templateVars["MetadataError"] = "No Metadata Found" } document, err := api.DB.Queries.GetDocumentWithStats(api.DB.Ctx, database.GetDocumentWithStatsParams{ - UserID: rUser.(string), + UserID: userID, DocumentID: rDocID.DocumentID, }) if err != nil { - log.Error("[identifyDocument] GetDocumentWithStats DB Error:", err) + log.Error("[appIdentifyDocument] GetDocumentWithStats DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocumentWithStats DB Error: %v", err)) return } @@ -765,24 +725,16 @@ func (api *API) identifyDocument(c *gin.Context) { c.HTML(http.StatusOK, "page/document", templateVars) } -func (api *API) saveNewDocument(c *gin.Context) { +func (api *API) appSaveNewDocument(c *gin.Context) { var rDocAdd requestDocumentAdd if err := c.ShouldBind(&rDocAdd); err != nil { - log.Error("[saveNewDocument] Invalid Form Bind") + log.Error("[appSaveNewDocument] Invalid Form Bind") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } // Render Initial Template - var userID string - if rUser, _ := c.Get("AuthorizedUser"); rUser != nil { - userID = rUser.(string) - } - templateVars := gin.H{ - "RouteName": "search", - "SearchEnabled": api.Config.SearchEnabled, - "User": userID, - } + templateVars := api.getBaseTemplateVars("search", c) c.HTML(http.StatusOK, "page/search", templateVars) // Create Streamer @@ -812,7 +764,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Save Book tempFilePath, err := search.SaveBook(rDocAdd.ID, rDocAdd.Source) if err != nil { - log.Warn("[saveNewDocument] Temp File Error: ", err) + log.Warn("[appSaveNewDocument] Temp File Error: ", err) sendDownloadMessage("Unable to download file", gin.H{"Error": true}) return } @@ -823,7 +775,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Calculate Partial MD5 ID partialMD5, err := utils.CalculatePartialMD5(tempFilePath) if err != nil { - log.Warn("[saveNewDocument] Partial MD5 Error: ", err) + log.Warn("[appSaveNewDocument] Partial MD5 Error: ", err) sendDownloadMessage("Unable to calculate partial MD5", gin.H{"Error": true}) } @@ -857,7 +809,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Open Source File sourceFile, err := os.Open(tempFilePath) if err != nil { - log.Error("[saveNewDocument] Source File Error:", err) + log.Error("[appSaveNewDocument] Source File Error:", err) sendDownloadMessage("Unable to open file", gin.H{"Error": true}) return } @@ -868,7 +820,7 @@ func (api *API) saveNewDocument(c *gin.Context) { safePath := filepath.Join(api.Config.DataPath, "documents", fileName) destFile, err := os.Create(safePath) if err != nil { - log.Error("[saveNewDocument] Dest File Error:", err) + log.Error("[appSaveNewDocument] Dest File Error:", err) sendDownloadMessage("Unable to create file", gin.H{"Error": true}) return } @@ -876,7 +828,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Copy File if _, err = io.Copy(destFile, sourceFile); err != nil { - log.Error("[saveNewDocument] Copy Temp File Error:", err) + log.Error("[appSaveNewDocument] Copy Temp File Error:", err) sendDownloadMessage("Unable to save file", gin.H{"Error": true}) return } @@ -887,7 +839,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Get MD5 Hash fileHash, err := getFileMD5(safePath) if err != nil { - log.Error("[saveNewDocument] Hash Failure:", err) + log.Error("[appSaveNewDocument] Hash Failure:", err) sendDownloadMessage("Unable to calculate MD5", gin.H{"Error": true}) return } @@ -898,7 +850,7 @@ func (api *API) saveNewDocument(c *gin.Context) { // Get Word Count wordCount, err := metadata.GetWordCount(safePath) if err != nil { - log.Error("[saveNewDocument] Word Count Failure:", err) + log.Error("[appSaveNewDocument] Word Count Failure:", err) sendDownloadMessage("Unable to calculate word count", gin.H{"Error": true}) return } @@ -915,7 +867,7 @@ func (api *API) saveNewDocument(c *gin.Context) { Filepath: &fileName, Words: &wordCount, }); err != nil { - log.Error("[saveNewDocument] UpsertDocument DB Error:", err) + log.Error("[appSaveNewDocument] UpsertDocument DB Error:", err) sendDownloadMessage("Unable to save to database", gin.H{"Error": true}) return } @@ -928,34 +880,32 @@ func (api *API) saveNewDocument(c *gin.Context) { }) } -func (api *API) editSettings(c *gin.Context) { - rUser, _ := c.Get("AuthorizedUser") - +func (api *API) appEditSettings(c *gin.Context) { var rUserSettings requestSettingsEdit if err := c.ShouldBind(&rUserSettings); err != nil { - log.Error("[editSettings] Invalid Form Bind") + log.Error("[appEditSettings] Invalid Form Bind") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } // Validate Something Exists if rUserSettings.Password == nil && rUserSettings.NewPassword == nil && rUserSettings.TimeOffset == nil { - log.Error("[editSettings] Missing Form Values") + log.Error("[appEditSettings] Missing Form Values") errorPage(c, http.StatusBadRequest, "Invalid or missing form values.") return } - templateVars := gin.H{ - "User": rUser, - } + templateVars := api.getBaseTemplateVars("settings", c) + userID := templateVars["User"].(string) + newUserSettings := database.UpdateUserParams{ - UserID: rUser.(string), + UserID: userID, } // Set New Password if rUserSettings.Password != nil && rUserSettings.NewPassword != nil { password := fmt.Sprintf("%x", md5.Sum([]byte(*rUserSettings.Password))) - authorized := api.authorizeCredentials(rUser.(string), password) + authorized := api.authorizeCredentials(userID, password) if authorized == true { password := fmt.Sprintf("%x", md5.Sum([]byte(*rUserSettings.NewPassword))) hashedPassword, err := argon2.CreateHash(password, argon2.DefaultParams) @@ -979,38 +929,39 @@ func (api *API) editSettings(c *gin.Context) { // Update User _, err := api.DB.Queries.UpdateUser(api.DB.Ctx, newUserSettings) if err != nil { - log.Error("[editSettings] UpdateUser DB Error:", err) + log.Error("[appEditSettings] UpdateUser DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("UpdateUser DB Error: %v", err)) return } // Get User - user, err := api.DB.Queries.GetUser(api.DB.Ctx, rUser.(string)) + user, err := api.DB.Queries.GetUser(api.DB.Ctx, userID) if err != nil { - log.Error("[editSettings] GetUser DB Error:", err) + log.Error("[appEditSettings] GetUser DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetUser DB Error: %v", err)) return } // Get Devices - devices, err := api.DB.Queries.GetDevices(api.DB.Ctx, rUser.(string)) + devices, err := api.DB.Queries.GetDevices(api.DB.Ctx, userID) if err != nil { - log.Error("[editSettings] GetDevices DB Error:", err) + log.Error("[appEditSettings] GetDevices DB Error:", err) errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDevices DB Error: %v", err)) return } templateVars["Data"] = gin.H{ - "Settings": gin.H{ - "TimeOffset": *user.TimeOffset, - }, - "Devices": devices, - "SearchEnabled": api.Config.SearchEnabled, + "TimeOffset": *user.TimeOffset, + "Devices": devices, } c.HTML(http.StatusOK, "page/settings", templateVars) } +func (api *API) appDemoModeError(c *gin.Context) { + errorPage(c, http.StatusUnauthorized, "Not Allowed in Demo Mode") +} + func (api *API) getDocumentsWordCount(documents []database.GetDocumentsWithStatsRow) error { // Do Transaction tx, err := api.DB.DB.Begin() @@ -1050,6 +1001,23 @@ func (api *API) getDocumentsWordCount(documents []database.GetDocumentsWithStats return nil } +func (api *API) getBaseTemplateVars(routeName string, c *gin.Context) gin.H { + var userID string + if rUser, _ := c.Get("AuthorizedUser"); rUser != nil { + userID = rUser.(string) + } + + return gin.H{ + "User": userID, + "RouteName": routeName, + "Config": gin.H{ + "Version": api.Config.Version, + "SearchEnabled": api.Config.SearchEnabled, + "RegistrationEnabled": api.Config.RegistrationEnabled, + }, + } +} + func bindQueryParams(c *gin.Context, defaultLimit int64) queryParams { var qParams queryParams c.BindQuery(&qParams) diff --git a/api/auth.go b/api/auth.go index bafcfca..06681cb 100644 --- a/api/auth.go +++ b/api/auth.go @@ -115,35 +115,31 @@ func (api *API) authWebAppMiddleware(c *gin.Context) { return } -func (api *API) authFormLogin(c *gin.Context) { +func (api *API) appAuthFormLogin(c *gin.Context) { + templateVars := api.getBaseTemplateVars("login", c) + username := strings.TrimSpace(c.PostForm("username")) rawPassword := strings.TrimSpace(c.PostForm("password")) if username == "" || rawPassword == "" { - c.HTML(http.StatusUnauthorized, "page/login", gin.H{ - "RegistrationEnabled": api.Config.RegistrationEnabled, - "Error": "Invalid Credentials", - }) + templateVars["Error"] = "Invalid Credentials" + c.HTML(http.StatusUnauthorized, "page/login", templateVars) return } // MD5 - KOSync Compatiblity password := fmt.Sprintf("%x", md5.Sum([]byte(rawPassword))) if authorized := api.authorizeCredentials(username, password); authorized != true { - c.HTML(http.StatusUnauthorized, "page/login", gin.H{ - "RegistrationEnabled": api.Config.RegistrationEnabled, - "Error": "Invalid Credentials", - }) + templateVars["Error"] = "Invalid Credentials" + c.HTML(http.StatusUnauthorized, "page/login", templateVars) return } // Set Session session := sessions.Default(c) if err := setSession(session, username); err != nil { - c.HTML(http.StatusUnauthorized, "page/login", gin.H{ - "RegistrationEnabled": api.Config.RegistrationEnabled, - "Error": "Unknown Error", - }) + templateVars["Error"] = "Invalid Credentials" + c.HTML(http.StatusUnauthorized, "page/login", templateVars) return } @@ -151,30 +147,29 @@ func (api *API) authFormLogin(c *gin.Context) { c.Redirect(http.StatusFound, "/") } -func (api *API) authFormRegister(c *gin.Context) { +func (api *API) appAuthFormRegister(c *gin.Context) { if !api.Config.RegistrationEnabled { errorPage(c, http.StatusUnauthorized, "Nice try. Registration is disabled.") return } + templateVars := api.getBaseTemplateVars("login", c) + templateVars["Register"] = true + username := strings.TrimSpace(c.PostForm("username")) rawPassword := strings.TrimSpace(c.PostForm("password")) if username == "" || rawPassword == "" { - c.HTML(http.StatusBadRequest, "page/login", gin.H{ - "Register": true, - "Error": "Registration Disabled or User Already Exists", - }) + templateVars["Error"] = "Invalid User or Password" + c.HTML(http.StatusBadRequest, "page/login", templateVars) return } password := fmt.Sprintf("%x", md5.Sum([]byte(rawPassword))) hashedPassword, err := argon2.CreateHash(password, argon2.DefaultParams) if err != nil { - c.HTML(http.StatusBadRequest, "page/login", gin.H{ - "Register": true, - "Error": "Registration Disabled or User Already Exists", - }) + templateVars["Error"] = "Registration Disabled or User Already Exists" + c.HTML(http.StatusBadRequest, "page/login", templateVars) return } @@ -185,19 +180,17 @@ func (api *API) authFormRegister(c *gin.Context) { // SQL Error if err != nil { - c.HTML(http.StatusBadRequest, "page/login", gin.H{ - "Register": true, - "Error": "Registration Disabled or User Already Exists", - }) + log.Error("[appAuthFormRegister] CreateUser DB Error:", err) + templateVars["Error"] = "Registration Disabled or User Already Exists" + c.HTML(http.StatusBadRequest, "page/login", templateVars) return } // User Already Exists if rows == 0 { - c.HTML(http.StatusBadRequest, "page/login", gin.H{ - "Register": true, - "Error": "Registration Disabled or User Already Exists", - }) + log.Warn("[appAuthFormRegister] User Already Exists:", username) + templateVars["Error"] = "Registration Disabled or User Already Exists" + c.HTML(http.StatusBadRequest, "page/login", templateVars) return } @@ -212,21 +205,13 @@ func (api *API) authFormRegister(c *gin.Context) { c.Redirect(http.StatusFound, "/") } -func (api *API) authLogout(c *gin.Context) { +func (api *API) appAuthLogout(c *gin.Context) { session := sessions.Default(c) session.Clear() session.Save() c.Redirect(http.StatusFound, "/login") } -func (api *API) demoModeAppError(c *gin.Context) { - errorPage(c, http.StatusUnauthorized, "Not Allowed in Demo Mode") -} - -func (api *API) demoModeJSONError(c *gin.Context) { - c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not Allowed in Demo Mode"}) -} - func getSession(session sessions.Session) (user string, ok bool) { // Check Session authorizedUser := session.Get("authorizedUser") diff --git a/api/common.go b/api/common.go new file mode 100644 index 0000000..2a0a12f --- /dev/null +++ b/api/common.go @@ -0,0 +1,140 @@ +package api + +import ( + "fmt" + "github.com/gin-gonic/gin" + log "github.com/sirupsen/logrus" + "net/http" + "os" + "path/filepath" + "reichard.io/bbank/database" + "reichard.io/bbank/metadata" +) + +func (api *API) downloadDocument(c *gin.Context) { + var rDoc requestDocumentID + if err := c.ShouldBindUri(&rDoc); err != nil { + log.Error("[downloadDocument] Invalid URI Bind") + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) + return + } + + // Get Document + document, err := api.DB.Queries.GetDocument(api.DB.Ctx, rDoc.DocumentID) + if err != nil { + log.Error("[downloadDocument] GetDocument DB Error:", err) + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Document"}) + return + } + + if document.Filepath == nil { + log.Error("[downloadDocument] Document Doesn't Have File:", rDoc.DocumentID) + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Document Doesn't Exist"}) + return + } + + // Derive Storage Location + filePath := filepath.Join(api.Config.DataPath, "documents", *document.Filepath) + + // Validate File Exists + _, err = os.Stat(filePath) + if os.IsNotExist(err) { + log.Error("[downloadDocument] File Doesn't Exist:", rDoc.DocumentID) + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Document Doesn't Exists"}) + return + } + + // Force Download (Security) + c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(*document.Filepath))) + c.File(filePath) +} + +func (api *API) getDocumentCover(c *gin.Context) { + var rDoc requestDocumentID + if err := c.ShouldBindUri(&rDoc); err != nil { + log.Error("[getDocumentCover] Invalid URI Bind") + errorPage(c, http.StatusNotFound, "Invalid cover.") + return + } + + // Validate Document Exists in DB + document, err := api.DB.Queries.GetDocument(api.DB.Ctx, rDoc.DocumentID) + if err != nil { + log.Error("[getDocumentCover] GetDocument DB Error:", err) + errorPage(c, http.StatusInternalServerError, fmt.Sprintf("GetDocument DB Error: %v", err)) + return + } + + // Handle Identified Document + if document.Coverfile != nil { + if *document.Coverfile == "UNKNOWN" { + c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) + return + } + + // Derive Path + safePath := filepath.Join(api.Config.DataPath, "covers", *document.Coverfile) + + // Validate File Exists + _, err = os.Stat(safePath) + if err != nil { + log.Error("[getDocumentCover] File Should But Doesn't Exist:", err) + c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) + return + } + + c.File(safePath) + return + } + + // Attempt Metadata + var coverDir string = filepath.Join(api.Config.DataPath, "covers") + var coverFile string = "UNKNOWN" + + // Identify Documents & Save Covers + metadataResults, err := metadata.SearchMetadata(metadata.GBOOK, metadata.MetadataInfo{ + Title: document.Title, + Author: document.Author, + }) + + if err == nil && len(metadataResults) > 0 && metadataResults[0].ID != nil { + firstResult := metadataResults[0] + + // Save Cover + fileName, err := metadata.CacheCover(*firstResult.ID, coverDir, document.ID, false) + if err == nil { + coverFile = *fileName + } + + // Store First Metadata Result + if _, err = api.DB.Queries.AddMetadata(api.DB.Ctx, database.AddMetadataParams{ + DocumentID: document.ID, + Title: firstResult.Title, + Author: firstResult.Author, + Description: firstResult.Description, + Gbid: firstResult.ID, + Olid: nil, + Isbn10: firstResult.ISBN10, + Isbn13: firstResult.ISBN13, + }); err != nil { + log.Error("[getDocumentCover] AddMetadata DB Error:", err) + } + } + + // Upsert Document + if _, err = api.DB.Queries.UpsertDocument(api.DB.Ctx, database.UpsertDocumentParams{ + ID: document.ID, + Coverfile: &coverFile, + }); err != nil { + log.Warn("[getDocumentCover] UpsertDocument DB Error:", err) + } + + // Return Unknown Cover + if coverFile == "UNKNOWN" { + c.FileFromFS("assets/images/no-cover.jpg", http.FS(api.Assets)) + return + } + + coverFilePath := filepath.Join(coverDir, coverFile) + c.File(coverFilePath) +} diff --git a/api/ko-routes.go b/api/ko-routes.go index 886e28e..bf940a2 100644 --- a/api/ko-routes.go +++ b/api/ko-routes.go @@ -75,13 +75,13 @@ type requestDocumentID struct { DocumentID string `uri:"document" binding:"required"` } -func (api *API) authorizeUser(c *gin.Context) { +func (api *API) koAuthorizeUser(c *gin.Context) { c.JSON(200, gin.H{ "authorized": "OK", }) } -func (api *API) createUser(c *gin.Context) { +func (api *API) koCreateUser(c *gin.Context) { if !api.Config.RegistrationEnabled { c.AbortWithStatus(http.StatusConflict) return @@ -89,20 +89,20 @@ func (api *API) createUser(c *gin.Context) { var rUser requestUser if err := c.ShouldBindJSON(&rUser); err != nil { - log.Error("[createUser] Invalid JSON Bind") + log.Error("[koCreateUser] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid User Data"}) return } if rUser.Username == "" || rUser.Password == "" { - log.Error("[createUser] Invalid User - Empty Username or Password") + log.Error("[koCreateUser] Invalid User - Empty Username or Password") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid User Data"}) return } hashedPassword, err := argon2.CreateHash(rUser.Password, argon2.DefaultParams) if err != nil { - log.Error("[createUser] Argon2 Hash Failure:", err) + log.Error("[koCreateUser] Argon2 Hash Failure:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -112,7 +112,7 @@ func (api *API) createUser(c *gin.Context) { Pass: &hashedPassword, }) if err != nil { - log.Error("[createUser] CreateUser DB Error:", err) + log.Error("[koCreateUser] CreateUser DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid User Data"}) return } @@ -128,12 +128,12 @@ func (api *API) createUser(c *gin.Context) { }) } -func (api *API) setProgress(c *gin.Context) { +func (api *API) koSetProgress(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") var rPosition requestPosition if err := c.ShouldBindJSON(&rPosition); err != nil { - log.Error("[setProgress] Invalid JSON Bind") + log.Error("[koSetProgress] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Progress Data"}) return } @@ -145,14 +145,14 @@ func (api *API) setProgress(c *gin.Context) { DeviceName: rPosition.Device, LastSynced: time.Now().UTC().Format(time.RFC3339), }); err != nil { - log.Error("[setProgress] UpsertDevice DB Error:", err) + log.Error("[koSetProgress] UpsertDevice DB Error:", err) } // Upsert Document if _, err := api.DB.Queries.UpsertDocument(api.DB.Ctx, database.UpsertDocumentParams{ ID: rPosition.DocumentID, }); err != nil { - log.Error("[setProgress] UpsertDocument DB Error:", err) + log.Error("[koSetProgress] UpsertDocument DB Error:", err) } // Create or Replace Progress @@ -164,17 +164,17 @@ func (api *API) setProgress(c *gin.Context) { Progress: rPosition.Progress, }) if err != nil { - log.Error("[setProgress] UpdateProgress DB Error:", err) + log.Error("[koSetProgress] UpdateProgress DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } // Update Statistic - log.Info("[setProgress] UpdateDocumentUserStatistic Running...") + log.Info("[koSetProgress] UpdateDocumentUserStatistic Running...") if err := api.DB.UpdateDocumentUserStatistic(rPosition.DocumentID, rUser.(string)); err != nil { - log.Error("[setProgress] UpdateDocumentUserStatistic Error:", err) + log.Error("[koSetProgress] UpdateDocumentUserStatistic Error:", err) } - log.Info("[setProgress] UpdateDocumentUserStatistic Complete") + log.Info("[koSetProgress] UpdateDocumentUserStatistic Complete") c.JSON(http.StatusOK, gin.H{ "document": progress.DocumentID, @@ -182,17 +182,17 @@ func (api *API) setProgress(c *gin.Context) { }) } -func (api *API) getProgress(c *gin.Context) { +func (api *API) koGetProgress(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") var rDocID requestDocumentID if err := c.ShouldBindUri(&rDocID); err != nil { - log.Error("[getProgress] Invalid URI Bind") + log.Error("[koGetProgress] Invalid URI Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } - progress, err := api.DB.Queries.GetProgress(api.DB.Ctx, database.GetProgressParams{ + progress, err := api.DB.Queries.GetDocumentProgress(api.DB.Ctx, database.GetDocumentProgressParams{ DocumentID: rDocID.DocumentID, UserID: rUser.(string), }) @@ -202,7 +202,7 @@ func (api *API) getProgress(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) return } else if err != nil { - log.Error("[getProgress] GetProgress DB Error:", err) + log.Error("[koGetProgress] GetDocumentProgress DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Document"}) return } @@ -216,12 +216,12 @@ func (api *API) getProgress(c *gin.Context) { }) } -func (api *API) addActivities(c *gin.Context) { +func (api *API) koAddActivities(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") var rActivity requestActivity if err := c.ShouldBindJSON(&rActivity); err != nil { - log.Error("[addActivity] Invalid JSON Bind") + log.Error("[koAddActivities] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Activity"}) return } @@ -229,7 +229,7 @@ func (api *API) addActivities(c *gin.Context) { // Do Transaction tx, err := api.DB.DB.Begin() if err != nil { - log.Error("[addActivities] Transaction Begin DB Error:", err) + log.Error("[koAddActivities] Transaction Begin DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -250,7 +250,7 @@ func (api *API) addActivities(c *gin.Context) { if _, err := qtx.UpsertDocument(api.DB.Ctx, database.UpsertDocumentParams{ ID: doc, }); err != nil { - log.Error("[addActivities] UpsertDocument DB Error:", err) + log.Error("[koAddActivities] UpsertDocument DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Document"}) return } @@ -263,7 +263,7 @@ func (api *API) addActivities(c *gin.Context) { DeviceName: rActivity.Device, LastSynced: time.Now().UTC().Format(time.RFC3339), }); err != nil { - log.Error("[addActivities] UpsertDevice DB Error:", err) + log.Error("[koAddActivities] UpsertDevice DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Device"}) return } @@ -279,7 +279,7 @@ func (api *API) addActivities(c *gin.Context) { StartPercentage: float64(item.Page) / float64(item.Pages), EndPercentage: float64(item.Page+1) / float64(item.Pages), }); err != nil { - log.Error("[addActivities] AddActivity DB Error:", err) + log.Error("[koAddActivities] AddActivity DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Activity"}) return } @@ -287,18 +287,18 @@ func (api *API) addActivities(c *gin.Context) { // Commit Transaction if err := tx.Commit(); err != nil { - log.Error("[addActivities] Transaction Commit DB Error:", err) + log.Error("[koAddActivities] Transaction Commit DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } // Update Statistic for _, doc := range allDocuments { - log.Info("[addActivities] UpdateDocumentUserStatistic Running...") + log.Info("[koAddActivities] UpdateDocumentUserStatistic Running...") if err := api.DB.UpdateDocumentUserStatistic(doc, rUser.(string)); err != nil { - log.Error("[addActivities] UpdateDocumentUserStatistic Error:", err) + log.Error("[koAddActivities] UpdateDocumentUserStatistic Error:", err) } - log.Info("[addActivities] UpdateDocumentUserStatistic Complete") + log.Info("[koAddActivities] UpdateDocumentUserStatistic Complete") } c.JSON(http.StatusOK, gin.H{ @@ -306,12 +306,12 @@ func (api *API) addActivities(c *gin.Context) { }) } -func (api *API) checkActivitySync(c *gin.Context) { +func (api *API) koCheckActivitySync(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") var rCheckActivity requestCheckActivitySync if err := c.ShouldBindJSON(&rCheckActivity); err != nil { - log.Error("[checkActivitySync] Invalid JSON Bind") + log.Error("[koCheckActivitySync] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } @@ -323,7 +323,7 @@ func (api *API) checkActivitySync(c *gin.Context) { DeviceName: rCheckActivity.Device, LastSynced: time.Now().UTC().Format(time.RFC3339), }); err != nil { - log.Error("[checkActivitySync] UpsertDevice DB Error", err) + log.Error("[koCheckActivitySync] UpsertDevice DB Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Device"}) return } @@ -336,7 +336,7 @@ func (api *API) checkActivitySync(c *gin.Context) { if err == sql.ErrNoRows { lastActivity = time.UnixMilli(0).Format(time.RFC3339) } else if err != nil { - log.Error("[checkActivitySync] GetLastActivity DB Error:", err) + log.Error("[koCheckActivitySync] GetLastActivity DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -344,7 +344,7 @@ func (api *API) checkActivitySync(c *gin.Context) { // Parse Time parsedTime, err := time.Parse(time.RFC3339, lastActivity) if err != nil { - log.Error("[checkActivitySync] Time Parse Error:", err) + log.Error("[koCheckActivitySync] Time Parse Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -354,10 +354,10 @@ func (api *API) checkActivitySync(c *gin.Context) { }) } -func (api *API) addDocuments(c *gin.Context) { +func (api *API) koAddDocuments(c *gin.Context) { var rNewDocs requestDocument if err := c.ShouldBindJSON(&rNewDocs); err != nil { - log.Error("[addDocuments] Invalid JSON Bind") + log.Error("[koAddDocuments] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Document(s)"}) return } @@ -365,7 +365,7 @@ func (api *API) addDocuments(c *gin.Context) { // Do Transaction tx, err := api.DB.DB.Begin() if err != nil { - log.Error("[addDocuments] Transaction Begin DB Error:", err) + log.Error("[koAddDocuments] Transaction Begin DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -386,7 +386,7 @@ func (api *API) addDocuments(c *gin.Context) { Description: api.sanitizeInput(doc.Description), }) if err != nil { - log.Error("[addDocuments] UpsertDocument DB Error:", err) + log.Error("[koAddDocuments] UpsertDocument DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Document"}) return } @@ -394,7 +394,7 @@ func (api *API) addDocuments(c *gin.Context) { // Commit Transaction if err := tx.Commit(); err != nil { - log.Error("[addDocuments] Transaction Commit DB Error:", err) + log.Error("[koAddDocuments] Transaction Commit DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Error"}) return } @@ -404,12 +404,12 @@ func (api *API) addDocuments(c *gin.Context) { }) } -func (api *API) checkDocumentsSync(c *gin.Context) { +func (api *API) koCheckDocumentsSync(c *gin.Context) { rUser, _ := c.Get("AuthorizedUser") var rCheckDocs requestCheckDocumentSync if err := c.ShouldBindJSON(&rCheckDocs); err != nil { - log.Error("[checkDocumentsSync] Invalid JSON Bind") + log.Error("[koCheckDocumentsSync] Invalid JSON Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } @@ -422,7 +422,7 @@ func (api *API) checkDocumentsSync(c *gin.Context) { LastSynced: time.Now().UTC().Format(time.RFC3339), }) if err != nil { - log.Error("[checkDocumentsSync] UpsertDevice DB Error", err) + log.Error("[koCheckDocumentsSync] UpsertDevice DB Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Device"}) return } @@ -433,7 +433,7 @@ func (api *API) checkDocumentsSync(c *gin.Context) { // Get Missing Documents missingDocs, err = api.DB.Queries.GetMissingDocuments(api.DB.Ctx, rCheckDocs.Have) if err != nil { - log.Error("[checkDocumentsSync] GetMissingDocuments DB Error", err) + log.Error("[koCheckDocumentsSync] GetMissingDocuments DB Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } @@ -441,7 +441,7 @@ func (api *API) checkDocumentsSync(c *gin.Context) { // Get Deleted Documents deletedDocIDs, err = api.DB.Queries.GetDeletedDocuments(api.DB.Ctx, rCheckDocs.Have) if err != nil { - log.Error("[checkDocumentsSync] GetDeletedDocuments DB Error", err) + log.Error("[koCheckDocumentsSync] GetDeletedDocuments DB Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } @@ -449,14 +449,14 @@ func (api *API) checkDocumentsSync(c *gin.Context) { // Get Wanted Documents jsonHaves, err := json.Marshal(rCheckDocs.Have) if err != nil { - log.Error("[checkDocumentsSync] JSON Marshal Error", err) + log.Error("[koCheckDocumentsSync] JSON Marshal Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } wantedDocs, err := api.DB.Queries.GetWantedDocuments(api.DB.Ctx, string(jsonHaves)) if err != nil { - log.Error("[checkDocumentsSync] GetWantedDocuments DB Error", err) + log.Error("[koCheckDocumentsSync] GetWantedDocuments DB Error", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } @@ -497,17 +497,17 @@ func (api *API) checkDocumentsSync(c *gin.Context) { c.JSON(http.StatusOK, rCheckDocSync) } -func (api *API) uploadExistingDocument(c *gin.Context) { +func (api *API) koUploadExistingDocument(c *gin.Context) { var rDoc requestDocumentID if err := c.ShouldBindUri(&rDoc); err != nil { - log.Error("[uploadExistingDocument] Invalid URI Bind") + log.Error("[koUploadExistingDocument] Invalid URI Bind") c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) return } fileData, err := c.FormFile("file") if err != nil { - log.Error("[uploadExistingDocument] File Error:", err) + log.Error("[koUploadExistingDocument] File Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "File Error"}) return } @@ -518,7 +518,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { fileExtension := fileMime.Extension() if !slices.Contains([]string{".epub", ".html"}, fileExtension) { - log.Error("[uploadExistingDocument] Invalid FileType:", fileExtension) + log.Error("[koUploadExistingDocument] Invalid FileType:", fileExtension) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Filetype"}) return } @@ -526,7 +526,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { // Validate Document Exists in DB document, err := api.DB.Queries.GetDocument(api.DB.Ctx, rDoc.DocumentID) if err != nil { - log.Error("[uploadExistingDocument] GetDocument DB Error:", err) + log.Error("[koUploadExistingDocument] GetDocument DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Document"}) return } @@ -559,7 +559,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { if os.IsNotExist(err) { err = c.SaveUploadedFile(fileData, safePath) if err != nil { - log.Error("[uploadExistingDocument] Save Failure:", err) + log.Error("[koUploadExistingDocument] Save Failure:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "File Error"}) return } @@ -568,7 +568,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { // Get MD5 Hash fileHash, err := getFileMD5(safePath) if err != nil { - log.Error("[uploadExistingDocument] Hash Failure:", err) + log.Error("[koUploadExistingDocument] Hash Failure:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "File Error"}) return } @@ -576,7 +576,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { // Get Word Count wordCount, err := metadata.GetWordCount(safePath) if err != nil { - log.Error("[uploadExistingDocument] Word Count Failure:", err) + log.Error("[koUploadExistingDocument] Word Count Failure:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "File Error"}) return } @@ -588,7 +588,7 @@ func (api *API) uploadExistingDocument(c *gin.Context) { Filepath: &fileName, Words: &wordCount, }); err != nil { - log.Error("[uploadExistingDocument] UpsertDocument DB Error:", err) + log.Error("[koUploadExistingDocument] UpsertDocument DB Error:", err) c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Document Error"}) return } @@ -598,42 +598,8 @@ func (api *API) uploadExistingDocument(c *gin.Context) { }) } -func (api *API) downloadDocument(c *gin.Context) { - var rDoc requestDocumentID - if err := c.ShouldBindUri(&rDoc); err != nil { - log.Error("[downloadDocument] Invalid URI Bind") - c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid Request"}) - return - } - - // Get Document - document, err := api.DB.Queries.GetDocument(api.DB.Ctx, rDoc.DocumentID) - if err != nil { - log.Error("[downloadDocument] GetDocument DB Error:", err) - c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Unknown Document"}) - return - } - - if document.Filepath == nil { - log.Error("[downloadDocument] Document Doesn't Have File:", rDoc.DocumentID) - c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Document Doesn't Exist"}) - return - } - - // Derive Storage Location - filePath := filepath.Join(api.Config.DataPath, "documents", *document.Filepath) - - // Validate File Exists - _, err = os.Stat(filePath) - if os.IsNotExist(err) { - log.Error("[downloadDocument] File Doesn't Exist:", rDoc.DocumentID) - c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Document Doesn't Exists"}) - return - } - - // Force Download (Security) - c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(*document.Filepath))) - c.File(filePath) +func (api *API) koDemoModeJSONError(c *gin.Context) { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not Allowed in Demo Mode"}) } func (api *API) sanitizeInput(val any) *string { diff --git a/assets/reader/index.js b/assets/reader/index.js index 8f27684..e866470 100644 --- a/assets/reader/index.js +++ b/assets/reader/index.js @@ -1272,3 +1272,14 @@ class EBookReader { } document.addEventListener("DOMContentLoaded", initReader); + +// WIP +async function getTOC() { + let toc = currentReader.book.navigation.toc; + + // Alternatively: + // let nav = await currentReader.book.loaded.navigation; + // let toc = nav.toc; + + currentReader.rendition.display(nav.toc[10].href); +} diff --git a/assets/style.css b/assets/style.css index f4783c9..3e26f98 100644 --- a/assets/style.css +++ b/assets/style.css @@ -1 +1 @@ -/*! tailwindcss v3.3.2 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,::backdrop,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.visible{visibility:visible}.invisible{visibility:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.-bottom-28{bottom:-7rem}.-bottom-5{bottom:-1.25rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.bottom-7{bottom:1.75rem}.left-0{left:0}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.right-0{right:0}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-1\/2{top:50%}.top-16{top:4rem}.top-3{top:.75rem}.top-6{top:1.5rem}.top-7{top:1.75rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.float-left{float:left}.m-4{margin:1rem}.m-auto{margin:auto}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.my-6{margin-top:1.5rem;margin-bottom:1.5rem}.my-auto{margin-top:auto;margin-bottom:auto}.-ml-6{margin-left:-1.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-8{margin-bottom:2rem}.ml-6{margin-left:1.5rem}.mr-4{margin-right:1rem}.mt-0{margin-top:0}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-0{height:0}.h-0\.5{height:.125rem}.h-16{height:4rem}.h-2{height:.5rem}.h-32{height:8rem}.h-4{height:1rem}.h-48{height:12rem}.h-7{height:1.75rem}.h-\[100dvh\]{height:100dvh}.h-full{height:100%}.h-screen{height:100vh}.max-h-\[10em\]{max-height:10em}.max-h-\[95\%\]{max-height:95%}.min-h-\[10em\]{min-height:10em}.w-0{width:0}.w-1\/2{width:50%}.w-12{width:3rem}.w-16{width:4rem}.w-24{width:6rem}.w-32{width:8rem}.w-4{width:1rem}.w-44{width:11rem}.w-5\/6{width:83.333333%}.w-56{width:14rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-\[90\%\]{width:90%}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.w-screen{width:100vw}.min-w-\[12em\]{min-width:12em}.min-w-\[50\%\]{min-width:50%}.min-w-fit{min-width:-moz-fit-content;min-width:fit-content}.min-w-full{min-width:100%}.max-w-\[50dvw\]{max-width:50dvw}.max-w-screen-sm{max-width:640px}.max-w-screen-xl{max-width:1280px}.flex-1{flex:1 1 0%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-right{transform-origin:top right}.-translate-x-2\/4{--tw-translate-x:-50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2,.-translate-y-2\/4{--tw-translate-y:-50%}.-translate-y-1\/2,.-translate-y-2\/4,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-pointer{cursor:pointer}.resize{resize:both}.snap-x{scroll-snap-type:x var(--tw-scroll-snap-strictness)}.snap-mandatory{--tw-scroll-snap-strictness:mandatory}.snap-center{scroll-snap-align:center}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.flex-wrap-reverse{flex-wrap:wrap-reverse}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.gap-1{gap:.25rem}.gap-10{gap:2.5rem}.gap-2{gap:.5rem}.gap-4{gap:1rem}.gap-7{gap:1.75rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.5rem*var(--tw-space-x-reverse));margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-scroll{overflow:scroll}.overflow-x-auto{overflow-x:auto}.overflow-y-scroll{overflow-y:scroll}.text-ellipsis{text-overflow:ellipsis}.hyphens-auto{-webkit-hyphens:auto;hyphens:auto}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-none{border-radius:0}.rounded-l{border-top-left-radius:.25rem}.rounded-bl,.rounded-l{border-bottom-left-radius:.25rem}.rounded-tr{border-top-right-radius:.25rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-t{border-top-width:1px}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.border-gray-500{--tw-border-opacity:1;border-color:rgb(107 114 128/var(--tw-border-opacity))}.border-purple-500{--tw-border-opacity:1;border-color:rgb(168 85 247/var(--tw-border-opacity))}.border-transparent{border-color:#0000}.border-white{--tw-border-opacity:1;border-color:rgb(255 255 255/var(--tw-border-opacity))}.bg-\[\#000\]{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-\[\#1f2937\]{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.bg-\[\#232323\]{--tw-bg-opacity:1;background-color:rgb(35 35 35/var(--tw-bg-opacity))}.bg-\[\#d2b48c\]{--tw-bg-opacity:1;background-color:rgb(210 180 140/var(--tw-bg-opacity))}.bg-\[\#fff\]{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity))}.bg-blue-700{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity))}.bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity))}.bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity))}.bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.bg-green-200{--tw-bg-opacity:1;background-color:rgb(187 247 208/var(--tw-bg-opacity))}.bg-green-600{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity))}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.object-cover{-o-object-fit:cover;object-fit:cover}.object-fill{-o-object-fit:fill;object-fit:fill}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-12{padding-bottom:3rem}.pb-2{padding-bottom:.5rem}.pb-4{padding-bottom:1rem}.pl-0{padding-left:0}.pl-14{padding-left:3.5rem}.pl-6{padding-left:1.5rem}.pr-8{padding-right:2rem}.pt-12{padding-top:3rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-8{padding-top:2rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.text-justify{text-align:justify}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-5xl{font-size:3rem;line-height:1}.text-7xl{font-size:4.5rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-6{line-height:1.5rem}.leading-normal{line-height:1.5}.tracking-tight{letter-spacing:-.025em}.text-\[\#000\]{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-\[\#333\]{--tw-text-opacity:1;color:rgb(51 51 51/var(--tw-text-opacity))}.text-\[\#ccc\]{--tw-text-opacity:1;color:rgb(204 204 204/var(--tw-text-opacity))}.text-\[\#fff\]{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity))}.text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.underline{text-decoration-line:underline}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.opacity-0{opacity:0}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.shadow{--tw-shadow:0 1px 3px 0 #0000001a,0 1px 2px -1px #0000001a;--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-2xl{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px #00000040;--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-lg{--tw-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a;--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-lg,.shadow-md{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px #0000001a,0 2px 4px -2px #0000001a;--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.shadow-sm{--tw-shadow:0 1px 2px 0 #0000000d;--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-gray-500{--tw-shadow-color:#6b7280;--tw-shadow:var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.ring-black{--tw-ring-opacity:1;--tw-ring-color:rgb(0 0 0/var(--tw-ring-opacity))}.ring-opacity-5{--tw-ring-opacity:0.05}.invert{--tw-invert:invert(100%)}.filter,.invert{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:bg-blue-800:hover{--tw-bg-opacity:1;background-color:rgb(30 64 175/var(--tw-bg-opacity))}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.hover\:bg-gray-400:hover{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity))}.hover\:bg-gray-800:hover{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.hover\:bg-white:hover{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.hover\:text-black:hover{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.hover\:text-gray-800:hover{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.hover\:text-gray-900:hover{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity))}.hover\:opacity-100:hover{opacity:1}.focus\:border-transparent:focus{border-color:#0000}.focus\:outline-none:focus{outline:2px solid #0000;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\:ring-2:focus,.focus\:ring-4:focus{box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-4:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\:ring-blue-300:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(147 197 253/var(--tw-ring-opacity))}.focus\:ring-purple-600:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(147 51 234/var(--tw-ring-opacity))}@media (prefers-color-scheme:dark){.dark\:border-black{--tw-border-opacity:1;border-color:rgb(0 0 0/var(--tw-border-opacity))}.dark\:border-gray-500{--tw-border-opacity:1;border-color:rgb(107 114 128/var(--tw-border-opacity))}.dark\:border-gray-800{--tw-border-opacity:1;border-color:rgb(31 41 55/var(--tw-border-opacity))}.dark\:bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity))}.dark\:bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity))}.dark\:bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity))}.dark\:bg-gray-600{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.dark\:bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.dark\:bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.dark\:bg-gray-900{--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity))}.dark\:bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.dark\:text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.dark\:text-gray-100{--tw-text-opacity:1;color:rgb(243 244 246/var(--tw-text-opacity))}.dark\:text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity))}.dark\:text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity))}.dark\:text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.dark\:text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.dark\:text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.dark\:text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.dark\:text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.dark\:shadow-gray-800{--tw-shadow-color:#1f2937;--tw-shadow:var(--tw-shadow-colored)}.dark\:shadow-gray-900{--tw-shadow-color:#111827;--tw-shadow:var(--tw-shadow-colored)}.dark\:hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-600:hover{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-700:hover{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.dark\:hover\:text-gray-100:hover{--tw-text-opacity:1;color:rgb(243 244 246/var(--tw-text-opacity))}.dark\:hover\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.dark\:focus\:ring-blue-800:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(30 64 175/var(--tw-ring-opacity))}}@media (min-width:640px){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:mt-0{margin-top:0}.sm\:grid{display:grid}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:gap-4{gap:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:mr-2{margin-right:.5rem}.md\:block{display:block}.md\:table-cell{display:table-cell}.md\:w-1\/2{width:50%}.md\:w-60{width:15rem}.md\:w-fit{width:-moz-fit-content;width:fit-content}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:justify-start{justify-content:flex-start}.md\:px-24{padding-left:6rem;padding-right:6rem}.md\:px-6{padding-left:1.5rem;padding-right:1.5rem}.md\:pt-0{padding-top:0}.md\:pt-8{padding-top:2rem}.md\:text-4xl{font-size:2.25rem;line-height:2.5rem}.md\:text-sm{font-size:.875rem;line-height:1.25rem}}@media (min-width:1024px){.lg\:mx-48{margin-left:12rem;margin-right:12rem}.lg\:ml-44{margin-left:11rem}.lg\:ml-48{margin-left:12rem}.lg\:hidden{display:none}.lg\:w-48{width:12rem}.lg\:w-80{width:20rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:justify-around{justify-content:space-around}.lg\:px-32{padding-left:8rem;padding-right:8rem}.lg\:px-6{padding-left:1.5rem;padding-right:1.5rem}.lg\:py-16{padding-top:4rem;padding-bottom:4rem}.lg\:pr-0{padding-right:0}.lg\:text-9xl{font-size:8rem;line-height:1}} \ No newline at end of file +/*! tailwindcss v3.3.2 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,::backdrop,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.visible{visibility:visible}.invisible{visibility:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.-bottom-28{bottom:-7rem}.-bottom-5{bottom:-1.25rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.bottom-7{bottom:1.75rem}.left-0{left:0}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.right-0{right:0}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-1\/2{top:50%}.top-16{top:4rem}.top-3{top:.75rem}.top-6{top:1.5rem}.top-7{top:1.75rem}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.float-left{float:left}.m-4{margin:1rem}.m-auto{margin:auto}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.my-6{margin-top:1.5rem;margin-bottom:1.5rem}.my-auto{margin-top:auto;margin-bottom:auto}.-ml-6{margin-left:-1.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-8{margin-bottom:2rem}.ml-6{margin-left:1.5rem}.mr-4{margin-right:1rem}.mt-0{margin-top:0}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.h-0{height:0}.h-0\.5{height:.125rem}.h-16{height:4rem}.h-2{height:.5rem}.h-32{height:8rem}.h-4{height:1rem}.h-48{height:12rem}.h-7{height:1.75rem}.h-\[100dvh\]{height:100dvh}.h-full{height:100%}.h-screen{height:100vh}.max-h-\[10em\]{max-height:10em}.max-h-\[95\%\]{max-height:95%}.min-h-\[10em\]{min-height:10em}.w-0{width:0}.w-1\/2{width:50%}.w-12{width:3rem}.w-16{width:4rem}.w-24{width:6rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-44{width:11rem}.w-5\/6{width:83.333333%}.w-56{width:14rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-\[90\%\]{width:90%}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.w-screen{width:100vw}.min-w-\[12em\]{min-width:12em}.min-w-\[50\%\]{min-width:50%}.min-w-fit{min-width:-moz-fit-content;min-width:fit-content}.min-w-full{min-width:100%}.max-w-\[50dvw\]{max-width:50dvw}.max-w-screen-sm{max-width:640px}.max-w-screen-xl{max-width:1280px}.flex-1{flex:1 1 0%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-right{transform-origin:top right}.-translate-x-2\/4{--tw-translate-x:-50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2,.-translate-y-2\/4{--tw-translate-y:-50%}.-translate-y-1\/2,.-translate-y-2\/4,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-pointer{cursor:pointer}.resize{resize:both}.snap-x{scroll-snap-type:x var(--tw-scroll-snap-strictness)}.snap-mandatory{--tw-scroll-snap-strictness:mandatory}.snap-center{scroll-snap-align:center}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.flex-wrap-reverse{flex-wrap:wrap-reverse}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.gap-1{gap:.25rem}.gap-10{gap:2.5rem}.gap-2{gap:.5rem}.gap-4{gap:1rem}.gap-7{gap:1.75rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.5rem*var(--tw-space-x-reverse));margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-scroll{overflow:scroll}.overflow-x-auto{overflow-x:auto}.overflow-y-scroll{overflow-y:scroll}.text-ellipsis{text-overflow:ellipsis}.hyphens-auto{-webkit-hyphens:auto;hyphens:auto}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-none{border-radius:0}.rounded-l{border-top-left-radius:.25rem}.rounded-bl,.rounded-l{border-bottom-left-radius:.25rem}.rounded-tr{border-top-right-radius:.25rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-l-4{border-left-width:4px}.border-t{border-top-width:1px}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.border-gray-500{--tw-border-opacity:1;border-color:rgb(107 114 128/var(--tw-border-opacity))}.border-purple-500{--tw-border-opacity:1;border-color:rgb(168 85 247/var(--tw-border-opacity))}.border-transparent{border-color:#0000}.border-white{--tw-border-opacity:1;border-color:rgb(255 255 255/var(--tw-border-opacity))}.bg-\[\#000\]{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-\[\#1f2937\]{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.bg-\[\#232323\]{--tw-bg-opacity:1;background-color:rgb(35 35 35/var(--tw-bg-opacity))}.bg-\[\#d2b48c\]{--tw-bg-opacity:1;background-color:rgb(210 180 140/var(--tw-bg-opacity))}.bg-\[\#fff\]{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity))}.bg-blue-700{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity))}.bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity))}.bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity))}.bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.bg-green-200{--tw-bg-opacity:1;background-color:rgb(187 247 208/var(--tw-bg-opacity))}.bg-green-600{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity))}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.object-cover{-o-object-fit:cover;object-fit:cover}.object-fill{-o-object-fit:fill;object-fit:fill}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-12{padding-bottom:3rem}.pb-2{padding-bottom:.5rem}.pb-4{padding-bottom:1rem}.pl-0{padding-left:0}.pl-14{padding-left:3.5rem}.pl-6{padding-left:1.5rem}.pr-8{padding-right:2rem}.pt-12{padding-top:3rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-8{padding-top:2rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.text-justify{text-align:justify}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-5xl{font-size:3rem;line-height:1}.text-7xl{font-size:4.5rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-6{line-height:1.5rem}.leading-normal{line-height:1.5}.tracking-tight{letter-spacing:-.025em}.text-\[\#000\]{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-\[\#333\]{--tw-text-opacity:1;color:rgb(51 51 51/var(--tw-text-opacity))}.text-\[\#ccc\]{--tw-text-opacity:1;color:rgb(204 204 204/var(--tw-text-opacity))}.text-\[\#fff\]{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity))}.text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.underline{text-decoration-line:underline}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.opacity-0{opacity:0}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.shadow{--tw-shadow:0 1px 3px 0 #0000001a,0 1px 2px -1px #0000001a;--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-2xl{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px #00000040;--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-lg{--tw-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a;--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-lg,.shadow-md{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px #0000001a,0 2px 4px -2px #0000001a;--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.shadow-sm{--tw-shadow:0 1px 2px 0 #0000000d;--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-gray-500{--tw-shadow-color:#6b7280;--tw-shadow:var(--tw-shadow-colored)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.ring-black{--tw-ring-opacity:1;--tw-ring-color:rgb(0 0 0/var(--tw-ring-opacity))}.ring-opacity-5{--tw-ring-opacity:0.05}.invert{--tw-invert:invert(100%)}.filter,.invert{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:bg-blue-800:hover{--tw-bg-opacity:1;background-color:rgb(30 64 175/var(--tw-bg-opacity))}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.hover\:bg-gray-400:hover{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity))}.hover\:bg-gray-800:hover{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.hover\:bg-white:hover{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.hover\:text-black:hover{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.hover\:text-gray-800:hover{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.hover\:text-gray-900:hover{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity))}.hover\:opacity-100:hover{opacity:1}.focus\:border-transparent:focus{border-color:#0000}.focus\:outline-none:focus{outline:2px solid #0000;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\:ring-2:focus,.focus\:ring-4:focus{box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-4:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\:ring-blue-300:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(147 197 253/var(--tw-ring-opacity))}.focus\:ring-purple-600:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(147 51 234/var(--tw-ring-opacity))}@media (prefers-color-scheme:dark){.dark\:border-black{--tw-border-opacity:1;border-color:rgb(0 0 0/var(--tw-border-opacity))}.dark\:border-gray-500{--tw-border-opacity:1;border-color:rgb(107 114 128/var(--tw-border-opacity))}.dark\:border-gray-800{--tw-border-opacity:1;border-color:rgb(31 41 55/var(--tw-border-opacity))}.dark\:bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity))}.dark\:bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity))}.dark\:bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity))}.dark\:bg-gray-600{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.dark\:bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.dark\:bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.dark\:bg-gray-900{--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity))}.dark\:bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.dark\:text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.dark\:text-gray-100{--tw-text-opacity:1;color:rgb(243 244 246/var(--tw-text-opacity))}.dark\:text-gray-200{--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity))}.dark\:text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity))}.dark\:text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.dark\:text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.dark\:text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.dark\:text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.dark\:text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.dark\:shadow-gray-800{--tw-shadow-color:#1f2937;--tw-shadow:var(--tw-shadow-colored)}.dark\:shadow-gray-900{--tw-shadow-color:#111827;--tw-shadow:var(--tw-shadow-colored)}.dark\:hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-600:hover{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-700:hover{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.dark\:hover\:text-gray-100:hover{--tw-text-opacity:1;color:rgb(243 244 246/var(--tw-text-opacity))}.dark\:hover\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.dark\:focus\:ring-blue-800:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(30 64 175/var(--tw-ring-opacity))}}@media (min-width:640px){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:mt-0{margin-top:0}.sm\:grid{display:grid}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:gap-4{gap:1rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:mr-2{margin-right:.5rem}.md\:block{display:block}.md\:table-cell{display:table-cell}.md\:w-1\/2{width:50%}.md\:w-60{width:15rem}.md\:w-fit{width:-moz-fit-content;width:fit-content}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:justify-start{justify-content:flex-start}.md\:px-24{padding-left:6rem;padding-right:6rem}.md\:px-6{padding-left:1.5rem;padding-right:1.5rem}.md\:pt-0{padding-top:0}.md\:pt-8{padding-top:2rem}.md\:text-4xl{font-size:2.25rem;line-height:2.5rem}.md\:text-sm{font-size:.875rem;line-height:1.25rem}}@media (min-width:1024px){.lg\:mx-48{margin-left:12rem;margin-right:12rem}.lg\:ml-44{margin-left:11rem}.lg\:ml-48{margin-left:12rem}.lg\:hidden{display:none}.lg\:w-48{width:12rem}.lg\:w-80{width:20rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:justify-around{justify-content:space-around}.lg\:px-32{padding-left:8rem;padding-right:8rem}.lg\:px-6{padding-left:1.5rem;padding-right:1.5rem}.lg\:py-16{padding-top:4rem;padding-bottom:4rem}.lg\:pr-0{padding-right:0}.lg\:text-9xl{font-size:8rem;line-height:1}} \ No newline at end of file diff --git a/database/query.sql b/database/query.sql index d74d310..39ea8b5 100644 --- a/database/query.sql +++ b/database/query.sql @@ -146,6 +146,20 @@ ORDER BY devices.last_synced DESC; SELECT * FROM documents WHERE id = $document_id LIMIT 1; +-- name: GetDocumentProgress :one +SELECT + document_progress.*, + devices.device_name +FROM document_progress +JOIN devices ON document_progress.device_id = devices.id +WHERE + document_progress.user_id = $user_id + AND document_progress.document_id = $document_id +ORDER BY + document_progress.created_at + DESC +LIMIT 1; + -- name: GetDocumentWithStats :one SELECT docs.id, @@ -258,19 +272,30 @@ WHERE AND documents.deleted = false AND documents.id NOT IN (sqlc.slice('document_ids')); --- name: GetProgress :one +-- name: GetProgress :many SELECT - document_progress.*, - devices.device_name -FROM document_progress -JOIN devices ON document_progress.device_id = devices.id + documents.title, + documents.author, + devices.device_name, + ROUND(CAST(progress.percentage AS REAL) * 100, 2) AS percentage, + progress.document_id, + progress.user_id, + CAST(STRFTIME('%Y-%m-%d %H:%M:%S', progress.created_at, users.time_offset) AS TEXT) AS created_at +FROM document_progress AS progress +LEFT JOIN users ON progress.user_id = users.id +LEFT JOIN devices ON progress.device_id = devices.id +LEFT JOIN documents ON progress.document_id = documents.id WHERE - document_progress.user_id = $user_id - AND document_progress.document_id = $document_id -ORDER BY - document_progress.created_at - DESC -LIMIT 1; + progress.user_id = $user_id + AND ( + ( + CAST($doc_filter AS BOOLEAN) = TRUE + AND document_id = $document_id + ) OR $doc_filter = FALSE + ) +ORDER BY created_at DESC +LIMIT $limit +OFFSET $offset; -- name: GetUser :one SELECT * FROM users diff --git a/database/query.sql.go b/database/query.sql.go index 0897cf4..8706d63 100644 --- a/database/query.sql.go +++ b/database/query.sql.go @@ -478,6 +478,51 @@ func (q *Queries) GetDocument(ctx context.Context, documentID string) (Document, return i, err } +const getDocumentProgress = `-- name: GetDocumentProgress :one +SELECT + document_progress.user_id, document_progress.document_id, document_progress.device_id, document_progress.percentage, document_progress.progress, document_progress.created_at, + devices.device_name +FROM document_progress +JOIN devices ON document_progress.device_id = devices.id +WHERE + document_progress.user_id = ?1 + AND document_progress.document_id = ?2 +ORDER BY + document_progress.created_at + DESC +LIMIT 1 +` + +type GetDocumentProgressParams struct { + UserID string `json:"user_id"` + DocumentID string `json:"document_id"` +} + +type GetDocumentProgressRow struct { + UserID string `json:"user_id"` + DocumentID string `json:"document_id"` + DeviceID string `json:"device_id"` + Percentage float64 `json:"percentage"` + Progress string `json:"progress"` + CreatedAt string `json:"created_at"` + DeviceName string `json:"device_name"` +} + +func (q *Queries) GetDocumentProgress(ctx context.Context, arg GetDocumentProgressParams) (GetDocumentProgressRow, error) { + row := q.db.QueryRowContext(ctx, getDocumentProgress, arg.UserID, arg.DocumentID) + var i GetDocumentProgressRow + err := row.Scan( + &i.UserID, + &i.DocumentID, + &i.DeviceID, + &i.Percentage, + &i.Progress, + &i.CreatedAt, + &i.DeviceName, + ) + return i, err +} + const getDocumentWithStats = `-- name: GetDocumentWithStats :one SELECT docs.id, @@ -827,49 +872,85 @@ func (q *Queries) GetMissingDocuments(ctx context.Context, documentIds []string) return items, nil } -const getProgress = `-- name: GetProgress :one +const getProgress = `-- name: GetProgress :many SELECT - document_progress.user_id, document_progress.document_id, document_progress.device_id, document_progress.percentage, document_progress.progress, document_progress.created_at, - devices.device_name -FROM document_progress -JOIN devices ON document_progress.device_id = devices.id + documents.title, + documents.author, + devices.device_name, + ROUND(CAST(progress.percentage AS REAL) * 100, 2) AS percentage, + progress.document_id, + progress.user_id, + CAST(STRFTIME('%Y-%m-%d %H:%M:%S', progress.created_at, users.time_offset) AS TEXT) AS created_at +FROM document_progress AS progress +LEFT JOIN users ON progress.user_id = users.id +LEFT JOIN devices ON progress.device_id = devices.id +LEFT JOIN documents ON progress.document_id = documents.id WHERE - document_progress.user_id = ?1 - AND document_progress.document_id = ?2 -ORDER BY - document_progress.created_at - DESC -LIMIT 1 + progress.user_id = ?1 + AND ( + ( + CAST(?2 AS BOOLEAN) = TRUE + AND document_id = ?3 + ) OR ?2 = FALSE + ) +ORDER BY created_at DESC +LIMIT ?5 +OFFSET ?4 ` type GetProgressParams struct { UserID string `json:"user_id"` + DocFilter bool `json:"doc_filter"` DocumentID string `json:"document_id"` + Offset int64 `json:"offset"` + Limit int64 `json:"limit"` } type GetProgressRow struct { - UserID string `json:"user_id"` - DocumentID string `json:"document_id"` - DeviceID string `json:"device_id"` - Percentage float64 `json:"percentage"` - Progress string `json:"progress"` - CreatedAt string `json:"created_at"` + Title *string `json:"title"` + Author *string `json:"author"` DeviceName string `json:"device_name"` + Percentage float64 `json:"percentage"` + DocumentID string `json:"document_id"` + UserID string `json:"user_id"` + CreatedAt string `json:"created_at"` } -func (q *Queries) GetProgress(ctx context.Context, arg GetProgressParams) (GetProgressRow, error) { - row := q.db.QueryRowContext(ctx, getProgress, arg.UserID, arg.DocumentID) - var i GetProgressRow - err := row.Scan( - &i.UserID, - &i.DocumentID, - &i.DeviceID, - &i.Percentage, - &i.Progress, - &i.CreatedAt, - &i.DeviceName, +func (q *Queries) GetProgress(ctx context.Context, arg GetProgressParams) ([]GetProgressRow, error) { + rows, err := q.db.QueryContext(ctx, getProgress, + arg.UserID, + arg.DocFilter, + arg.DocumentID, + arg.Offset, + arg.Limit, ) - return i, err + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetProgressRow + for rows.Next() { + var i GetProgressRow + if err := rows.Scan( + &i.Title, + &i.Author, + &i.DeviceName, + &i.Percentage, + &i.DocumentID, + &i.UserID, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil } const getUser = `-- name: GetUser :one diff --git a/templates/base.html b/templates/base.html index c3e12ad..3e8e5e8 100644 --- a/templates/base.html +++ b/templates/base.html @@ -152,11 +152,11 @@ Documents - {{ template "svg/documents" (dict "Size" 20) }} - Local + {{ template "svg/activity" (dict "Size" 20) }} + Progress {{ template "svg/activity" (dict "Size" 20) }} Activity - {{ if .SearchEnabled }} + {{ if .Config.SearchEnabled }}
- -
+
- {{ if .RegistrationEnabled }} {{ if .Register }} + {{ if .Config.RegistrationEnabled }} {{ if .Register }}

Trying to login? diff --git a/templates/pages/progress.html b/templates/pages/progress.html new file mode 100644 index 0000000..5baca70 --- /dev/null +++ b/templates/pages/progress.html @@ -0,0 +1,49 @@ +{{template "base" .}} {{define "title"}}Progress{{end}} {{define "header"}} +Progress +{{end}} {{define "content"}} +

+
+ + + + + + + + + + + {{ if not .Data }} + + + + {{ end }} + {{range $progress := .Data }} + + + + + + + {{end}} + +
+ Document + + Device + + Percent + + Time +
No Results
+ {{ $progress.Author }} - {{ $progress.Title }}

+
+

{{ $progress.DeviceName }}

+
+

{{ $progress.Percentage }}%

+
+

{{ $progress.CreatedAt }}

+
+
+
+{{end}} diff --git a/templates/pages/settings.html b/templates/pages/settings.html index 9330243..e98d0b8 100644 --- a/templates/pages/settings.html +++ b/templates/pages/settings.html @@ -89,14 +89,7 @@ > {{ range $item := GetUTCOffsets }}