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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
package dal

import (
	"database/sql"
	"embed"
	"errors"
	"fmt"
	"github.com/mattn/go-sqlite3"
	"rss_parrot/shared"
	"sync"
	"time"
)

const schemaVer = 7

//go:embed scripts/*
var scripts embed.FS

type IRepo interface {
	InitUpdateDb()
	Vacuum() error
	GetNextId() uint64
	AddAccountIfNotExist(account *Account, privKey string) (isNew bool, err error)
	DoesAccountExist(user string) (bool, error)
	GetPrivKey(user string) (string, error)
	GetAccount(user string) (*Account, error)
	BruteDeleteAccount(accountId int) error
	GetAccountsPage(offset, limit int) ([]*Account, int, error)
	AddToot(accountId int, toot *Toot) error
	GetToot(statusId string) (*Toot, error)
	GetPostCount(user string) (uint, error)
	GetTotalPostCount() (uint, error)
	GetPostsPage(accountId int, offset, limit int) ([]*FeedPost, error)
	GetTootExtracts(accountId int) ([]*Toot, error)
	GetFeedLastUpdated(accountId int) (time.Time, error)
	UpdateAccountFeedTimes(accountId int, lastUpdated, nextCheckDue time.Time) error
	SetFeedFetchState(accountId int, etag, lastModified string, failures int) error
	AddFeedPostIfNew(accountId int, post *FeedPost) (isNew bool, err error)
	GetAccountToCheck(checkDue time.Time) (*Account, int, error)
	GetFollowerCount(user string, onlyApproved bool) (uint, error)

	// Returns number of all followers of feeds. Includes unapproved and banned ones, but excludes followers of birb.
	GetFeedFollowerCount() (int, error)

	GetFollowersByUser(user string, onlyApproved bool) ([]*FollowerInfo, error)
	GetFollowersById(accountId int, onlyApproved bool) ([]*FollowerInfo, error)
	SetFollowerApproveStatus(user, followerUserUrl string, status int) error
	AddFollower(user string, follower *FollowerInfo) error
	RemoveFollower(user, followerUserUrl string) error
	AddTootQueueItem(tqi *TootQueueItem) error
	GetTootQueueItems(aboveId, maxCount int) ([]*TootQueueItem, int, error)
	DeleteTootQueueItem(id int) error
	PurgePostsAndToots(accountId int, fromBefore time.Time) error
	MarkActivityHandled(id string, when time.Time) (alreadyHandled bool, err error)
	DeleteHandledActivities(before time.Time) error
}

type Repo struct {
	cfg    *shared.Config
	logger shared.ILogger
	db     *sql.DB
	muDb   sync.RWMutex
	muId   sync.Mutex
	nextId uint64
}

func NewRepo(cfg *shared.Config, logger shared.ILogger) IRepo {

	var err error
	var db *sql.DB

	// https://phiresky.github.io/blog/2020/sqlite-performance-tuning/
	// https://www.reddit.com/r/golang/comments/16xswxd/concurrency_when_writing_data_into_sqlite/
	// https://github.com/mattn/go-sqlite3/issues/1022#issuecomment-1067353980
	// _synchronous=1 is "normal"
	cstr := "file:%s?cache=shared&mode=rwc&_journal_mode=WAL&_synchronous=1&_busy_timeout=5000"
	db, err = sql.Open("sqlite3", fmt.Sprintf(cstr, cfg.DbFile))
	if err != nil {
		logger.Errorf("Failed to open/create DB file: %s: %v", cfg.DbFile, err)
		panic(err)
	}

	repo := Repo{
		cfg:    cfg,
		logger: logger,
		db:     db,
		nextId: uint64(time.Now().UnixNano()),
	}

	return &repo
}

func (repo *Repo) GetNextId() uint64 {
	repo.muId.Lock()
	res := repo.nextId + 1
	repo.nextId = res
	repo.muId.Unlock()
	return res
}

