-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
205 lines (188 loc) · 5.31 KB
/
main.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
package main
import (
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
"github.com/rs/zerolog"
"golang.org/x/net/context"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/util"
)
func makeClient(cfg *Config, log *zerolog.Logger) (*mautrix.Client, error) {
cli, err := mautrix.NewClient(cfg.HomeserverURL, "", "")
if err != nil {
return nil, fmt.Errorf("failed to initialize client: %w", err)
}
cli.Log = log.With().Str("component", "matrix").Logger()
_, err = cli.Login(&mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: cfg.UserID.String(),
},
Password: cfg.Password,
DeviceID: "feedserv",
InitialDeviceDisplayName: "feedserv",
StoreCredentials: true,
})
if err != nil {
return nil, fmt.Errorf("failed to log in: %w", err)
}
cfg.homeserverDomain = cli.UserID.Homeserver()
return cli, nil
}
type FeedServ struct {
Config *Config
Client *mautrix.Client
Media *mautrix.Client
Log *zerolog.Logger
}
var (
Commit = "unknown"
BuildTime = ""
)
func main() {
cfg, err := loadConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
log, err := cfg.LogConfig.Compile()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to compile log config:", err)
os.Exit(1)
}
log.Info().
Str("go_version", runtime.Version()).
Str("feedserv_commit", Commit).
Str("build_time", BuildTime).
Msg("Initializing feedserv")
cli, err := makeClient(cfg, log)
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize mautrix client")
}
mediaCli, err := mautrix.NewClient(cfg.MediaURL, "", "")
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize media client")
}
fs := &FeedServ{
Config: cfg,
Client: cli,
Media: mediaCli,
Log: log,
}
var wg sync.WaitGroup
cfg.feedsByRoomID = make(map[id.RoomID]*FeedConfig)
wg.Add(len(cfg.Feeds))
allowedRoomIDs := make([]id.RoomID, 0, len(cfg.Feeds))
log.Info().Msg("Preparing feeds")
for feedID, feed := range cfg.Feeds {
if feed.RoomID == "" && feed.RoomAlias != "" {
resp, err := fs.Client.ResolveAlias(feed.RoomAlias)
if err != nil {
log.Fatal().
Str("room_alias", feed.RoomAlias.String()).
Str("feed_id", feedID).
Msg("Failed to resolve room ID for feed")
}
feed.RoomID = resp.RoomID
log.Debug().
Str("room_alias", feed.RoomAlias.String()).
Str("room_id", feed.RoomID.String()).
Str("feed_id", feedID).
Msg("Resolved room ID for feed")
}
_, err = fs.Client.JoinRoomByID(feed.RoomID)
if err != nil {
log.Warn().Str("feed_id", feedID).Err(err).Msg("Error joining room")
}
feed.id = feedID
feed.entries = util.NewRingBuffer[id.EventID, *event.Event](feed.MaxEntries)
feed.lastUpdate = time.Now().UTC()
if existing, alreadyExists := cfg.feedsByRoomID[feed.RoomID]; alreadyExists {
log.Fatal().
Str("room_id", feed.RoomID.String()).
Str("prev_feed_id", existing.id).
Str("new_feed_id", feedID).
Msg("Multiple feeds pointing at same room")
}
go func(feed *FeedConfig) {
fs.InitSyncFeed(feed)
wg.Done()
}(feed)
cfg.feedsByRoomID[feed.RoomID] = feed
allowedRoomIDs = append(allowedRoomIDs, feed.RoomID)
}
wg.Wait()
ctx, cancel := context.WithCancel(context.Background())
wg.Add(2)
syncer := cli.Syncer.(*mautrix.DefaultSyncer)
syncer.OnEventType(event.EventMessage, fs.HandleFeedEvent)
syncer.OnEventType(event.StateMember, fs.HandleInvite)
syncer.OnEventType(event.StateMember, fs.HandleMetadata)
syncer.OnEventType(event.StatePowerLevels, fs.HandleMetadata)
syncer.OnEventType(event.StateRoomName, fs.HandleMetadata)
syncer.OnEventType(event.StateTopic, fs.HandleMetadata)
syncer.OnEventType(event.StateRoomAvatar, fs.HandleMetadata)
nothing := mautrix.FilterPart{NotTypes: []event.Type{{Type: "*"}}}
importantTypes := mautrix.FilterPart{
Types: []event.Type{
event.EventMessage, event.StateMember, event.StatePowerLevels,
event.StateRoomName, event.StateTopic, event.StateRoomAvatar,
},
}
syncer.FilterJSON = &mautrix.Filter{
AccountData: nothing,
Presence: nothing,
Room: mautrix.RoomFilter{
AccountData: nothing,
Ephemeral: nothing,
Rooms: allowedRoomIDs,
State: importantTypes,
Timeline: importantTypes,
},
}
cli.Store = mautrix.NewAccountDataStore("com.beeper.feedserv_sync_token", cli)
server := http.Server{
Addr: cfg.ListenAddress,
Handler: fs,
}
go func() {
defer wg.Done()
err := cli.SyncWithContext(ctx)
if err != nil && !errors.Is(err, context.Canceled) {
log.Fatal().Err(err).Msg("Error in syncer")
} else {
log.Debug().Msg("Syncer finished cleanly")
}
}()
go func() {
defer wg.Done()
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal().Err(err).Msg("Error in HTTP server")
} else {
log.Debug().Msg("HTTP server finished cleanly")
}
}()
log.Info().Msg("Feedserv initialization complete")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
log.Info().Msg("Interrupt received, stopping...")
cancel()
err = server.Close()
if err != nil {
log.Warn().Err(err).Msg("Error closing HTTP server")
}
wg.Wait()
log.Info().Msg("Feedserv stopped")
}