Skip to content

Commit

Permalink
Improved actions code and behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
svera authored Dec 29, 2024
1 parent e5809dc commit 52f449b
Show file tree
Hide file tree
Showing 22 changed files with 116 additions and 110 deletions.
14 changes: 11 additions & 3 deletions internal/webserver/controller/auth/signin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/svera/coreander/v4/internal/webserver/infrastructure"
"github.com/svera/coreander/v4/internal/webserver/model"
)

Expand All @@ -23,9 +24,16 @@ func (a *Controller) SignIn(c *fiber.Ctx) error {
}

if user == nil || user.Password != model.Hash(c.FormValue("password")) {
emailSendingConfigured := true
if _, ok := a.sender.(*infrastructure.NoEmail); ok {
emailSendingConfigured = false
}

return c.Status(fiber.StatusUnauthorized).Render("auth/login", fiber.Map{
"Title": "Login",
"Error": "Wrong email or password",
"Title": "Login",
"Error": "Wrong email or password",
"EmailSendingConfigured": emailSendingConfigured,
"DisableLoginLink": true,
}, "layout")
}

Expand All @@ -46,7 +54,7 @@ func (a *Controller) SignIn(c *fiber.Ctx) error {
})

referer := string(c.Context().Referer())
if referer != "" && !strings.HasSuffix(referer, "sessions/new") {
if referer != "" && !strings.Contains(referer, "/sessions") {
return c.Redirect(referer)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/controller/document/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
const relatedDocuments = 4

type Sender interface {
SendDocument(address string, libraryPath string, fileName string) error
SendDocument(address, subject, libraryPath, fileName string) error
From() string
}

Expand Down
45 changes: 29 additions & 16 deletions internal/webserver/controller/document/detail.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/gofiber/fiber/v2"
"github.com/svera/coreander/v4/internal/index"
"github.com/svera/coreander/v4/internal/webserver/infrastructure"
"github.com/svera/coreander/v4/internal/webserver/model"
)
Expand Down Expand Up @@ -41,25 +42,12 @@ func (d *Controller) Detail(c *fiber.Ctx) error {
return fiber.ErrNotFound
}

title := fmt.Sprintf("%s | Coreander", document.Title)
title := fmt.Sprintf("%s", document.Title)
if len(document.Authors) > 0 {
title = fmt.Sprintf("%s - %s | Coreander", strings.Join(document.Authors, ", "), document.Title)
title = fmt.Sprintf("%s - %s", strings.Join(document.Authors, ", "), document.Title)
}

sameSubjects, err := d.idx.SameSubjects(document.Slug, relatedDocuments)
if err != nil {
fmt.Println(err)
}

sameAuthors, err := d.idx.SameAuthors(document.Slug, relatedDocuments)
if err != nil {
fmt.Println(err)
}

sameSeries, err := d.idx.SameSeries(document.Slug, relatedDocuments)
if err != nil {
fmt.Println(err)
}
sameSubjects, sameAuthors, sameSeries := d.related(document.Slug, (int(session.ID)))

if session.ID > 0 {
document = d.hlRepository.Highlighted(int(session.ID), document)
Expand All @@ -82,3 +70,28 @@ func (d *Controller) Detail(c *fiber.Ctx) error {
"Message": msg,
}, "layout")
}