func (repo *Repo) InitUpdateDb() {

	dbVer := 0
	sysParamsExists := false
	var err error
	var rows *sql.Rows

	rows, err = repo.db.Query("SELECT name FROM sqlite_master WHERE type='table' AND name='sys_params'")
	if err != nil {
		repo.logger.Errorf("Failed to check if 'sys_params' table exists: %v", err)
		panic(err)
	}
	for rows.Next() {
		sysParamsExists = true
	}
	_ = rows.Close()
	if !sysParamsExists {
		repo.logger.Printf("Database appears to be empty; current schema version is %d", schemaVer)
	} else {
		row := repo.db.QueryRow("SELECT val FROM sys_params WHERE name='schema_ver'")
		if err = row.Scan(&dbVer); err != nil {
			repo.logger.Errorf("Failed to query schema version: %v", err)
			panic(err)
		}
		repo.logger.Printf("Database is at version %d; current schema version is %d", dbVer, schemaVer)
	}
	for i := dbVer; i < schemaVer; i += 1 {
		nextVer := i + 1
		fn := fmt.Sprintf("scripts/create-%02d.sql", nextVer)
		repo.logger.Printf("Running %s", fn)
		var sqlBytes []byte
		if sqlBytes, err = scripts.ReadFile(fn); err != nil {
			repo.logger.Errorf("Failed to read init script %s: %v", fn, err)
			panic(err)
		}
		sqlStr := string(sqlBytes)
		if _, err = repo.db.Exec(sqlStr); err != nil {
			repo.logger.Errorf("Failed to execute init script %s: %v", fn, err)
			panic(err)
		}
		//if nextVer == 5 {
		//	if err = repo.upgrade05(); err != nil {
		//		repo.logger.Errorf("Failed to execute upgrade code to %d: %v", nextVer, err)
		//		panic(err)
		//	}
		//}
		_, err = repo.db.Exec("UPDATE sys_params SET val=? WHERE name='schema_ver'", nextVer)
		if err != nil {
			repo.logger.Errorf("Failed to update schema_ver to %d: %v", nextVer, err)
			panic(err)
		}
	}

	if dbVer == 0 {
		repo.mustAddBuiltInUsers()
	}
}

type postToFix struct {
	accountId    int
	postGuidHash int
	title        string
	description  string
}

func (repo *Repo) mustAddBuiltInUsers() {

	idb := shared.IdBuilder{Host: repo.cfg.Host}

	_, err := repo.db.Exec(`INSERT INTO accounts
    	(created_at, user_url, handle, pubkey, privkey)
		VALUES(?, ?, ?, ?, ?)`,
		repo.cfg.Birb.Published, idb.UserUrl(repo.cfg.Birb.User),
		repo.cfg.Birb.User, repo.cfg.Birb.PubKey, repo.cfg.Birb.PrivKey)

	if err != nil {
		repo.logger.Errorf("Failed to add built-in user '%s': %v", repo.cfg.Birb.User, err)
		panic(err)
	}
}

func (repo *Repo) Vacuum() error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	repo.logger.Info("Acquired DB lock for vacuuming")

	if _, err := repo.db.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`); err != nil {
		return err
	}
	repo.logger.Info("Executed pre-vacumm checkpoint with truncation")
	if _, err := repo.db.Exec(`VACUUM`); err != nil {
		return err
	}
	repo.logger.Info("Executed vacuum command")
	_, err := repo.db.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`)
	repo.logger.Info("Executed post-vacumm checkpoint with truncation")
	return err
}

func (repo *Repo) AddAccountIfNotExist(acct *Account, privKey string) (isNew bool, err error) {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	isNew = true
	_, err = repo.db.Exec(`INSERT INTO accounts
    	(created_at, user_url, handle, feed_name, feed_summary, profile_image_url, site_url, feed_url, pubkey, privkey)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		acct.CreatedAt, acct.UserUrl, acct.Handle, acct.FeedName, acct.FeedSummary, acct.ProfileImageUrl,
		acct.SiteUrl, acct.FeedUrl, acct.PubKey, privKey)
	if err == nil {
		return
	}
	// MySQL: mysql.MySQLError; mysqlErr.Number == 1062
	if sqliteErr, ok := err.(sqlite3.Error); ok {
		// Duplicate key: account with this handle already exists
		if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 2067 {
			isNew = false
			_, err = repo.getAccount(acct.Handle)
			return
		}
	}
	return
}

func (repo *Repo) DoesAccountExist(user string) (bool, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	row := repo.db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE handle=?`, user)
	var err error
	var count int
	if err = row.Scan(&count); err != nil {
		return false, err
	}
	return count != 0, nil
}

