ekster/cmd/eksterd/micropub.go

207 lines
5.6 KiB
Go
Raw Normal View History

/*
* Ekster is a microsub server
* Copyright (c) 2021 The Ekster authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"crypto/sha1"
"database/sql"
"encoding/json"
"fmt"
2018-07-03 20:51:31 +00:00
"log"
"net/http"
2018-07-03 21:01:39 +00:00
"strings"
"time"
"p83.nl/go/ekster/pkg/jf2"
"p83.nl/go/ekster/pkg/microsub"
2018-08-15 17:04:15 +00:00
"github.com/gomodule/redigo/redis"
2019-03-23 20:03:45 +00:00
"github.com/pkg/errors"
"willnorris.com/go/microformats"
)
type micropubHandler struct {
Backend *memoryBackend
pool *redis.Pool
}
func (h *micropubHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2019-03-23 22:13:32 +00:00
defer func() {
err := r.Body.Close()
if err != nil {
log.Printf("could not close request body: %v", err)
}
}()
conn := h.pool.Get()
2019-03-23 22:13:32 +00:00
defer func() {
err := conn.Close()
if err != nil {
log.Printf("could not close redis connection: %v", err)
}
}()
2018-04-09 17:20:32 +00:00
2019-03-23 19:53:52 +00:00
err := r.ParseForm()
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
2019-03-23 19:53:52 +00:00
return
}
2018-07-03 20:51:31 +00:00
2019-03-23 20:04:42 +00:00
if r.Method == http.MethodPost {
2019-03-23 22:13:32 +00:00
var channel string
sourceID, channel, err := getChannelFromAuthorization(r, conn, h.Backend.database)
2019-03-23 22:13:32 +00:00
if err != nil {
log.Println(err)
http.Error(w, "unauthorized", http.StatusUnauthorized)
2019-03-23 22:13:32 +00:00
return
}
2019-03-23 22:13:32 +00:00
// no channel is found
if channel == "" {
http.Error(w, "bad request, unknown channel", http.StatusBadRequest)
2019-03-23 22:13:32 +00:00
return
}
2021-10-21 19:47:37 +00:00
// TODO: We could try to fill the Source of the Item with something, but what?
2019-03-23 20:03:45 +00:00
item, err := parseIncomingItem(r)
if err != nil {
2021-10-31 22:04:49 +00:00
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2021-10-31 22:08:43 +00:00
log.Printf("Item published: %s", item.Published)
if item.Published == "" {
item.Published = time.Now().Format(time.RFC3339)
}
2019-03-23 20:03:45 +00:00
item.Read = false
2019-03-24 09:25:20 +00:00
newID, err := generateItemID(conn, channel)
if err != nil {
2021-10-31 22:04:49 +00:00
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
2019-03-24 09:25:20 +00:00
return
}
item.ID = newID
item.Source = &microsub.Source{
ID: fmt.Sprintf("micropub:%d", sourceID),
Name: fmt.Sprintf("Source %d", sourceID),
}
_, err = h.Backend.channelAddItemWithMatcher(channel, *item)
2019-03-23 22:13:32 +00:00
if err != nil {
log.Printf("could not add item to channel %s: %v", channel, err)
}
2021-10-21 19:47:37 +00:00
2019-03-23 20:03:45 +00:00
err = h.Backend.updateChannelUnreadCount(channel)
if err != nil {
log.Printf("could not update channel unread content %s: %v", channel, err)
}
w.Header().Set("Content-Type", "application/json")
2019-03-23 22:13:32 +00:00
if err = json.NewEncoder(w).Encode(map[string]string{"ok": "1"}); err != nil {
2021-10-31 22:04:49 +00:00
log.Println(err)
http.Error(w, "internal server error", http.StatusInternalServerError)
2019-03-23 22:13:32 +00:00
}
2021-10-20 18:23:54 +00:00
return
}
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
2019-03-23 22:13:32 +00:00
2019-03-24 09:25:20 +00:00
func generateItemID(conn redis.Conn, channel string) (string, error) {
id, err := redis.Int(conn.Do("INCR", fmt.Sprintf("source:%s:next_id", channel)))
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprintf("source:%s:%d", channel, id)))), nil
}
func parseIncomingItem(r *http.Request) (*microsub.Item, error) {
contentType := r.Header.Get("content-type")
if contentType == "application/jf2+json" {
2021-10-20 18:23:54 +00:00
var item microsub.Item
if err := json.NewDecoder(r.Body).Decode(&item); err != nil {
return nil, fmt.Errorf("could not decode request body as %q: %v", contentType, err)
2019-03-24 09:25:20 +00:00
}
2021-10-20 18:23:54 +00:00
return &item, nil
2019-03-24 09:25:20 +00:00
} else if contentType == "application/json" {
var mfItem microformats.Microformat
2021-10-20 18:23:54 +00:00
if err := json.NewDecoder(r.Body).Decode(&mfItem); err != nil {
return nil, fmt.Errorf("could not decode request body as %q: %v", contentType, err)
2019-03-24 09:25:20 +00:00
}
author := microsub.Card{}
2021-10-20 18:23:54 +00:00
item, ok := jf2.SimplifyMicroformatItem(&mfItem, author)
2019-03-24 09:25:20 +00:00
if !ok {
return nil, fmt.Errorf("could not simplify microformat item to jf2")
}
2021-10-20 18:23:54 +00:00
return &item, nil
2019-03-24 09:25:20 +00:00
} else if contentType == "application/x-www-form-urlencoded" {
2021-10-20 18:23:54 +00:00
// TODO: improve handling of form-urlencoded
var item microsub.Item
2019-03-24 09:25:20 +00:00
content := r.FormValue("content")
name := r.FormValue("name")
item.Type = "entry"
item.Name = name
item.Content = &microsub.Content{Text: content}
item.Published = time.Now().Format(time.RFC3339)
2021-10-20 18:23:54 +00:00
return &item, nil
2019-03-24 09:25:20 +00:00
}
2021-10-20 18:23:54 +00:00
return nil, fmt.Errorf("content-type %q is not supported", contentType)
2019-03-24 09:25:20 +00:00
}
func getChannelFromAuthorization(r *http.Request, conn redis.Conn, database *sql.DB) (int, string, error) {
2019-03-23 22:13:32 +00:00
// backward compatible
sourceID := r.URL.Query().Get("source_id")
if sourceID != "" {
row := database.QueryRow(`
SELECT s.id as source_id, c.uid
FROM "sources" AS "s"
INNER JOIN "channels" AS "c" ON s.channel_id = c.id
WHERE "auth_code" = $1
`, sourceID)
var channel string
var sourceID int
if err := row.Scan(&sourceID, &channel); err == sql.ErrNoRows {
return 0, "", errors.New("channel not found")
2019-03-23 22:13:32 +00:00
}
return sourceID, channel, nil
2019-03-23 22:13:32 +00:00
}
// full micropub with indieauth
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
token := authHeader[7:]
channel, err := redis.String(conn.Do("HGET", "token:"+token, "channel"))
if err != nil {
return 0, "", errors.Wrap(err, "could not get channel for token")
2019-03-23 22:13:32 +00:00
}
return 0, channel, nil
2019-03-23 22:13:32 +00:00
}
return 0, "", fmt.Errorf("could not get channel from authorization")
2019-03-23 22:13:32 +00:00
}