intake/web/item.go

120 lines
2.8 KiB
Go
Raw Permalink Normal View History

package web
import (
2025-01-29 22:54:29 +00:00
"encoding/json"
2025-01-30 06:21:17 +00:00
"log"
"net/http"
2025-01-30 06:21:17 +00:00
"strings"
2025-01-29 22:54:29 +00:00
"time"
"github.com/Jaculabilis/intake/core"
"github.com/Jaculabilis/intake/web/html"
)
func (env *Env) getItem(writer http.ResponseWriter, req *http.Request) {
source := req.PathValue("source")
id := req.PathValue("id")
item, err := core.GetItem(env.db, source, id)
if err != nil {
writer.Write([]byte(err.Error()))
return
}
html.Item(writer, html.ItemData{Item: item})
}
2025-01-28 05:04:21 +00:00
func (env *Env) deleteItem(writer http.ResponseWriter, req *http.Request) {
source := req.PathValue("source")
id := req.PathValue("id")
_, err := core.DeactivateItem(env.db, source, id)
if err != nil {
writer.Write([]byte(err.Error()))
return
}
item, err := core.GetItem(env.db, source, id)
if err != nil {
writer.Write([]byte(err.Error()))
return
}
html.Item(writer, html.ItemData{Item: item})
}
2025-01-29 22:54:29 +00:00
func (env *Env) doAction(writer http.ResponseWriter, req *http.Request) {
source := req.PathValue("source")
id := req.PathValue("id")
action := req.PathValue("action")
item, err := core.GetItem(env.db, source, id)
if err != nil {
http.Error(writer, err.Error(), 500)
return
}
if item.Action[action] == nil {
http.Error(writer, "no such action", 500)
return
}
argv, err := core.GetArgvForAction(env.db, source, action)
if err != nil {
http.Error(writer, err.Error(), 500)
return
}
itemJson, err := json.Marshal(item)
if err != nil {
http.Error(writer, err.Error(), 500)
return
}
res, err := core.Execute(source, argv, nil, string(itemJson), time.Minute)
if err != nil {
http.Error(writer, err.Error(), 500)
return
}
if len(res) != 1 {
http.Error(writer, "not exactly one item", 500)
return
}
newItem := res[0]
core.BackfillItem(&newItem, &item)
if err = core.UpdateItems(env.db, []core.Item{newItem}); err != nil {
http.Error(writer, err.Error(), 500)
return
}
html.Item(writer, html.ItemData{Item: newItem})
}
2025-01-30 06:21:17 +00:00
func (env *Env) massDeactivate(writer http.ResponseWriter, req *http.Request) {
if err := req.ParseForm(); err != nil {
log.Printf("error parsing form data: %v", err)
http.Error(writer, "", http.StatusBadRequest)
return
}
for _, item := range req.PostForm["items"] {
i := strings.Index(item, "/")
if i == -1 {
log.Printf("error: invalid source/item: %s", item)
http.Error(writer, "", http.StatusBadRequest)
return
}
}
for _, item := range req.PostForm["items"] {
i := strings.Index(item, "/")
source := item[:i]
id := item[i+1:]
active, err := core.DeactivateItem(env.db, source, id)
if err != nil {
log.Printf("error: failed to deactivate %s/%s: %v", source, id, err)
}
if active {
log.Printf("deactivated %s/%s", source, id)
}
}
writer.Header()["HX-Refresh"] = []string{"true"}
http.Error(writer, "ok", http.StatusNoContent)
}