func (repo *Repo) GetAccount(user string) (*Account, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	return repo.getAccount(user)
}

func (repo *Repo) getAccount(user string) (*Account, error) {

	row := repo.db.QueryRow(
		`SELECT id, created_at, user_url, handle, feed_name, feed_summary, profile_image_url, site_url, feed_url,
         		feed_last_updated, next_check_due, pubkey
		FROM accounts WHERE handle=?`, user)
	var err error
	var res Account
	err = row.Scan(&res.Id, &res.CreatedAt, &res.UserUrl, &res.Handle, &res.FeedName, &res.FeedSummary,
		&res.ProfileImageUrl, &res.SiteUrl, &res.FeedUrl, &res.FeedLastUpdated, &res.NextCheckDue, &res.PubKey)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &res, nil
}

func (repo *Repo) BruteDeleteAccount(accountId int) error {

	step1 := func() error {
		repo.muDb.Lock()
		defer repo.muDb.Unlock()
		_, err := repo.db.Exec(`DELETE FROM toots WHERE account_id=?`, accountId)
		if err != nil {
			return err
		}
		return nil
	}

	step2 := func() error {
		repo.muDb.Lock()
		defer repo.muDb.Unlock()
		_, err := repo.db.Exec(`DELETE FROM feed_posts WHERE account_id=?`, accountId)
		if err != nil {
			return err
		}
		return nil
	}

	step3 := func() error {
		repo.muDb.Lock()
		defer repo.muDb.Unlock()
		_, err := repo.db.Exec(`DELETE FROM followers WHERE account_id=?`, accountId)
		if err != nil {
			return err
		}
		return nil
	}

	step4 := func() error {
		repo.muDb.Lock()
		defer repo.muDb.Unlock()
		_, err := repo.db.Exec(`DELETE FROM accounts WHERE id=?`, accountId)
		if err != nil {
			return err
		}
		return nil
	}

	if err := step1(); err != nil {
		return err
	}
	time.Sleep(100 * time.Millisecond)
	if err := step2(); err != nil {
		return err
	}
	time.Sleep(100 * time.Millisecond)
	if err := step3(); err != nil {
		return err
	}
	time.Sleep(100 * time.Millisecond)
	if err := step4(); err != nil {
		return err
	}

	return nil
}

func (repo *Repo) GetAccountsPage(offset, limit int) ([]*Account, int, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	var res []*Account
	var total int
	var err error

	row := repo.db.QueryRow(`SELECT COUNT(*) FROM accounts`)
	if err = row.Scan(&total); err != nil {
		return nil, 0, err
	}

	query := `SELECT id, created_at, user_url, handle, feed_name, feed_summary, profile_image_url, site_url, feed_url,
        feed_last_updated, next_check_due, pubkey
		FROM accounts ORDER BY ID DESC LIMIT ? OFFSET ?`
	rows, err := repo.db.Query(query, limit, offset)
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()

	for rows.Next() {
		a := Account{}
		err = rows.Scan(&a.Id, &a.CreatedAt, &a.UserUrl, &a.Handle, &a.FeedName, &a.FeedSummary,
			&a.ProfileImageUrl, &a.SiteUrl, &a.FeedUrl, &a.FeedLastUpdated, &a.NextCheckDue, &a.PubKey)
		if err = rows.Err(); err != nil {
			return nil, 0, err
		}
		res = append(res, &a)
	}
	return res, total, nil
}

func (repo *Repo) GetPrivKey(user string) (string, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	row := repo.db.QueryRow(`SELECT privkey FROM accounts WHERE handle=?`, user)
	var err error
	var res string
	err = row.Scan(&res)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return "", nil
		} else {
			return "", err
		}
	}
	return res, nil
}

func (repo *Repo) SetPrivKey(user, privKey string) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec("UPDATE accounts SET privkey=? WHERE handle=?", privKey, user)
	if err != nil {
		return err
	}
	return nil
}

