forked from davecheney/pub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actor.go
279 lines (243 loc) · 7.79 KB
/
actor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package models
import (
"context"
"fmt"
"net/http"
"time"
"github.com/bardic/pub/internal/snowflake"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
type Actor struct {
snowflake.ID `gorm:"primarykey;autoIncrement:false"`
UpdatedAt time.Time `gorm:"autoUpdateTime:false"`
Type ActorType `gorm:"default:'Person';not null"`
URI string `gorm:"uniqueIndex;size:128;not null"`
Name string `gorm:"size:64;uniqueIndex:idx_actor_name_domain;not null"`
Domain string `gorm:"size:64;uniqueIndex:idx_actor_name_domain;not null"`
DisplayName string `gorm:"size:128;not null"`
Locked bool `gorm:"default:false;not null"`
Note string `gorm:"type:text"` // max 2^16
FollowersCount int32 `gorm:"default:0;not null"`
FollowingCount int32 `gorm:"default:0;not null"`
StatusesCount int32 `gorm:"default:0;not null"`
LastStatusAt time.Time
Avatar string `gorm:"size:255"`
Header string `gorm:"size:255"`
PublicKey []byte `gorm:"size:16384;type:blob;not null"`
Attributes []*ActorAttribute `gorm:"constraint:OnDelete:CASCADE;"`
InboxURL string `gorm:"size:255;not null;default:''"`
OutboxURL string `gorm:"size:255;not null;default:''"`
SharedInboxURL string `gorm:"size:255;not null;default:''"`
}
type ActorType string
func (ActorType) GormDBDataType(db *gorm.DB, field *schema.Field) string {
switch db.Dialector.Name() {
case "mysql", "postgres":
return "enum('Person', 'Application', 'Service', 'Group', 'Organization', 'LocalPerson', 'LocalService')"
case "sqlite":
return "TEXT"
default:
return ""
}
}
// Inbox returns the actor's inbox URL, or shared inbox URL if applicable.
func (a *Actor) Inbox() string {
if a.SharedInboxURL != "" {
return a.SharedInboxURL
}
return a.InboxURL
}
func (a *Actor) AfterCreate(tx *gorm.DB) error {
return forEach(tx, a.updateInstanceDomainsCount)
}
func (a *Actor) AfterUpdate(tx *gorm.DB) error {
return forEach(tx, a.maybeScheduleRefresh)
}
func (a *Actor) AfterSave(tx *gorm.DB) error {
peer := &Peer{
Domain: a.Domain,
}
// save peer ignore if exists
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "domain"}},
DoNothing: true,
}).Create(peer).Error
}
func (a *Actor) updateInstanceDomainsCount(tx *gorm.DB) error {
return tx.Model(&Instance{}).Where("1 = 1").UpdateColumns(map[string]interface{}{
"domains_count": tx.Select("COUNT(distinct domain)").Model(&Actor{}),
}).Error // update domain count on all instances.
}
func (a *Actor) maybeScheduleRefresh(tx *gorm.DB) error {
if !a.needsRefresh() {
return nil
}
fmt.Println("scheduling refresh for", a.URI)
return NewActors(tx).Refresh(a)
}
func (a *Actor) needsRefresh() bool {
if a.OutboxURL == "" || (a.InboxURL == "" && a.SharedInboxURL == "") {
return true
}
return false
}
func (a *Actor) Acct() string {
if a.IsLocal() {
return a.Name
}
return fmt.Sprintf("%s@%s", a.Name, a.Domain)
}
func (a *Actor) IsBot() bool {
return !a.IsPerson()
}
func (a *Actor) IsPerson() bool {
return a.Type == "Person" || a.Type == "LocalPerson"
}
// IsLocal indicates whether the actor is local to the instance.
func (a *Actor) IsLocal() bool {
switch a.Type {
case "LocalPerson", "LocalService":
return true
default:
return false
}
}
// IsRemote indicates whether the actor is not local to the instance.
func (a *Actor) IsRemote() bool {
return !a.IsLocal()
}
func (a *Actor) IsGroup() bool {
return a.Type == "Group"
}
func (a *Actor) ActorType() string {
switch a.Type {
case "LocalPerson":
return "Person"
case "LocalService":
return "Service"
default:
return string(a.Type)
}
}
func (a *Actor) PublicKeyID() string {
return fmt.Sprintf("%s#main-key", a.URI)
}
func (a *Actor) URL() string {
return fmt.Sprintf("https://%s/@%s", a.Domain, a.Name)
}
type ActorAttribute struct {
ID uint32 `gorm:"primarykey"`
ActorID snowflake.ID `gorm:"index;not null"`
Name string `gorm:"size:255;not null"`
Value string `gorm:"type:text;not null"`
}
type Actors struct {
db *gorm.DB
}
func NewActors(db *gorm.DB) *Actors {
return &Actors{db: db}
}
// FindOrCreate finds an account by its URI, or creates it if it doesn't exist.
func (a *Actors) FindOrCreate(uri string, createFn func(context.Context, string) (*Actor, error)) (*Actor, error) {
// use find to avoid record not found error in case of empty result
var actors []Actor
if err := a.db.Limit(1).Find(&actors, "uri = ?", uri).Error; err != nil {
return nil, err
}
if len(actors) > 0 {
// found cached key
return &actors[0], nil
}
acc, err := createFn(a.db.Statement.Context, uri)
if err != nil {
return nil, err
}
err = a.db.Create(acc).Error
return acc, err
}
// FindByURI returns an account by its URI if it exists locally.
func (a *Actors) FindByURI(uri string) (*Actor, error) {
var actor Actor
err := a.db.Scopes(PreloadActor).Where("URI = ?", uri).Take(&actor).Error
return &actor, err
}
// Refesh schedules a refresh of an actor's data.
func (a *Actors) Refresh(actor *Actor) error {
db := a.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "actor_id"}},
DoUpdates: clause.AssignmentColumns([]string{
"created_at",
"updated_at",
"attempts", // resets the attempts counter
}),
})
return db.Create(&ActorRefreshRequest{ActorID: actor.ID}).Error
}
type Request struct {
ID uint32 `gorm:"primarykey;"`
// CreatedAt is the time the request was created.
CreatedAt time.Time
// UpdatedAt is the time the request was last updated.
UpdatedAt time.Time
// Attempts is the number of times the request has been attempted.
Attempts uint32 `gorm:"not null;default:0"`
// LastAttempt is the time the request was last attempted.
LastAttempt time.Time
// LastResult is the result of the last attempt if it failed.
LastResult string `gorm:"type:text;"`
}
// ActorRefreshRequest is a request to refresh an actor's data.
type ActorRefreshRequest struct {
Request
// ActorID is the ID of the actor to refresh.
ActorID snowflake.ID `gorm:"uniqueIndex;not null;"`
// Actor is the actor to refresh.
Actor *Actor `gorm:"constraint:OnDelete:CASCADE;<-:false;"`
}
// MaybeExcludeReplies returns a query that excludes replies if the request contains
// the exclude_replies parameter.
func MaybeExcludeReplies(r *http.Request) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if excludeReplies := parseBool(r, "exclude_replies"); excludeReplies {
db = db.Where("in_reply_to_id IS NULL")
}
return db
}
}
// MaybeExcludeReblogs returns a query that excludes reblogs if the request contains
// the exclude_reblogs parameter.
func MaybeExcludeReblogs(r *http.Request) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if excludeReblogs := parseBool(r, "exclude_reblogs"); excludeReblogs {
db = db.Where("reblog_id IS NULL")
}
return db
}
}
// MaybePinned returns a query that only includes pinned statuses if the request contains
// the pinned parameter.
func MaybePinned(r *http.Request) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if pinned := parseBool(r, "pinned"); pinned {
db = db.Joins("JOIN reactions ON reactions.status_id = statuses.id AND reactions.pinned = true AND reactions.actor_id = statuses.actor_id")
}
return db
}
}
// PreloadActor preloads all of an Actor's relations and associations.
func PreloadActor(query *gorm.DB) *gorm.DB {
return query.Preload("Attributes")
}
// parseBool parses a boolean value from a request parameter.
// If the parameter is not present, it returns false.
// If the parameter is present but cannot be parsed, it returns false
func parseBool(r *http.Request, key string) bool {
switch r.URL.Query().Get(key) {
case "true", "1":
return true
default:
return false
}
}