Live video on the AT Protocol
1package model
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "time"
9
10 comatproto "github.com/bluesky-social/indigo/api/atproto"
11 "github.com/bluesky-social/indigo/api/bsky"
12 "github.com/bluesky-social/indigo/atproto/syntax"
13 "gorm.io/driver/sqlite"
14 "gorm.io/gorm"
15 "gorm.io/plugin/prometheus"
16 "stream.place/streamplace/pkg/config"
17 "stream.place/streamplace/pkg/log"
18 "stream.place/streamplace/pkg/streamplace"
19)
20
21type DBModel struct {
22 DB *gorm.DB
23}
24
25type Model interface {
26 CreatePlayerEvent(event PlayerEventAPI) error
27 ListPlayerEvents(playerID string) ([]PlayerEvent, error)
28 PlayerReport(playerID string) (map[string]any, error)
29 ClearPlayerEvents() error
30
31 GetIdentity(id string) (*Identity, error)
32 UpdateIdentity(ident *Identity) error
33
34 GetRepo(did string) (*Repo, error)
35 GetRepoByHandle(handle string) (*Repo, error)
36 GetRepoByHandleOrDID(arg string) (*Repo, error)
37 GetRepoBySigningKey(signingKey string) (*Repo, error)
38 GetAllRepos() ([]Repo, error)
39 SearchReposByHandle(query string, limit int) ([]Repo, error)
40 UpdateRepo(repo *Repo) error
41
42 UpdateSigningKey(key *SigningKey) error
43 GetSigningKey(ctx context.Context, did, repoDID string) (*SigningKey, error)
44 GetSigningKeyByRKey(ctx context.Context, rkey string) (*SigningKey, error)
45 GetSigningKeysForRepo(repoDID string) ([]SigningKey, error)
46
47 CreateFollow(ctx context.Context, userDID, rev string, follow *bsky.GraphFollow) error
48 GetUserFollowing(ctx context.Context, userDID string) ([]Follow, error)
49 GetUserFollowers(ctx context.Context, userDID string) ([]Follow, error)
50 GetUserFollowingUser(ctx context.Context, userDID, subjectDID string) (*Follow, error)
51 DeleteFollow(ctx context.Context, userDID, rev string) error
52
53 CreateFeedPost(ctx context.Context, post *FeedPost) error
54 ListFeedPosts() ([]FeedPost, error)
55 ListFeedPostsByType(feedType string, limit int, after int64) ([]FeedPost, error)
56 GetFeedPost(uri string) (*FeedPost, error)
57 GetReplies(repoDID string) ([]*bsky.FeedDefs_PostView, error)
58
59 CreateLivestream(ctx context.Context, ls *Livestream) error
60 GetLivestream(uri string) (*Livestream, error)
61 GetLatestLivestreamForRepo(repoDID string) (*Livestream, error)
62 GetLivestreamByPostURI(postURI string) (*Livestream, error)
63 GetLatestLivestreams(limit int, before *time.Time, dids []string) ([]Livestream, error)
64
65 CreateTeleport(ctx context.Context, tp *Teleport) error
66 GetLatestTeleportForRepo(repoDID string) (*Teleport, error)
67 GetActiveTeleportsForRepo(repoDID string) ([]Teleport, error)
68 GetActiveTeleportsToRepo(targetDID string) ([]Teleport, error)
69 GetTeleportByURI(uri string) (*Teleport, error)
70 DeleteTeleport(ctx context.Context, uri string) error
71 DenyTeleport(ctx context.Context, uri string) error
72
73 CreateBlock(ctx context.Context, block *Block) error
74 GetBlock(ctx context.Context, rkey string) (*Block, error)
75 GetUserBlock(ctx context.Context, userDID, subjectDID string) (*Block, error)
76 DeleteBlock(ctx context.Context, rkey string) error
77
78 CreateChatMessage(ctx context.Context, message *ChatMessage) error
79 MostRecentChatMessages(repoDID string) ([]*streamplace.ChatDefs_MessageView, error)
80 GetChatMessage(uri string) (*ChatMessage, error)
81 DeleteChatMessage(ctx context.Context, uri string, deletedAt *time.Time) error
82
83 CreateGate(ctx context.Context, gate *Gate) error
84 DeleteGate(ctx context.Context, rkey string) error
85 GetGate(ctx context.Context, rkey string) (*Gate, error)
86 GetUserGates(ctx context.Context, userDID string) ([]*Gate, error)
87
88 CreateChatProfile(ctx context.Context, profile *ChatProfile) error
89 GetChatProfile(ctx context.Context, repoDID string) (*ChatProfile, error)
90
91 UpdateServerSettings(ctx context.Context, settings *ServerSettings) error
92 GetServerSettings(ctx context.Context, server string, repoDID string) (*ServerSettings, error)
93 DeleteServerSettings(ctx context.Context, server string, repoDID string) error
94
95 CreateLabeler(did string) (*Labeler, error)
96 GetLabeler(did string) (*Labeler, error)
97 UpdateLabelerCursor(did string, cursor int64) error
98
99 CreateLabel(label *Label) error
100 GetActiveLabels(uri string) ([]*comatproto.LabelDefs_Label, error)
101
102 UpdateBroadcastOrigin(ctx context.Context, origin *streamplace.BroadcastOrigin, aturi syntax.ATURI) error
103 GetRecentBroadcastOrigins(ctx context.Context) ([]*streamplace.BroadcastDefs_BroadcastOriginView, error)
104
105 CreateMetadataConfiguration(ctx context.Context, metadata *MetadataConfiguration) error
106 GetMetadataConfiguration(ctx context.Context, repoDID string) (*MetadataConfiguration, error)
107 DeleteMetadataConfiguration(ctx context.Context, repoDID string) error
108
109 CreateModerationDelegation(ctx context.Context, rec *streamplace.ModerationPermission, aturi syntax.ATURI) error
110 DeleteModerationDelegation(ctx context.Context, rkey string) error
111 GetModerationDelegation(ctx context.Context, streamerDID, moderatorDID string) (*streamplace.ModerationDefs_PermissionView, error)
112 GetModerationDelegations(ctx context.Context, streamerDID, moderatorDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
113 GetModeratorDelegations(ctx context.Context, moderatorDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
114 GetStreamerModerators(ctx context.Context, streamerDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
115
116 GetRecommendation(userDID string) (*Recommendation, error)
117 UpsertRecommendation(rec *Recommendation) error
118
119 UpsertBskyProfile(ctx context.Context, aturi syntax.ATURI, profileBs []byte, wasStreamplace bool) error
120 GetBskyProfile(ctx context.Context, did string, wasStreamplace bool) (*bsky.ActorProfile, error)
121}
122
123var DBRevision = 2
124
125func MakeDB(dbURL string) (Model, error) {
126 sqliteSuffix := dbURL
127 if dbURL != ":memory:" {
128 // Ensure dbURL exists as a directory on the filesystem
129 if err := os.MkdirAll(dbURL, os.ModePerm); err != nil {
130 return nil, fmt.Errorf("error creating database directory: %w", err)
131 }
132 dbPath := filepath.Join(dbURL, fmt.Sprintf("index_%d.sqlite", DBRevision))
133 sqliteSuffix = dbPath
134 // if this isn't ":memory:", ensure that directory exists (eg, if db
135 // file is being initialized)
136 if err := os.MkdirAll(filepath.Dir(sqliteSuffix), os.ModePerm); err != nil {
137 return nil, fmt.Errorf("error creating database path: %w", err)
138 }
139 }
140 log.Log(context.Background(), "starting database", "dbURL", sqliteSuffix)
141 dial := sqlite.Open(sqliteSuffix)
142
143 db, err := gorm.Open(dial, &gorm.Config{
144 SkipDefaultTransaction: true,
145 TranslateError: true,
146 Logger: config.GormLogger,
147 })
148 if err != nil {
149 return nil, fmt.Errorf("error starting database: %w", err)
150 }
151 err = db.Exec("PRAGMA journal_mode=WAL;").Error
152 if err != nil {
153 return nil, fmt.Errorf("error setting journal mode: %w", err)
154 }
155
156 err = db.Use(prometheus.New(prometheus.Config{
157 DBName: "index",
158 RefreshInterval: 10,
159 StartServer: false,
160 }))
161 if err != nil {
162 return nil, fmt.Errorf("error using prometheus plugin: %w", err)
163 }
164
165 sqlDB, err := db.DB()
166 if err != nil {
167 return nil, fmt.Errorf("error getting database: %w", err)
168 }
169 sqlDB.SetMaxOpenConns(1)
170 for _, model := range []any{
171 PlayerEvent{},
172 Identity{},
173 Repo{},
174 SigningKey{},
175 Follow{},
176 FeedPost{},
177 Livestream{},
178 Block{},
179 ChatMessage{},
180 ChatProfile{},
181 Gate{},
182 ServerSettings{},
183 Labeler{},
184 Label{},
185 BroadcastOrigin{},
186 MetadataConfiguration{},
187 Teleport{},
188 ModerationDelegation{},
189 Recommendation{},
190 BskyProfile{},
191 } {
192 err = db.AutoMigrate(model)
193 if err != nil {
194 return nil, err
195 }
196 }
197 return &DBModel{DB: db}, nil
198}