func (repo *Repo) AddToot(accountId int, toot *Toot) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`INSERT INTO toots (account_id, post_guid_hash, tooted_at, status_id, content)
		VALUES(?, ?, ?, ?, ?)`,
		accountId, toot.PostGuidHash, toot.TootedAt, toot.StatusId, toot.Content)
	if err != nil {
		return err
	}
	return nil
}

func (repo *Repo) GetToot(statusId string) (*Toot, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	query := `SELECT post_guid_hash, tooted_at, status_id, content FROM toots WHERE status_id=?`
	rows, err := repo.db.Query(query, statusId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		t := Toot{}
		err = rows.Scan(&t.PostGuidHash, &t.TootedAt, &t.StatusId, &t.Content)
		if err = rows.Err(); err != nil {
			return nil, err
		}
		return &t, nil
	}
	return nil, nil
}

func (repo *Repo) GetPostCount(user string) (uint, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	row := repo.db.QueryRow(`SELECT COUNT(*) FROM feed_posts JOIN accounts
		ON feed_posts.account_id=accounts.id AND accounts.handle=?`, user)
	var err error
	var count int
	if err = row.Scan(&count); err != nil {
		return 0, err
	}
	return uint(count), nil
}

func (repo *Repo) GetTotalPostCount() (uint, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	row := repo.db.QueryRow(`SELECT COUNT(*) FROM feed_posts`)
	var err error
	var count int
	if err = row.Scan(&count); err != nil {
		return 0, err
	}
	return uint(count), nil
}

func (repo *Repo) GetPostsPage(accountId int, offset, limit int) ([]*FeedPost, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	var res []*FeedPost
	var err error

	query := `SELECT post_guid_hash, post_time, link, title, description
		FROM feed_posts WHERE account_id=? ORDER BY post_time DESC LIMIT ? OFFSET ?`
	rows, err := repo.db.Query(query, accountId, limit, offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		p := FeedPost{}
		err = rows.Scan(&p.PostGuidHash, &p.PostTime, &p.Link, &p.Title, &p.Description)
		if err = rows.Err(); err != nil {
			return nil, err
		}
		res = append(res, &p)
	}
	return res, nil
}

func (repo *Repo) GetTootExtracts(accountId int) ([]*Toot, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	var res []*Toot
	var err error

	query := `SELECT post_guid_hash, tooted_at FROM toots WHERE account_id=?`
	rows, err := repo.db.Query(query, accountId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		p := Toot{}
		err = rows.Scan(&p.PostGuidHash, &p.TootedAt)
		if err = rows.Err(); err != nil {
			return nil, err
		}
		res = append(res, &p)
	}
	return res, nil

}

func (repo *Repo) GetFollowerCount(user string, onlyApproved bool) (uint, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	sql := `SELECT COUNT(*) FROM followers JOIN accounts
		ON followers.account_id=accounts.id AND accounts.handle=?`
	if onlyApproved {
		sql += ` WHERE followers.approve_status=1`
	}

	row := repo.db.QueryRow(sql, user)
	var err error
	var count int
	if err = row.Scan(&count); err != nil {
		return 0, err
	}
	return uint(count), nil
}

func (repo *Repo) GetFeedFollowerCount() (int, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	row := repo.db.QueryRow(`SELECT COUNT(*) FROM followers WHERE account_id NOT IN
        (SELECT id FROM accounts WHERE handle='?');`, repo.cfg.Birb.User)
	var err error
	var count int
	if err = row.Scan(&count); err != nil {
		return 0, err
	}
	return count, nil
}

func (repo *Repo) SetFollowerApproveStatus(user, followerUserUrl string, status int) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	acct, err := repo.getAccount(user)
	if err != nil {
		return err
	}
	_, err = repo.db.Exec(`UPDATE followers SET approve_status=? WHERE account_id=? AND user_url=?`,
		status, acct.Id, followerUserUrl)
	if err != nil {
		return err
	}
	return nil
}

