Skip to content

Commit

Permalink
Refactor "file uses": Instead of displaying the count, add a new butt…
Browse files Browse the repository at this point in the history
…on to see an index of posts (maybe) containing that file
  • Loading branch information
jlelse committed Feb 18, 2025
1 parent 18c6ab1 commit 1a9930f
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 115 deletions.
47 changes: 35 additions & 12 deletions editorFiles.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
package main

import (
"context"
"net/http"
"sort"

"github.com/samber/lo"
"github.com/go-chi/chi/v5"
)

const (
editorFilesPath = "/files"
editorFileViewPath = editorFilesPath + "/view"
editorFileUsesPath = editorFilesPath + "/uses"
editorFileUsesPathPlaceholder = "/{filename}"
editorFileDeletePath = editorFilesPath + "/delete"
)

func (a *goBlog) serveEditorFiles(w http.ResponseWriter, r *http.Request) {
Expand All @@ -25,20 +34,10 @@ func (a *goBlog) serveEditorFiles(w http.ResponseWriter, r *http.Request) {
sort.Slice(files, func(i, j int) bool {
return files[i].Time.After(files[j].Time)
})
// Find uses
fileNames := lo.Map(files, func(f *mediaFile, _ int) string {
return f.Name
})
uses, err := a.db.usesOfMediaFile(fileNames...)
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
// Serve HTML
a.render(w, r, a.renderEditorFiles, &renderData{
Data: &editorFilesRenderData{
files: files,
uses: uses,
},
})
}
Expand All @@ -52,6 +51,30 @@ func (a *goBlog) serveEditorFilesView(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, a.mediaFileLocation(filename), http.StatusFound)
}

func (a *goBlog) serveEditorFilesUses(w http.ResponseWriter, r *http.Request) {
filename := r.FormValue("filename")
if filename == "" {
a.serveError(w, r, "No file selected", http.StatusBadRequest)
return
}
_, bc := a.getBlog(r)
http.Redirect(w, r, bc.getRelativePath(editorPath)+editorFileUsesPath+"/"+filename, http.StatusFound)
}

func (a *goBlog) serveEditorFilesUsesResults(w http.ResponseWriter, r *http.Request) {
filename := chi.URLParam(r, "filename")
if filename == "" {
a.serveError(w, r, "No file selected", http.StatusBadRequest)
return
}
_, bc := a.getBlog(r)
a.serveIndex(w, r.WithContext(context.WithValue(r.Context(), indexConfigKey, &indexConfig{
path: bc.getRelativePath(editorPath + editorFileUsesPath + "/" + filename),
usesFile: filename,
withoutFeeds: true,
})))
}