func (d *Controller) related(slug string, sessionID int) (sameSubjects, sameAuthors, sameSeries []index.Document) {
var err error
if sameSubjects, err = d.idx.SameSubjects(slug, relatedDocuments); err != nil {
fmt.Println(err)
}
for i := range sameSubjects {
sameSubjects[i] = d.hlRepository.Highlighted(sessionID, sameSubjects[i])
}

if sameAuthors, err = d.idx.SameAuthors(slug, relatedDocuments); err != nil {
fmt.Println(err)
}
for i := range sameAuthors {
sameAuthors[i] = d.hlRepository.Highlighted(sessionID, sameAuthors[i])
}

if sameSeries, err = d.idx.SameSeries(slug, relatedDocuments); err != nil {
fmt.Println(err)
}
for i := range sameSeries {
sameSeries[i] = d.hlRepository.Highlighted(sessionID, sameSeries[i])
}
return sameSubjects, sameAuthors, sameSeries
}
4 changes: 2 additions & 2 deletions internal/webserver/controller/document/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ func (d *Controller) Reader(c *fiber.Ctx) error {

template := "reader"

title := fmt.Sprintf("%s | Coreander", document.Title)
title := fmt.Sprintf("%s", document.Title)
authors := strings.Join(document.Authors, ", ")
if authors != "" {
title = fmt.Sprintf("%s - %s | Coreander", authors, document.Title)
title = fmt.Sprintf("%s - %s", authors, document.Title)
}
return c.Render(template, fiber.Map{
"Title": title,
Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/controller/document/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ func (d *Controller) Send(c *fiber.Ctx) error {
return fiber.ErrInternalServerError
}

return d.sender.SendDocument(c.FormValue("email"), d.config.LibraryPath, document.ID)
return d.sender.SendDocument(c.FormValue("email"), document.Title, d.config.LibraryPath, document.ID)
}
10 changes: 5 additions & 5 deletions internal/webserver/controller/document/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (

func (d *Controller) UploadForm(c *fiber.Ctx) error {
return c.Render("upload", fiber.Map{
"Title": "Coreander",
"Title": "Upload document",
"MaxSize": d.config.UploadDocumentMaxSize,
}, "layout")
}
Expand All @@ -27,7 +27,7 @@ func (d *Controller) Upload(c *fiber.Ctx) error {
if err != nil {
if errors.Is(err, fasthttp.ErrMissingFile) {
return c.Status(fiber.StatusBadRequest).Render("upload", fiber.Map{
"Title": "Coreander",
"Title": "Upload document",
"Error": "Invalid file type",
}, "layout")
}
Expand All @@ -36,21 +36,21 @@ func (d *Controller) Upload(c *fiber.Ctx) error {
allowedTypes := []string{"application/epub+zip", "application/pdf"}
if !slices.Contains(allowedTypes, file.Header.Get("Content-Type")) {
return c.Status(fiber.StatusBadRequest).Render("upload", fiber.Map{
"Title": "Coreander",
"Title": "Upload document",
"Error": "Invalid file type",
}, "layout")
}

if file.Size > int64(d.config.UploadDocumentMaxSize*1024*1024) {
return c.Status(fiber.StatusRequestEntityTooLarge).Render("upload", fiber.Map{
"Title": "Coreander",
"Title": "Upload Document",
"Error": fmt.Sprintf("Document too large, the maximum allowed size is %d megabytes", d.config.UploadDocumentMaxSize),
}, "layout")
}

destination := filepath.Join(d.config.LibraryPath, file.Filename)
internalServerErrorStatus := c.Status(fiber.StatusInternalServerError).Render("upload", fiber.Map{
"Title": "Coreander",
"Title": "Upload Document",
"Error": "Error uploading document",
}, "layout")

Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/controller/highlight/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type usersRepository interface {
}

type Sender interface {
SendDocument(address string, libraryPath string, fileName string) error
SendDocument(address, subject, libraryPath, fileName string) error
From() string
}

Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/controller/home/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

type Sender interface {
SendDocument(address string, libraryPath string, fileName string) error
SendDocument(address, subject, libraryPath, fileName string) error
From() string
}

Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/controller/home/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (d *Controller) Index(c *fiber.Ctx) error {

return c.Render("index", fiber.Map{
"Count": count,
"Title": "Coreander",
"Title": "Home",
"EmailSendingConfigured": emailSendingConfigured,
"EmailFrom": d.sender.From(),
"HomeNavbar": true,
Expand Down
80 changes: 28 additions & 52 deletions internal/webserver/embedded/js/send-email.js
Original file line number Diff line number Diff line change
@@ -1,63 +1,39 @@
"use strict"

Array.from(document.getElementsByClassName("send-email")).forEach(form => {
form.addEventListener("submit", event => {
event.preventDefault();
document.body.addEventListener('htmx:configRequest', function (evt) {
const post = evt.detail.elt.getAttribute("hx-post")

if (!post || !post.includes("/send")) {
return
}

const submit = form.querySelector('button');
let sendIcon = form.querySelector('.bi-send-fill');
let spinner = form.querySelector('.spinner-border');
let text = evt.detail.elt.getAttribute("data-success-message")
text = text.replace("${email}", evt.detail.parameters['email'])
evt.detail.elt.setAttribute("data-success-message", text)

submit.setAttribute("disabled", true);
spinner.classList.remove("visually-hidden");
sendIcon.classList.add("visually-hidden");
fetch(form.getAttribute("action"), {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'email': form.elements[0].value
})
})
.then((response) => {
let message = form.querySelector(".send-email-message")
message.classList.remove("visually-hidden");
if (!response.ok) {
if (response.status == "403") {
location.reload()
} else {
message.innerHTML = form.getAttribute("data-error-message");
message.classList.remove("text-success");
message.classList.add("text-danger");
}
} else {
message.innerHTML = form.getAttribute("data-success-message");
message.classList.remove("text-danger");
message.classList.add("text-success");
}
submit.removeAttribute("disabled");
sendIcon.classList.remove("visually-hidden");
spinner.classList.add("visually-hidden");
})
.catch(function (error) {
// Catch errors
console.log(error);
});
});
});
text = evt.detail.elt.getAttribute("data-error-message")
text = text.replace("${email}", evt.detail.parameters['email'])
evt.detail.elt.setAttribute("data-error-message", text)
})

document.body.addEventListener('htmx:responseError', function (evt) {
const parent = evt.detail.elt.closest(".actions").parentNode;
parent.querySelector(".quick-email-error").classList.remove("d-none");
parent.querySelector(".quick-email-success").classList.add("d-none");
});
if (evt.detail.xhr.status === 403) {
location.reload()
return
}

const toast = document.getElementById('live-toast')
toast.querySelector(".toast-body").innerHTML = evt.detail.elt.getAttribute("data-error-message")
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toast)
toastBootstrap.show()
})

document.body.addEventListener('htmx:afterRequest', function (evt) {
const post = evt.detail.elt.getAttribute("hx-post")
if (!evt.detail.failed && post && post.includes("/send")) {
const parent = evt.detail.elt.closest(".actions").parentNode;
parent.querySelector(".quick-email-error").classList.add("d-none");
parent.querySelector(".quick-email-success").classList.remove("d-none");
const toast = document.getElementById('live-toast')
toast.querySelector(".toast-body").innerHTML = evt.detail.elt.getAttribute("data-success-message")
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toast)
toastBootstrap.show()
}
});
})
6 changes: 4 additions & 2 deletions internal/webserver/embedded/translations/es.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
"Send": Enviar
"Actions": Acciones
"Send to email unavailable, no email service configured": "Enviar a correo electrónico no disponible, no se ha configurado ningún servicio"
"Document sent successfully": "Documento enviado con éxito"
"There was an error sending the document, please try again later": "Hubo un error al enviar el documento, por favor, vuelva a intentarlo más tarde"
"%s sent to ${email}": "%s enviado a ${email}"
"There was an error sending %s to ${email}, please try again later": "Hubo un error al enviar %s a ${email}, por favor, vuelva a intentarlo más tarde"
"Read": "Leer"
"Users": "Usuarios"
"Username": "Usuario"
Expand Down Expand Up @@ -136,3 +136,5 @@
"Unexpected error, check your connection and try to refresh the page.": "Error inesperado, comprueba tu conexión y recarga la página."
"Unexpected server error": "Error inesperado en el servidor"
"Titles by %s": "Títulos de %s"
"Send to %s": "Enviar a %s"
"Home": "Inicio"
6 changes: 4 additions & 2 deletions internal/webserver/embedded/translations/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
"Send": Envoyer
"Actions": Actions
"Send to email unavailable, no email service configured": "Envoyer par e-mail indisponible, aucun service de messagerie configuré"
"Document sent successfully": "Document envoyé avec succès"
"There was an error sending the document, please try again later": "Une erreur s'est produite lors de l'envoi du document, veuillez réessayer ultérieurement"
"%s sent to ${email}": "%s envoyé à ${email}"
"There was an error sending %s to ${email}, please try again later": "Une erreur s'est produite lors de l'envoi du %s à ${email}, veuillez réessayer ultérieurement"
"Read": "Lire"
"Users": "Utilisateurs"
"Username": "Nom d'utilisateur"
Expand Down Expand Up @@ -136,3 +136,5 @@
"Unexpected error, check your connection and try to refresh the page.": "Erreur inattendue, vérifiez votre connexion et essayez d'actualiser la page."
"Unexpected server error": "Erreur de serveur inattendue"
"Titles by %s": "Titres par %s"
"Send to %s": "Envoyer à %s"
"Home": "Accueil"
4 changes: 2 additions & 2 deletions internal/webserver/embedded/views/document.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
{{$document := .Document}}

<div class="row mt-5">
<div class="col-md-4 col-sm-12 pe-3">
<div class="col-12 col-md-4 pe-3">
<div class="card border border-0">
{{template "partials/cover" dict "Lang" .Lang "Document" .Document "Session" .Session "DisableCoverMainLink" true}}
</div>
{{template "partials/actions" dict "Lang" $lang "Document" .Document "Session" $session "EmailSendingConfigured" .EmailSendingConfigured "EmailFrom" $emailFrom}}
</div>
<div class="col-md-8 col-sm-12 ps-3">
<div class="col-12 col-md-8 ps-3">
<div class="row">
<div class="col-12">
{{ if ne .Document.Series "" }} {{$seriesTitle := t $lang "Search for more titles belonging to %s"
Expand Down
2 changes: 1 addition & 1 deletion internal/webserver/embedded/views/layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Sergio Vera">
<title>{{t .Lang .Title}}</title>
<title>{{t .Lang .Title}} | Coreander</title>

<!-- Bootstrap core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet">
Expand Down
Loading

0 comments on commit 52f449b

Please sign in to comment.