func (repo *Repo) GetFollowersByUser(user string, onlyApproved bool) ([]*FollowerInfo, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	query := `SELECT followers.request_id, followers.user_url, followers.handle, host, user_inbox, shared_inbox
		FROM followers JOIN accounts ON followers.account_id=accounts.id AND accounts.handle=?`
	if onlyApproved {
		query += ` WHERE followers.approve_status=1`
	}
	rows, err := repo.db.Query(query, user)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	return readGetFollowers(rows)
}

func (repo *Repo) GetFollowersById(accountId int, onlyApproved bool) ([]*FollowerInfo, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	query := `SELECT request_id, user_url, handle, host, user_inbox, shared_inbox FROM followers WHERE account_id=?`
	if onlyApproved {
		query += ` AND followers.approve_status=1`
	}
	rows, err := repo.db.Query(query, accountId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	return readGetFollowers(rows)
}

func readGetFollowers(rows *sql.Rows) ([]*FollowerInfo, error) {
	var err error
	res := make([]*FollowerInfo, 0)
	for rows.Next() {
		mui := FollowerInfo{}
		err = rows.Scan(&mui.RequestId, &mui.UserUrl, &mui.Handle, &mui.Host, &mui.UserInbox, &mui.SharedInbox)
		if err != nil {
			return nil, err
		}
		res = append(res, &mui)
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}
	return res, nil
}

func (repo *Repo) AddFollower(user string, flwr *FollowerInfo) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	row := repo.db.QueryRow(`SELECT id FROM accounts WHERE handle=?`, user)
	var err error
	var accountId int
	if err = row.Scan(&accountId); err != nil {
		return err
	}
	_, err = repo.db.Exec(`INSERT INTO followers VALUES(?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT DO UPDATE SET request_id=excluded.request_id, approve_status=excluded.approve_status`,
		accountId, flwr.RequestId, flwr.ApproveStatus, flwr.UserUrl, flwr.Handle, flwr.Host,
		flwr.UserInbox, flwr.SharedInbox)
	if err != nil {
		return err
	}
	return nil
}

func (repo *Repo) RemoveFollower(user, followerUserUrl string) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	row := repo.db.QueryRow(`SELECT id FROM accounts WHERE handle=?`, user)
	var err error
	var accountId int
	if err = row.Scan(&accountId); err != nil {
		return err
	}
	_, err = repo.db.Exec(`DELETE FROM followers WHERE account_id=? AND user_url=?`,
		accountId, followerUserUrl)
	if err != nil {
		return err
	}
	return nil
}

func (repo *Repo) GetFeedLastUpdated(accountId int) (res time.Time, err error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	res = time.Time{}
	err = nil
	row := repo.db.QueryRow("SELECT feed_last_updated FROM accounts WHERE id=?", accountId)
	if err = row.Scan(&res); err != nil {
		return
	}
	return
}

func (repo *Repo) UpdateAccountFeedTimes(accountId int, lastUpdated, nextCheckDue time.Time) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`UPDATE accounts SET feed_last_updated=?, next_check_due=?
        WHERE id=?`, lastUpdated, nextCheckDue, accountId)
	return err
}

func (repo *Repo) SetFeedFetchState(accountId int, etag, lastModified string, failures int) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`UPDATE accounts SET feed_etag=?, feed_last_modified=?, fetch_failures=?
        WHERE id=?`, etag, lastModified, failures, accountId)
	return err
}

