Compare commits

...

114 Commits
v2 ... main

Author SHA1 Message Date
Niko Abeler da06541e11 spacing var 2024-05-18 22:05:44 +02:00
Niko Abeler 7b047a609f powered by 2024-05-18 22:04:23 +02:00
Niko Abeler a5f24427a1 cleanup + primary color usage 2024-05-18 21:59:32 +02:00
Niko Abeler ec13fffbe9 release flow 3 2024-05-18 21:11:03 +02:00
Niko Abeler 686cd72ec2 release flow 2 2024-05-18 21:06:42 +02:00
Niko Abeler 29e875d2e5 release flow 2024-05-18 20:49:07 +02:00
Niko Abeler f958fa36fd fix test 2024-05-18 20:31:50 +02:00
Niko Abeler 1b347bcdac CI setup 4 2024-05-18 20:20:00 +02:00
Niko Abeler c8b759a834 CI setup 3 2024-05-18 20:16:47 +02:00
Niko Abeler 943bc10eaf CI setup 2 2024-05-18 20:00:19 +02:00
Niko Abeler 4543e448ed update requirements 2024-05-18 19:57:15 +02:00
Niko Abeler e0d6f4f223 CI setup 1 2024-05-18 19:54:58 +02:00
Niko Abeler 49a602f68b
Create test.yml 2024-05-18 19:53:06 +02:00
Niko Abeler 596ab0047e CI prep + README 2024-05-18 19:49:55 +02:00
Niko Abeler 5c05f48be3 prevent publishing of drafts + support for recipes 2024-05-18 19:34:44 +02:00
Niko Abeler 3c924ac8a4 support for images 2024-05-18 16:12:35 +02:00
Niko Abeler 26737ea21d remove files 2024-05-18 15:21:12 +02:00
Niko Abeler 29ae7e717f actor details 2024-05-18 13:10:14 +02:00
Niko Abeler 741ccfac73 support announce, publish deletions, add 'hashtags' to notes 2024-05-18 12:42:49 +02:00
Niko Abeler 9cfbf0b9b7 process likes from ActivityPub 2024-05-17 22:37:18 +02:00
Niko Abeler cba57ba708 first working toot 2024-05-17 21:05:13 +02:00
Niko Abeler ced3907880 move actor to main url 2024-05-17 20:23:38 +02:00
Niko Abeler 3cbf952ae6 sending accepts 2024-05-16 21:11:02 +02:00
Niko Abeler 0c8779def7 test follow/unfollow 2024-05-16 20:27:08 +02:00
Niko Abeler 652f81805d WIP mock amsto + tests 2024-05-14 21:23:37 +02:00
Niko Abeler 624f19a1d9 WIP copying code from fedi-games 2024-05-13 19:03:24 +02:00
Niko Abeler 10ca2bdcd9 add follower repository 2024-05-12 21:45:04 +02:00
Niko Abeler 633c0991e9 add me links again 2024-05-11 21:21:39 +02:00
Niko Abeler 2bf2e409b6 fixes for small screens 2024-05-11 19:46:47 +02:00
Niko Abeler 390a58b404 using owl styling 2024-05-11 16:33:29 +02:00
Niko Abeler d7e5df2a95 tables 2024-05-09 16:52:13 +02:00
Niko Abeler 3a3655b587 remove picocss files 2024-05-09 16:11:35 +02:00
Niko Abeler cba07e961d actions and forms 2024-05-09 16:11:13 +02:00
Niko Abeler 1524820d5e extending own stylesheet to remove pico 2024-05-09 14:15:19 +02:00
Niko Abeler 91b82f0e57 package updates 2024-05-09 11:13:42 +02:00
Niko Abeler 2a4b76ee03 add indication of upload error 2024-05-09 11:02:41 +02:00
Niko Abeler 4bdb920c71 add animation while uploading a dropped file 2024-05-09 10:58:32 +02:00
Niko Abeler ff10f6c5eb raise upload limit 2024-05-09 10:47:10 +02:00
Niko Abeler bc7b146e91 add @context to actor 2024-02-26 20:17:53 +01:00
Niko Abeler 7eb3bf0b44 update README with build and run 2024-02-25 20:29:41 +01:00
Niko Abeler 5cc55a79ff refactoring to have a dedicated site config service. Default config for new setups 2024-02-25 14:01:55 +01:00
Niko Abeler be62bcd627 use static favicon 2024-02-24 21:53:39 +01:00
Niko Abeler d794ad0865 remove empty tag 2024-02-24 21:22:23 +01:00
Niko Abeler f5946ea823 Open Graph Meta data 2024-02-24 21:21:48 +01:00
Niko Abeler 8200e3384c fix for interactions 2024-02-24 20:11:09 +01:00
Niko Abeler 0bf7c492c9 WIP interaction list 2024-02-24 19:53:49 +01:00
Niko Abeler 765698b1a6 compact file site in admin 2024-02-23 13:02:13 +01:00
Niko Abeler 1485a7efbe update to pico 2 2024-02-23 12:57:43 +01:00
Niko Abeler bc50388f58 filter for binary files 2024-02-23 12:34:05 +01:00
Niko Abeler 7ceb00799a add drop file to more forms 2024-02-23 10:15:06 +01:00
Niko Abeler 6d115dd74e finish drop file and moved into function for reusablility 2024-02-23 10:10:07 +01:00
Niko Abeler 4941b5d027 drag files into article 2024-02-21 21:21:58 +01:00
Niko Abeler 2f81bf8678 unified interface Formable 2024-02-21 20:24:18 +01:00
h4kor c36b9abbcf Merge pull request 'Better Editor Forms' (#56) from better_forms into main
Reviewed-on: #56
2024-02-21 19:05:07 +00:00
Niko Abeler 1613d3dd11 remove owl annotations 2024-02-21 20:04:22 +01:00
Niko Abeler bd11b88338 removal of forms 2024-02-21 20:03:18 +01:00
Niko Abeler 1fdcdff41d all entry types with custom forms 2024-02-14 21:05:50 +01:00
Niko Abeler eee2131a76 more custom forms 2024-02-14 20:43:43 +01:00
Niko Abeler fcc0132758 first custom form 2024-02-14 19:53:49 +01:00
Niko Abeler b86eee27ce WIP, large refactoring to allow custom form code per type 2024-02-13 21:43:52 +01:00
Niko Abeler 50997c051b slimmer action on entry 2024-01-25 22:12:14 +01:00
Niko Abeler 4bbaf3362e action tiles on main admin page 2024-01-24 22:04:15 +01:00
Niko Abeler c196a72d34 WIP grid buttons 2024-01-23 19:17:04 +01:00
Niko Abeler 94b6628411 fix build 2024-01-17 21:38:41 +01:00
Niko Abeler 8d3bdb6f4c ensure trailing slash on entries to avoid duplicate urls 2024-01-17 20:04:27 +01:00
Niko Abeler 30e54f99fb add links to rss 2023-09-04 20:23:02 +02:00
Niko Abeler 0bbcde6ff6 reset password command 2023-08-12 20:39:07 +02:00
Niko Abeler b0a6a0d417 better time format 2023-08-11 17:37:22 +02:00
Niko Abeler ad8cbbf556 sending webmentions again 2023-08-11 16:11:59 +02:00
Niko Abeler 08678e2697 move webmention stuff into util function (same code as v1) 2023-08-11 15:52:14 +02:00
Niko Abeler cd116b9a57 more generalized bus 2023-08-11 15:17:30 +02:00
Niko Abeler a89aa7ee27 upload images to instagram 2023-08-10 21:56:06 +02:00
Niko Abeler 9322e59b96 Prototype plugin 2023-08-09 21:56:56 +02:00
Niko Abeler d4351af8f1 tidy up 2023-08-09 21:45:56 +02:00
Niko Abeler 975761af2f test for interaction repo 2023-08-09 21:44:29 +02:00
Niko Abeler 55fb101ab5 Merge branch 'interactions' 2023-08-09 20:48:36 +02:00
Niko Abeler 653efcc487 deletion of webmentions 2023-08-09 20:48:16 +02:00
Niko Abeler 723a6000bf first retrieved webmention 2023-08-09 20:36:44 +02:00
Niko Abeler df5215d943 tests for incoming webmention 2023-08-09 20:10:51 +02:00
Niko Abeler 3f7b1bae50 disallow GPT in robots.txt 2023-08-09 19:16:17 +02:00
Niko Abeler 6ab9af2d53 WIP rebuilding incoming webmention from v1 code 2023-08-08 21:32:24 +02:00
Niko Abeler b1c46a86aa layouting webmention 2023-08-08 20:17:04 +02:00
Niko Abeler 5939bbd09d better entry ids 2023-08-08 19:42:11 +02:00
Niko Abeler 304db7ec03 no max width 2023-08-06 12:14:41 +02:00
Niko Abeler fb824ac07e smaller images 2023-08-06 12:08:46 +02:00
Niko Abeler 482a962351 link to admin page 2023-08-05 21:45:59 +02:00
Niko Abeler 74760707dd start refactoring forms. Allow list for recipe ingredients 2023-08-05 21:24:26 +02:00
Niko Abeler 349aa0dd5d draft list 2023-08-05 13:35:56 +02:00
Niko Abeler 70902af7e0 publishing in edit 2023-08-05 10:15:08 +02:00
Niko Abeler 42d960f185 allow draft publish + view drafts as author 2023-08-05 10:14:05 +02:00
Niko Abeler 9e64672f9c unpublish entry 2023-07-30 11:29:30 +02:00
Niko Abeler 080614e83f linking binary page 2023-07-27 22:04:00 +02:00
Niko Abeler ebca3e84f2 simple binary create, delete, list 2023-07-27 22:02:13 +02:00
Niko Abeler e998272f81 fix login redirect 2023-07-27 21:19:52 +02:00
Niko Abeler 7ead1ffe22 restructure admin area 2023-07-27 21:18:09 +02:00
Niko Abeler 0de18e89fc send 404 on messing binary 2023-07-27 20:56:26 +02:00
Niko Abeler 40117dab37 fix crash on missing file 2023-07-27 20:55:50 +02:00
Niko Abeler 5e77fdd33b WIP minimal AP 2023-07-26 21:28:57 +02:00
Niko Abeler 5f49754b71 deletion 2023-07-25 21:49:09 +02:00
Niko Abeler 34e4984af9 content type for media 2023-07-25 21:39:57 +02:00
Niko Abeler e35bf9af5d microformats improvement 2023-07-25 21:37:26 +02:00
Niko Abeler e628735ab2 edit feature 2023-07-25 21:31:03 +02:00
Niko Abeler a610515d5e sitemap 2023-07-25 19:10:37 +02:00
Niko Abeler ea9059f9f0 robots.txt 2023-07-25 18:59:25 +02:00
Niko Abeler 802e9a399e option to add html header and footer html 2023-07-24 21:27:51 +02:00
Niko Abeler a38ebb61a9 form to edit registered configs 2023-07-22 21:12:53 +02:00
Niko Abeler 68e8f84220 WIP activity pub PoC 2023-07-22 20:34:17 +02:00
Niko Abeler 0a4106be9c more RSS 2023-07-21 22:09:48 +02:00
Niko Abeler ea06b26c9f add self atom:link 2023-07-21 21:59:25 +02:00
Niko Abeler d736679418 improve rss 2023-07-21 21:40:32 +02:00
Niko Abeler e31dbeb18c trailing slash 2023-07-20 19:56:43 +02:00
Niko Abeler 128e38651d minimal xml from v1 2023-07-20 19:49:52 +02:00
Niko Abeler 838e949e57 tidy mod 2023-07-19 21:11:21 +02:00
h4kor 2932f2f16c Merge pull request 'v2' (#43) from v2 into main
Reviewed-on: #43
2023-07-19 19:09:19 +00:00
133 changed files with 6366 additions and 981 deletions

46
.air.toml Normal file
View File

@ -0,0 +1,46 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "/tmp"
[build]
args_bin = ["web"]
bin = "/tmp/main"
cmd = "go build -buildvcs=false -o /tmp/main owl-blogs/cmd/owl"
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html", "css"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
main_only = false
time = false
[misc]
clean_on_exit = false
[screen]
clear_on_rebuild = false
keep_scroll = true

3
.dockerignore Normal file
View File

@ -0,0 +1,3 @@
e2e_tests/
tmp/
*.db

45
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,45 @@
on:
release:
types: [created]
permissions:
contents: write
packages: write
jobs:
release-linux-amd64:
name: release linux/amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.22'
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
- name: E2E Test
run: |
cd e2e_tests
docker compose -f docker-compose.ci.yml up -d
pip install -r requirements.txt
pytest
- name: Build Release
env:
CGO_ENABLED: 1
GOOS: linux
GOARCH: amd64
GH_TOKEN: ${{ github.token }}
run: |
go build -o owl-linux-amd64 ./cmd/owl
gh release upload ${{github.event.release.tag_name}} owl-linux-amd64

38
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,38 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
name: Go
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.22'
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
- name: E2E Test
run: |
cd e2e_tests
docker compose -f docker-compose.ci.yml up -d
pip install -r requirements.txt
pytest

6
.gitignore vendored
View File

@ -26,4 +26,8 @@ users/
*.swp
*.db
*.db
tmp/
venv/
*.pyc

View File

@ -1,10 +1,10 @@
##
## Build Container
##
FROM golang:1.20-alpine as build
FROM golang:1.22-alpine as build
RUN apk add --no-cache git
RUN apk add --no-cache --update git gcc g++
WORKDIR /tmp/owl
@ -15,7 +15,7 @@ RUN go mod download
COPY . .
RUN go build -o ./out/owl ./cmd/owl
RUN CGO_ENABLED=1 GOOS=linux go build -o ./out/owl ./cmd/owl
##
@ -27,7 +27,9 @@ RUN apk add ca-certificates
COPY --from=build /tmp/owl/out/ /bin/
# This container exposes port 8080 to the outside world
EXPOSE 8080
EXPOSE 3000
WORKDIR /owl
# Run the binary program produced by `go install`
ENTRYPOINT ["/bin/owl"]

View File

@ -2,7 +2,60 @@
# Owl Blogs
A simple web server for blogs generated from Markdown files.
Owl-blogs is a blogging software focused on simplicity with IndieWeb and Fediverse support.
**_This project is not yet stable. Expect frequent breaking changes! Only use this if you are willing to regularly adjust your project accordingly._**
# Usage
## Run
To run the web server use the command:
```
owl web
```
The blog will run on port 3000 (http://localhost:3000)
To create a new account:
```
owl new-author -u <name> -p <password>
```
To retrieve a list of all commands run:
```
owl -h
```
# Development
## Build
```
CGO_ENABLED=1 go build -o owl ./cmd/owl
```
For development with live reload use `air` ([has to be install first](https://github.com/cosmtrek/air))
## Tests
The project has two test suites; "unit tests" written in go and "end-to-end tests" written in python.
### Unit Tests
```
go test ./...
```
### End-to-End tests
- Start the docker compose setup in the `e2e_tests` directory.
- Install the python dependencies into a virtualenv
```
cd e2e_tests
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
```
- Run the e2e_tests with `pytest`

712
app/activity_pub_service.go Normal file
View File

@ -0,0 +1,712 @@
package app
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io"
"log/slog"
"net/http"
"net/url"
"owl-blogs/app/repository"
"owl-blogs/config"
"owl-blogs/domain/model"
entrytypes "owl-blogs/entry_types"
"owl-blogs/interactions"
"owl-blogs/render"
"reflect"
"regexp"
"strconv"
"strings"
"time"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/jsonld"
"github.com/go-fed/httpsig"
)
type ActivityPubConfig struct {
PreferredUsername string
PublicKeyPem string
PrivateKeyPem string
}
// Form implements app.AppConfig.
func (cfg *ActivityPubConfig) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/ActivityPubConfig", cfg)
return f
}
// ParseFormData implements app.AppConfig.
func (cfg *ActivityPubConfig) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
cfg.PreferredUsername = data.FormValue("PreferredUsername")
cfg.PublicKeyPem = data.FormValue("PublicKeyPem")
cfg.PrivateKeyPem = data.FormValue("PrivateKeyPem")
return nil
}
func (cfg *ActivityPubConfig) PrivateKey() *rsa.PrivateKey {
block, _ := pem.Decode([]byte(cfg.PrivateKeyPem))
privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
slog.Error("error x509.ParsePKCS1PrivateKey", "err", err)
}
return privKey
}
type ActivityPubService struct {
followersRepo repository.FollowerRepository
configRepo repository.ConfigRepository
interactionRepository repository.InteractionRepository
entryService *EntryService
siteConfigServcie *SiteConfigService
binService *BinaryService
}
func NewActivityPubService(
followersRepo repository.FollowerRepository,
configRepo repository.ConfigRepository,
interactionRepository repository.InteractionRepository,
entryService *EntryService,
siteConfigServcie *SiteConfigService,
binService *BinaryService,
bus *EventBus,
) *ActivityPubService {
service := &ActivityPubService{
followersRepo: followersRepo,
configRepo: configRepo,
interactionRepository: interactionRepository,
entryService: entryService,
binService: binService,
siteConfigServcie: siteConfigServcie,
}
bus.Subscribe(service)
return service
}
func (svc *ActivityPubService) defaultConfig() ActivityPubConfig {
privKey, _ := rsa.GenerateKey(rand.Reader, 2048)
pubKey := privKey.Public().(*rsa.PublicKey)
pubKeyPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(pubKey),
},
)
privKeyPrm := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privKey),
},
)
return ActivityPubConfig{
PreferredUsername: "blog",
PublicKeyPem: string(pubKeyPem),
PrivateKeyPem: string(privKeyPrm),
}
}
func (svc *ActivityPubService) GetApConfig() (ActivityPubConfig, error) {
apConfig := ActivityPubConfig{}
err := svc.configRepo.Get(config.ACT_PUB_CONF_NAME, &apConfig)
if err != nil {
println("ERROR IN ACTIVITY PUB CONFIG")
return ActivityPubConfig{}, err
}
if reflect.ValueOf(apConfig).IsZero() {
cfg := svc.defaultConfig()
svc.configRepo.Update(config.ACT_PUB_CONF_NAME, cfg)
return cfg, nil
}
return apConfig, nil
}
func (svc *ActivityPubService) ActorUrl() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl
}
func (svc *ActivityPubService) MainKeyUri() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "#main-key"
}
func (svc *ActivityPubService) InboxUrl() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "/activitypub/inbox"
}
func (svc *ActivityPubService) OutboxUrl() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "/activitypub/outbox"
}
func (svc *ActivityPubService) FollowersUrl() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "/activitypub/followers"
}
func (svc *ActivityPubService) AcccepId() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "#accept-" + strconv.FormatInt(time.Now().UnixNano(), 16)
}
func (svc *ActivityPubService) HashtagId(hashtag string) string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.FullUrl + "/tags/" + strings.ReplaceAll(hashtag, "#", "")
}
func (svc *ActivityPubService) ActorName() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.Title
}
func (svc *ActivityPubService) ActorIcon() vocab.Image {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
u := cfg.AvatarUrl
pUrl, _ := url.Parse(u)
parts := strings.Split(pUrl.Path, ".")
fullUrl, _ := url.JoinPath(cfg.FullUrl, u)
return vocab.Image{
Type: vocab.ImageType,
MediaType: vocab.MimeType("image/" + parts[len(parts)-1]),
URL: vocab.IRI(fullUrl),
}
}
func (svc *ActivityPubService) ActorSummary() string {
cfg, _ := svc.siteConfigServcie.GetSiteConfig()
return cfg.SubTitle
}
func (s *ActivityPubService) AddFollower(follower string) error {
return s.followersRepo.Add(follower)
}
func (s *ActivityPubService) RemoveFollower(follower string) error {
return s.followersRepo.Remove(follower)
}
func (s *ActivityPubService) AllFollowers() ([]string, error) {
return s.followersRepo.All()
}
func (s *ActivityPubService) sign(privateKey *rsa.PrivateKey, pubKeyId string, body []byte, r *http.Request) error {
prefs := []httpsig.Algorithm{httpsig.RSA_SHA256}
digestAlgorithm := httpsig.DigestSha256
// The "Date" and "Digest" headers must already be set on r, as well as r.URL.
headersToSign := []string{httpsig.RequestTarget, "host", "date"}
if body != nil {
headersToSign = append(headersToSign, "digest")
}
signer, _, err := httpsig.NewSigner(prefs, digestAlgorithm, headersToSign, httpsig.Signature, 0)
if err != nil {
return err
}
// To sign the digest, we need to give the signer a copy of the body...
// ...but it is optional, no digest will be signed if given "nil"
// If r were a http.ResponseWriter, call SignResponse instead.
err = signer.SignRequest(privateKey, pubKeyId, r, body)
slog.Info("Signed Request", "req", r.Header)
return err
}
func (s *ActivityPubService) GetActor(reqUrl string) (vocab.Actor, error) {
siteConfig := model.SiteConfig{}
apConfig := ActivityPubConfig{}
s.configRepo.Get(config.ACT_PUB_CONF_NAME, &apConfig)
s.configRepo.Get(config.SITE_CONFIG, &siteConfig)
c := http.Client{}
parsedUrl, err := url.Parse(reqUrl)
if err != nil {
slog.Error("parse error", "err", err)
return vocab.Actor{}, err
}
req, _ := http.NewRequest("GET", reqUrl, nil)
req.Header.Set("Accept", "application/ld+json")
req.Header.Set("Date", time.Now().Format(http.TimeFormat))
req.Header.Set("Host", parsedUrl.Host)
err = s.sign(apConfig.PrivateKey(), s.MainKeyUri(), nil, req)
if err != nil {
slog.Error("Signing error", "err", err)
return vocab.Actor{}, err
}
resp, err := c.Do(req)
if err != nil {
slog.Error("failed to retrieve sender actor", "err", err, "url", reqUrl)
return vocab.Actor{}, err
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return vocab.Actor{}, err
}
item, err := vocab.UnmarshalJSON(data)
if err != nil {
return vocab.Actor{}, err
}
var actor vocab.Actor
err = vocab.OnActor(item, func(o *vocab.Actor) error {
actor = *o
return nil
})
return actor, err
}
func (s *ActivityPubService) VerifySignature(r *http.Request, sender string) error {
siteConfig := model.SiteConfig{}
apConfig := ActivityPubConfig{}
s.configRepo.Get(config.ACT_PUB_CONF_NAME, &apConfig)
s.configRepo.Get(config.SITE_CONFIG, &siteConfig)
slog.Info("verifying for", "sender", sender, "retriever", s.ActorUrl())
actor, err := s.GetActor(sender)
// actor does not have a pub key -> don't verify
if actor.PublicKey.PublicKeyPem == "" {
return nil
}
if err != nil {
slog.Error("unable to retrieve actor for sig verification", "sender", sender)
return err
}
block, _ := pem.Decode([]byte(actor.PublicKey.PublicKeyPem))
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
slog.Error("unable to decode pub key pem", "pubKeyPem", actor.PublicKey.PublicKeyPem)
return err
}
slog.Info("retrieved pub key of sender", "actor", actor, "pubKey", pubKey)
verifier, err := httpsig.NewVerifier(r)
if err != nil {
slog.Error("invalid signature", "err", err)
return err
}
return verifier.Verify(pubKey, httpsig.RSA_SHA256)
}
func (s *ActivityPubService) Accept(act *vocab.Activity) error {
actor, err := s.GetActor(act.Actor.GetID().String())
if err != nil {
return err
}
accept := vocab.AcceptNew(vocab.IRI(s.AcccepId()), act)
data, err := jsonld.WithContext(
jsonld.IRI(vocab.ActivityBaseURI),
).Marshal(accept)
if err != nil {
slog.Error("marshalling error", "err", err)
return err
}
return s.sendObject(actor, data)
}
func (s *ActivityPubService) AddLike(sender string, liked string, likeId string) error {
entry, err := s.entryService.FindByUrl(liked)
if err != nil {
return err
}
actor, err := s.GetActor(sender)
if err != nil {
return err
}
var like *interactions.Like
interaction, err := s.interactionRepository.FindById(likeId)
if err != nil {
interaction = &interactions.Like{}
}
like, ok := interaction.(*interactions.Like)
if !ok {
return errors.New("existing interaction with same id is not a like")
}
existing := like.ID() != ""
likeMeta := interactions.LikeMetaData{
SenderUrl: sender,
SenderName: actor.Name.String(),
}
like.SetID(likeId)
like.SetMetaData(&likeMeta)
like.SetEntryID(entry.ID())
like.SetCreatedAt(time.Now())
if !existing {
return s.interactionRepository.Create(like)
} else {
return s.interactionRepository.Update(like)
}
}
func (s *ActivityPubService) RemoveLike(id string) error {
interaction, err := s.interactionRepository.FindById(id)
if err != nil {
interaction = &interactions.Like{}
}
return s.interactionRepository.Delete(interaction)
}
func (s *ActivityPubService) AddRepost(sender string, reposted string, respostId string) error {
entry, err := s.entryService.FindByUrl(reposted)
if err != nil {
return err
}
actor, err := s.GetActor(sender)
if err != nil {
return err
}
var repost *interactions.Repost
interaction, err := s.interactionRepository.FindById(respostId)
if err != nil {
interaction = &interactions.Repost{}
}
repost, ok := interaction.(*interactions.Repost)
if !ok {
return errors.New("existing interaction with same id is not a like")
}
existing := repost.ID() != ""
repostMeta := interactions.RepostMetaData{
SenderUrl: sender,
SenderName: actor.Name.String(),
}
repost.SetID(respostId)
repost.SetMetaData(&repostMeta)
repost.SetEntryID(entry.ID())
repost.SetCreatedAt(time.Now())
if !existing {
return s.interactionRepository.Create(repost)
} else {
return s.interactionRepository.Update(repost)
}
}
func (s *ActivityPubService) RemoveRepost(id string) error {
interaction, err := s.interactionRepository.FindById(id)
if err != nil {
interaction = &interactions.Repost{}
}
return s.interactionRepository.Delete(interaction)
}
func (s *ActivityPubService) sendObject(to vocab.Actor, data []byte) error {
siteConfig := model.SiteConfig{}
apConfig := ActivityPubConfig{}
s.configRepo.Get(config.ACT_PUB_CONF_NAME, &apConfig)
s.configRepo.Get(config.SITE_CONFIG, &siteConfig)
if to.Inbox == nil {
slog.Error("actor has no inbox", "actor", to)
return errors.New("actor has no inbox")
}
actorUrl, err := url.Parse(to.Inbox.GetID().String())
if err != nil {
slog.Error("parse error", "err", err)
return err
}
c := http.Client{}
req, _ := http.NewRequest("POST", to.Inbox.GetID().String(), bytes.NewReader(data))
req.Header.Set("Accept", "application/ld+json")
req.Header.Set("Date", time.Now().Format(http.TimeFormat))
req.Header.Set("Host", actorUrl.Host)
err = s.sign(apConfig.PrivateKey(), s.MainKeyUri(), data, req)
if err != nil {
slog.Error("Signing error", "err", err)
return err
}
resp, err := c.Do(req)
if err != nil {
slog.Error("Sending error", "url", req.URL, "err", err)
return err
}
slog.Info("Request", "host", resp.Request.Header)
if resp.StatusCode > 299 {
body, _ := io.ReadAll(resp.Body)
slog.Error("Error sending Note", "method", resp.Request.Method, "url", resp.Request.URL, "status", resp.Status, "body", string(body))
return err
}
body, _ := io.ReadAll(resp.Body)
slog.Info("Sent Body", "body", string(data))
slog.Info("Retrieved", "status", resp.Status, "body", string(body))
return nil
}
/*
* Notifiers
*/
func (svc *ActivityPubService) NotifyEntryCreated(entry model.Entry) {
slog.Info("Processing Entry Create for ActivityPub")
followers, err := svc.AllFollowers()
if err != nil {
slog.Error("Cannot retrieve followers")
}
object, err := svc.entryToObject(entry)
if err != nil {
slog.Error("Cannot convert object", "err", err)
}
create := vocab.CreateNew(object.ID, object)
create.Actor = object.AttributedTo
create.To = object.To
create.Published = object.Published
data, err := jsonld.WithContext(
jsonld.IRI(vocab.ActivityBaseURI),
jsonld.Context{
jsonld.ContextElement{
Term: "toot",
IRI: jsonld.IRI("http://joinmastodon.org/ns#"),
},
},
).Marshal(create)
if err != nil {
slog.Error("marshalling error", "err", err)
}
for _, follower := range followers {
actor, err := svc.GetActor(follower)
if err != nil {
slog.Error("Unable to retrieve follower actor", "err", err)
}
svc.sendObject(actor, data)
}
}
func (svc *ActivityPubService) NotifyEntryUpdated(entry model.Entry) {
slog.Info("Processing Entry Create for ActivityPub")
followers, err := svc.AllFollowers()
if err != nil {
slog.Error("Cannot retrieve followers")
}
object, err := svc.entryToObject(entry)
if err != nil {
slog.Error("Cannot convert object", "err", err)
}
update := vocab.UpdateNew(object.ID, object)
update.Actor = object.AttributedTo
update.To = object.To
update.Published = object.Published
data, err := jsonld.WithContext(
jsonld.IRI(vocab.ActivityBaseURI),
jsonld.Context{
jsonld.ContextElement{
Term: "toot",
IRI: jsonld.IRI("http://joinmastodon.org/ns#"),
},
},
).Marshal(update)
if err != nil {
slog.Error("marshalling error", "err", err)
}
for _, follower := range followers {
actor, err := svc.GetActor(follower)
if err != nil {
slog.Error("Unable to retrieve follower actor", "err", err)
}
svc.sendObject(actor, data)
}
}
func (svc *ActivityPubService) NotifyEntryDeleted(entry model.Entry) {
obj, err := svc.entryToObject(entry)
if err != nil {
slog.Error("error converting to object", "err", err)
return
}
followers, err := svc.AllFollowers()
if err != nil {
slog.Error("Cannot retrieve followers")
}
delete := vocab.DeleteNew(obj.ID, obj)
delete.Actor = obj.AttributedTo
delete.To = obj.To
delete.Published = time.Now()
data, err := jsonld.WithContext(
jsonld.IRI(vocab.ActivityBaseURI),
).Marshal(delete)
if err != nil {
slog.Error("marshalling error", "err", err)
}
for _, follower := range followers {
actor, err := svc.GetActor(follower)
if err != nil {
slog.Error("Unable to retrieve follower actor", "err", err)
}
svc.sendObject(actor, data)
}
}
func (svc *ActivityPubService) entryToObject(entry model.Entry) (vocab.Object, error) {
// limit to notes for now
if noteEntry, ok := entry.(*entrytypes.Note); ok {
return svc.noteToObject(noteEntry), nil
}
if imageEntry, ok := entry.(*entrytypes.Image); ok {
return svc.imageToObject(imageEntry), nil
}
if articleEntry, ok := entry.(*entrytypes.Article); ok {
return svc.articleToObject(articleEntry), nil
}
if recipeEntry, ok := entry.(*entrytypes.Recipe); ok {
return svc.recipeToObject(recipeEntry), nil
}
slog.Warn("entry type not yet supported for activity pub")
return vocab.Object{}, errors.New("entry type not supported")
}
func (svc *ActivityPubService) noteToObject(noteEntry *entrytypes.Note) vocab.Object {
siteCfg, _ := svc.siteConfigServcie.GetSiteConfig()
content := noteEntry.Content()
r := regexp.MustCompile("#[a-z0-9_]+")
matches := r.FindAllString(string(content), -1)
tags := vocab.ItemCollection{}
for _, hashtag := range matches {
tags.Append(vocab.Object{
ID: vocab.ID(svc.HashtagId(hashtag)),
Name: vocab.NaturalLanguageValues{{Value: vocab.Content(hashtag)}},
})
}
note := vocab.Note{
ID: vocab.ID(noteEntry.FullUrl(siteCfg)),
Type: "Note",
To: vocab.ItemCollection{
vocab.PublicNS,
vocab.IRI(svc.FollowersUrl()),
},
Published: *noteEntry.PublishedAt(),
AttributedTo: vocab.ID(svc.ActorUrl()),
Content: vocab.NaturalLanguageValues{
{Value: vocab.Content(content)},
},
Tag: tags,
}
return note
}
func (svc *ActivityPubService) imageToObject(imageEntry *entrytypes.Image) vocab.Object {
siteCfg, _ := svc.siteConfigServcie.GetSiteConfig()
content := imageEntry.Content()
imgPath := imageEntry.ImageUrl()
fullImageUrl, _ := url.JoinPath(siteCfg.FullUrl, imgPath)
binaryFile, err := svc.binService.FindById(imageEntry.MetaData().(*entrytypes.ImageMetaData).ImageId)
if err != nil {
slog.Error("cannot get image file")
}
attachments := vocab.ItemCollection{}
attachments = append(attachments, vocab.Document{
Type: vocab.DocumentType,
MediaType: vocab.MimeType(binaryFile.Mime()),
URL: vocab.ID(fullImageUrl),
Name: vocab.NaturalLanguageValues{
{Value: vocab.Content(content)},
},
})
image := vocab.Image{
ID: vocab.ID(imageEntry.FullUrl(siteCfg)),
Type: "Image",
To: vocab.ItemCollection{
vocab.PublicNS,
vocab.IRI(svc.FollowersUrl()),
},
Published: *imageEntry.PublishedAt(),
AttributedTo: vocab.ID(svc.ActorUrl()),
Name: vocab.NaturalLanguageValues{
{Value: vocab.Content(imageEntry.Title())},
},
Content: vocab.NaturalLanguageValues{
{Value: vocab.Content(imageEntry.Title() + "<br><br>" + string(content))},
},
Attachment: attachments,
// Tag: tags,
}
return image
}
func (svc *ActivityPubService) articleToObject(articleEntry *entrytypes.Article) vocab.Object {
siteCfg, _ := svc.siteConfigServcie.GetSiteConfig()
content := articleEntry.Content()
image := vocab.Article{
ID: vocab.ID(articleEntry.FullUrl(siteCfg)),
Type: "Article",
To: vocab.ItemCollection{
vocab.PublicNS,
vocab.IRI(svc.FollowersUrl()),
},
Published: *articleEntry.PublishedAt(),
AttributedTo: vocab.ID(svc.ActorUrl()),
Name: vocab.NaturalLanguageValues{
{Value: vocab.Content(articleEntry.Title())},
},
Content: vocab.NaturalLanguageValues{
{Value: vocab.Content(string(content))},
},
}
return image
}
func (svc *ActivityPubService) recipeToObject(recipeEntry *entrytypes.Recipe) vocab.Object {
siteCfg, _ := svc.siteConfigServcie.GetSiteConfig()
content := recipeEntry.Content()
image := vocab.Article{
ID: vocab.ID(recipeEntry.FullUrl(siteCfg)),
Type: "Article",
To: vocab.ItemCollection{
vocab.PublicNS,
vocab.IRI(svc.FollowersUrl()),
},
Published: *recipeEntry.PublishedAt(),
AttributedTo: vocab.ID(svc.ActorUrl()),
Name: vocab.NaturalLanguageValues{
{Value: vocab.Content(recipeEntry.Title())},
},
Content: vocab.NaturalLanguageValues{
{Value: vocab.Content(string(content))},
},
}
return image
}

