-
Notifications
You must be signed in to change notification settings - Fork 1
/
migrate.go
82 lines (70 loc) · 2.2 KB
/
migrate.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
package migration
import (
"errors"
"fmt"
"net/url"
"github.com/shigde/sfu/internal/activitypub/instance"
"github.com/shigde/sfu/internal/activitypub/models"
"github.com/shigde/sfu/internal/auth"
"github.com/shigde/sfu/internal/lobby"
"github.com/shigde/sfu/internal/storage"
"github.com/shigde/sfu/internal/stream"
"golang.org/x/exp/slog"
"gorm.io/gorm"
)
func Migrate(config *instance.FederationConfig, storage storage.Storage) error {
storage.GetDatabase()
db := storage.GetDatabase()
if err := db.AutoMigrate(
&models.Video{},
&models.Follow{},
&models.Actor{},
&models.Instance{},
&auth.Account{},
&lobby.LobbyEntity{},
&stream.Space{},
&stream.LiveStream{},
); err != nil {
return fmt.Errorf("migrating the space schema: %w", err)
}
if db.Migrator().HasTable(&models.Actor{}) {
if err := db.First(&models.Actor{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
slog.Info("creating instance actor")
instanceActor, err := models.NewInstanceActor(config.InstanceUrl, config.InstanceUsername)
if err != nil {
return fmt.Errorf("creating instance actor: %w", err)
}
db.Create(instanceActor)
shigInstance := models.NewInstance(instanceActor)
db.Create(shigInstance)
for _, inst := range config.TrustedInstances {
if err := buildTrustedInstanceAccount(db, inst); err != nil {
return err
}
}
}
}
return nil
}
func buildTrustedInstanceAccount(db *gorm.DB, trustedInstance instance.TrustedInstance) error {
actorIri, err := url.Parse(trustedInstance.Actor)
if err != nil {
return fmt.Errorf("migration parsing trusted instance actor id: %w", err)
}
actorId := fmt.Sprintf("%s@%s", trustedInstance.Name, actorIri.Host)
actor, err := models.NewTrustedInstanceActor(actorIri, trustedInstance.Name)
if err != nil {
return fmt.Errorf("migration building actor: %w", err)
}
db.Create(actor)
var savedActor models.Actor
result := db.Where("actor_iri=?", actorIri.String()).First(&savedActor)
if result.Error != nil {
return fmt.Errorf("migration loading actor: %w", result.Error)
}
account := auth.CreateInstanceAccount(actorId, &savedActor)
db.Create(account)
trInstance := models.NewInstance(&savedActor)
db.Create(trInstance)
return nil
}