func (repo *Repo) GetAccountToCheck(checkDue time.Time) (*Account, int, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	var nCheckableAccounts int
	row := repo.db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE next_check_due<?`, checkDue)
	if err := row.Scan(&nCheckableAccounts); err != nil {
		return nil, 0, err
	}

	rows, err := repo.db.Query(`SELECT id, created_at, user_url, handle, feed_name, feed_summary,
    	profile_image_url, site_url, feed_url, feed_last_updated, next_check_due, pubkey,
		feed_etag, feed_last_modified, fetch_failures
		FROM accounts WHERE next_check_due<? LIMIT 1`, checkDue)
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()
	var acct *Account = nil
	for rows.Next() {
		res := Account{}
		err = rows.Scan(&res.Id, &res.CreatedAt, &res.UserUrl, &res.Handle, &res.FeedName, &res.FeedSummary,
			&res.ProfileImageUrl, &res.SiteUrl, &res.FeedUrl, &res.FeedLastUpdated, &res.NextCheckDue, &res.PubKey,
			&res.FeedEtag, &res.FeedLastModified, &res.FetchFailures)
		if err != nil {
			return nil, 0, err
		}
		if err = rows.Err(); err != nil {
			return nil, 0, err
		}
		acct = &res
	}
	return acct, nCheckableAccounts, nil

}

func (repo *Repo) AddFeedPostIfNew(accountId int, post *FeedPost) (isNew bool, err error) {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	err = nil

	_, err = repo.db.Exec(`INSERT INTO feed_posts
    	(account_id, post_guid_hash, post_time, link, title, description)
		VALUES (?, ?, ?, ?, ?, ?)`,
		accountId, post.PostGuidHash, post.PostTime, post.Link, post.Title, post.Description)

	if err == nil {
		isNew = true
		return
	}

	// Duplicate key: feed post for this account+guid_hash already exists
	if sqliteErr, ok := err.(sqlite3.Error); ok {
		// Duplicate key: record with this unique key already exists
		if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 2067 {
			isNew = false
			err = nil
			return
		}
	}

	return
}

func (repo *Repo) AddTootQueueItem(tqi *TootQueueItem) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`INSERT INTO toot_queue (sending_user, to_inbox, tooted_at, status_id, content)
		VALUES(?, ?, ?, ?, ?)`,
		tqi.SendingUser, tqi.ToInbox, tqi.TootedAt, tqi.StatusId, tqi.Content)
	return err
}

func (repo *Repo) GetTootQueueItems(aboveId, maxCount int) ([]*TootQueueItem, int, error) {

	repo.muDb.RLock()
	defer repo.muDb.RUnlock()

	var itmCount int
	row := repo.db.QueryRow(`SELECT COUNT(*) FROM toot_queue`)
	if err := row.Scan(&itmCount); err != nil {
		return nil, 0, err
	}

	rows, err := repo.db.Query(`SELECT id, sending_user, to_inbox, tooted_at, status_id, content
		FROM toot_queue WHERE id>? ORDER BY id ASC LIMIT ?`, aboveId, maxCount)
	if err != nil {
		return nil, itmCount, err
	}
	defer rows.Close()
	res := make([]*TootQueueItem, 0, maxCount)
	for rows.Next() {
		tqi := TootQueueItem{}
		err = rows.Scan(&tqi.Id, &tqi.SendingUser, &tqi.ToInbox, &tqi.TootedAt, &tqi.StatusId, &tqi.Content)
		if err != nil {
			return nil, itmCount, err
		}
		res = append(res, &tqi)
	}
	if err = rows.Err(); err != nil {
		return nil, itmCount, err
	}
	return res, itmCount, nil
}

func (repo *Repo) DeleteTootQueueItem(id int) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`DELETE FROM toot_queue WHERE id=?`, id)
	return err
}

func (repo *Repo) PurgePostsAndToots(accountId int, fromBefore time.Time) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	if _, err := repo.db.Exec(`DELETE FROM feed_posts
       	WHERE account_id=? AND post_time<=?`, accountId, fromBefore); err != nil {
		return err
	}
	if _, err := repo.db.Exec(`DELETE FROM toots
       	WHERE account_id=? AND tooted_at<=?`, accountId, fromBefore); err != nil {
		return err
	}

	return nil
}

func (repo *Repo) MarkActivityHandled(id string, when time.Time) (alreadyHandled bool, err error) {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	alreadyHandled = false
	err = nil

	_, err = repo.db.Exec(`INSERT INTO handled_activities VALUES (?, ?)`, id, when)

	if err == nil {
		return
	}

	// Duplicate key: activity was handled before
	if sqliteErr, ok := err.(sqlite3.Error); ok {
		// Duplicate key: account with this handle already exists
		if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 2067 {
			alreadyHandled = true
			err = nil
			return
		}
	}

	return
}

func (repo *Repo) DeleteHandledActivities(before time.Time) error {

	repo.muDb.Lock()
	defer repo.muDb.Unlock()

	_, err := repo.db.Exec(`DELETE FROM handled_activities WHERE handled_at<?`, before)
	return err
}