View File

@ -4,7 +4,6 @@ import (
"crypto/sha256"
"fmt"
"owl-blogs/app/repository"
"owl-blogs/config"
"owl-blogs/domain/model"
"strings"
@ -12,12 +11,12 @@ import (
)
type AuthorService struct {
repo repository.AuthorRepository
siteConfigRepo repository.ConfigRepository
repo repository.AuthorRepository
siteConfigService *SiteConfigService
}
func NewAuthorService(repo repository.AuthorRepository, siteConfigRepo repository.ConfigRepository) *AuthorService {
return &AuthorService{repo: repo, siteConfigRepo: siteConfigRepo}
func NewAuthorService(repo repository.AuthorRepository, siteConfigService *SiteConfigService) *AuthorService {
return &AuthorService{repo: repo, siteConfigService: siteConfigService}
}
func hashPassword(password string) (string, error) {
@ -36,6 +35,21 @@ func (s *AuthorService) Create(name string, password string) (*model.Author, err
return s.repo.Create(name, hash)
}
func (s *AuthorService) SetPassword(name string, password string) error {
hash, err := hashPassword(password)
if err != nil {
return err
}
author, err := s.repo.FindByName(name)
if err != nil {
return err
}
author.PasswordHash = hash
err = s.repo.Update(author)
return err
}
func (s *AuthorService) FindByName(name string) (*model.Author, error) {
return s.repo.FindByName(name)
}
@ -50,14 +64,13 @@ func (s *AuthorService) Authenticate(name string, password string) bool {
}
func (s *AuthorService) getSecretKey() string {
siteConfig := model.SiteConfig{}
err := s.siteConfigRepo.Get(config.SITE_CONFIG, &siteConfig)
siteConfig, err := s.siteConfigService.GetSiteConfig()
if err != nil {
panic(err)
}
if siteConfig.Secret == "" {
siteConfig.Secret = RandStringRunes(64)
err = s.siteConfigRepo.Update(config.SITE_CONFIG, siteConfig)
err = s.siteConfigService.UpdateSiteConfig(siteConfig)
if err != nil {
panic(err)
}

View File

@ -30,7 +30,7 @@ func (c *testConfigRepo) Update(name string, result interface{}) error {
func getAutherService() *app.AuthorService {
db := test.NewMockDb()
authorRepo := infra.NewDefaultAuthorRepo(db)
authorService := app.NewAuthorService(authorRepo, &testConfigRepo{})
authorService := app.NewAuthorService(authorRepo, app.NewSiteConfigService(&testConfigRepo{}))
return authorService
}

View File

@ -24,3 +24,14 @@ func (s *BinaryService) CreateEntryFile(name string, file []byte, entry model.En
func (s *BinaryService) FindById(id string) (*model.BinaryFile, error) {
return s.repo.FindById(id)
}
// ListIds list all ids of binary files
// if filter is not empty, the list will be filter to all ids which include the filter filter substring
// ids and filters are compared in lower case
func (s *BinaryService) ListIds(filter string) ([]string, error) {
return s.repo.ListIds(filter)
}
func (s *BinaryService) Delete(binary *model.BinaryFile) error {
return s.repo.Delete(binary)
}

39
app/config_register.go Normal file
View File

@ -0,0 +1,39 @@
package app
import "owl-blogs/domain/model"
type AppConfig interface {
model.Formable
}
type ConfigRegister struct {
configs map[string]AppConfig
}
type RegisteredConfig struct {
Name string
Config AppConfig
}
func NewConfigRegister() *ConfigRegister {
return &ConfigRegister{configs: map[string]AppConfig{}}
}
func (r *ConfigRegister) Register(name string, config AppConfig) {
r.configs[name] = config
}
func (r *ConfigRegister) Configs() []RegisteredConfig {
var configs []RegisteredConfig
for name, config := range r.configs {
configs = append(configs, RegisteredConfig{
Name: name,
Config: config,
})
}
return configs
}
func (r *ConfigRegister) GetConfig(name string) AppConfig {
return r.configs[name]
}

View File

@ -1,58 +1,11 @@
package app
import (
"errors"
"owl-blogs/domain/model"
"reflect"
)
type EntryTypeRegistry struct {
types map[string]model.Entry
}
type EntryTypeRegistry = TypeRegistry[model.Entry]
func NewEntryTypeRegistry() *EntryTypeRegistry {
return &EntryTypeRegistry{types: map[string]model.Entry{}}
}
func (r *EntryTypeRegistry) entryType(entry model.Entry) string {
return reflect.TypeOf(entry).Elem().Name()
}
func (r *EntryTypeRegistry) Register(entry model.Entry) error {
t := r.entryType(entry)
if _, ok := r.types[t]; ok {
return errors.New("entry type already registered")
}
r.types[t] = entry
return nil
}
func (r *EntryTypeRegistry) Types() []model.Entry {
types := []model.Entry{}
for _, t := range r.types {
types = append(types, t)
}
return types
}
func (r *EntryTypeRegistry) TypeName(entry model.Entry) (string, error) {
t := r.entryType(entry)
if _, ok := r.types[t]; !ok {
return "", errors.New("entry type not registered")
}
return t, nil
}
func (r *EntryTypeRegistry) Type(name string) (model.Entry, error) {
if _, ok := r.types[name]; !ok {
return nil, errors.New("entry type not registered")
}
val := reflect.ValueOf(r.types[name])
if val.Kind() == reflect.Ptr {
val = reflect.Indirect(val)
}
newEntry := reflect.New(val.Type()).Interface().(model.Entry)
return newEntry, nil
return NewTypeRegistry[model.Entry]()
}

View File

@ -1,34 +1,107 @@
package app
import (
"errors"
"fmt"
"owl-blogs/app/repository"
"owl-blogs/domain/model"
"regexp"
"strings"
)
type EntryService struct {
EntryRepository repository.EntryRepository
EntryRepository repository.EntryRepository
siteConfigServcie *SiteConfigService
Bus *EventBus
}
func NewEntryService(entryRepository repository.EntryRepository) *EntryService {
return &EntryService{EntryRepository: entryRepository}
func NewEntryService(
entryRepository repository.EntryRepository,
siteConfigServcie *SiteConfigService,
bus *EventBus,
) *EntryService {
return &EntryService{
EntryRepository: entryRepository,
siteConfigServcie: siteConfigServcie,
Bus: bus,
}
}
func (s *EntryService) Create(entry model.Entry) error {
return s.EntryRepository.Create(entry)
// try to find a good ID
m := regexp.MustCompile(`[^a-z0-9-]`)
prefix := m.ReplaceAllString(strings.ToLower(entry.Title()), "-")
title := prefix
counter := 0
for {
_, err := s.EntryRepository.FindById(title)
if err == nil {
counter += 1
title = prefix + "-" + fmt.Sprintf("%s-%d", prefix, counter)
} else {
break
}
}
entry.SetID(title)
err := s.EntryRepository.Create(entry)
if err != nil {
return err
}
// only notify if the publishing date is set
// otherwise this is a draft.
// listeners might publish the entry to other services/platforms
// this should only happen for publshed content
if entry.PublishedAt() != nil && !entry.PublishedAt().IsZero() {
s.Bus.NotifyCreated(entry)
}
return nil
}
func (s *EntryService) Update(entry model.Entry) error {
return s.EntryRepository.Update(entry)
err := s.EntryRepository.Update(entry)
if err != nil {
return err
}
// only notify if the publishing date is set
// otherwise this is a draft.
// listeners might publish the entry to other services/platforms
// this should only happen for publshed content
if entry.PublishedAt() != nil && !entry.PublishedAt().IsZero() {
s.Bus.NotifyUpdated(entry)
}
return nil
}
func (s *EntryService) Delete(entry model.Entry) error {
return s.EntryRepository.Delete(entry)
err := s.EntryRepository.Delete(entry)
if err != nil {
return err
}
// deletes should always be notfied
// a published entry might be converted to a draft before deletion
// omitting the deletion in this case would prevent deletion on other platforms
s.Bus.NotifyDeleted(entry)
return nil
}
func (s *EntryService) FindById(id string) (model.Entry, error) {
return s.EntryRepository.FindById(id)
}
func (s *EntryService) FindByUrl(url string) (model.Entry, error) {
cfg, _ := s.siteConfigServcie.GetSiteConfig()
if !strings.HasPrefix(url, cfg.FullUrl) {
return nil, errors.New("url does not belong to blog")
}
if strings.HasSuffix(url, "/") {
url = url[:len(url)-1]
}
parts := strings.Split(url, "/")
id := parts[len(parts)-1]
return s.FindById(id)
}
func (s *EntryService) filterEntries(entries []model.Entry, published bool, drafts bool) []model.Entry {
filteredEntries := make([]model.Entry, 0)
for _, entry := range entries {

47
app/entry_service_test.go Normal file
View File

@ -0,0 +1,47 @@
package app_test
import (
"owl-blogs/app"
"owl-blogs/infra"
"owl-blogs/test"
"testing"
"github.com/stretchr/testify/require"
)
func setupService() *app.EntryService {
db := test.NewMockDb()
register := app.NewEntryTypeRegistry()
register.Register(&test.MockEntry{})
repo := infra.NewEntryRepository(db, register)
cfgRepo := infra.NewConfigRepo(db)
cfgService := app.NewSiteConfigService(cfgRepo)
service := app.NewEntryService(repo, cfgService, app.NewEventBus())
return service
}
func TestNiceEntryId(t *testing.T) {
service := setupService()
entry := &test.MockEntry{}
meta := test.MockEntryMetaData{
Title: "Hello World",
}
entry.SetMetaData(&meta)
err := service.Create(entry)
require.NoError(t, err)
require.Equal(t, "hello-world", entry.ID())
}
func TestNoTitleCreation(t *testing.T) {
service := setupService()
entry := &test.MockEntry{}
meta := test.MockEntryMetaData{
Title: "",
}
entry.SetMetaData(&meta)
err := service.Create(entry)
require.NoError(t, err)
require.NotEqual(t, "", entry.ID())
}

51
app/event_bus.go Normal file
View File

@ -0,0 +1,51 @@
package app
import "owl-blogs/domain/model"
type Subscriber interface{}
type EntryCreatedSubscriber interface {
NotifyEntryCreated(entry model.Entry)
}
type EntryUpdatedSubscriber interface {
NotifyEntryUpdated(entry model.Entry)
}
type EntryDeletedSubscriber interface {
NotifyEntryDeleted(entry model.Entry)
}
type EventBus struct {
subscribers []Subscriber
}
func NewEventBus() *EventBus {
return &EventBus{subscribers: make([]Subscriber, 0)}
}
func (b *EventBus) Subscribe(subscriber Subscriber) {
b.subscribers = append(b.subscribers, subscriber)
}
func (b *EventBus) NotifyCreated(entry model.Entry) {
for _, subscriber := range b.subscribers {
if sub, ok := subscriber.(EntryCreatedSubscriber); ok {
go sub.NotifyEntryCreated(entry)
}
}
}
func (b *EventBus) NotifyUpdated(entry model.Entry) {
for _, subscriber := range b.subscribers {
if sub, ok := subscriber.(EntryUpdatedSubscriber); ok {
go sub.NotifyEntryUpdated(entry)
}
}
}
func (b *EventBus) NotifyDeleted(entry model.Entry) {
for _, subscriber := range b.subscribers {
if sub, ok := subscriber.(EntryDeletedSubscriber); ok {
go sub.NotifyEntryDeleted(entry)
}
}
}

57
app/generic_register.go Normal file
View File

@ -0,0 +1,57 @@
package app
import (
"errors"
"reflect"
)
type TypeRegistry[T any] struct {
types map[string]T
}
func NewTypeRegistry[T any]() *TypeRegistry[T] {
return &TypeRegistry[T]{types: map[string]T{}}
}
func (r *TypeRegistry[T]) entryType(entry T) string {
return reflect.TypeOf(entry).Elem().Name()
}
func (r *TypeRegistry[T]) Register(entry T) error {
t := r.entryType(entry)
if _, ok := r.types[t]; ok {
return errors.New("entry type already registered")
}
r.types[t] = entry
return nil
}
func (r *TypeRegistry[T]) Types() []T {
types := []T{}
for _, t := range r.types {
types = append(types, t)
}
return types
}
func (r *TypeRegistry[T]) TypeName(entry T) (string, error) {
t := r.entryType(entry)
if _, ok := r.types[t]; !ok {
return "", errors.New("entry type not registered")
}
return t, nil
}
func (r *TypeRegistry[T]) Type(name string) (T, error) {
if _, ok := r.types[name]; !ok {
return *new(T), errors.New("entry type not registered")
}
val := reflect.ValueOf(r.types[name])
if val.Kind() == reflect.Ptr {
val = reflect.Indirect(val)
}
newEntry := reflect.New(val.Type()).Interface().(T)
return newEntry, nil
}

267
app/indieweb_utils.go Normal file
View File

@ -0,0 +1,267 @@
package app
import (
"bytes"
"errors"
"io"
"net/http"
"net/url"
"strings"
"golang.org/x/net/html"
)
type HtmlParser interface {
ParseHEntry(resp *http.Response) (ParsedHEntry, error)
ParseLinks(resp *http.Response) ([]string, error)
ParseLinksFromString(string) ([]string, error)
GetWebmentionEndpoint(resp *http.Response) (string, error)
GetRedirctUris(resp *http.Response) ([]string, error)
}
type ParsedHEntry struct {
Title string
}
func collectText(n *html.Node, buf *bytes.Buffer) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
collectText(c, buf)
}
}
func readResponseBody(resp *http.Response) (string, error) {
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bodyBytes), nil
}
func ParseHEntry(resp *http.Response) (ParsedHEntry, error) {
htmlStr, err := readResponseBody(resp)
if err != nil {
return ParsedHEntry{}, err
}
doc, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
return ParsedHEntry{}, err
}
var interpretHFeed func(*html.Node, *ParsedHEntry, bool) (ParsedHEntry, error)
interpretHFeed = func(n *html.Node, curr *ParsedHEntry, parent bool) (ParsedHEntry, error) {
attrs := n.Attr
for _, attr := range attrs {
if attr.Key == "class" && strings.Contains(attr.Val, "p-name") {
buf := &bytes.Buffer{}
collectText(n, buf)
curr.Title = buf.String()
return *curr, nil
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
interpretHFeed(c, curr, false)
}
return *curr, nil
}
var findHFeed func(*html.Node) (ParsedHEntry, error)
findHFeed = func(n *html.Node) (ParsedHEntry, error) {
attrs := n.Attr
for _, attr := range attrs {
if attr.Key == "class" && strings.Contains(attr.Val, "h-entry") {
return interpretHFeed(n, &ParsedHEntry{}, true)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
entry, err := findHFeed(c)
if err == nil {
return entry, nil
}
}
return ParsedHEntry{}, errors.New("no h-entry found")
}
return findHFeed(doc)
}
func ParseLinks(resp *http.Response) ([]string, error) {
htmlStr, err := readResponseBody(resp)
if err != nil {
return []string{}, err
}
return ParseLinksFromString(htmlStr)
}
func ParseLinksFromString(htmlStr string) ([]string, error) {
doc, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
return make([]string, 0), err
}
var findLinks func(*html.Node) ([]string, error)
findLinks = func(n *html.Node) ([]string, error) {
links := make([]string, 0)
if n.Type == html.ElementNode && n.Data == "a" {
for _, attr := range n.Attr {
if attr.Key == "href" {
links = append(links, attr.Val)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
childLinks, _ := findLinks(c)
links = append(links, childLinks...)
}
return links, nil
}
return findLinks(doc)
}
func GetWebmentionEndpoint(resp *http.Response) (string, error) {
//request url
requestUrl := resp.Request.URL
// Check link headers
for _, linkHeader := range resp.Header["Link"] {
linkHeaderParts := strings.Split(linkHeader, ",")
for _, linkHeaderPart := range linkHeaderParts {
linkHeaderPart = strings.TrimSpace(linkHeaderPart)
params := strings.Split(linkHeaderPart, ";")
if len(params) != 2 {
continue
}
for _, param := range params[1:] {
param = strings.TrimSpace(param)
if strings.Contains(param, "webmention") {
link := strings.Split(params[0], ";")[0]
link = strings.Trim(link, "<>")
linkUrl, err := url.Parse(link)
if err != nil {
return "", err
}
return requestUrl.ResolveReference(linkUrl).String(), nil
}
}
}
}
htmlStr, err := readResponseBody(resp)
if err != nil {
return "", err
}
doc, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
return "", err
}
var findEndpoint func(*html.Node) (string, error)
findEndpoint = func(n *html.Node) (string, error) {
if n.Type == html.ElementNode && (n.Data == "link" || n.Data == "a") {
for _, attr := range n.Attr {
if attr.Key == "rel" {
vals := strings.Split(attr.Val, " ")
for _, val := range vals {
if val == "webmention" {
for _, attr := range n.Attr {
if attr.Key == "href" {
return attr.Val, nil
}
}
}
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
endpoint, err := findEndpoint(c)
if err == nil {
return endpoint, nil
}
}
return "", errors.New("no webmention endpoint found")
}
linkUrlStr, err := findEndpoint(doc)
if err != nil {
return "", err
}
linkUrl, err := url.Parse(linkUrlStr)
if err != nil {
return "", err
}
return requestUrl.ResolveReference(linkUrl).String(), nil
}
func GetRedirctUris(resp *http.Response) ([]string, error) {
//request url
requestUrl := resp.Request.URL
htmlStr, err := readResponseBody(resp)
if err != nil {
return make([]string, 0), err
}
doc, err := html.Parse(strings.NewReader(htmlStr))
if err != nil {
return make([]string, 0), err
}
var findLinks func(*html.Node) ([]string, error)
// Check link headers
header_links := make([]string, 0)
for _, linkHeader := range resp.Header["Link"] {
linkHeaderParts := strings.Split(linkHeader, ",")
for _, linkHeaderPart := range linkHeaderParts {
linkHeaderPart = strings.TrimSpace(linkHeaderPart)
params := strings.Split(linkHeaderPart, ";")
if len(params) != 2 {
continue
}
for _, param := range params[1:] {
param = strings.TrimSpace(param)
if strings.Contains(param, "redirect_uri") {
link := strings.Split(params[0], ";")[0]
link = strings.Trim(link, "<>")
linkUrl, err := url.Parse(link)
if err == nil {
header_links = append(header_links, requestUrl.ResolveReference(linkUrl).String())
}
}
}
}
}
findLinks = func(n *html.Node) ([]string, error) {
links := make([]string, 0)
if n.Type == html.ElementNode && n.Data == "link" {
// check for rel="redirect_uri"
rel := ""
href := ""
for _, attr := range n.Attr {
if attr.Key == "href" {
href = attr.Val
}
if attr.Key == "rel" {
rel = attr.Val
}
}
if rel == "redirect_uri" {
linkUrl, err := url.Parse(href)
if err == nil {
links = append(links, requestUrl.ResolveReference(linkUrl).String())
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
childLinks, _ := findLinks(c)
links = append(links, childLinks...)
}
return links, nil
}
body_links, err := findLinks(doc)
return append(body_links, header_links...), err
}

View File

@ -0,0 +1,11 @@
package app
import (
"owl-blogs/domain/model"
)
type InteractionTypeRegistry = TypeRegistry[model.Interaction]
func NewInteractionTypeRegistry() *InteractionTypeRegistry {
return NewTypeRegistry[model.Interaction]()
}

View File

@ -0,0 +1,14 @@
package app
import (
"owl-blogs/app/repository"
"owl-blogs/domain/model"
)
type InteractionService struct {
repo repository.InteractionRepository
}
func (s *InteractionService) ListInteractions() ([]model.Interaction, error) {
return s.repo.ListAllInteractions()
}

13
app/owlhttp/interface.go Normal file
View File

@ -0,0 +1,13 @@
package owlhttp
import (
"io"
"net/http"
"net/url"
)
type HttpClient interface {
Get(url string) (resp *http.Response, err error)
Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
PostForm(url string, data url.Values) (resp *http.Response, err error)
}

View File

@ -19,12 +19,19 @@ type BinaryRepository interface {
Create(name string, data []byte, entry model.Entry) (*model.BinaryFile, error)
FindById(id string) (*model.BinaryFile, error)
FindByNameForEntry(name string, entry model.Entry) (*model.BinaryFile, error)
// ListIds list all ids of binary files
// if filter is not empty, the list will be filter to all ids which include the filter filter substring
// ids and filters are compared in lower case
ListIds(filter string) ([]string, error)
Delete(binary *model.BinaryFile) error
}
type AuthorRepository interface {
// Create creates a new author
// It returns an error if the name is already taken
Create(name string, passwordHash string) (*model.Author, error)
Update(author *model.Author) error
// FindByName finds an author by name
// It returns an error if the author is not found
FindByName(name string) (*model.Author, error)
@ -34,3 +41,19 @@ type ConfigRepository interface {
Get(name string, config interface{}) error
Update(name string, siteConfig interface{}) error
}
type InteractionRepository interface {
Create(interaction model.Interaction) error
Update(interaction model.Interaction) error
Delete(interaction model.Interaction) error
FindById(id string) (model.Interaction, error)
FindAll(entryId string) ([]model.Interaction, error)
// ListAllInteractions lists all interactions, sorted by creation date (descending)
ListAllInteractions() ([]model.Interaction, error)
}
type FollowerRepository interface {
Add(follower string) error
Remove(follower string) error
All() ([]string, error)
}

View File

@ -0,0 +1,58 @@
package app
import (
"owl-blogs/app/repository"
"owl-blogs/config"
"owl-blogs/domain/model"
"reflect"
)
// SiteConfigService is a service to retrieve and store the site config
// Even though the site config is a standard config, it is handle by an extra service
// as it is used in many places.
// The SiteConfig contains global settings require by multiple parts of the app
type SiteConfigService struct {
repo repository.ConfigRepository
}
func NewSiteConfigService(repo repository.ConfigRepository) *SiteConfigService {
return &SiteConfigService{
repo: repo,
}
}
func (svc *SiteConfigService) defaultConfig() model.SiteConfig {
return model.SiteConfig{
Title: "My Owl-Blog",
SubTitle: "A freshly created blog",
PrimaryColor: "#d37f12",
AuthorName: "",
Me: []model.MeLinks{},
Lists: []model.EntryList{},
PrimaryListInclude: []string{},
HeaderMenu: []model.MenuItem{},
FooterMenu: []model.MenuItem{},
Secret: "",
AvatarUrl: "",
FullUrl: "http://localhost:3000",
HtmlHeadExtra: "",
FooterExtra: "",
}
}
func (svc *SiteConfigService) GetSiteConfig() (model.SiteConfig, error) {
siteConfig := model.SiteConfig{}
err := svc.repo.Get(config.SITE_CONFIG, &siteConfig)
if err != nil {
println("ERROR IN SITE CONFIG")
return model.SiteConfig{}, err
}
if reflect.ValueOf(siteConfig).IsZero() {
return svc.defaultConfig(), nil
}
return siteConfig, nil
}
func (svc *SiteConfigService) UpdateSiteConfig(cfg model.SiteConfig) error {
return svc.repo.Update(config.SITE_CONFIG, cfg)
}

View File

@ -2,6 +2,7 @@ package app
import (
"math/rand"
"strings"
)
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
@ -13,3 +14,12 @@ func RandStringRunes(n int) string {
}
return string(b)
}
func UrlToEntryId(url string) string {
parts := strings.Split(url, "/")
if parts[len(parts)-1] == "" {
return parts[len(parts)-2]
} else {
return parts[len(parts)-1]
}
}

151
app/webmention_service.go Normal file
View File

@ -0,0 +1,151 @@
package app
import (
"fmt"
"net/url"
"owl-blogs/app/owlhttp"
"owl-blogs/app/repository"
"owl-blogs/domain/model"
"owl-blogs/interactions"
"time"
)
type WebmentionService struct {
siteConfigService *SiteConfigService
InteractionRepository repository.InteractionRepository
EntryRepository repository.EntryRepository
Http owlhttp.HttpClient
}
func NewWebmentionService(
siteConfigService *SiteConfigService,
interactionRepository repository.InteractionRepository,
entryRepository repository.EntryRepository,
http owlhttp.HttpClient,
bus *EventBus,
) *WebmentionService {
svc := &WebmentionService{
siteConfigService: siteConfigService,
InteractionRepository: interactionRepository,
EntryRepository: entryRepository,
Http: http,
}
bus.Subscribe(svc)
return svc
}
func (s *WebmentionService) GetExistingWebmention(entryId string, source string, target string) (*interactions.Webmention, error) {
inters, err := s.InteractionRepository.FindAll(entryId)
if err != nil {
return nil, err
}
for _, interaction := range inters {
if webm, ok := interaction.(*interactions.Webmention); ok {
m := webm.MetaData().(*interactions.WebmentionMetaData)
if m.Source == source && m.Target == target {
return webm, nil
}
}
}
return nil, nil
}
func (s *WebmentionService) ProcessWebmention(source string, target string) error {
resp, err := s.Http.Get(source)
if err != nil {
return err
}
hEntry, err := ParseHEntry(resp)
if err != nil {
return err
}
entryId := UrlToEntryId(target)
_, err = s.EntryRepository.FindById(entryId)
if err != nil {
return err
}
webmention, err := s.GetExistingWebmention(entryId, source, target)
if err != nil {
return err
}
if webmention != nil {
data := interactions.WebmentionMetaData{
Source: source,
Target: target,
Title: hEntry.Title,
}
webmention.SetMetaData(&data)
webmention.SetEntryID(entryId)
webmention.SetCreatedAt(time.Now())
err = s.InteractionRepository.Update(webmention)
return err
} else {
webmention = &interactions.Webmention{}
data := interactions.WebmentionMetaData{
Source: source,
Target: target,
Title: hEntry.Title,
}
webmention.SetMetaData(&data)
webmention.SetEntryID(entryId)
webmention.SetCreatedAt(time.Now())
err = s.InteractionRepository.Create(webmention)
return err
}
}
func (s *WebmentionService) ScanForLinks(entry model.Entry) ([]string, error) {
content := string(entry.Content())
return ParseLinksFromString(content)
}
func (s *WebmentionService) FullEntryUrl(entry model.Entry) string {
siteConfig, _ := s.siteConfigService.GetSiteConfig()
url, _ := url.JoinPath(
siteConfig.FullUrl,
fmt.Sprintf("/posts/%s/", entry.ID()),
)
return url
}
func (s *WebmentionService) SendWebmention(entry model.Entry) error {
links, err := s.ScanForLinks(entry)
if err != nil {
return err
}
for _, target := range links {
resp, err := s.Http.Get(target)
if err != nil {
continue
}
endpoint, err := GetWebmentionEndpoint(resp)
if err != nil {
continue
}
payload := url.Values{}
payload.Set("source", s.FullEntryUrl(entry))
payload.Set("target", target)
_, err = s.Http.PostForm(endpoint, payload)
if err != nil {
continue
}
println("Send webmention for target", target)
}
return nil
}
func (s *WebmentionService) NotifyEntryCreated(entry model.Entry) {
s.SendWebmention(entry)
}
func (s *WebmentionService) NotifyEntryUpdated(entry model.Entry) {
s.SendWebmention(entry)
}
func (s *WebmentionService) NotifyEntryDeleted(entry model.Entry) {
s.SendWebmention(entry)
}

217
app/webmention_test.go Normal file
View File

@ -0,0 +1,217 @@
package app_test
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"owl-blogs/app"
"owl-blogs/infra"
"owl-blogs/interactions"
"owl-blogs/test"
"testing"
"github.com/stretchr/testify/require"
)
func constructResponse(html []byte) *http.Response {
url, _ := url.Parse("http://example.com/foo/bar")
return &http.Response{
Request: &http.Request{
URL: url,
},
Body: io.NopCloser(bytes.NewReader([]byte(html))),
}
}
type MockHttpClient struct {
PageContent string
}
// Post implements owlhttp.HttpClient.
func (MockHttpClient) Post(url string, contentType string, body io.Reader) (resp *http.Response, err error) {
panic("unimplemented")
}
// PostForm implements owlhttp.HttpClient.
func (MockHttpClient) PostForm(url string, data url.Values) (resp *http.Response, err error) {
panic("unimplemented")
}
func (c *MockHttpClient) Get(url string) (*http.Response, error) {
return &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte(c.PageContent))),
}, nil
}
func getWebmentionService() *app.WebmentionService {
db := test.NewMockDb()
entryRegister := app.NewEntryTypeRegistry()
entryRegister.Register(&test.MockEntry{})
entryRepo := infra.NewEntryRepository(db, entryRegister)
interactionRegister := app.NewInteractionTypeRegistry()
interactionRegister.Register(&interactions.Webmention{})
interactionRepo := infra.NewInteractionRepo(db, interactionRegister)
configRepo := infra.NewConfigRepo(db)
bus := app.NewEventBus()
http := infra.OwlHttpClient{}
return app.NewWebmentionService(
app.NewSiteConfigService(configRepo), interactionRepo, entryRepo, &http, bus,
)
}
//
// https://www.w3.org/TR/webmention/#h-webmention-verification
//
func TestParseValidHEntry(t *testing.T) {
html := []byte("<div class=\"h-entry\"><div class=\"p-name\">Foo</div></div>")
entry, err := app.ParseHEntry(&http.Response{Body: io.NopCloser(bytes.NewReader(html))})
require.NoError(t, err)
require.Equal(t, entry.Title, "Foo")
}
func TestParseValidHEntryWithoutTitle(t *testing.T) {
html := []byte("<div class=\"h-entry\"></div><div class=\"p-name\">Foo</div>")
entry, err := app.ParseHEntry(&http.Response{Body: io.NopCloser(bytes.NewReader(html))})
require.NoError(t, err)
require.Equal(t, entry.Title, "")
}
func TestCreateNewWebmention(t *testing.T) {
service := getWebmentionService()
service.Http = &MockHttpClient{
PageContent: "<div class=\"h-entry\"><div class=\"p-name\">Foo</div></div>",
}
entry := test.MockEntry{}
service.EntryRepository.Create(&entry)
err := service.ProcessWebmention(
"http://example.com/foo",
fmt.Sprintf("https.//example.com/posts/%s/", entry.ID()),
)
require.NoError(t, err)
inters, err := service.InteractionRepository.FindAll(entry.ID())
require.NoError(t, err)
require.Equal(t, len(inters), 1)
webm := inters[0].(*interactions.Webmention)
meta := webm.MetaData().(*interactions.WebmentionMetaData)
require.Equal(t, meta.Source, "http://example.com/foo")
require.Equal(t, meta.Target, fmt.Sprintf("https.//example.com/posts/%s/", entry.ID()))
require.Equal(t, meta.Title, "Foo")
}
func TestGetWebmentionEndpointLink(t *testing.T) {
html := []byte("<link rel=\"webmention\" href=\"http://example.com/webmention\" />")
endpoint, err := app.GetWebmentionEndpoint(constructResponse(html))
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
func TestGetWebmentionEndpointLinkA(t *testing.T) {
html := []byte("<a rel=\"webmention\" href=\"http://example.com/webmention\" />")
endpoint, err := app.GetWebmentionEndpoint(constructResponse(html))
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
func TestGetWebmentionEndpointLinkAFakeWebmention(t *testing.T) {
html := []byte("<a rel=\"not-webmention\" href=\"http://example.com/foo\" /><a rel=\"webmention\" href=\"http://example.com/webmention\" />")
endpoint, err := app.GetWebmentionEndpoint(constructResponse(html))
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
func TestGetWebmentionEndpointLinkHeader(t *testing.T) {
html := []byte("")
resp := constructResponse(html)
resp.Header = http.Header{"Link": []string{"<http://example.com/webmention>; rel=\"webmention\""}}
endpoint, err := app.GetWebmentionEndpoint(resp)
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
func TestGetWebmentionEndpointLinkHeaderCommas(t *testing.T) {
html := []byte("")
resp := constructResponse(html)
resp.Header = http.Header{
"Link": []string{"<https://webmention.rocks/test/19/webmention/error>; rel=\"other\", <https://webmention.rocks/test/19/webmention>; rel=\"webmention\""},
}
endpoint, err := app.GetWebmentionEndpoint(resp)
require.NoError(t, err)
require.Equal(t, endpoint, "https://webmention.rocks/test/19/webmention")
}
func TestGetWebmentionEndpointRelativeLink(t *testing.T) {
html := []byte("<link rel=\"webmention\" href=\"/webmention\" />")
endpoint, err := app.GetWebmentionEndpoint(constructResponse(html))
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
func TestGetWebmentionEndpointRelativeLinkInHeader(t *testing.T) {
html := []byte("<link rel=\"webmention\" href=\"/webmention\" />")
resp := constructResponse(html)
resp.Header = http.Header{"Link": []string{"</webmention>; rel=\"webmention\""}}
endpoint, err := app.GetWebmentionEndpoint(resp)
require.NoError(t, err)
require.Equal(t, endpoint, "http://example.com/webmention")
}
// func TestRealWorldWebmention(t *testing.T) {
// service := getWebmentionService()
// links := []string{
// "https://webmention.rocks/test/1",
// "https://webmention.rocks/test/2",
// "https://webmention.rocks/test/3",
// "https://webmention.rocks/test/4",
// "https://webmention.rocks/test/5",
// "https://webmention.rocks/test/6",
// "https://webmention.rocks/test/7",
// "https://webmention.rocks/test/8",
// "https://webmention.rocks/test/9",
// // "https://webmention.rocks/test/10", // not supported
// "https://webmention.rocks/test/11",
// "https://webmention.rocks/test/12",
// "https://webmention.rocks/test/13",
// "https://webmention.rocks/test/14",
// "https://webmention.rocks/test/15",
// "https://webmention.rocks/test/16",
// "https://webmention.rocks/test/17",
// "https://webmention.rocks/test/18",
// "https://webmention.rocks/test/19",
// "https://webmention.rocks/test/20",
// "https://webmention.rocks/test/21",
// "https://webmention.rocks/test/22",
// "https://webmention.rocks/test/23/page",
// }
// for _, link := range links {
//
// client := &owl.OwlHttpClient{}
// html, _ := client.Get(link)
// _, err := app.GetWebmentionEndpoint(html)
// if err != nil {
// t.Errorf("Unable to find webmention: %v for link %v", err, link)
// }
// }
// }

View File

@ -38,7 +38,7 @@ func TestEditorFormGet(t *testing.T) {
app := owlApp.FiberApp
token := getUserToken(owlApp.AuthorService)
req := httptest.NewRequest("GET", "/editor/Image", nil)
req := httptest.NewRequest("GET", "/editor/new/Image", nil)
req.AddCookie(&http.Cookie{Name: "token", Value: token})
resp, err := app.Test(req)
require.NoError(t, err)
@ -50,7 +50,7 @@ func TestEditorFormGetNoAuth(t *testing.T) {
owlApp := App(db)
app := owlApp.FiberApp
req := httptest.NewRequest("GET", "/editor/Image", nil)
req := httptest.NewRequest("GET", "/editor/new/Image", nil)
req.AddCookie(&http.Cookie{Name: "token", Value: "invalid"})
resp, err := app.Test(req)
require.NoError(t, err)
@ -77,13 +77,13 @@ func TestEditorFormPost(t *testing.T) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("ImageId", filepath.Base(file.Name()))
part, _ := writer.CreateFormFile("image", filepath.Base(file.Name()))
io.Copy(part, file)
part, _ = writer.CreateFormField("Content")
part, _ = writer.CreateFormField("content")
io.WriteString(part, "test content")
writer.Close()
req := httptest.NewRequest("POST", "/editor/Image", body)
req := httptest.NewRequest("POST", "/editor/new/Image", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.AddCookie(&http.Cookie{Name: "token", Value: token})
resp, err := app.Test(req)
@ -125,7 +125,7 @@ func TestEditorFormPostNoAuth(t *testing.T) {
io.WriteString(part, "test content")
writer.Close()
req := httptest.NewRequest("POST", "/editor/Image", body)
req := httptest.NewRequest("POST", "/editor/new/Image", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.AddCookie(&http.Cookie{Name: "token", Value: "invalid"})
resp, err := app.Test(req)

View File

@ -92,7 +92,6 @@ var importCmd = &cobra.Command{
}
v2Config.Title = v1Config.Title
v2Config.SubTitle = v1Config.SubTitle
v2Config.HeaderColor = v1Config.HeaderColor
v2Config.AuthorName = v1Config.AuthorName
v2Config.Me = mes
v2Config.Lists = lists

View File

@ -6,6 +6,9 @@ import (
"owl-blogs/app"
entrytypes "owl-blogs/entry_types"
"owl-blogs/infra"
"owl-blogs/interactions"
"owl-blogs/plugings"
"owl-blogs/render"
"owl-blogs/web"
"github.com/spf13/cobra"
@ -26,25 +29,67 @@ func Execute() {
}
func App(db infra.Database) *web.WebApp {
registry := app.NewEntryTypeRegistry()
registry.Register(&entrytypes.Image{})
registry.Register(&entrytypes.Article{})
registry.Register(&entrytypes.Page{})
registry.Register(&entrytypes.Recipe{})
registry.Register(&entrytypes.Note{})
registry.Register(&entrytypes.Bookmark{})
registry.Register(&entrytypes.Reply{})
// Register Types
entryRegister := app.NewEntryTypeRegistry()
entryRegister.Register(&entrytypes.Image{})
entryRegister.Register(&entrytypes.Article{})
entryRegister.Register(&entrytypes.Page{})
entryRegister.Register(&entrytypes.Recipe{})
entryRegister.Register(&entrytypes.Note{})
entryRegister.Register(&entrytypes.Bookmark{})
entryRegister.Register(&entrytypes.Reply{})
entryRepo := infra.NewEntryRepository(db, registry)
interactionRegister := app.NewInteractionTypeRegistry()
interactionRegister.Register(&interactions.Webmention{})
interactionRegister.Register(&interactions.Like{})
interactionRegister.Register(&interactions.Repost{})
configRegister := app.NewConfigRegister()
// Create Repositories
entryRepo := infra.NewEntryRepository(db, entryRegister)
binRepo := infra.NewBinaryFileRepo(db)
authorRepo := infra.NewDefaultAuthorRepo(db)
siteConfigRepo := infra.NewConfigRepo(db)
configRepo := infra.NewConfigRepo(db)
interactionRepo := infra.NewInteractionRepo(db, interactionRegister)
followersRepo := infra.NewFollowerRepository(db)
entryService := app.NewEntryService(entryRepo)
// Create External Services
httpClient := &infra.OwlHttpClient{}
// busses
eventBus := app.NewEventBus()
// Create Services
siteConfigService := app.NewSiteConfigService(configRepo)
entryService := app.NewEntryService(entryRepo, siteConfigService, eventBus)
binaryService := app.NewBinaryFileService(binRepo)
authorService := app.NewAuthorService(authorRepo, siteConfigRepo)
authorService := app.NewAuthorService(authorRepo, siteConfigService)
webmentionService := app.NewWebmentionService(
siteConfigService, interactionRepo, entryRepo, httpClient, eventBus,
)
apService := app.NewActivityPubService(
followersRepo, configRepo, interactionRepo,
entryService, siteConfigService, binaryService,
eventBus,
)
return web.NewWebApp(entryService, registry, binaryService, authorService, siteConfigRepo)
// setup render functions
render.SiteConfigService = siteConfigService
// plugins
plugings.NewEcho(eventBus)
plugings.RegisterInstagram(
configRepo, configRegister, binaryService, eventBus,
)
// Create WebApp
return web.NewWebApp(
entryService, entryRegister, binaryService,
authorService, configRepo, configRegister,
siteConfigService, webmentionService, interactionRepo,
apService,
)
}

26
cmd/owl/reset_password.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"owl-blogs/infra"
"github.com/spf13/cobra"
)
func init() {
rootCmd.AddCommand(resetPasswordCmd)
resetPasswordCmd.Flags().StringVarP(&user, "user", "u", "", "The user name")
resetPasswordCmd.MarkFlagRequired("user")
resetPasswordCmd.Flags().StringVarP(&password, "password", "p", "", "The new password")
resetPasswordCmd.MarkFlagRequired("password")
}
var resetPasswordCmd = &cobra.Command{
Use: "reset-password",
Short: "Resets the password of an author",
Long: `Resets the password of an author`,
Run: func(cmd *cobra.Command, args []string) {
db := infra.NewSqliteDB(DbPath)
App(db).AuthorService.Create(user, password)
},
}

View File

@ -3,7 +3,8 @@ package config
import "os"
const (
SITE_CONFIG = "site_config"
SITE_CONFIG = "site_config"
ACT_PUB_CONF_NAME = "activity_pub"
)
type Config interface {

View File

@ -0,0 +1,5 @@
package model
type BinaryStorageInterface interface {
Create(name string, file []byte) (*BinaryFile, error)
}

View File

@ -1,6 +1,9 @@
package model
import "time"
import (
"net/url"
"time"
)
type EntryContent string
@ -9,18 +12,22 @@ type Entry interface {
Content() EntryContent
PublishedAt() *time.Time
AuthorId() string
MetaData() interface{}
MetaData() EntryMetaData
// Optional: can return empty string
Title() string
ImageUrl() string
SetID(id string)
SetPublishedAt(publishedAt *time.Time)
SetMetaData(metaData interface{})
SetMetaData(metaData EntryMetaData)
SetAuthorId(authorId string)
FullUrl(cfg SiteConfig) string
}
type EntryMetaData interface {
Formable
}
type EntryBase struct {
@ -37,6 +44,10 @@ func (e *EntryBase) PublishedAt() *time.Time {
return e.publishedAt
}
func (e *EntryBase) ImageUrl() string {
return ""
}
func (e *EntryBase) SetID(id string) {
e.id = id
}
@ -52,3 +63,8 @@ func (e *EntryBase) AuthorId() string {
func (e *EntryBase) SetAuthorId(authorId string) {
e.authorId = authorId
}
func (e *EntryBase) FullUrl(cfg SiteConfig) string {
u, _ := url.JoinPath(cfg.FullUrl, "/posts/", e.ID(), "/")
return u
}

View File

@ -0,0 +1,34 @@
package model_test
import (
"owl-blogs/domain/model"
"testing"
"github.com/stretchr/testify/require"
)
func TestEntryFullUrl(t *testing.T) {
type testCase struct {
Id string
Url string
Want string
}
testCases := []testCase{
{Id: "foobar", Url: "https://example.com", Want: "https://example.com/posts/foobar/"},
{Id: "foobar", Url: "https://example.com/", Want: "https://example.com/posts/foobar/"},
{Id: "foobar", Url: "http://example.com", Want: "http://example.com/posts/foobar/"},
{Id: "foobar", Url: "http://example.com/", Want: "http://example.com/posts/foobar/"},
{Id: "bi-bar-buz", Url: "https://example.com", Want: "https://example.com/posts/bi-bar-buz/"},
{Id: "foobar", Url: "https://example.com/lol/", Want: "https://example.com/lol/posts/foobar/"},
}
for _, test := range testCases {
e := model.EntryBase{}
e.SetID(test.Id)
cfg := model.SiteConfig{FullUrl: test.Url}
require.Equal(t, e.FullUrl(cfg), test.Want)
}
}

20
domain/model/form_data.go Normal file
View File

@ -0,0 +1,20 @@
package model
import "mime/multipart"
type Formable interface {
Form(binSvc BinaryStorageInterface) string
ParseFormData(data HttpFormData, binSvc BinaryStorageInterface) error
}
type HttpFormData interface {
// FormFile returns the first file by key from a MultipartForm.
FormFile(key string) (*multipart.FileHeader, error)
// FormValue returns the first value by key from a MultipartForm.
// Search is performed in QueryArgs, PostArgs, MultipartForm and FormFile in this particular order.
// Defaults to the empty string "" if the form value doesn't exist.
// If a default value is given, it will return that value if the form value does not exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
FormValue(key string, defaultValue ...string) string
}

View File

@ -0,0 +1,53 @@
package model
import "time"
type InteractionContent string
// Interaction is a generic interface for all interactions with entries
// These interactions can be:
// - Webmention, Pingback, Trackback
// - Likes, Comments on third party sites
// - Comments on the site itself
type Interaction interface {
ID() string
EntryID() string
Content() InteractionContent
CreatedAt() time.Time
MetaData() interface{}
SetID(id string)
SetEntryID(entryID string)
SetCreatedAt(createdAt time.Time)
SetMetaData(metaData interface{})
}
type InteractionBase struct {
id string
entryID string
createdAt time.Time
}
func (i *InteractionBase) ID() string {
return i.id
}
func (i *InteractionBase) EntryID() string {
return i.entryID
}
func (i *InteractionBase) CreatedAt() time.Time {
return i.createdAt
}
func (i *InteractionBase) SetID(id string) {
i.id = id
}
func (i *InteractionBase) SetEntryID(entryID string) {
i.entryID = entryID
}
func (i *InteractionBase) SetCreatedAt(createdAt time.Time) {
i.createdAt = createdAt
}

View File

@ -22,7 +22,7 @@ type MenuItem struct {
type SiteConfig struct {
Title string
SubTitle string
HeaderColor string
PrimaryColor string
AuthorName string
Me []MeLinks
Lists []EntryList
@ -31,4 +31,7 @@ type SiteConfig struct {
FooterMenu []MenuItem
Secret string
AvatarUrl string
FullUrl string
HtmlHeadExtra string
FooterExtra string
}

View File

@ -0,0 +1,6 @@
package model
type SiteConfigInterface interface {
GetSiteConfig() (SiteConfig, error)
UpdateSiteConfig(cfg SiteConfig) error
}

49
e2e_tests/conftest.py Normal file
View File

@ -0,0 +1,49 @@
import pytest
from requests import Session
from urllib.parse import urljoin
from tests.fixtures import ACCT_NAME
class LiveServerSession(Session):
def __init__(self, base_url=None):
super().__init__()
self.base_url = base_url
def request(self, method, url, *args, **kwargs):
joined_url = urljoin(self.base_url, url)
return super().request(method, joined_url, *args, **kwargs)
@pytest.fixture
def client():
return LiveServerSession("http://localhost:3000")
@pytest.fixture
def actor_url(client):
resp = client.get(f"/.well-known/webfinger?resource={ACCT_NAME}")
data = resp.json()
self_link = [x for x in data["links"] if x["rel"] == "self"][0]
return self_link["href"]
@pytest.fixture
def actor(client, actor_url):
resp = client.get(actor_url, headers={"Content-Type": "application/activity+json"})
assert resp.status_code == 200
return resp.json()
@pytest.fixture
def inbox_url(actor):
return actor["inbox"]
@pytest.fixture
def outbox_url(actor):
return actor["outbox"]
@pytest.fixture
def followers_url(actor):
return actor["followers"]

View File

@ -0,0 +1,12 @@
services:
web:
build:
context: ../
dockerfile: Dockerfile
command: web
ports:
- "3000:3000"
mock_masto:
build: mock_masto
ports:
- 8000:8000

View File

@ -0,0 +1,24 @@
services:
web:
build:
context: ../
dockerfile: Dockerfile.test
volumes:
- ../app:/go/owl/app
- ../assets:/go/owl/assets
- ../cmd:/go/owl/cmd
- ../config:/go/owl/config
- ../domain:/go/owl/domain
- ../entry_types:/go/owl/entry_types
- ../importer:/go/owl/importer
- ../infra:/go/owl/infra
- ../interactions:/go/owl/interactions
- ../plugings:/go/owl/plugings
- ../render:/go/owl/render
- ../web:/go/owl/web
ports:
- "3000:3000"
mock_masto:
build: mock_masto
ports:
- 8000:8000

View File

@ -0,0 +1,6 @@
FROM python:3.11
COPY . .
RUN pip install -r requirements.txt
CMD [ "python", "main.py" ]

View File

@ -0,0 +1,214 @@
import json
from flask import Flask, request
app = Flask(__name__)
PRIV_KEY_PEM = """-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCni8P4bvkC/3Sx
NTrDw1qw0vWtJKZMsyJ3Mcs4+1apoVqOQhujUqGqFSiRT7Vmc7OEhB0vikdiTkCk
1PcoTd/rOa/0WbG8385JcLzaJfTIG+rrRtHwZ1TwxwBju43jpGEZjpbA0dqoXMkr
J1MyD7aPLoAiVe0ikw2czSZumv4ncemOtk0VG3b2TnIxo3CMKtUOWu8xT08MMIuo
3cZRnpI6Xr/ULzvjv8e3EjIpwRJqMPECtGsfdcjFmR0yFIrjrlmkZTiW31z/Dk7i
xRGD0ADy3WEQ3lA4l3mNZeyG4S0Wi4iYe9/wegESMZcakLoME7ks+KNS388Mdbcd
DKy9NmWvAgMBAAECggEABLQAA0hHhdWv6+Lc9xkpFuTvxTV4fuyvCf4u1eGlnstg
ZF/nW1/6w8XQ8WCgbJ4mKuZz1J14FYKxfoRaj8S9MA2Ff+wd+M77gRpAuDWajRzO
LQk8OW2yd7POXKkAzvln9F9eofkCFKR4zSpPGTenCJaQkuYrQEOKfUf7oofdRzQi
w9kmp3wAxM/EseHZpknYDCgDQV7MDQAaMD7kbynL2WfXPxebktwpRlKUwgtGrevj
gagQL8J/GX6wO3ymw9sln4BhlI2+3LuiMXQdQc1tamkXFCguCuOZCu/2VRdCHmiS
nnpu+FMspBHbvxO+RXo3Cu/S6jjJgoQxD2WZTE0gqQKBgQDM6AQdqBYjISdkI9Gl
6ZLLjwZRJSYpopujtX7pun61l9kUwQevaR2Z39rMWxX62DD6arazi/ygIUBw6Kgp
s/qBEb29ec+0cESdC8aJYb3dGvDzh/8C05p7ozxj8JZQcxq5W5jql/BELlSsUONO
jfqQv8RGZNSkD9uy6TxOr4eWIwKBgQDRUuO/XRDLt8Mp10mTshxTznSQ3gAJYKeG
0WfEC3kPEukHBQb8huqFcQDiQ71oBWuEdOQWgT3aBS6L+nIMyZMT5u+BejQm7/E5
pMM+z0VRpfFSsIrCvU8yKam0aemQGlKQAfhTct1gCg+wKnYsSQMlNHKWEfDbw9I/
cns/IN+dBQKBgQC6/Of0oFVDTZgC3GUPAO3C8QwUtM/0or1hUdk1Nck3shCZzeVT
f5tRtmSWpHCUbwGTJBsCEjdBcda6srXzCJkLe8Moy6ZtxR34KqzM5fM7eMB1nJ9s
Vunc9gPAN+cUF1ZF3H7ZZjoOHjGK5m3oW8xSl41np9Acv5P/2rP8Ilaa/QKBgQDJ
YwISfitGk8mEW8hB/L4cMykapztJyl/i6Vz31EHoKr1fL4sFMZg4QfwjtCBqD6zd
hshajoU/WHTr30wS2WxTXX9YBoZeX8KpPsdJioiagRioAYm+yfuDu2m2VZ+MMIb2
Xa7YOk6Zs5RcXL3M5YHNLaSAlUoxZTjGKhJBLhN1MQKBgQCbo3ngBl7Qjjx4WJ93
2WEEKvSDCv69eecNQDuKWKEiFqBN23LheNrN8DXMWFTtE4miY106dzQ0dUMh418x
K98rXSX3VvY4w48AznvPMKVLqesFjcvwnBdvk/NqXod20CMSpOEVj6W/nGoTBQt2
0PuW3IUym9KvO0WX9E+1Qw8mbw==
-----END PRIVATE KEY-----"""
PUB_KEY_PEM = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp4vD+G75Av90sTU6w8Na
sNL1rSSmTLMidzHLOPtWqaFajkIbo1KhqhUokU+1ZnOzhIQdL4pHYk5ApNT3KE3f
6zmv9FmxvN/OSXC82iX0yBvq60bR8GdU8McAY7uN46RhGY6WwNHaqFzJKydTMg+2
jy6AIlXtIpMNnM0mbpr+J3HpjrZNFRt29k5yMaNwjCrVDlrvMU9PDDCLqN3GUZ6S
Ol6/1C8747/HtxIyKcESajDxArRrH3XIxZkdMhSK465ZpGU4lt9c/w5O4sURg9AA
8t1hEN5QOJd5jWXshuEtFouImHvf8HoBEjGXGpC6DBO5LPijUt/PDHW3HQysvTZl
rwIDAQAB
-----END PUBLIC KEY-----"""
INBOX = []
@app.route("/.well-known/webfinger")
def webfinger():
return json.dumps(
{
"subject": "acct:h4kor@mock_masto",
"aliases": [
"http://mock_masto:8000/@h4kor",
"http://mock_masto:8000/users/h4kor",
],
"links": [
{
"rel": "http://webfinger.net/rel/profile-page",
"type": "text/html",
"href": "http://mock_masto:8000/@h4kor",
},
{
"rel": "self",
"type": "application/activity+json",
"href": "http://mock_masto:8000/users/h4kor",
},
{
"rel": "http://ostatus.org/schema/1.0/subscribe",
"template": "http://mock_masto:8000/authorize_interaction?uri={uri}",
},
{
"rel": "http://webfinger.net/rel/avatar",
"type": "image/png",
"href": "http://assets.mock_masto/accounts/avatars/000/082/056/original/a4be9944e3b03229.png",
},
],
}
)
@app.route("/users/h4kor")
def actor():
print("request to actor")
return json.dumps(
{
"@context": [
"http://www.w3.org/ns/activitystreams",
"http://w3id.org/security/v1",
{
"manuallyApprovesFollowers": "as:manuallyApprovesFollowers",
"toot": "http://joinmastodon.org/ns#",
"featured": {"@id": "toot:featured", "@type": "@id"},
"featuredTags": {"@id": "toot:featuredTags", "@type": "@id"},
"alsoKnownAs": {"@id": "as:alsoKnownAs", "@type": "@id"},
"movedTo": {"@id": "as:movedTo", "@type": "@id"},
"schema": "http://schema.org#",
"PropertyValue": "schema:PropertyValue",
"value": "schema:value",
"discoverable": "toot:discoverable",
"Device": "toot:Device",
"Ed25519Signature": "toot:Ed25519Signature",
"Ed25519Key": "toot:Ed25519Key",
"Curve25519Key": "toot:Curve25519Key",
"EncryptedMessage": "toot:EncryptedMessage",
"publicKeyBase64": "toot:publicKeyBase64",
"deviceId": "toot:deviceId",
"claim": {"@type": "@id", "@id": "toot:claim"},
"fingerprintKey": {"@type": "@id", "@id": "toot:fingerprintKey"},
"identityKey": {"@type": "@id", "@id": "toot:identityKey"},
"devices": {"@type": "@id", "@id": "toot:devices"},
"messageFranking": "toot:messageFranking",
"messageType": "toot:messageType",
"cipherText": "toot:cipherText",
"suspended": "toot:suspended",
"memorial": "toot:memorial",
"indexable": "toot:indexable",
"Hashtag": "as:Hashtag",
"focalPoint": {"@container": "@list", "@id": "toot:focalPoint"},
},
],
"id": "http://mock_masto:8000/users/h4kor",
"type": "Person",
"following": "http://mock_masto:8000/users/h4kor/following",
"followers": "http://mock_masto:8000/users/h4kor/followers",
"inbox": "http://mock_masto:8000/users/h4kor/inbox",
"outbox": "http://mock_masto:8000/users/h4kor/outbox",
"featured": "http://mock_masto:8000/users/h4kor/collections/featured",
"featuredTags": "http://mock_masto:8000/users/h4kor/collections/tags",
"preferredUsername": "h4kor",
"name": "Niko",
"summary": '<p>Teaching computers to do things with arguable efficiency.</p><p>he/him</p><p><a href="http://mock_masto:8000/tags/vegan" class="mention hashtag" rel="tag">#<span>vegan</span></a> <a href="http://mock_masto:8000/tags/cooking" class="mention hashtag" rel="tag">#<span>cooking</span></a> <a href="http://mock_masto:8000/tags/programming" class="mention hashtag" rel="tag">#<span>programming</span></a> <a href="http://mock_masto:8000/tags/politics" class="mention hashtag" rel="tag">#<span>politics</span></a> <a href="http://mock_masto:8000/tags/climate" class="mention hashtag" rel="tag">#<span>climate</span></a></p>',
"url": "http://mock_masto:8000/@h4kor",
"manuallyApprovesFollowers": False,
"discoverable": True,
"indexable": False,
"published": "2018-08-16T00:00:00Z",
"memorial": False,
"devices": "http://mock_masto:8000/users/h4kor/collections/devices",
"publicKey": {
"id": "http://mock_masto:8000/users/h4kor#main-key",
"owner": "http://mock_masto:8000/users/h4kor",
"publicKeyPem": PUB_KEY_PEM,
},
"tag": [
{
"type": "Hashtag",
"href": "http://mock_masto:8000/tags/politics",
"name": "#politics",
},
{
"type": "Hashtag",
"href": "http://mock_masto:8000/tags/climate",
"name": "#climate",
},
{
"type": "Hashtag",
"href": "http://mock_masto:8000/tags/vegan",
"name": "#vegan",
},
{
"type": "Hashtag",
"href": "http://mock_masto:8000/tags/programming",
"name": "#programming",
},
{
"type": "Hashtag",
"href": "http://mock_masto:8000/tags/cooking",
"name": "#cooking",
},
],
"attachment": [
{
"type": "PropertyValue",
"name": "Me",
"value": '<a href="http://rerere.org" target="_blank" rel="nofollow noopener noreferrer me" translate="no"><span class="invisible">http://</span><span class="">rerere.org</span><span class="invisible"></span></a>',
},
{
"type": "PropertyValue",
"name": "Blog",
"value": '<a href="http://blog.libove.org" target="_blank" rel="nofollow noopener noreferrer me" translate="no"><span class="invisible">http://</span><span class="">blog.libove.org</span><span class="invisible"></span></a>',
},
{"type": "PropertyValue", "name": "Location", "value": "Münster"},
{
"type": "PropertyValue",
"name": "Current Project",
"value": '<a href="http://git.libove.org/h4kor/owl-blogs" target="_blank" rel="nofollow noopener noreferrer me" translate="no"><span class="invisible">http://</span><span class="">git.libove.org/h4kor/owl-blogs</span><span class="invisible"></span></a>',
},
],
"endpoints": {"sharedInbox": "http://mock_masto:8000/inbox"},
"icon": {
"type": "Image",
"mediaType": "image/png",
"url": "http://assets.mock_masto/accounts/avatars/000/082/056/original/a4be9944e3b03229.png",
},
}
)
@app.route("/users/h4kor/inbox", methods=["POST"])
def inbox():
if request.method == "POST":
INBOX.append(json.loads(request.get_data()))
return ""
@app.route("/msgs")
def msgs():
return json.dumps(INBOX)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port="8000")

View File

@ -0,0 +1 @@
Flask==3.0.3

View File

@ -0,0 +1,17 @@
certifi==2024.2.2
cffi==1.16.0
charset-normalizer==3.3.2
cryptography==42.0.7
exceptiongroup==1.2.1
http-message-signatures==0.5.0
http_sfv==0.9.9
idna==3.7
iniconfig==2.0.0
packaging==24.0
pluggy==1.5.0
pycparser==2.22
pytest==8.2.0
requests==2.31.0
tomli==2.0.1
typing_extensions==4.11.0
urllib3==2.2.1

View File

102
e2e_tests/tests/fixtures.py Normal file
View File

@ -0,0 +1,102 @@
from contextlib import contextmanager
from datetime import datetime, timezone
import json
from time import sleep
from urllib.parse import urlparse
import requests, base64, hashlib
from urllib.parse import urlparse
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
ACCT_NAME = "acct:blog@localhost:3000"
PRIV_KEY_PEM = """-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCni8P4bvkC/3Sx
NTrDw1qw0vWtJKZMsyJ3Mcs4+1apoVqOQhujUqGqFSiRT7Vmc7OEhB0vikdiTkCk
1PcoTd/rOa/0WbG8385JcLzaJfTIG+rrRtHwZ1TwxwBju43jpGEZjpbA0dqoXMkr
J1MyD7aPLoAiVe0ikw2czSZumv4ncemOtk0VG3b2TnIxo3CMKtUOWu8xT08MMIuo
3cZRnpI6Xr/ULzvjv8e3EjIpwRJqMPECtGsfdcjFmR0yFIrjrlmkZTiW31z/Dk7i
xRGD0ADy3WEQ3lA4l3mNZeyG4S0Wi4iYe9/wegESMZcakLoME7ks+KNS388Mdbcd
DKy9NmWvAgMBAAECggEABLQAA0hHhdWv6+Lc9xkpFuTvxTV4fuyvCf4u1eGlnstg
ZF/nW1/6w8XQ8WCgbJ4mKuZz1J14FYKxfoRaj8S9MA2Ff+wd+M77gRpAuDWajRzO
LQk8OW2yd7POXKkAzvln9F9eofkCFKR4zSpPGTenCJaQkuYrQEOKfUf7oofdRzQi
w9kmp3wAxM/EseHZpknYDCgDQV7MDQAaMD7kbynL2WfXPxebktwpRlKUwgtGrevj
gagQL8J/GX6wO3ymw9sln4BhlI2+3LuiMXQdQc1tamkXFCguCuOZCu/2VRdCHmiS
nnpu+FMspBHbvxO+RXo3Cu/S6jjJgoQxD2WZTE0gqQKBgQDM6AQdqBYjISdkI9Gl
6ZLLjwZRJSYpopujtX7pun61l9kUwQevaR2Z39rMWxX62DD6arazi/ygIUBw6Kgp
s/qBEb29ec+0cESdC8aJYb3dGvDzh/8C05p7ozxj8JZQcxq5W5jql/BELlSsUONO
jfqQv8RGZNSkD9uy6TxOr4eWIwKBgQDRUuO/XRDLt8Mp10mTshxTznSQ3gAJYKeG
0WfEC3kPEukHBQb8huqFcQDiQ71oBWuEdOQWgT3aBS6L+nIMyZMT5u+BejQm7/E5
pMM+z0VRpfFSsIrCvU8yKam0aemQGlKQAfhTct1gCg+wKnYsSQMlNHKWEfDbw9I/
cns/IN+dBQKBgQC6/Of0oFVDTZgC3GUPAO3C8QwUtM/0or1hUdk1Nck3shCZzeVT
f5tRtmSWpHCUbwGTJBsCEjdBcda6srXzCJkLe8Moy6ZtxR34KqzM5fM7eMB1nJ9s
Vunc9gPAN+cUF1ZF3H7ZZjoOHjGK5m3oW8xSl41np9Acv5P/2rP8Ilaa/QKBgQDJ
YwISfitGk8mEW8hB/L4cMykapztJyl/i6Vz31EHoKr1fL4sFMZg4QfwjtCBqD6zd
hshajoU/WHTr30wS2WxTXX9YBoZeX8KpPsdJioiagRioAYm+yfuDu2m2VZ+MMIb2
Xa7YOk6Zs5RcXL3M5YHNLaSAlUoxZTjGKhJBLhN1MQKBgQCbo3ngBl7Qjjx4WJ93
2WEEKvSDCv69eecNQDuKWKEiFqBN23LheNrN8DXMWFTtE4miY106dzQ0dUMh418x
K98rXSX3VvY4w48AznvPMKVLqesFjcvwnBdvk/NqXod20CMSpOEVj6W/nGoTBQt2
0PuW3IUym9KvO0WX9E+1Qw8mbw==
-----END PRIVATE KEY-----"""
def ensure_follow(client, inbox_url, actor_url):
req = sign(
"POST",
inbox_url,
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "http://mock_masto:8000/d0b5768b-a15b-4ed6-bc84-84c7e2b57588",
"type": "Follow",
"actor": "http://mock_masto:8000/users/h4kor",
"object": actor_url,
},
)
resp = requests.Session().send(req)
assert resp.status_code == 200
def sign(method, url, data):
priv_key = load_pem_private_key(PRIV_KEY_PEM.encode(), None)
body = json.dumps(data).encode()
body_hash = hashlib.sha256(body).digest()
digest = "SHA-256=" + base64.b64encode(body_hash).decode()
date = datetime.now(tz=timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT")
host = "localhost:3000"
target = urlparse(url).path
to_sign = f"""(request-target): {method.lower()} {target}
host: {host}
date: {date}""".encode()
sig = priv_key.sign(
to_sign,
padding.PKCS1v15(),
hashes.SHA256(),
)
sig_str = base64.b64encode(sig).decode()
request = requests.Request(method, url, data=body)
request = request.prepare()
request.headers["Content-Digest"] = digest
request.headers["Host"] = host
request.headers["Date"] = date
request.headers["Signature"] = (
f'keyId="http://mock_masto:8000/users/h4kor#main-key",headers="(request-target) host date",signature="{sig_str}"'
)
return request
@contextmanager
def msg_inc(n):
resp = requests.get("http://localhost:8000/msgs")
data = resp.json()
msgs = len(data)
yield
sleep(0.2)
resp = requests.get("http://localhost:8000/msgs")
data = resp.json()
assert msgs + n == len(
data
), f"prev: {msgs}, now: {len(data)}, expected: {msgs + n}"

View File

@ -0,0 +1,88 @@
from pprint import pprint
from time import sleep
import requests
from .fixtures import ensure_follow, msg_inc, sign
import pytest
def test_actor(client, actor_url):
resp = client.get(actor_url, headers={"Content-Type": "application/activity+json"})
assert resp.status_code == 200
data = resp.json()
assert "id" in data
assert "type" in data
assert "inbox" in data
assert "outbox" in data
assert "followers" in data
assert "preferredUsername" in data
assert "publicKey" in data
assert len(data["publicKey"])
pubKey = data["publicKey"]
assert "id" in pubKey
assert "owner" in pubKey
assert "publicKeyPem" in pubKey
assert pubKey["owner"] == data["id"]
assert pubKey["id"] != data["id"]
assert "-----BEGIN RSA PUBLIC KEY-----" in pubKey["publicKeyPem"]
def test_following(client, inbox_url, followers_url, actor_url):
with msg_inc(1):
req = sign(
"POST",
inbox_url,
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "http://mock_masto:8000/d0b5768b-a15b-4ed6-bc84-84c7e2b57588",
"type": "Follow",
"actor": "http://mock_masto:8000/users/h4kor",
"object": actor_url,
},
)
resp = requests.Session().send(req)
assert resp.status_code == 200
resp = client.get(
followers_url, headers={"Content-Type": "application/activity+json"}
)
assert resp.status_code == 200
data = resp.json()
pprint(data)
assert "items" in data
assert len(data["items"]) == 1
def test_unfollow(client, inbox_url, followers_url, actor_url):
ensure_follow(client, inbox_url, actor_url)
sleep(0.5)
with msg_inc(1):
req = sign(
"POST",
inbox_url,
{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "http://mock_masto:8000/users/h4kor#follows/3632040/undo",
"type": "Undo",
"actor": "http://mock_masto:8000/users/h4kor",
"object": {
"id": "http://mock_masto:8000/d0b5768b-a15b-4ed6-bc84-84c7e2b57588",
"type": "Follow",
"actor": "http://mock_masto:8000/users/h4kor",
"object": actor_url,
},
},
)
resp = requests.Session().send(req)
assert resp.status_code == 200
resp = client.get(
followers_url, headers={"Content-Type": "application/activity+json"}
)
assert resp.status_code == 200
data = resp.json()
pprint(data)
assert "totalItems" in data
assert data["totalItems"] == 0

View File

@ -0,0 +1,27 @@
import pytest
from .fixtures import ACCT_NAME
@pytest.mark.parametrize(
["query", "status"],
[
["", 404],
["?foo=bar", 404],
["?resource=lol@bar.com", 404],
[f"?resource={ACCT_NAME}", 200],
],
)
def test_webfinger_status(client, query, status):
resp = client.get("/.well-known/webfinger" + query)
assert resp.status_code == status
def test_webfinger(client):
resp = client.get(f"/.well-known/webfinger?resource={ACCT_NAME}")
assert resp.status_code == 200
data = resp.json()
assert data["subject"] == ACCT_NAME
assert len(data["links"]) > 0
self_link = [x for x in data["links"] if x["rel"] == "self"][0]
assert self_link["type"] == "application/activity+json"
assert "href" in self_link

View File

@ -12,8 +12,21 @@ type Article struct {
}
type ArticleMetaData struct {
Title string `owl:"inputType=text"`
Content string `owl:"inputType=text widget=textarea"`
Title string
Content string
}
// Form implements model.EntryMetaData.
func (meta *ArticleMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Article", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *ArticleMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
meta.Title = data.FormValue("title")
meta.Content = data.FormValue("content")
return nil
}
func (e *Article) Title() string {
@ -28,10 +41,10 @@ func (e *Article) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Article) MetaData() interface{} {
func (e *Article) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Article) SetMetaData(metaData interface{}) {
func (e *Article) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*ArticleMetaData)
}

View File

@ -12,9 +12,23 @@ type Bookmark struct {
}
type BookmarkMetaData struct {
Title string `owl:"inputType=text"`
Url string `owl:"inputType=text"`
Content string `owl:"inputType=text widget=textarea"`
Title string
Url string
Content string
}
// Form implements model.EntryMetaData.
func (meta *BookmarkMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Bookmark", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *BookmarkMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
meta.Title = data.FormValue("title")
meta.Url = data.FormValue("url")
meta.Content = data.FormValue("content")
return nil
}
func (e *Bookmark) Title() string {
@ -29,10 +43,10 @@ func (e *Bookmark) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Bookmark) MetaData() interface{} {
func (e *Bookmark) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Bookmark) SetMetaData(metaData interface{}) {
func (e *Bookmark) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*BookmarkMetaData)
}

View File

@ -12,15 +12,56 @@ type Image struct {
}
type ImageMetaData struct {
ImageId string `owl:"inputType=file"`
Title string `owl:"inputType=text"`
Content string `owl:"inputType=text widget=textarea"`
ImageId string
Title string
Content string
}
// Form implements model.EntryMetaData.
func (meta *ImageMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Image", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *ImageMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
file, err := data.FormFile("image")
var imgId = meta.ImageId
if err != nil && imgId == "" {
return err
} else if err == nil {
fileData, err := file.Open()
if err != nil {
return err
}
defer fileData.Close()
fileBytes := make([]byte, file.Size)
_, err = fileData.Read(fileBytes)
if err != nil {
return err
}
bin, err := binSvc.Create(file.Filename, fileBytes)
if err != nil {
return err
}
imgId = bin.Id
}
meta.ImageId = imgId
meta.Title = data.FormValue("title")
meta.Content = data.FormValue("content")
return nil
}
func (e *Image) Title() string {
return e.meta.Title
}
func (e *Image) ImageUrl() string {
return "/media/" + e.meta.ImageId
}
func (e *Image) Content() model.EntryContent {
str, err := render.RenderTemplateToString("entry/Image", e)
if err != nil {
@ -29,10 +70,10 @@ func (e *Image) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Image) MetaData() interface{} {
func (e *Image) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Image) SetMetaData(metaData interface{}) {
func (e *Image) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*ImageMetaData)
}

View File

@ -12,7 +12,19 @@ type Note struct {
}
type NoteMetaData struct {
Content string `owl:"inputType=text widget=textarea"`
Content string
}
// Form implements model.EntryMetaData.
func (meta *NoteMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Note", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *NoteMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
meta.Content = data.FormValue("content")
return nil
}
func (e *Note) Title() string {
@ -27,10 +39,10 @@ func (e *Note) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Note) MetaData() interface{} {
func (e *Note) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Note) SetMetaData(metaData interface{}) {
func (e *Note) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*NoteMetaData)
}

View File

@ -12,8 +12,21 @@ type Page struct {
}
type PageMetaData struct {
Title string `owl:"inputType=text"`
Content string `owl:"inputType=text widget=textarea"`
Title string
Content string
}
// Form implements model.EntryMetaData.
func (meta *PageMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Page", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *PageMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
meta.Title = data.FormValue("title")
meta.Content = data.FormValue("content")
return nil
}
func (e *Page) Title() string {
@ -28,10 +41,10 @@ func (e *Page) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Page) MetaData() interface{} {
func (e *Page) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Page) SetMetaData(metaData interface{}) {
func (e *Page) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*PageMetaData)
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
"owl-blogs/domain/model"
"owl-blogs/render"
"strings"
)
type Recipe struct {
@ -12,11 +13,34 @@ type Recipe struct {
}
type RecipeMetaData struct {
Title string `owl:"inputType=text"`
Yield string `owl:"inputType=text"`
Duration string `owl:"inputType=text"`
Ingredients []string `owl:"inputType=text widget=textarea"`
Content string `owl:"inputType=text widget=textarea"`
Title string
Yield string
Duration string
Ingredients []string
Content string
}
// Form implements model.EntryMetaData.
func (meta *RecipeMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Recipe", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *RecipeMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
ings := strings.Split(data.FormValue("ingredients"), "\n")
clean := make([]string, 0)
for _, ing := range ings {
if strings.TrimSpace(ing) != "" {
clean = append(clean, strings.TrimSpace(ing))
}
}
meta.Title = data.FormValue("title")
meta.Yield = data.FormValue("yield")
meta.Duration = data.FormValue("duration")
meta.Ingredients = clean
meta.Content = data.FormValue("content")
return nil
}
func (e *Recipe) Title() string {
@ -31,10 +55,10 @@ func (e *Recipe) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Recipe) MetaData() interface{} {
func (e *Recipe) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Recipe) SetMetaData(metaData interface{}) {
func (e *Recipe) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*RecipeMetaData)
}

View File

@ -12,9 +12,23 @@ type Reply struct {
}
type ReplyMetaData struct {
Title string `owl:"inputType=text"`
Url string `owl:"inputType=text"`
Content string `owl:"inputType=text widget=textarea"`
Title string
Url string
Content string
}
// Form implements model.EntryMetaData.
func (meta *ReplyMetaData) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/Reply", meta)
return f
}
// ParseFormData implements model.EntryMetaData.
func (meta *ReplyMetaData) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
meta.Title = data.FormValue("title")
meta.Url = data.FormValue("url")
meta.Content = data.FormValue("content")
return nil
}
func (e *Reply) Title() string {
@ -29,10 +43,10 @@ func (e *Reply) Content() model.EntryContent {
return model.EntryContent(str)
}
func (e *Reply) MetaData() interface{} {
func (e *Reply) MetaData() model.EntryMetaData {
return &e.meta
}
func (e *Reply) SetMetaData(metaData interface{}) {
func (e *Reply) SetMetaData(metaData model.EntryMetaData) {
e.meta = *metaData.(*ReplyMetaData)
}

59
go.mod
View File

@ -1,35 +1,50 @@
module owl-blogs
go 1.20
go 1.22
require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/Davincible/goinsta/v3 v3.2.6
github.com/go-ap/activitypub v0.0.0-20240408091739-ba76b44c2594
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73
github.com/gofiber/fiber/v2 v2.52.4
github.com/google/uuid v1.6.0
github.com/jmoiron/sqlx v1.4.0
github.com/mattn/go-sqlite3 v1.14.22
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.8.4
github.com/yuin/goldmark v1.7.1
golang.org/x/crypto v0.23.0
golang.org/x/net v0.25.0
gopkg.in/yaml.v2 v2.4.0
)
require (
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/chromedp/cdproto v0.0.0-20240501202034-ef67d660e9fd // indirect
github.com/chromedp/chromedp v0.9.5 // indirect
github.com/chromedp/sysutil v1.0.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gofiber/fiber/v2 v2.47.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/go-ap/errors v0.0.0-20240304112515-6077fa9c17b0 // indirect
github.com/go-fed/httpsig v1.1.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/klauspost/compress v1.16.3 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 // indirect
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
github.com/spf13/cobra v1.7.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
github.com/tinylib/msgp v1.1.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.47.0 // indirect
github.com/valyala/fasthttp v1.52.0 // indirect
github.com/valyala/fastjson v1.6.4 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
github.com/yuin/goldmark v1.5.4 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
golang.org/x/sys v0.20.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

165
go.sum
View File

@ -1,120 +1,109 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 h1:cliQ4HHsCo6xi2oWZYKWW4bly/Ory9FuTpFPRxj/mAg=
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078/go.mod h1:g/V2Hjas6Z1UHUp4yIx6bATpNzJ7DYtD0FG3+xARWxs=
github.com/Davincible/goinsta/v3 v3.2.6 h1:+lNIWU6NABWd2VSGe83UQypnef+kzWwjmfgGihPbwD8=
github.com/Davincible/goinsta/v3 v3.2.6/go.mod h1:jIDhrWZmttL/gtXj/mkCaZyeNdAAqW3UYjasOUW0YEw=
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
github.com/chromedp/cdproto v0.0.0-20240501202034-ef67d660e9fd h1:5/HXKq8EaAWVmnl6Hnyl4SVq7FF5990DBW6AuTrWtVw=
github.com/chromedp/cdproto v0.0.0-20240501202034-ef67d660e9fd/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
github.com/chromedp/chromedp v0.9.5 h1:viASzruPJOiThk7c5bueOUY91jGLJVximoEMGoH93rg=
github.com/chromedp/chromedp v0.9.5/go.mod h1:D4I2qONslauw/C7INoCir1BJkSwBYMyZgx8X276z3+Y=
github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gofiber/fiber/v2 v2.47.0 h1:EN5lHVCc+Pyqh5OEsk8fzRiifgwpbrP0rulQ4iNf3fs=
github.com/gofiber/fiber/v2 v2.47.0/go.mod h1:mbFMVN1lQuzziTkkakgtKKdjfsXSw9BKR5lmcNksUoU=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/go-ap/activitypub v0.0.0-20240408091739-ba76b44c2594 h1:er3GvGCm7bJwHostjZlsRy7uiUuCquUVF9Fe0TrwiPI=
github.com/go-ap/activitypub v0.0.0-20240408091739-ba76b44c2594/go.mod h1:yRUfFCoZY6C1CWalauqEQ5xYgSckzEBEO/2MBC6BOME=
github.com/go-ap/errors v0.0.0-20240304112515-6077fa9c17b0 h1:H9MGShwybHLSln6K8RxHPMHiLcD86Lru+5TVW2TcXHY=
github.com/go-ap/errors v0.0.0-20240304112515-6077fa9c17b0/go.mod h1:5x8a6P/dhmMGFxWLcyYlyOuJ2lRNaHGhRv+yu8BaTSI=
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73 h1:GMKIYXyXPGIp+hYiWOhfqK4A023HdgisDT4YGgf99mw=
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73/go.mod h1:jyveZeGw5LaADntW+UEsMjl3IlIwk+DxlYNsbofQkGA=
github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.3.2/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/gofiber/fiber/v2 v2.52.4 h1:P+T+4iK7VaqUsq2PALYEfBBo6bJZ4q3FP8cZ84EggTM=
github.com/gofiber/fiber/v2 v2.52.4/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY=
github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU=
github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw=
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94 h1:rmMl4fXJhKMNWl+K+r/fq4FbbKI+Ia2m9hYBLm2h4G4=
github.com/savsgio/dictpool v0.0.0-20221023140959-7bf2e61cea94/go.mod h1:90zrgN3D/WJsDd1iXHT96alCoN2KJo6/4x1DZC3wZs8=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tinylib/msgp v1.1.6/go.mod h1:75BAfg2hauQhs3qedfdDZmWAPcFMAvJE5b9rGOMufyw=
github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0=
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.47.0 h1:y7moDoxYzMooFpT5aHgNgVOQDrS3qlkfiP9mDtGGK9c=
github.com/valyala/fasthttp v1.47.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0=
github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ=
github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXVQ=
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.5.4 h1:2uY/xC0roWy8IBEGLgB1ywIoEJFGmRrX21YQcvGZzjU=
github.com/yuin/goldmark v1.5.4/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.7.1 h1:3bajkSilaCbjdKVsKdZjZCLBNPL9pYzrCakKaf4U49U=
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -59,3 +59,12 @@ func (r *DefaultAuthorRepo) Create(name string, passwordHash string) (*model.Aut
PasswordHash: author.PasswordHash,
}, nil
}
func (r *DefaultAuthorRepo) Update(author *model.Author) error {
sqlA := sqlAuthor{
Name: author.Name,
PasswordHash: author.PasswordHash,
}
_, err := r.db.NamedExec("UPDATE authors SET password_hash = :password_hash WHERE name = :name", sqlA)
return err
}

View File

@ -45,3 +45,19 @@ func TestAuthorRepoNoSideEffect(t *testing.T) {
require.Equal(t, author2.Name, "name2")
require.Equal(t, author2.PasswordHash, "password2")
}
func TestAuthorUpdate(t *testing.T) {
repo := setupAutherRepo()
author, err := repo.Create("name1", "password1")
require.NoError(t, err)
author.PasswordHash = "password2"
err = repo.Update(author)
require.NoError(t, err)
author, err = repo.FindByName("name1")
require.NoError(t, err)
require.Equal(t, author.PasswordHash, "password2")
}

View File

@ -99,3 +99,27 @@ func (repo *DefaultBinaryFileRepo) FindByNameForEntry(name string, entry model.E
}
return &model.BinaryFile{Id: sqlFile.Id, Name: sqlFile.Name, Data: sqlFile.Data}, nil
}
// ListIds implements repository.BinaryRepository
func (repo *DefaultBinaryFileRepo) ListIds(filter string) ([]string, error) {
filter = strings.TrimSpace(strings.ToLower(filter))
if filter == "" {
filter = "%"
} else {
filter = "%" + filter + "%"
}
var ids []string
err := repo.db.Select(&ids, "SELECT id FROM binary_files WHERE LOWER(id) LIKE ?", filter)
if err != nil {
return nil, err
}
return ids, nil
}
// Delete implements repository.BinaryRepository
func (repo *DefaultBinaryFileRepo) Delete(binary *model.BinaryFile) error {
id := binary.Id
println("Deleting binary file", id)
_, err := repo.db.Exec("DELETE FROM binary_files WHERE id = ?", id)
return err
}

View File

@ -28,6 +28,26 @@ type DefaultEntryRepo struct {
db *sqlx.DB
}
func NewEntryRepository(db Database, register *app.EntryTypeRegistry) repository.EntryRepository {
sqlxdb := db.Get()
// Create tables if not exists
sqlxdb.MustExec(`
CREATE TABLE IF NOT EXISTS entries (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
published_at DATETIME,
author_id TEXT NOT NULL,
meta_data TEXT NOT NULL
);
`)
return &DefaultEntryRepo{
db: sqlxdb,
typeRegistry: register,
}
}
// Create implements repository.EntryRepository.
func (r *DefaultEntryRepo) Create(entry model.Entry) error {
t, err := r.typeRegistry.TypeName(entry)
@ -50,6 +70,9 @@ func (r *DefaultEntryRepo) Create(entry model.Entry) error {
// Delete implements repository.EntryRepository.
func (r *DefaultEntryRepo) Delete(entry model.Entry) error {
if entry.ID() == "" {
return errors.New("entry not found")
}
_, err := r.db.Exec("DELETE FROM entries WHERE id = ?", entry.ID())
return err
}
@ -97,7 +120,7 @@ func (r *DefaultEntryRepo) FindById(id string) (model.Entry, error) {
return nil, err
}
if data.Id == "" {
return nil, nil
return nil, errors.New("entry not found")
}
return r.sqlEntryToEntry(data)
}
@ -123,32 +146,12 @@ func (r *DefaultEntryRepo) Update(entry model.Entry) error {
return err
}
func NewEntryRepository(db Database, register *app.EntryTypeRegistry) repository.EntryRepository {
sqlxdb := db.Get()
// Create tables if not exists
sqlxdb.MustExec(`
CREATE TABLE IF NOT EXISTS entries (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
published_at DATETIME,
author_id TEXT NOT NULL,
meta_data TEXT NOT NULL
);
`)
return &DefaultEntryRepo{
db: sqlxdb,
typeRegistry: register,
}
}
func (r *DefaultEntryRepo) sqlEntryToEntry(entry sqlEntry) (model.Entry, error) {
e, err := r.typeRegistry.Type(entry.Type)
if err != nil {
return nil, errors.New("entry type not registered")
}
metaData := reflect.New(reflect.TypeOf(e.MetaData()).Elem()).Interface()
metaData := reflect.New(reflect.TypeOf(e.MetaData()).Elem()).Interface().(model.EntryMetaData)
json.Unmarshal([]byte(*entry.MetaData), metaData)
e.SetID(entry.Id)
e.SetPublishedAt(entry.PublishedAt)

View File

@ -0,0 +1,57 @@
package infra
import (
"owl-blogs/app/repository"
"github.com/jmoiron/sqlx"
)
type sqlFollower struct {
Follwer string `db:"follower"`
}
type DefaultFollowerRepo struct {
db *sqlx.DB
}
func NewFollowerRepository(db Database) repository.FollowerRepository {
sqlxdb := db.Get()
// Create tables if not exists
sqlxdb.MustExec(`
CREATE TABLE IF NOT EXISTS followers (
follower TEXT PRIMARY KEY
);
`)
return &DefaultFollowerRepo{
db: sqlxdb,
}
}
// Add implements repository.FollowerRepository.
func (d *DefaultFollowerRepo) Add(follower string) error {
_, err := d.db.Exec("INSERT INTO followers (follower) VALUES (?) ON CONFLICT DO NOTHING", follower)
return err
}
// Remove implements repository.FollowerRepository.
func (d *DefaultFollowerRepo) Remove(follower string) error {
_, err := d.db.Exec("DELETE FROM followers WHERE follower = ?", follower)
return err
}
// All implements repository.FollowerRepository.
func (d *DefaultFollowerRepo) All() ([]string, error) {
var followers []sqlFollower
err := d.db.Select(&followers, "SELECT * FROM followers")
if err != nil {
return nil, err
}
result := []string{}
for _, follower := range followers {
result = append(result, follower.Follwer)
}
return result, nil
}

View File

@ -0,0 +1,91 @@
package infra_test
import (
"owl-blogs/app/repository"
"owl-blogs/infra"
"owl-blogs/test"
"testing"
"github.com/stretchr/testify/require"
)
func setupFollowerRepo() repository.FollowerRepository {
db := test.NewMockDb()
repo := infra.NewFollowerRepository(db)
return repo
}
func TestAddFollower(t *testing.T) {
repo := setupFollowerRepo()
err := repo.Add("foo@example.com")
require.NoError(t, err)
followers, err := repo.All()
require.NoError(t, err)
require.Len(t, followers, 1)
require.Equal(t, followers[0], "foo@example.com")
}
func TestDoubleAddFollower(t *testing.T) {
repo := setupFollowerRepo()
err := repo.Add("foo@example.com")
require.NoError(t, err)
err = repo.Add("foo@example.com")
require.NoError(t, err)
followers, err := repo.All()
require.NoError(t, err)
require.Len(t, followers, 1)
require.Equal(t, followers[0], "foo@example.com")
}
func TestMultipleAddFollower(t *testing.T) {
repo := setupFollowerRepo()
err := repo.Add("foo@example.com")
require.NoError(t, err)
err = repo.Add("bar@example.com")
require.NoError(t, err)
err = repo.Add("baz@example.com")
require.NoError(t, err)
followers, err := repo.All()
require.NoError(t, err)
require.Len(t, followers, 3)
}
func TestRemoveFollower(t *testing.T) {
repo := setupFollowerRepo()
err := repo.Add("foo@example.com")
require.NoError(t, err)
followers, err := repo.All()
require.NoError(t, err)
require.Len(t, followers, 1)
err = repo.Remove("foo@example.com")
require.NoError(t, err)
followers, err = repo.All()
require.NoError(t, err)
require.Len(t, followers, 0)
}
func TestRemoveNonExistingFollower(t *testing.T) {
repo := setupFollowerRepo()
err := repo.Remove("foo@example.com")
require.NoError(t, err)
followers, err := repo.All()
require.NoError(t, err)
require.Len(t, followers, 0)
}

5
infra/http.go Normal file
View File

@ -0,0 +1,5 @@
package infra
import "net/http"
type OwlHttpClient = http.Client

View File

@ -0,0 +1,178 @@
package infra
import (
"encoding/json"
"errors"
"owl-blogs/app"
"owl-blogs/app/repository"
"owl-blogs/domain/model"
"reflect"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
type sqlInteraction struct {
Id string `db:"id"`
Type string `db:"type"`
EntryId string `db:"entry_id"`
CreatedAt time.Time `db:"created_at"`
MetaData *string `db:"meta_data"`
}
type DefaultInteractionRepo struct {
typeRegistry *app.InteractionTypeRegistry
db *sqlx.DB
}
func NewInteractionRepo(db Database, register *app.InteractionTypeRegistry) repository.InteractionRepository {
sqlxdb := db.Get()
// Create tables if not exists
sqlxdb.MustExec(`
CREATE TABLE IF NOT EXISTS interactions (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
entry_id TEXT NOT NULL,
created_at DATETIME NOT NULL,
meta_data TEXT NOT NULL
);
`)
return &DefaultInteractionRepo{
db: sqlxdb,
typeRegistry: register,
}
}
// Create implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) Create(interaction model.Interaction) error {
t, err := repo.typeRegistry.TypeName(interaction)
if err != nil {
return errors.New("interaction type not registered")
}
if interaction.ID() == "" {
interaction.SetID(uuid.New().String())
}
var metaDataJson []byte
if interaction.MetaData() != nil {
metaDataJson, _ = json.Marshal(interaction.MetaData())
}
metaDataStr := string(metaDataJson)
_, err = repo.db.NamedExec(`
INSERT INTO interactions (id, type, entry_id, created_at, meta_data)
VALUES (:id, :type, :entry_id, :created_at, :meta_data)
`, sqlInteraction{
Id: interaction.ID(),
Type: t,
EntryId: interaction.EntryID(),
CreatedAt: interaction.CreatedAt(),
MetaData: &metaDataStr,
})
return err
}
// Delete implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) Delete(interaction model.Interaction) error {
if interaction.ID() == "" {
return errors.New("interaction not found")
}
_, err := repo.db.Exec("DELETE FROM interactions WHERE id = ?", interaction.ID())
return err
}
// FindAll implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) FindAll(entryId string) ([]model.Interaction, error) {
data := []sqlInteraction{}
err := repo.db.Select(&data, "SELECT * FROM interactions WHERE entry_id = ? ORDER BY created_at DESC", entryId)
if err != nil {
return nil, err
}
interactions := []model.Interaction{}
for _, d := range data {
i, err := repo.sqlInteractionToInteraction(d)
if err != nil {
return nil, err
}
interactions = append(interactions, i)
}
return interactions, nil
}
// FindById implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) FindById(id string) (model.Interaction, error) {
data := sqlInteraction{}
err := repo.db.Get(&data, "SELECT * FROM interactions WHERE id = ?", id)
if err != nil {
return nil, err
}
if data.Id == "" {
return nil, errors.New("interaction not found")
}
return repo.sqlInteractionToInteraction(data)
}
// Update implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) Update(interaction model.Interaction) error {
exInter, _ := repo.FindById(interaction.ID())
if exInter == nil {
return errors.New("interaction not found")
}
_, err := repo.typeRegistry.TypeName(interaction)
if err != nil {
return errors.New("interaction type not registered")
}
var metaDataJson []byte
if interaction.MetaData() != nil {
metaDataJson, _ = json.Marshal(interaction.MetaData())
}
_, err = repo.db.Exec("UPDATE interactions SET entry_id = ?, meta_data = ? WHERE id = ?", interaction.EntryID(), metaDataJson, interaction.ID())
return err
}
func (repo *DefaultInteractionRepo) sqlInteractionToInteraction(interaction sqlInteraction) (model.Interaction, error) {
i, err := repo.typeRegistry.Type(interaction.Type)
if err != nil {
return nil, errors.New("interaction type not registered")
}
metaData := reflect.New(reflect.TypeOf(i.MetaData()).Elem()).Interface()
json.Unmarshal([]byte(*interaction.MetaData), metaData)
i.SetID(interaction.Id)
i.SetEntryID(interaction.EntryId)
i.SetCreatedAt(interaction.CreatedAt)
i.SetMetaData(metaData)
return i, nil
}
// ListAllInteractions implements repository.InteractionRepository.
func (repo *DefaultInteractionRepo) ListAllInteractions() ([]model.Interaction, error) {
data := []sqlInteraction{}
err := repo.db.Select(&data, "SELECT * FROM interactions ORDER BY created_at DESC")
if err != nil {
return nil, err
}
interactions := []model.Interaction{}
for _, d := range data {
i, err := repo.sqlInteractionToInteraction(d)
if err != nil {
return nil, err
}
interactions = append(interactions, i)
}
return interactions, nil
}

View File

@ -0,0 +1,125 @@
package infra_test
import (
"owl-blogs/app"
"owl-blogs/app/repository"
"owl-blogs/infra"
"owl-blogs/test"
"testing"
"github.com/stretchr/testify/require"
)
func setupInteractionRepo() repository.InteractionRepository {
db := test.NewMockDb()
register := app.NewInteractionTypeRegistry()
register.Register(&test.MockInteraction{})
repo := infra.NewInteractionRepo(db, register)
return repo
}
func TestCreateInteraction(t *testing.T) {
repo := setupInteractionRepo()
i := &test.MockInteraction{}
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i.SetEntryID("entryId")
err := repo.Create(i)
require.NoError(t, err)
require.NotEmpty(t, i.ID())
}
func TestFindInteractionById(t *testing.T) {
repo := setupInteractionRepo()
i := &test.MockInteraction{}
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i.SetEntryID("entryId")
err := repo.Create(i)
require.NoError(t, err)
i2, err := repo.FindById(i.ID())
require.NoError(t, err)
require.Equal(t, i.ID(), i2.ID())
require.Equal(t, i.Content(), i2.Content())
meta := i.MetaData().(*test.MockInteractionMetaData)
meta2 := i2.MetaData().(*test.MockInteractionMetaData)
require.Equal(t, meta.Str, meta2.Str)
require.Equal(t, meta.Number, meta2.Number)
require.Equal(t, i2.EntryID(), "entryId")
}
func TestFindInteractionByEntryId(t *testing.T) {
repo := setupInteractionRepo()
i := &test.MockInteraction{}
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i.SetEntryID("entryId")
err := repo.Create(i)
require.NoError(t, err)
i2 := &test.MockInteraction{}
i2.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i2.SetEntryID("entryId2")
err = repo.Create(i2)
require.NoError(t, err)
inters, err := repo.FindAll("entryId")
require.NoError(t, err)
require.Equal(t, 1, len(inters))
}
func TestUpdateInteraction(t *testing.T) {
repo := setupInteractionRepo()
i := &test.MockInteraction{}
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i.SetEntryID("entryId")
err := repo.Create(i)
require.NoError(t, err)
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str2",
Number: 2,
})
err = repo.Update(i)
require.NoError(t, err)
i2, err := repo.FindById(i.ID())
require.NoError(t, err)
meta := i.MetaData().(*test.MockInteractionMetaData)
meta2 := i2.MetaData().(*test.MockInteractionMetaData)
require.Equal(t, meta.Str, meta2.Str)
require.Equal(t, meta.Number, meta2.Number)
}
func TestDeleteInteraction(t *testing.T) {
repo := setupInteractionRepo()
i := &test.MockInteraction{}
i.SetMetaData(&test.MockInteractionMetaData{
Str: "str",
Number: 1,
})
i.SetEntryID("entryId")
err := repo.Create(i)
require.NoError(t, err)
err = repo.Delete(i)
require.NoError(t, err)
i2, err := repo.FindById(i.ID())
require.Error(t, err)
require.Nil(t, i2)
}

33
interactions/like.go Normal file
View File

@ -0,0 +1,33 @@
package interactions
import (
"fmt"
"owl-blogs/domain/model"
"owl-blogs/render"
)
type Like struct {
model.InteractionBase
meta LikeMetaData
}
type LikeMetaData struct {
SenderUrl string
SenderName string
}
func (i *Like) Content() model.InteractionContent {
str, err := render.RenderTemplateToString("interaction/Like", i)
if err != nil {
fmt.Println(err)
}
return model.InteractionContent(str)
}
func (i *Like) MetaData() interface{} {
return &i.meta
}
func (i *Like) SetMetaData(metaData interface{}) {
i.meta = *metaData.(*LikeMetaData)
}

33
interactions/repost.go Normal file
View File

@ -0,0 +1,33 @@
package interactions
import (
"fmt"
"owl-blogs/domain/model"
"owl-blogs/render"
)
type Repost struct {
model.InteractionBase
meta RepostMetaData
}
type RepostMetaData struct {
SenderUrl string
SenderName string
}
func (i *Repost) Content() model.InteractionContent {
str, err := render.RenderTemplateToString("interaction/Repost", i)
if err != nil {
fmt.Println(err)
}
return model.InteractionContent(str)
}
func (i *Repost) MetaData() interface{} {
return &i.meta
}
func (i *Repost) SetMetaData(metaData interface{}) {
i.meta = *metaData.(*RepostMetaData)
}

View File

@ -0,0 +1,34 @@
package interactions
import (
"fmt"
"owl-blogs/domain/model"
"owl-blogs/render"
)
type Webmention struct {
model.InteractionBase
meta WebmentionMetaData
}
type WebmentionMetaData struct {
Source string
Target string
Title string
}
func (i *Webmention) Content() model.InteractionContent {
str, err := render.RenderTemplateToString("interaction/Webmention", i)
if err != nil {
fmt.Println(err)
}
return model.InteractionContent(str)
}
func (i *Webmention) MetaData() interface{} {
return &i.meta
}
func (i *Webmention) SetMetaData(metaData interface{}) {
i.meta = *metaData.(*WebmentionMetaData)
}

23
plugings/echo.go Normal file
View File

@ -0,0 +1,23 @@
package plugings
import (
"fmt"
"owl-blogs/app"
"owl-blogs/domain/model"
)
type Echo struct {
}
func NewEcho(bus *app.EventBus) *Echo {
echo := &Echo{}
bus.Subscribe(echo)
return echo
}
func (e *Echo) NotifyEntryCreated(entry model.Entry) {
fmt.Println("Entry Created:")
fmt.Println("\tID: ", entry.ID())
fmt.Println("\tTitle: ", entry.Title())
fmt.Println("\tPublishedAt: ", entry.PublishedAt())
}

96
plugings/instagram.go Normal file
View File

@ -0,0 +1,96 @@
package plugings
import (
"bytes"
"owl-blogs/app"
"owl-blogs/app/repository"
"owl-blogs/domain/model"
entrytypes "owl-blogs/entry_types"
"owl-blogs/render"
"github.com/Davincible/goinsta/v3"
)
type Instagram struct {
configRepo repository.ConfigRepository
binService *app.BinaryService
}
type InstagramConfig struct {
User string
Password string
}
// Form implements app.AppConfig.
func (cfg *InstagramConfig) Form(binSvc model.BinaryStorageInterface) string {
f, _ := render.RenderTemplateToString("forms/InstagramConfig", cfg)
return f
}
// ParseFormData implements app.AppConfig.
func (cfg *InstagramConfig) ParseFormData(data model.HttpFormData, binSvc model.BinaryStorageInterface) error {
cfg.User = data.FormValue("User")
cfg.Password = data.FormValue("Password")
return nil
}
func RegisterInstagram(
configRepo repository.ConfigRepository,
configRegister *app.ConfigRegister,
binService *app.BinaryService,
bus *app.EventBus,
) *Instagram {
configRegister.Register("instagram", &InstagramConfig{})
insta := &Instagram{
configRepo: configRepo,
binService: binService,
}
bus.Subscribe(insta)
return insta
}
// NotifyEntryCreated implements app.EntryCreationSubscriber.
func (i *Instagram) NotifyEntryCreated(entry model.Entry) {
image, ok := entry.(*entrytypes.Image)
if !ok {
println("not an image")
return
}
config := &InstagramConfig{}
err := i.configRepo.Get("instagram", config)
if err != nil {
println("no instagram config")
return
}
client := goinsta.New(config.User, config.Password)
err = client.Login()
if err != nil {
println("login failed")
return
}
meta := image.MetaData().(*entrytypes.ImageMetaData)
bin, err := i.binService.FindById(meta.ImageId)
if err != nil {
println("image data not found")
return
}
_, err = client.Upload(
&goinsta.UploadOptions{
File: bytes.NewReader(bin.Data),
Caption: image.Title(),
},
)
if err != nil {
println("upload failed")
return
}
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"embed"
"io"
"net/url"
"owl-blogs/domain/model"
"text/template"
@ -20,6 +21,7 @@ type TemplateData struct {
//go:embed templates
var templates embed.FS
var SiteConfigService model.SiteConfigInterface
var funcMap = template.FuncMap{
"markdown": func(text string) string {
@ -29,6 +31,10 @@ var funcMap = template.FuncMap{
}
return html
},
"urljoin": func(elems ...string) string {
r, _ := url.JoinPath(elems[0], elems[1:]...)
return r
},
}
func CreateTemplateWithBase(templateName string) (*template.Template, error) {
@ -40,7 +46,7 @@ func CreateTemplateWithBase(templateName string) (*template.Template, error) {
)
}
func RenderTemplateWithBase(w io.Writer, siteConfig model.SiteConfig, templateName string, data interface{}) error {
func RenderTemplateWithBase(w io.Writer, templateName string, data interface{}) error {
t, err := CreateTemplateWithBase(templateName)
@ -48,6 +54,11 @@ func RenderTemplateWithBase(w io.Writer, siteConfig model.SiteConfig, templateNa
return err
}
siteConfig, err := SiteConfigService.GetSiteConfig()
if err != nil {
return err
}
err = t.ExecuteTemplate(w, "base", TemplateData{
Data: data,
SiteConfig: siteConfig,

View File

@ -1,110 +1,39 @@
{{define "base"}}
<!doctype html>
<html lang='en'>
<html lang='en' data-theme="light">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{template "title" .Data}} - {{ .SiteConfig.Title }}</title>
<meta property="og:title" content="{{template "title" .Data}}" />
<link rel='stylesheet' href='/static/pico.min.css'>
{{ template "head" .}}
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<link rel="webmention" href="/webmention/" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="/index.xml">
<link rel='stylesheet' href='/static/owl.css'>
<link rel='stylesheet' href='/static/style.css'>
<style>
header {
background-color: {{.SiteConfig.HeaderColor}};
padding-bottom: 1rem !important;
:root {
--primary: {{.SiteConfig.PrimaryColor}};
}
footer {
border-top: dashed 2px;
border-color: #ccc;
}
.avatar {
float: left;
margin-right: 1rem;
border-radius: 50%;
}
.header {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
align-items: flex-start;
}
.header-title {
order: 0;
}
.header-profile {
order: 1;
}
hgroup h2 a { color: inherit; }
.photo-grid {
display: flex;
flex-wrap: wrap;
padding: 0 4px;
}
.photo-grid-item {
flex: 1 0 25%;
padding: 4px;
}
.photo-grid-item img {
width: 100%;
height: 100%;
aspect-ratio: 1 / 1 ;
object-fit: cover;
}
</style>
</style>
{{ .SiteConfig.HtmlHeadExtra }}
</head>
<body>
<header>
<div class="container header h-card">
<hgroup class="header-title">
<h2><a class="p-name u-url" href="/">{{ .SiteConfig.Title }}</a></h2>
<h3 class="p-note">{{ .SiteConfig.SubTitle }}</h3>
</hgroup>
<header class="h-card">
{{ if .SiteConfig.AvatarUrl }}
<img class="u-photo u-logo avatar" src="{{ .SiteConfig.AvatarUrl }}" alt="{{ .SiteConfig.Title }}" />
{{ end }}
<div class="header-profile">
{{ if .SiteConfig.AvatarUrl }}
<img class="u-photo u-logo avatar" src="{{ .SiteConfig.AvatarUrl }}" alt="{{ .SiteConfig.Title }}" width="100" height="100" />
{{ end }}
<div style="float: right; list-style: none;">
{{ range $me := .SiteConfig.Me }}
<li><a href="{{$me.Url}}" rel="me">{{$me.Name}}</a>
</li>
{{ end }}
</div>
</div>
</div>
<div class="container">
<nav>
<ul>
{{ range $link := .SiteConfig.HeaderMenu }}
{{ if $link.List }}
<li><a href="/lists/{{ $link.List }}">{{ $link.Title }}</a></li>
{{ else if $link.Post }}
<li><a href="/posts/{{ $link.Post }}">{{ $link.Title }}</a></li>
{{ else }}
<li><a href="{{ $link.Url }}">{{ $link.Title }}</a></li>
{{ end }}
{{ end }}
</ul>
</nav>
</div>
</header>
<main class="container">
{{template "main" .Data}}
</main>
<footer class="container">
<hgroup>
<h1><a class="p-name u-url" href="/">{{ .SiteConfig.Title }}</a></h1>
<p class="p-note">{{ .SiteConfig.SubTitle }}</p>
</hgroup>
<nav>
<ul>
{{ range $link := .SiteConfig.FooterMenu }}
{{ range $link := .SiteConfig.HeaderMenu }}
{{ if $link.List }}
<li><a href="/lists/{{ $link.List }}">{{ $link.Title }}</a></li>
{{ else if $link.Post }}
@ -115,6 +44,38 @@
{{ end }}
</ul>
</nav>
</header>
<main>
{{template "main" .Data}}
</main>
<footer>
<nav>
<ul>
<li><a target="_blank" href="/index.xml">RSS Feed</a></li>
{{ range $link := .SiteConfig.FooterMenu }}
{{ if $link.List }}
<li><a href="/lists/{{ $link.List }}">{{ $link.Title }}</a></li>
{{ else if $link.Post }}
<li><a href="/posts/{{ $link.Post }}">{{ $link.Title }}</a></li>
{{ else }}
<li><a href="{{ $link.Url }}">{{ $link.Title }}</a></li>
{{ end }}
{{ end }}
{{ range $me := .SiteConfig.Me }}
<li><a href="{{$me.Url}}" rel="me">{{$me.Name}}</a>
</li>
{{ end }}
<li><a href="/admin/">Editor</a></li>
</ul>
</nav>
<div>
{{ .SiteConfig.FooterExtra}}
</div>
<div style="margin-top:var(--s2);">
powered by <i><a href="https://github.com/H4kor/owl-blogs" target="_blank">owl-blogs</a></i>
</a>
</footer>
</body>
</html>

View File

@ -1,4 +1,6 @@
<img src="/media/{{.MetaData.ImageId}}">
<a href="/media/{{.MetaData.ImageId}}" class="u-photo">
<img src="/media/{{.MetaData.ImageId}}" alt="{{.MetaData.Title}}" />
</a>
{{.MetaData.Content}}

View File

@ -0,0 +1,27 @@
<small>
{{ if .MetaData.Yield }}
Servings: <span class="p-yield">{{ .MetaData.Yield }}</span>
{{ if .MetaData.Duration }}, {{end}}
{{ end }}
{{ if .MetaData.Duration }}
Prep Time: <time class="dt-duration" value="{{ .MetaData.Duration }}">
{{ .MetaData.Duration }}
</time>
{{ end }}
</small>
<br> <br>
<h2>Ingredients</h2>
<ul>
{{ range $ingredient := .MetaData.Ingredients }}
<li class="p-ingredient">
{{ $ingredient }}
</li>
{{ end }}
</ul>
<h2>Instructions</h2>
{{.MetaData.Content | markdown }}

View File

@ -0,0 +1,8 @@
<label for="PreferredUsername">Preferred Username</label>
<input type="text" name="PreferredUsername" value="{{.PreferredUsername}}" />
<label for="PublicKeyPem">PublicKeyPem</label>
<textarea name="PublicKeyPem" rows="4">{{.PublicKeyPem}}</textarea>
<label for="PrivateKeyPem">PrivateKeyPem</label>
<textarea name="PrivateKeyPem" rows="4">{{.PrivateKeyPem}}</textarea>

View File

@ -0,0 +1,14 @@
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="content">Content</label>
<textarea
id="contentField"
name="content"
rows="16"
>{{.Content}}</textarea>
<script src="/static/editor.js"></script>
<script>
addFileDrop("contentField")
</script>

View File

@ -0,0 +1,8 @@
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="url">URL</label>
<input type="text" name="url" value="{{.Url}}" placeholder="https://..." />
<label for="content">Content</label>
<textarea name="content" rows="16">{{.Content}}</textarea></textarea>

View File

@ -0,0 +1,8 @@
<label for="image">Image</label>
<input type="file" name="image" />
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="content">Content</label>
<textarea name="content" rows="16">{{.Content}}</textarea>

View File

@ -0,0 +1,5 @@
<label for="User">User</label>
<input type="text" name="User" value="{{.User}}" />
<label for="Password">Password</label>
<input type="password" name="Password" value="{{.Password}}" />

View File

@ -0,0 +1,7 @@
<label for="content">Content</label>
<textarea id="contentField" name="content" rows="8">{{.Content}}</textarea>
<script src="/static/editor.js"></script>
<script>
addFileDrop("contentField")
</script>

View File

@ -0,0 +1,10 @@
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="content">Content</label>
<textarea id="contentField" name="content" rows="16">{{.Content}}</textarea>
<script src="/static/editor.js"></script>
<script>
addFileDrop("contentField")
</script>

View File

@ -0,0 +1,20 @@
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="yield">Yield</label>
<input type="text" name="yield" value="{{.Yield}}" />
<label for="duration">Duration</label>
<input type="text" name="duration" value="{{.Duration}}" />
<label for="ingredients">Ingredients</label>
<textarea name="ingredients" rows="8">{{ range $i := .Ingredients }}
{{$i}}{{ end }}</textarea>
<label for="content">Content</label>
<textarea id="contentField" name="content" rows="16">{{.Content}}</textarea>
<script src="/static/editor.js"></script>
<script>
addFileDrop("contentField")
</script>

View File

@ -0,0 +1,13 @@
<label for="title">Title</label>
<input type="text" name="title" value="{{.Title}}" />
<label for="url">Reply To</label>
<input type="text" name="url" value="{{.Url}}" placeholder="https://..." />
<label for="content">Content</label>
<textarea id="contentField" name="content" rows="16">{{.Content}}</textarea></textarea>
<script src="/static/editor.js"></script>
<script>
addFileDrop("contentField")
</script>

View File

@ -0,0 +1,3 @@
Liked by <a href="{{.MetaData.SenderUrl}}">
{{.MetaData.SenderName}}
</a>

View File

@ -0,0 +1,3 @@
Reposted by <a href="{{.MetaData.SenderUrl}}">
{{.MetaData.SenderName}}
</a>

View File

@ -0,0 +1,7 @@
<a href="{{.MetaData.Source}}">
{{if .MetaData.Title}}
{{.MetaData.Title}}
{{else}}
{{.MetaData.Source}}
{{end}}
</a>

View File

@ -0,0 +1,42 @@
{{define "title"}}Admin{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<h2 style="margin-bottom: 1rem;">Write</h2>
<div class="action-tile-list">
{{range .Types}}
<a class="action-tile" href="/editor/new/{{.}}/">{{.}}</a>
{{end}}
</div>
<br>
<br>
<h2 style="margin-bottom: 1rem;">Content</h2>
<div class="action-tile-list">
<a class="action-tile" href="/admin/drafts/">Drafts</a>
<a class="action-tile" href="/admin/binaries/">Files</a>
<a class="action-tile" href="/admin/interactions/">Interactions</a>
</div>
<br>
<br>
<h2 style="margin-bottom: 1rem;">Configurations</h2>
<div class="action-tile-list">
<a class="action-tile" href="/site-config">Site Settings</a>
<a class="action-tile" href="/site-config/me">Me Links</a>
<a class="action-tile" href="/site-config/lists">Lists</a>
<a class="action-tile" href="/site-config/menus">Menus</a>
</div>
<br>
<br>
<h3>Module Configuration</h3>
<div class="action-tile-list">
{{ range .Configs }}
<a class="action-tile" href="/admin/config/{{.Name}}">{{.Name}}</a>
{{ end }}
</div>
<br>
<br>
{{end}}

View File

@ -0,0 +1,17 @@
{{define "title"}}Configuration{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<a href="/admin">&larr; Back</a>
<br>
<br>
<form method="POST" enctype="multipart/form-data">
{{.}}
<input type="submit" value="Submit" />
</form>
{{end}}

View File

@ -0,0 +1,73 @@
{{define "title"}}Files{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<a href="/admin">&larr; Back</a>
<br>
<br>
<h2>Files</h2>
<h3>Upload File</h3>
<form action="/admin/binaries/new" method="post" enctype="multipart/form-data">
<fieldset role="group">
<input type="file" name="file" id="file">
<input type="submit" value="Upload">
</fieldset>
</form>
<hr>
<h3>Files</h3>
<form action="" method="get">
<fieldset role="search">
<input type="filter" name="filter" id="filter" value="{{.Filter}}">
<input type="submit" value="Search">
</fieldset>
</form>
<table role="grid">
<thead>
<tr>
<th scope="col">File</th>
<th scope="col">Actions</th>
</tr>
</thead>
{{ range .Binaries }}
<tr>
<td scope="row">
<a href="/media/{{ . }}">{{ . }}</a>
</td>
<td>
<form action="/admin/binaries/delete" method="post">
<input type="hidden" name="file" value="{{ . }}">
<label for="confirm">
<input type="checkbox" name="confirm"> Confirm
</label>
<input style="padding:0;height:2rem;" type="submit" value="Delete">
</form>
</td>
</tr>
{{ end }}
</table>
<hr>
<nav class="row">
{{ if not .FirstPage }}
<div>
<a href="?page={{ .PrevPage }}">Prev</a>
</div>
{{ end }}
<div>Page {{.Page}}</div>
{{ if not .LastPage }}
<div>
<a href="?page={{ .NextPage }}">Next</a>
</div>
{{ end }}
</nav>
{{end}}

View File

@ -0,0 +1,45 @@
{{define "title"}}Index{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<a href="/admin">&larr; Back</a>
<br>
<hr>
<div class="h-feed">
{{ range .Entries }}
<div class="h-entry">
<hgroup>
<h3>
<a class="u-url" href="/posts/{{ .ID }}">
{{if .Title}}
{{ .Title }}
{{else}}
#
{{end}}
</a>
</h3>
</hgroup>
</div>
<hr>
{{ end }}
</div>
<hr>
<nav class="row">
{{ if not .FirstPage }}
<div>
<a href="?page={{ .PrevPage }}">Prev</a>
</div>
{{ end }}
<div>Page {{.Page}}</div>
{{ if not .LastPage }}
<div>
<a href="?page={{ .NextPage }}">Next</a>
</div>
{{ end }}
</nav>
{{end}}

View File

@ -1,11 +1,19 @@
{{define "title"}}Editor{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<a href="/editor">Back</a>
<a href="/admin">&larr; Back</a>
<br>
<br>
<form method="POST" enctype="multipart/form-data">
{{.}}
<div class="grid">
<input type="submit" name="action" value="Publish" />
<input class="secondary" type="submit" name="action" value="Save as Draft" />
</div>
</form>
{{end}}

View File

@ -1,24 +0,0 @@
{{define "title"}}Editor List{{end}}
{{define "main"}}
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/editor">Editor</a></li>
<li><a href="/site-config">Site Settings</a></li>
<li><a href="/site-config/me">Me Links</a></li>
<li><a href="/site-config/lists">Lists</a></li>
<li><a href="/site-config/menus">Menus</a></li>
</ul>
</nav>
<h1>Editor List</h1>
<ul>
{{range .Types}}
<li><a href="/editor/{{.}}">{{.}}</a></li>
{{end}}
{{end}}

View File

@ -1,34 +1,122 @@
{{define "title"}}{{.Entry.Title}}{{end}}
{{define "head"}}
<meta property="og:url" content="{{ urljoin .SiteConfig.FullUrl "/posts/" .Data.Entry.ID }}/" />
<meta property="og:type" content="article" />
{{ if .Data.Entry.ImageUrl}}
<meta property="og:image" content="{{ urljoin .SiteConfig.FullUrl .Data.Entry.ImageUrl}}" />
{{ end }}
{{ if .Data.Entry.PublishedAt }}
<meta property="og:article:published_time" content="{{.Data.Entry.PublishedAt.Format "2006-01-02T15:04:05" }}" />
{{ end }}
{{end}}
{{define "main"}}
{{ if not .Entry.PublishedAt }}
<mark>
This entry is a draft. It is only visible to logged in authors.
</mark>
<br>
<br>
{{ end }}
<div class="h-entry">
<hgroup>
{{if .Entry.Title}}
<h1 class="p-name">{{.Entry.Title}}</h1>
{{end}}
<small>
<a class="u-url" href="">#</a>
Published:
<time class="dt-published" datetime="{{.Entry.PublishedAt}}">
{{.Entry.PublishedAt}}
{{if .Entry.Title}}
<h1 class="p-name entry-title">{{.Entry.Title}}</h1>
{{else}}
<div style="padding-top:4rem;"></div>
{{end}}
<div class="entry-meta">
<a class="u-url" href="/posts/{{ .Entry.ID }}/">#</a>
Published:
{{ if .Entry.PublishedAt }}
<time class="dt-published" datetime="{{.Entry.PublishedAt.Format "2006-01-02T15:04:05" }}">
{{.Entry.PublishedAt.Format "2006-01-02" }}
</time>
{{ if .Author.Name }}
by
<a class="p-author h-card" href="{{.Author.FullUrl}}">
{{ if .Author.AvatarUrl }}
<img class="u-photo u-logo" style="height: 1em;" src="{{ .Author.AvatarUrl }}" alt="{{ .Author.Config.Title }}" />
{{ end }}
{{.Author.Name}}
</a>
{{ end }}
</small>
{{ end }}
{{ if .Author.Name }}
by
<a class="p-author h-card" href="{{.Author.FullUrl}}">
{{ if .Author.AvatarUrl }}
<img class="u-photo u-logo" style="height: 1em;" src="{{ .Author.AvatarUrl }}" alt="{{ .Author.Config.Title }}" />
{{ end }}
{{.Author.Name}}
</a>
{{ end }}
</div>
</hgroup>
{{.Entry.Content}}
<div class="e-content">
{{.Entry.Content}}
</div>
</div>
{{if .Interactions}}
<br>
<br>
<br>
<hr>
<h4>
Interactions
</h4>
<ul>
{{range .Interactions}}
<li>
{{ .Content }}
{{ if $.LoggedIn }}
<form method="post" action="/admin/interactions/{{.ID}}/delete/" class="grid">
<label for="confirm">
Confirm deletion
<input type="checkbox" name="confirm" id="confirm" required />
</label>
<input type="submit" class="secondary outline" value="Delete" />
</form>
{{ end }}
</li>
{{end}}
</ul>
{{end}}
{{ if .LoggedIn }}
<br>
<br>
<br>
<h3>Actions</h3>
<div class="grid">
<div>
<a style="width:100%;" href="/editor/edit/{{.Entry.ID}}/" role="button" class="">Edit</a>
</div>
<div>
<form method="post" action="/editor/unpublish/{{.Entry.ID}}/">
<input type="submit" class="secondary" value="Unpublish" />
<br>
<label for="confirm">
Confirm unpublishing
<input type="checkbox" name="confirm" id="confirm" required />
</label>
</form>
</div>
<div>
<form method="post" action="/editor/delete/{{.Entry.ID}}/">
<input type="submit" class="danger" value="Delete" />
<br>
<label for="confirm">
Confirm deletion
<input type="checkbox" name="confirm" id="confirm" required />
</label>
</form>
</div>
</div>
{{ end }}
{{end}}

View File

@ -1,24 +1,28 @@
{{define "title"}}Index{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<div class="h-feed">
{{ range .Entries }}
<div class="h-entry">
<hgroup>
<h3>
<a class="u-url" href="/posts/{{ .ID }}">
{{if .Title}}
{{ .Title }}
{{else}}
#
{{end}}
</a>
</h3>
<small style="font-size: 0.75em;">
<time class="dt-published" datetime="{{ .PublishedAt }}">{{ .PublishedAt }}</time>
</small>
</hgroup>
<h1 class="entry-title">
<a class="u-url" href="/posts/{{ .ID }}/">
{{if .Title}}
{{ .Title }}
{{else}}
#
{{end}}
</a>
</h1>
<div class="entry-meta">
Published:
{{ if .PublishedAt }}
<time class="dt-published" datetime="{{.PublishedAt.Format "2006-01-02T15:04:05" }}">
{{.PublishedAt.Format "2006-01-02" }}
</time>
{{ end }}
</div>
{{ .Content }}
</div>
<hr>

View File

@ -0,0 +1,48 @@
{{define "title"}}Interactions{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<a href="/admin">&larr; Back</a>
<br>
<br>
<h2>Recent Interactions</h2>
<table role="grid">
<thead>
<tr>
<th scope="col">Entry</th>
<th scope="col">Created At</th>
</tr>
</thead>
{{ range .Interactions }}
<tr>
<td scope="row">
<a href="/posts/{{ .EntryID }}">{{ .EntryID }}</a>
</td>
<td>
{{ .CreatedAt.Format "2006-01-02 15:04" }}
</td>
</tr>
{{ end }}
</table>
<hr>
<nav class="row">
{{ if not .FirstPage }}
<div>
<a href="?page={{ .PrevPage }}">Prev</a>
</div>
{{ end }}
<div>Page {{.Page}}</div>
{{ if not .LastPage }}
<div>
<a href="?page={{ .NextPage }}">Next</a>
</div>
{{ end }}
</nav>
{{end}}

View File

@ -1,24 +1,28 @@
{{define "title"}}Index{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<div class="h-feed">
{{ range .Entries }}
<div class="h-entry">
<hgroup>
<h3>
<a class="u-url" href="/posts/{{ .ID }}">
{{if .Title}}
{{ .Title }}
{{else}}
#
{{end}}
</a>
</h3>
<small style="font-size: 0.75em;">
<time class="dt-published" datetime="{{ .PublishedAt }}">{{ .PublishedAt }}</time>
</small>
</hgroup>
<h1 class="entry-title">
<a class="u-url" href="/posts/{{ .ID }}/">
{{if .Title}}
{{ .Title }}
{{else}}
#
{{end}}
</a>
</h1>
<div class="entry-meta">
Published:
{{ if .PublishedAt }}
<time class="dt-published" datetime="{{.PublishedAt.Format "2006-01-02T15:04:05" }}">
{{.PublishedAt.Format "2006-01-02" }}
</time>
{{ end }}
</div>
{{ .Content }}
</div>
<hr>

View File

@ -1,4 +1,5 @@
{{define "title"}}Editor List{{end}}
{{define "head"}}{{end}}
{{define "main"}}

View File

@ -1,17 +1,9 @@
{{define "title"}}Editor{{end}}
{{define "head"}}{{end}}
{{define "main"}}
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/editor">Editor</a></li>
<li><a href="/site-config">Site Settings</a></li>
<li><a href="/site-config/me">Me Links</a></li>
<li><a href="/site-config/lists">Lists</a></li>
<li><a href="/site-config/menus">Menus</a></li>
</ul>
</nav>
<a href="/admin">&larr; Back</a>
<h2>Site Settings</h2>
@ -22,8 +14,8 @@
<label for="SubTitle">SubTitle</label>
<input type="text" name="SubTitle" id="SubTitle" value="{{.SubTitle}}"/>
<label for="HeaderColor">HeaderColor</label>
<input type="color" name="HeaderColor" id="HeaderColor" value="{{.HeaderColor}}"/>
<label for="PrimaryColor">PrimaryColor</label>
<input type="color" name="PrimaryColor" id="PrimaryColor" value="{{.PrimaryColor}}"/>
<label for="AuthorName">AuthorName</label>
<input type="text" name="AuthorName" id="AuthorName" value="{{.AuthorName}}"/>
@ -31,6 +23,15 @@
<label for="AvatarUrl">AvatarUrl</label>
<input type="text" name="AvatarUrl" id="AvatarUrl" value="{{.AvatarUrl}}"/>
<label for="FullUrl">FullUrl</label>
<input type="text" name="FullUrl" id="FullUrl" value="{{.FullUrl}}"/>
<label for="HtmlHeadExtra">HtmlHeadExtra</label>
<textarea name="HtmlHeadExtra" id="HtmlHeadExtra">{{.HtmlHeadExtra}}</textarea>
<label for="FooterExtra">FooterExtra</label>
<textarea name="FooterExtra" id="FooterExtra">{{.FooterExtra}}</textarea>
<input type="submit" value="Save" />
</form>

Some files were not shown because too many files have changed in this diff Show More