func (a *goBlog) serveEditorFilesDelete(w http.ResponseWriter, r *http.Request) {
filename := r.FormValue("filename")
if filename == "" {
Expand All @@ -63,5 +86,5 @@ func (a *goBlog) serveEditorFilesDelete(w http.ResponseWriter, r *http.Request)
return
}
_, bc := a.getBlog(r)
http.Redirect(w, r, bc.getRelativePath("/editor/files"), http.StatusFound)
http.Redirect(w, r, bc.getRelativePath(editorPath+editorFilesPath), http.StatusFound)
}
12 changes: 6 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
git.jlel.se/jlelse/go-shutdowner v0.0.0-20210707065515-773db8099c30
git.jlel.se/jlelse/goldmark-mark v0.0.0-20210522162520-9788c89266a4
git.jlel.se/jlelse/template-strings v0.0.0-20220211095702-c012e3b5045b
github.com/PuerkitoBio/goquery v1.10.1
github.com/PuerkitoBio/goquery v1.10.2
github.com/alecthomas/chroma/v2 v2.15.0
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
github.com/c2h5oh/datasize v0.0.0-20231215233829-aa82cc1e6500
Expand Down Expand Up @@ -49,7 +49,7 @@ require (
github.com/snabb/sitemap v1.0.4
github.com/sourcegraph/conc v0.3.0
github.com/spf13/cast v1.7.1
github.com/spf13/cobra v1.8.1
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.10.0
github.com/tdewolff/minify/v2 v2.21.3
Expand All @@ -58,7 +58,7 @@ require (
github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80
github.com/traefik/yaegi v0.16.1
github.com/vcraescu/go-paginator/v2 v2.0.0
github.com/wneessen/go-mail v0.6.1
github.com/wneessen/go-mail v0.6.2
github.com/yuin/goldmark v1.7.8
github.com/yuin/goldmark-emoji v1.0.4
go.hacdias.com/indielib v0.4.3
Expand All @@ -67,7 +67,7 @@ require (
golang.org/x/sync v0.11.0
golang.org/x/text v0.22.0
gopkg.in/yaml.v3 v3.0.1
maunium.net/go/mautrix v0.23.0
maunium.net/go/mautrix v0.23.1
willnorris.com/go/microformats v1.2.1-0.20240301064101-b5d1b9d2120e
)

Expand Down Expand Up @@ -123,9 +123,9 @@ require (
github.com/tidwall/sjson v1.2.5 // indirect
github.com/valyala/fastjson v1.6.4 // indirect
github.com/x448/float16 v0.8.4 // indirect
go.mau.fi/util v0.8.4 // indirect
go.mau.fi/util v0.8.5 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac // indirect
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa // indirect
golang.org/x/image v0.24.0 // indirect
golang.org/x/oauth2 v0.26.0 // indirect
golang.org/x/sys v0.30.0 // indirect
Expand Down
30 changes: 13 additions & 17 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ git.sr.ht/~mariusor/lw v0.0.0-20250114195945-ba9c7bcca3c1 h1:8a6fvSA8qd8EJLRYASm
git.sr.ht/~mariusor/lw v0.0.0-20250114195945-ba9c7bcca3c1/go.mod h1:kdxjbCGCqOyOGzTANLtNhS7TM2866n+To693WnpJSuE=
git.sr.ht/~mariusor/mask v0.0.0-20250114195353-98705a6977b7 h1:mforQrhdB8Xz4xxamqJOlDzdWMTV5BNlzn24NQ/gGiM=
git.sr.ht/~mariusor/mask v0.0.0-20250114195353-98705a6977b7/go.mod h1:Mw0HVQc45uMVOiZNDngXg6zQiO2h/yTsNhI5cm0uk3A=
github.com/PuerkitoBio/goquery v1.10.1 h1:Y8JGYUkXWTGRB6Ars3+j3kN0xg1YqqlwvdTV8WTFQcU=
github.com/PuerkitoBio/goquery v1.10.1/go.mod h1:IYiHrOMps66ag56LEH7QYDDupKXyo5A8qrjIx3ZtujY=
github.com/PuerkitoBio/goquery v1.10.2 h1:7fh2BdHcG6VFZsK7toXBT/Bh1z5Wmy8Q9MV9HqT2AM8=
github.com/PuerkitoBio/goquery v1.10.2/go.mod h1:0guWGjcLu9AYC7C1GHnpysHy056u9aEkUHwhdnePMCU=
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/chroma/v2 v2.15.0 h1:LxXTQHFoYrstG2nnV9y2X5O94sOBzf0CIUpSTbpxvMc=
Expand All @@ -41,7 +41,7 @@ github.com/carlmjohnson/requests v0.24.3/go.mod h1:duYA/jDnyZ6f3xbcF5PpZ9N8clgop
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
Expand Down Expand Up @@ -242,9 +242,8 @@ github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
Expand Down Expand Up @@ -289,8 +288,8 @@ github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXV
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
github.com/vcraescu/go-paginator/v2 v2.0.0 h1:m9If0wF7pSjYfocrJZcyWNiWn7OfIeLFVQLbiDvHf3k=
github.com/vcraescu/go-paginator/v2 v2.0.0/go.mod h1:qsrC8+/YgRL0LfurxeY3gCAtsN7oOthkIbmBdqpMX9U=
github.com/wneessen/go-mail v0.6.1 h1:cDGqlGuEEhdILRe53VFzmM9WBk8Xh/QMvbO0oxrNJB4=
github.com/wneessen/go-mail v0.6.1/go.mod h1:G702XlFhzHV0Z4w9j2VsH5K9dJDvj0hx+yOOp1oX9vc=
github.com/wneessen/go-mail v0.6.2 h1:c6V7c8D2mz868z9WJ+8zDKtUyLfZ1++uAZmo2GRFji8=
github.com/wneessen/go-mail v0.6.2/go.mod h1:L/PYjPK3/2ZlNb2/FjEBIn9n1rUWjW+Toy531oVmeb4=
github.com/wsxiaoys/terminal v0.0.0-20160513160801-0940f3fc43a0/go.mod h1:IXCdmsXIht47RaVFLEdVnh1t+pgYtTAhQGj73kz+2DM=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
Expand All @@ -303,8 +302,8 @@ github.com/yuin/goldmark-emoji v1.0.4 h1:vCwMkPZSNefSUnOW2ZKRUjBSD5Ok3W78IXhGxxA
github.com/yuin/goldmark-emoji v1.0.4/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
go.hacdias.com/indielib v0.4.3 h1:1QT0ZzMk+vMkoe4uZ31DLnWlLklGPgBYry0I+lCl0qM=
go.hacdias.com/indielib v0.4.3/go.mod h1:W7tSM6pCiM2JLdZ8xzSMpPf3GBB2hz+ONvGfvdp6S9o=
go.mau.fi/util v0.8.4 h1:mVKlJcXWfVo8ZW3f4vqtjGpqtZqJvX4ETekxawt2vnQ=
go.mau.fi/util v0.8.4/go.mod h1:MOfGTs1CBuK6ERTcSL4lb5YU7/ujz09eOPVEDckuazY=
go.mau.fi/util v0.8.5 h1:PwCAAtcfK0XxZ4sdErJyfBMkTEWoQU33aB7QqDDzQRI=
go.mau.fi/util v0.8.5/go.mod h1:Ycug9mrbztlahHPEJ6H5r8Nu/xqZaWbE5vPHVWmfz6M=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
Expand All @@ -314,11 +313,10 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac h1:l5+whBCLH3iH2ZNHYLbAe58bo7yrN4mVcnkHDYz5vvs=
golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac/go.mod h1:hH+7mtFmImwwcMvScyxUhjuVHR3HGaDPMn9rMSUUbxo=
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa h1:t2QcU6V556bFjYgu4L6C+6VrCPyJZ+eyRsABUPs1mz4=
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa/go.mod h1:BHOTPb3L19zxehTsLoJXVaTktb06DFgmdW6Wb9s8jqk=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
Expand Down Expand Up @@ -368,7 +366,6 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
Expand All @@ -380,7 +377,6 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down Expand Up @@ -415,8 +411,8 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.3/go.mod h1:AKDgRWk8lcSQSw+9kxCJnX/yySj8G3rdwYlU57cB45c=
gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.20.6/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
maunium.net/go/mautrix v0.23.0 h1:HNlR19eew5lvrNSL2muhExaGhYdaGk5FfEiA82QqUP4=
maunium.net/go/mautrix v0.23.0/go.mod h1:AGnnaz3ylGikUo1I1MJVn9QLsl2No1/ZNnGDyO0QD5s=
maunium.net/go/mautrix v0.23.1 h1:xZtX43YZF3WRxkdR+oMUrpiQe+jbjc+LeXLxHuXP5IM=
maunium.net/go/mautrix v0.23.1/go.mod h1:kldoZQDneV/jquIhwG1MmMw5j2A2M/MnQYRSWt863cY=
willnorris.com/go/microformats v1.2.1-0.20240301064101-b5d1b9d2120e h1:TRIOwo0NxN4KVSgYlYmiQktd9I96YgZ3942/JVzhwTM=
willnorris.com/go/microformats v1.2.1-0.20240301064101-b5d1b9d2120e/go.mod h1:zzo0hFA/E/nl1ZAjXiXA7KCKwCTdgBU+7HXltGgHeGA=
willnorris.com/go/webmention v0.0.0-20220108183051-4a23794272f0 h1:V5+O+YZHchEwu6ZmPcqT1dQ+mHgE356Q+w9SVOQ+QZg=
Expand Down
9 changes: 6 additions & 3 deletions httpRouters.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,9 +361,12 @@ func (a *goBlog) blogEditorRouter(_ *configBlog) func(r chi.Router) {
r.Use(a.authMiddleware)
r.Get("/", a.serveEditor)
r.Post("/", a.serveEditorPost)
r.Get("/files", a.serveEditorFiles)
r.Post("/files/view", a.serveEditorFilesView)
r.Post("/files/delete", a.serveEditorFilesDelete)
r.Get(editorFilesPath, a.serveEditorFiles)
r.Post(editorFileViewPath, a.serveEditorFilesView)
r.Post(editorFileUsesPath, a.serveEditorFilesUses)
r.Get(editorFileUsesPath+editorFileUsesPathPlaceholder, a.serveEditorFilesUsesResults)
r.Get(editorFileUsesPath+editorFileUsesPathPlaceholder+paginationPath, a.serveEditorFilesUsesResults)
r.Post(editorFileDeletePath, a.serveEditorFilesDelete)
r.Get("/drafts", a.serveDrafts)
r.Get("/drafts"+feedPath, a.serveDrafts)
r.Get("/drafts"+paginationPath, a.serveDrafts)
Expand Down
4 changes: 4 additions & 0 deletions posts.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,8 @@ type indexConfig struct {
status []postStatus
visibility []postVisibility
search string
usesFile string
withoutFeeds bool
}

const defaultPhotosPath = "/photos"
Expand Down Expand Up @@ -344,6 +346,7 @@ func (a *goBlog) serveIndex(w http.ResponseWriter, r *http.Request) {
publishedYear: ic.year,
publishedMonth: ic.month,
publishedDay: ic.day,
usesFile: ic.usesFile,
status: status,
visibility: visibility,
priorityOrder: true,
Expand Down Expand Up @@ -418,6 +421,7 @@ func (a *goBlog) serveIndex(w http.ResponseWriter, r *http.Request) {
next: nextPath,
summaryTemplate: summaryTemplate,
paramUrlQuery: paramUrlQuery,
withoutFeeds: ic.withoutFeeds,
},
})
}
67 changes: 9 additions & 58 deletions postsDb.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ type postsRequestConfig struct {
fetchWithoutParams bool // fetch posts without parameters
fetchParams []string // only fetch these parameters
withoutRenderedTitle bool // fetch posts without rendered title
usesFile string
}

func buildPostsQuery(c *postsRequestConfig, selection string) (query string, args []any, err error) {
Expand All @@ -405,16 +406,13 @@ func buildPostsQuery(c *postsRequestConfig, selection string) (query string, arg
// Selection
queryBuilder.WriteString("select ")
queryBuilder.WriteString(selection)
queryBuilder.WriteString(" from ")
// Table
queryBuilder.WriteString(" from posts")
// Filter
queryBuilder.WriteString(" where 1")
if c.search != "" {
queryBuilder.WriteString("(select p.* from posts_fts(@search) ps, posts p where ps.path = p.path)")
queryBuilder.WriteString(" and path in (select ps.path from posts_fts(@search) ps)")
args = append(args, sql.Named("search", c.search))
} else {
queryBuilder.WriteString("posts")
}
// Filter
queryBuilder.WriteString(" where 1")
if c.path != "" {
queryBuilder.WriteString(" and path = @path")
args = append(args, sql.Named("path", c.path))
Expand Down Expand Up @@ -547,6 +545,10 @@ func buildPostsQuery(c *postsRequestConfig, selection string) (query string, arg
queryBuilder.WriteString(" and toutc(published) < @publishedbefore")
args = append(args, sql.Named("publishedbefore", c.publishedBefore.UTC().Format(time.RFC3339)))
}
if c.usesFile != "" {
queryBuilder.WriteString(" and path in (select ps.path from posts_fts ps where ps.content MATCH '\"' || @usesfile || '\"' union all select pp.path from post_parameters pp where pp.value LIKE '%' || @usesfile || '%' )")
args = append(args, sql.Named("usesfile", c.usesFile))
}
// Order
queryBuilder.WriteString(" order by ")
if c.randomOrder {
Expand Down Expand Up @@ -752,54 +754,3 @@ func (d *database) allTaxonomyValues(blog string, taxonomy string) ([]string, er
}
return values, nil
}

const mediaUseSql = `
WITH mediafiles (name) AS (VALUES XXX)
SELECT name, COUNT(DISTINCT path) AS count
FROM (
SELECT m.name, p.path
FROM mediafiles m, post_parameters p
WHERE p.value LIKE '%' || m.name || '%'
UNION ALL
SELECT m.name, p.path
FROM mediafiles m, posts_fts p
WHERE p.content MATCH '"' || m.name || '"'
)
GROUP BY name;
`

func (db *database) usesOfMediaFile(names ...string) (counts []int, err error) {
sqlArgs := []any{}
nameValues := builderpool.Get()
defer builderpool.Put(nameValues)
for i, n := range names {
if i > 0 {
nameValues.WriteString(", ")
}
named := "name" + strconv.Itoa(i)
nameValues.WriteString("(@")
nameValues.WriteString(named)
nameValues.WriteString(")")
sqlArgs = append(sqlArgs, sql.Named(named, n))
}
rows, err := db.Query(strings.Replace(mediaUseSql, "XXX", nameValues.String(), 1), sqlArgs...)
if err != nil {
return nil, err
}
defer rows.Close()
countMap := make(map[string]int)
var name string
var count int
for rows.Next() {
err = rows.Scan(&name, &count)
if err != nil {
return nil, err
}
countMap[name] = count
}
counts = make([]int, len(names))
for i, n := range names {
counts[i] = countMap[n]
}
return counts, nil
}
12 changes: 7 additions & 5 deletions postsDb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ func Test_usesOfMediaFile(t *testing.T) {
err := app.db.savePost(&post{
Path: "/test/abc",
Content: "ABC test.jpg DEF",
Published: toLocalSafe(time.Now().String()),
Published: toLocalSafe(time.Now().Add(-1 * time.Hour).String()),
Blog: "en",
Section: "test",
Status: statusDraft,
Expand Down Expand Up @@ -338,11 +338,13 @@ func Test_usesOfMediaFile(t *testing.T) {
}, &postCreationOptions{new: true})
require.NoError(t, err)

counts, err := app.db.usesOfMediaFile("test.jpg")
results, err := app.getPosts(&postsRequestConfig{
usesFile: "test.jpg",
})
require.NoError(t, err)
assert.Len(t, counts, 1)
if assert.NotEmpty(t, counts) {
assert.Equal(t, 2, counts[0])
if assert.Len(t, results, 2) {
assert.Equal(t, "/test/def", results[0].Path)
assert.Equal(t, "/test/abc", results[1].Path)
}
}

Expand Down
2 changes: 1 addition & 1 deletion strings/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ editorpostdesc: "💡 Empty parameters are removed automatically. More possible
editorusetemplate: "Use template"
emailopt: "Email (optional)"
feed: "Feed"
fileuses: "file uses"
fileuses: "File uses"
follow: "Follow"
followusingactivitypub: "Follow using ActivityPub"
general: "General"
Expand Down
Loading

0 comments on commit 1a9930f

Please sign in to comment.