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 GetLatestLivestreamForRepo(repoDID string) (*Livestream, error)
61 GetLivestreamByPostURI(postURI string) (*Livestream, error)
62 GetLatestLivestreams(limit int, before *time.Time, dids []string) ([]Livestream, error)
63
64 CreateTeleport(ctx context.Context, tp *Teleport) error
65 GetLatestTeleportForRepo(repoDID string) (*Teleport, error)
66 GetActiveTeleportsForRepo(repoDID string) ([]Teleport, error)
67 GetActiveTeleportsToRepo(targetDID string) ([]Teleport, error)
68 GetTeleportByURI(uri string) (*Teleport, error)
69 DeleteTeleport(ctx context.Context, uri string) error
70 DenyTeleport(ctx context.Context, uri string) error
71
72 CreateBlock(ctx context.Context, block *Block) error
73 GetBlock(ctx context.Context, rkey string) (*Block, error)
74 GetBlockedDIDs(ctx context.Context, blockerDID string) ([]string, 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 MostRecentChatMessagesForViewer(repoDID, viewerDID string) ([]*streamplace.ChatDefs_MessageView, error)
81 GetChatMessage(uri string) (*ChatMessage, error)
82 DeleteChatMessage(ctx context.Context, uri string, deletedAt *time.Time) error
83
84 CreateGate(ctx context.Context, gate *Gate) error
85 DeleteGate(ctx context.Context, rkey string) error
86 GetGate(ctx context.Context, rkey string) (*Gate, error)
87 GetUserGates(ctx context.Context, userDID string) ([]*Gate, error)
88
89 CreateChatProfile(ctx context.Context, profile *ChatProfile) error
90 GetChatProfile(ctx context.Context, repoDID string) (*ChatProfile, error)
91
92 UpdateServerSettings(ctx context.Context, settings *ServerSettings) error
93 GetServerSettings(ctx context.Context, server string, repoDID string) (*ServerSettings, error)
94 DeleteServerSettings(ctx context.Context, server string, repoDID string) error
95
96 CreateLabeler(did string) (*Labeler, error)
97 GetLabeler(did string) (*Labeler, error)
98 UpdateLabelerCursor(did string, cursor int64) error
99
100 CreateLabel(label *Label) error
101 GetActiveLabels(uri string) ([]*comatproto.LabelDefs_Label, error)
102
103 UpdateBroadcastOrigin(ctx context.Context, origin *streamplace.BroadcastOrigin, aturi syntax.ATURI) error
104 GetRecentBroadcastOrigins(ctx context.Context) ([]*streamplace.BroadcastDefs_BroadcastOriginView, error)
105
106 CreateMetadataConfiguration(ctx context.Context, metadata *MetadataConfiguration) error
107 GetMetadataConfiguration(ctx context.Context, repoDID string) (*MetadataConfiguration, error)
108 DeleteMetadataConfiguration(ctx context.Context, repoDID string) error
109
110 CreateModerationDelegation(ctx context.Context, rec *streamplace.ModerationPermission, aturi syntax.ATURI) error
111 DeleteModerationDelegation(ctx context.Context, rkey string) error
112 GetModerationDelegation(ctx context.Context, streamerDID, moderatorDID string) (*streamplace.ModerationDefs_PermissionView, error)
113 GetModerationDelegations(ctx context.Context, streamerDID, moderatorDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
114 GetModeratorDelegations(ctx context.Context, moderatorDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
115 GetStreamerModerators(ctx context.Context, streamerDID string) ([]*streamplace.ModerationDefs_PermissionView, error)
116
117 GetRecommendation(userDID string) (*Recommendation, error)
118 UpsertRecommendation(rec *Recommendation) error
119}
120
121var DBRevision = 2
122
123func MakeDB(dbURL string) (Model, error) {
124 sqliteSuffix := dbURL
125 if dbURL != ":memory:" {
126 // Ensure dbURL exists as a directory on the filesystem
127 if err := os.MkdirAll(dbURL, os.ModePerm); err != nil {
128 return nil, fmt.Errorf("error creating database directory: %w", err)
129 }
130 dbPath := filepath.Join(dbURL, fmt.Sprintf("index_%d.sqlite", DBRevision))
131 sqliteSuffix = dbPath
132 // if this isn't ":memory:", ensure that directory exists (eg, if db
133 // file is being initialized)
134 if err := os.MkdirAll(filepath.Dir(sqliteSuffix), os.ModePerm); err != nil {
135 return nil, fmt.Errorf("error creating database path: %w", err)
136 }
137 }
138 log.Log(context.Background(), "starting database", "dbURL", sqliteSuffix)
139 dial := sqlite.Open(sqliteSuffix)
140
141 db, err := gorm.Open(dial, &gorm.Config{
142 SkipDefaultTransaction: true,
143 TranslateError: true,
144 Logger: config.GormLogger,
145 })
146 if err != nil {
147 return nil, fmt.Errorf("error starting database: %w", err)
148 }
149 err = db.Exec("PRAGMA journal_mode=WAL;").Error
150 if err != nil {
151 return nil, fmt.Errorf("error setting journal mode: %w", err)
152 }
153
154 err = db.Use(prometheus.New(prometheus.Config{
155 DBName: "index",
156 RefreshInterval: 10,
157 StartServer: false,
158 }))
159 if err != nil {
160 return nil, fmt.Errorf("error using prometheus plugin: %w", err)
161 }
162
163 sqlDB, err := db.DB()
164 if err != nil {
165 return nil, fmt.Errorf("error getting database: %w", err)
166 }
167 sqlDB.SetMaxOpenConns(1)
168 for _, model := range []any{
169 PlayerEvent{},
170 Identity{},
171 Repo{},
172 SigningKey{},
173 Follow{},
174 FeedPost{},
175 Livestream{},
176 Block{},
177 ChatMessage{},
178 ChatProfile{},
179 Gate{},
180 ServerSettings{},
181 Labeler{},
182 Label{},
183 BroadcastOrigin{},
184 MetadataConfiguration{},
185 Teleport{},
186 ModerationDelegation{},
187 Recommendation{},
188 } {
189 err = db.AutoMigrate(model)
190 if err != nil {
191 return nil, err
192 }
193 }
194 return &DBModel{DB: db}, nil
195}