-
Notifications
You must be signed in to change notification settings - Fork 11
/
data.go
374 lines (322 loc) · 10 KB
/
data.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package readas
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/writeas/impart"
"github.com/writeas/web-core/activitypub"
"github.com/writeas/web-core/activitystreams"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
)
const (
mySQLErrDuplicateKey = 1062
)
func initDatabase(app *app) error {
mysqlConnStr := app.cfg.MySQLConnStr
if mysqlConnStr == "" {
mysqlConnStr = os.Getenv("RA_MYSQL_CONNECTION")
if mysqlConnStr == "" {
return fmt.Errorf("No database configuration. Provide RA_MYSQL_CONNECTION environment variable.")
}
}
var err error
app.db, err = sql.Open("mysql", mysqlConnStr+"?charset=utf8mb4&parseTime=true")
if err != nil {
return err
}
return nil
}
func checkData(app *app) error {
users, err := app.getUsersCount()
if err != nil {
return fmt.Errorf("Unable to get users count: %v", err)
}
if users == 0 {
return fmt.Errorf("No users exist. Create one with: readas --user [username] --pass [password]")
}
return nil
}
func (app *app) createUser(u *LocalUser) error {
pub, priv := activitypub.GenerateKeys()
t, err := app.db.Begin()
if err != nil {
logError("Unable to start transaction: %v", err)
return err
}
res, err := t.Exec("INSERT INTO users (actor_id, username, password, name, summary, created) VALUES (?, ?, ?, ?, ?, NOW())", u.PreferredUsername, u.PreferredUsername, u.HashedPass, u.Name, u.Summary)
if err != nil {
t.Rollback()
return err
}
userID, err := res.LastInsertId()
if err != nil {
t.Rollback()
return err
}
_, err = t.Exec("INSERT INTO userkeys (id, user_id, public_key, private_key) VALUES (?, ?, ?, ?)", u.PreferredUsername+"#main-key", userID, pub, priv)
if err != nil {
t.Rollback()
return err
}
err = t.Commit()
if err != nil {
t.Rollback()
logError("Rolling back after Commit(): %v\n", err)
return err
}
return nil
}
func (app *app) addFoundUser(wfr *WebfingerResult) error {
stmt := "INSERT INTO foundusers (username, host, actor_id) VALUES (?, ?, ?)"
_, err := app.db.Exec(stmt, wfr.Username, wfr.Host, wfr.ActorIRI)
return err
}
func (app *app) addUser(u *activitystreams.Person) (int64, error) {
logInfo("Adding follower")
t, err := app.db.Begin()
if err != nil {
logError("Unable to start transaction: %v", err)
return 0, err
}
stmt := "INSERT INTO users (actor_id, username, type, name, summary, created, url, following_iri, followers_iri, inbox_iri, outbox_iri, shared_inbox_iri, avatar, avatar_type) VALUES (?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?)"
res, err := t.Exec(stmt, u.BaseObject.ID, u.PreferredUsername, u.Type, u.Name, u.Summary, u.URL, u.Following, u.Followers, u.Inbox, u.Outbox, u.Endpoints.SharedInbox, u.Icon.URL, u.Icon.Type)
if err != nil {
t.Rollback()
return 0, err
}
followerID, err := res.LastInsertId()
if err != nil {
t.Rollback()
logError("No lastinsertid for followers, rolling back: %v", err)
return 0, err
}
// Add in key
_, err = t.Exec("INSERT INTO userkeys (id, user_id, public_key) VALUES (?, ?, ?)", u.PublicKey.ID, followerID, u.PublicKey.PublicKeyPEM)
if err != nil {
if mysqlErr, ok := err.(*mysql.MySQLError); ok {
if mysqlErr.Number != mySQLErrDuplicateKey {
t.Rollback()
logError("Couldn't add follower keys in DB: %v\n", err)
return 0, err
}
} else {
t.Rollback()
logError("Couldn't add follower keys in DB: %v\n", err)
return 0, err
}
}
// Update found users
stmt = "UPDATE foundusers SET user_id = ? WHERE actor_id = ?"
_, err = t.Exec(stmt, followerID, u.BaseObject.ID)
if err != nil {
t.Rollback()
return 0, err
}
err = t.Commit()
if err != nil {
t.Rollback()
logError("Rolling back after Commit(): %v\n", err)
return 0, err
}
return followerID, nil
}
func (app *app) getLocalUser(username string) (*LocalUser, error) {
u := LocalUser{}
condition := "username = ?"
value := username
stmt := "SELECT u.id, username, password, name, summary, private_key, public_key FROM users u LEFT JOIN userkeys uk ON u.id = uk.user_id WHERE " + condition
err := app.db.QueryRow(stmt, value).Scan(&u.ID, &u.PreferredUsername, &u.HashedPass, &u.Name, &u.Summary, &u.privKey, &u.pubKey)
switch {
case err == sql.ErrNoRows:
return nil, impart.HTTPError{http.StatusNotFound, "User not found"}
case err != nil:
return nil, err
}
return &u, nil
}
func (app *app) getFollowers(id int64, page int) (*[]string, error) {
limitStr := ""
if page > 0 {
pagePosts := 10
start := page*pagePosts - pagePosts
limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
}
rows, err := app.db.Query(`SELECT actor_id
FROM follows
LEFT JOIN users
ON follower = id
WHERE followee = ?`+limitStr, id)
if err != nil {
logError("Failed selecting followers: %v", err)
return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve followers."}
}
defer rows.Close()
users := []string{}
for rows.Next() {
u := ""
err = rows.Scan(&u)
if err != nil {
logError("Failed scanning row in getFollowers: %v", err)
break
}
users = append(users, u)
}
err = rows.Err()
if err != nil {
logError("Error after Next() on rows in getFollowers: %v", err)
}
return &users, nil
}
func (app *app) getFollowing(id int64, page int) (*[]string, error) {
limitStr := ""
if page > 0 {
pagePosts := 10
start := page*pagePosts - pagePosts
limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
}
rows, err := app.db.Query(`SELECT actor_id
FROM follows
LEFT JOIN users
ON followee = id
WHERE follower = ?`+limitStr, id)
if err != nil {
logError("Failed selecting following: %v", err)
return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve following."}
}
defer rows.Close()
users := []string{}
for rows.Next() {
u := ""
err = rows.Scan(&u)
if err != nil {
logError("Failed scanning row in getFollowing: %v", err)
break
}
users = append(users, u)
}
err = rows.Err()
if err != nil {
logError("Error after Next() on rows in getFollowing: %v", err)
}
return &users, nil
}
func (app *app) getUsersCount() (uint64, error) {
var c uint64
err := app.db.QueryRow("SELECT COUNT(*) FROM users WHERE password IS NOT NULL").Scan(&c)
if err != nil {
logError("Couldn't get users count: %v", err)
return 0, err
}
return c, nil
}
func (app *app) getActor(id string) (*User, error) {
return app.getUserBy("actor_id = ?", id)
}
func (app *app) getUserBy(condition string, value interface{}) (*User, error) {
u := User{}
stmt := `SELECT id, actor_id, u.username, type, name, summary, created, url, following_iri, followers_iri, inbox_iri, outbox_iri, shared_inbox_iri, avatar, avatar_type, host
FROM users u
INNER JOIN foundusers
USING (actor_id)
WHERE ` + condition
err := app.db.QueryRow(stmt, value).Scan(&u.ID, &u.BaseObject.ID, &u.PreferredUsername, &u.Type, &u.Name, &u.Summary, &u.Created, &u.URL, &u.Following, &u.Followers, &u.Inbox, &u.Outbox, &u.Endpoints.SharedInbox, &u.Icon.URL, &u.Icon.Type, &u.Host)
switch {
case err == sql.ErrNoRows:
return nil, impart.HTTPError{http.StatusNotFound, "User not found"}
case err != nil:
return nil, err
}
return &u, nil
}
func (app *app) createPost(p *Post) error {
_, err := app.db.Exec("INSERT INTO posts (owner_id, activity_id, type, published, url, name, content) VALUES ((SELECT id FROM users WHERE actor_id = ?), ?, ?, ?, ?, ?, ?)", p.actorID, p.ActivityID, p.Type, p.Published, p.URL, p.Name, p.Content)
return err
}
func (app *app) updatePost(p *Post) error {
_, err := app.db.Exec("UPDATE posts SET url = ?, name = ?, content = ? WHERE activity_id = ?", p.URL, p.Name, p.Content, p.ActivityID)
return err
}
func (app *app) deletePost(postID string) error {
_, err := app.db.Exec("DELETE FROM posts WHERE activity_id = ?", postID)
return err
}
func (app *app) getUserFeed(id int64, page int) (*[]Post, error) {
pagePosts := 10
start := page*pagePosts - pagePosts
if page == 0 {
start = 0
pagePosts = 100
}
limitStr := ""
if page > 0 {
limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
}
rows, err := app.db.Query(`SELECT p.id, owner_id, activity_id, p.type, published, p.url, p.name, content, f.host, u.username, u.name, u.url
FROM posts p
INNER JOIN users u
ON owner_id = u.id
LEFT JOIN foundusers f
USING(actor_id)
WHERE owner_id
IN (SELECT followee FROM follows WHERE follower = ?)
ORDER BY published DESC `+limitStr, id)
if err != nil {
logError("Failed selecting from posts: %v", err)
return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user feed."}
}
defer rows.Close()
// TODO: extract this common row scanning logic for queries using `postCols`
posts := []Post{}
for rows.Next() {
p := Post{
Owner: &User{},
IsInFeed: true,
}
err = rows.Scan(&p.ID, &p.OwnerID, &p.ActivityID, &p.Type, &p.Published, &p.URL, &p.Name, &p.Content, &p.Owner.Host, &p.Owner.PreferredUsername, &p.Owner.Name, &p.Owner.URL)
if err != nil {
logError("Failed scanning row: %v", err)
break
}
posts = append(posts, p)
}
err = rows.Err()
if err != nil {
logError("Error after Next() on rows: %v", err)
}
return &posts, nil
}
func (app *app) getPost(id int64) (*Post, error) {
p := Post{
Owner: &User{},
IsInFeed: false,
}
stmt := `SELECT p.id, owner_id, activity_id, p.type, published, p.url, p.name, content, f.host, u.username, u.name, u.url
FROM posts p
INNER JOIN users u
ON owner_id = u.id
LEFT JOIN foundusers f
USING(actor_id)
WHERE p.id = ?`
err := app.db.QueryRow(stmt, id).Scan(&p.ID, &p.OwnerID, &p.ActivityID, &p.Type, &p.Published, &p.URL, &p.Name, &p.Content, &p.Owner.Host, &p.Owner.PreferredUsername, &p.Owner.Name, &p.Owner.URL)
switch {
case err == sql.ErrNoRows:
return nil, impart.HTTPError{http.StatusNotFound, "Post not found"}
case err != nil:
return nil, err
}
return &p, err
}
func (app *app) getActorKey(id string) ([]byte, error) {
k := []byte{}
stmt := "SELECT public_key FROM userkeys WHERE id = ?"
err := app.db.QueryRow(stmt, id).Scan(&k)
switch {
case err == sql.ErrNoRows:
return nil, impart.HTTPError{http.StatusNotFound, "Key not found"}
case err != nil:
return nil, err
}
return k, nil
}