From a60a3f92bd5b299e90f31727909ce99c0c2bf49b Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Mon, 21 Nov 2022 16:08:34 +0100 Subject: [PATCH] ActivityPub: Include MimeType in profile picture attribute --- activityStreams.go | 12 +++++++----- utils.go | 15 +++++++++++++++ utils_test.go | 20 ++++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/activityStreams.go b/activityStreams.go index d643413..6f87559 100644 --- a/activityStreams.go +++ b/activityStreams.go @@ -69,8 +69,9 @@ type asPerson struct { } type asAttachment struct { - Type string `json:"type,omitempty"` - URL string `json:"url,omitempty"` + Type string `json:"type,omitempty"` + URL string `json:"url,omitempty"` + MediaType string `json:"mediaType,omitempty"` } type asTag struct { @@ -188,10 +189,11 @@ func (a *goBlog) toAsPerson(blog string) *asPerson { })), }, } - if a.cfg.User.Picture != "" { + if pic := a.cfg.User.Picture; pic != "" { asBlog.Icon = &asAttachment{ - Type: "Image", - URL: a.cfg.User.Picture, + Type: "Image", + URL: pic, + MediaType: mimeTypeFromUrl(pic), } } return asBlog diff --git a/utils.go b/utils.go index d0b20c5..a0a4b1b 100644 --- a/utils.go +++ b/utils.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "math/rand" + "mime" "net/http" "net/http/httptest" "net/url" @@ -403,3 +404,17 @@ func stringToInt(s string) int { func loStringNotEmpty(s string, _ int) bool { return s != "" } + +func mimeTypeFromUrl(url string) string { + ext := path.Ext(url) + mimeType := mime.TypeByExtension(ext) + if mimeType == "" { + switch ext { + case ".jpg": + mimeType = "image/jpeg" + default: + mimeType = "image/" + strings.TrimPrefix(ext, ".") + } + } + return mimeType +} diff --git a/utils_test.go b/utils_test.go index 3076978..2de278a 100644 --- a/utils_test.go +++ b/utils_test.go @@ -1,6 +1,7 @@ package main import ( + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -167,3 +168,22 @@ func Test_groupStrings(t *testing.T) { assert.Equal(t, "H", groups[3].Identifier) assert.Equal(t, "🚴", groups[4].Identifier) } + +func Test_mimeTypeFromUrl(t *testing.T) { + type test struct { + url string + want string + } + tests := []*test{ + {url: "https://example.com/profile.jpg", want: "image/jpeg"}, + {url: "https://example.com/profile.jpeg", want: "image/jpeg"}, + {url: "https://example.com/profile.png", want: "image/png"}, + } + for i, tt := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + if got := mimeTypeFromUrl(tt.url); got != tt.want { + t.Errorf("mimeTypeFromUrl() = %v, want %v", got, tt.want) + } + }) + } +}