From d28ea1a30b0dc8d5f3c2baf5a79bdae3dd90c400 Mon Sep 17 00:00:00 2001 From: bom Date: Fri, 10 Nov 2023 16:43:44 +0100 Subject: [PATCH] Start implementing UnmarshalJSON for Star --- modules/forgefed/star.go | 21 ++++++++++++++++++ modules/forgefed/star_test.go | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/modules/forgefed/star.go b/modules/forgefed/star.go index e0001c7cbb..7444e32de4 100644 --- a/modules/forgefed/star.go +++ b/modules/forgefed/star.go @@ -6,6 +6,7 @@ package forgefed import ( "code.gitea.io/gitea/modules/context" ap "github.com/go-ap/activitypub" + "github.com/valyala/fastjson" ) type ( @@ -64,3 +65,23 @@ func (a Star) MarshalJSON() ([]byte, error) { ap.JSONWrite(&b, '}') return b, nil } + +func JSONLoadStar(val *fastjson.Value, s *Star) error { + if err := ap.OnActivity(&s.Activity, func(a *ap.Activity) error { + return ap.JSONLoadActivity(val, a) + }); err != nil { + return err + } + + s.Source = SourceType(ap.JSONGetString(val, "source")) + return nil +} + +func (s *Star) UnmarshalJSON(data []byte) error { + p := fastjson.Parser{} + val, err := p.ParseBytes(data) + if err != nil { + return err + } + return JSONLoadStar(val, s) +} diff --git a/modules/forgefed/star_test.go b/modules/forgefed/star_test.go index 04e6373778..6727e79e12 100644 --- a/modules/forgefed/star_test.go +++ b/modules/forgefed/star_test.go @@ -48,3 +48,43 @@ func Test_StarMarshalJSON(t *testing.T) { }) } } + +func Test_StarUnmarshalJSON(t *testing.T) { + type testPair struct { + item []byte + want Star + wantErr error + } + + tests := map[string]testPair{ + "empty": { + item: []byte(``), + want: Star{}, + }, + "with ID": { + item: []byte(`{"source":"forgejo","type":"Star","actor":"https://repo.prod.meissa.de/api/activitypub/user-id/1","object":"https://codeberg.org/api/activitypub/repository-id/1"}`), + want: Star{ + Source: "forgejo", + Activity: ap.Activity{ + Actor: ap.IRI("https://repo.prod.meissa.de/api/activitypub/user-id/1"), + Type: "Star", + Object: ap.IRI("https://codeberg.org/api/activitypub/repository-id/1"), + }, + }, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + got := new(Star) + err := got.UnmarshalJSON(tt.item) + if (err != nil || tt.wantErr != nil) && tt.wantErr.Error() != err.Error() { + t.Errorf("UnmarshalJSON() error = \"%v\", wantErr \"%v\"", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("UnmarshalJSON() got = %q, want %q", got, tt.want) + } + }) + } +}