-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
483 lines (419 loc) · 13.6 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
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
package main
import (
"context"
"encoding/gob"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
"io"
"github.com/sideshow/apns2"
"github.com/sideshow/apns2/payload"
"github.com/sideshow/apns2/token"
"tailscale.com/tailcfg"
"tailscale.com/tsnet"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
)
var (
hostname = flag.String("hostname", "cliff", "The hostname to use on the tailnet")
apnsKey = flag.String("apns-key", os.Getenv("CLIFF_APNS_KEY_PATH"), "Path to the APNs token signing key")
keyID = flag.String("key-id", os.Getenv("CLIFF_APNS_KEY_ID"), "ID of the APNs token signing key")
teamID = flag.String("team-id", os.Getenv("CLIFF_APNS_TEAM_ID"), "ID of the team signing the app")
bundleID = flag.String("bundle-id", os.Getenv("CLIFF_APP_BUNDLE_ID"), "Bundle ID of the app receiving notifications")
development = flag.Bool("development", false, "Whether to send APNs notifications to the dev environment")
)
func main() {
flag.Parse()
if *apnsKey == "" {
flag.PrintDefaults()
log.Fatal("Must provide a path to the APNs key file (can use the CLIFF_APNS_KEY_PATH env var)")
}
if *keyID == "" {
flag.PrintDefaults()
log.Fatal("Must provide the ID of the APNs key (can use the CLIFF_APNS_KEY_ID env var)")
}
if *teamID == "" {
flag.PrintDefaults()
log.Fatal("Must provide the ID of the team signing the app (can use the CLIFF_APNS_TEAM_ID env var)")
}
if *bundleID == "" {
flag.PrintDefaults()
log.Fatal("Must provide the bundle ID of the app recieving notifications (can use the CLIFF_APP_BUNDLE_ID env var)")
}
// MARK: - APNs client setup
log.Printf("[1/6] Creating APNs client")
authKey, err := token.AuthKeyFromFile(*apnsKey)
if err != nil {
log.Fatal("Token key error:", err)
}
token := &token.Token{
AuthKey: authKey,
KeyID: *keyID,
TeamID: *teamID,
}
apnsClient := apns2.NewTokenClient(token)
if *development {
apnsClient.Development() // default for now, but setting in case the default changes
} else {
apnsClient.Production()
}
log.Printf("[2/6] Creating FCM client")
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatal("Unable to create Firebase app:", err)
}
fcmClient, err := app.Messaging(context.Background())
if err != nil {
log.Fatal("Unable to create FCM client")
}
// MARK: - Tailscale setup
log.Printf("[3/6] Connecting to Tailscale")
s := new(tsnet.Server)
s.Hostname = *hostname
defer s.Close()
httpListener, err := s.Listen("tcp", ":80")
if err != nil {
log.Fatal(err)
}
defer httpListener.Close()
httpsListener, err := s.ListenTLS("tcp", ":443")
if err != nil {
log.Fatal(err)
}
defer httpsListener.Close()
lc, err := s.LocalClient()
if err != nil {
log.Fatal(err)
}
// MARK: - device data setup
log.Printf("[4/6] Loading registered devices")
type DeviceData struct {
NodeNameAtRegistration string
ApnsToken string
}
type FcmDeviceData struct {
NodeNameAtRegistration string
FcmToken string
}
type UserData struct {
UsernameAtRegistration string
Devices map[tailcfg.StableNodeID]DeviceData
FcmDevices map[tailcfg.StableNodeID]FcmDeviceData
}
var devices map[tailcfg.UserID]UserData
file, err := os.Open("devices.gob")
if err == nil {
decoder := gob.NewDecoder(file)
err := decoder.Decode(&devices)
if err != nil {
devices = map[tailcfg.UserID]UserData{}
}
file.Close()
} else {
devices = map[tailcfg.UserID]UserData{}
}
for _, userData := range devices {
log.Printf("Loaded user %s", userData.UsernameAtRegistration)
// These nil checks don't appear to work. Whatever
if userData.Devices == nil {
userData.Devices = map[tailcfg.StableNodeID]DeviceData{}
}
for _, deviceData := range userData.Devices {
log.Printf("..loaded device %s for user %s", deviceData.NodeNameAtRegistration, userData.UsernameAtRegistration)
}
if userData.FcmDevices == nil {
userData.FcmDevices = map[tailcfg.StableNodeID]FcmDeviceData{}
}
for _, fcmDeviceData := range userData.FcmDevices {
log.Printf("..loaded FCM device %s for user %s", fcmDeviceData.NodeNameAtRegistration, userData.UsernameAtRegistration)
}
}
interruptChannel := make(chan os.Signal, 1)
signal.Notify(interruptChannel, os.Interrupt, syscall.SIGTERM)
go func() {
<-interruptChannel
file, err := os.Create("devices.gob")
if err != nil {
log.Printf("Unable to create file! err: %s", err.Error())
}
encoder := gob.NewEncoder(file)
encoder.Encode(devices)
file.Close()
os.Exit(0)
}()
// MARK: - route setup
log.Printf("[5/6] Creating routes")
type NotificationContent struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Body string `json:"body"`
}
sendNotification := func(w http.ResponseWriter, uid tailcfg.UserID, nc NotificationContent) {
apnsPayload := payload.NewPayload()
fcmNotification := messaging.Notification{}
if nc.Title != "" {
apnsPayload.AlertTitle(nc.Title)
fcmNotification.Title = nc.Title
}
if nc.Subtitle != "" {
apnsPayload.AlertSubtitle(nc.Subtitle)
}
if nc.Body != "" {
apnsPayload.AlertBody(nc.Body)
fcmNotification.Body = nc.Body
}
apnsPayload.Sound("default").InterruptionLevel(payload.InterruptionLevelTimeSensitive)
// Send to all APNs devices
for _, deviceData := range devices[uid].Devices {
notification := &apns2.Notification{
DeviceToken: deviceData.ApnsToken,
Topic: *bundleID,
Payload: apnsPayload,
}
log.Printf("..sending APNS notification to %s", deviceData.NodeNameAtRegistration)
res, err := apnsClient.Push(notification)
if err != nil {
http.Error(w, err.Error(), 500)
log.Printf("....unrecoverable error: %s", err.Error())
return
}
if !res.Sent() {
log.Printf("....unable to send notification because %s", res.Reason)
// TODO: return error code if all notifications fail?
}
}
// Send to all FCM devices
for _, fcmDeviceData := range devices[uid].FcmDevices {
log.Printf("..sending FCM notification to %s", fcmDeviceData.NodeNameAtRegistration)
message := &messaging.Message{
Notification: &fcmNotification,
Android: &messaging.AndroidConfig{
Priority: "high",
},
Token: fcmDeviceData.FcmToken,
}
_, err := fcmClient.Send(context.Background(), message)
if err != nil {
http.Error(w, err.Error(), 500)
log.Printf("....error: %s", err.Error())
return
}
}
}
mux := http.NewServeMux()
mux.HandleFunc("POST /register", func(w http.ResponseWriter, r *http.Request) {
// Register this device with this Tailscale user
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
log.Printf("Registering device %s for user %s", who.Node.DisplayName(false), who.UserProfile.LoginName)
bytes, err := io.ReadAll(io.Reader(r.Body))
if err != nil {
log.Printf("Unable to extract APNs token from request body")
http.Error(w, err.Error(), 400)
}
apnsToken := string(bytes)
log.Printf("APNs token: '%s'", apnsToken)
if _, ok := devices[who.UserProfile.ID]; !ok {
// First device for this user
devices[who.UserProfile.ID] = UserData{
UsernameAtRegistration: who.UserProfile.LoginName,
Devices: map[tailcfg.StableNodeID]DeviceData{
who.Node.StableID: DeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
ApnsToken: apnsToken,
},
},
FcmDevices: map[tailcfg.StableNodeID]FcmDeviceData{},
}
} else {
if devices[who.UserProfile.ID].Devices == nil {
devs := map[tailcfg.StableNodeID]DeviceData{
who.Node.StableID: DeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
ApnsToken: apnsToken,
},
}
devices[who.UserProfile.ID] = UserData{
UsernameAtRegistration: who.UserProfile.LoginName,
Devices: devs,
FcmDevices: devices[who.UserProfile.ID].FcmDevices,
}
} else {
devices[who.UserProfile.ID].Devices[who.Node.StableID] = DeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
ApnsToken: apnsToken,
}
}
}
})
mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
})
mux.HandleFunc("/registerFCM", func(w http.ResponseWriter, r *http.Request) {
// Register this device with this Tailscale user
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
log.Printf("Registering FCM device %s for user %s", who.Node.DisplayName(false), who.UserProfile.LoginName)
bytes, err := io.ReadAll(io.Reader(r.Body))
if err != nil {
log.Printf("Unable to extract FCM token from request body")
http.Error(w, err.Error(), 400)
}
fcmToken := string(bytes)
log.Printf("FCM token: '%s'", fcmToken)
if _, ok := devices[who.UserProfile.ID]; !ok {
// First device for this user
devices[who.UserProfile.ID] = UserData{
UsernameAtRegistration: who.UserProfile.LoginName,
Devices: map[tailcfg.StableNodeID]DeviceData{},
FcmDevices: map[tailcfg.StableNodeID]FcmDeviceData{
who.Node.StableID: FcmDeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
FcmToken: fcmToken,
},
},
}
} else {
if devices[who.UserProfile.ID].FcmDevices == nil {
devs := map[tailcfg.StableNodeID]FcmDeviceData{
who.Node.StableID: FcmDeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
FcmToken: fcmToken,
},
}
devices[who.UserProfile.ID] = UserData{
UsernameAtRegistration: who.UserProfile.LoginName,
Devices: devices[who.UserProfile.ID].Devices,
FcmDevices: devs,
}
} else {
devices[who.UserProfile.ID].FcmDevices[who.Node.StableID] = FcmDeviceData{
NodeNameAtRegistration: who.Node.DisplayName(false),
FcmToken: fcmToken,
}
}
}
})
mux.HandleFunc("GET /send", func(w http.ResponseWriter, r *http.Request) {
// Send notification
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if r.URL.String() == "/send" {
log.Printf("Request to send simple notification from user %s", who.UserProfile.LoginName)
nc := NotificationContent{
Body: fmt.Sprintf("Notification triggered by %s", who.Node.DisplayName(false)),
}
sendNotification(w, who.UserProfile.ID, nc)
return
}
log.Printf("Request to send GET notification with data from user %s", who.UserProfile.LoginName)
params, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
nc := NotificationContent{}
if len(params["title"]) > 0 {
nc.Title = params["title"][0]
}
if len(params["subtitle"]) > 0 {
nc.Subtitle = params["subtitle"][0]
}
if len(params["body"]) > 0 {
nc.Body = params["body"][0]
}
if nc.Title == "" && nc.Body == "" {
// This notification would have no content
log.Printf("..notification has none of: title, body")
http.Error(w, "Notification must have content", 400)
return
}
sendNotification(w, who.UserProfile.ID, nc)
})
mux.HandleFunc("POST /send", func(w http.ResponseWriter, r *http.Request) {
// Send notification to APNs
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
log.Printf("Request to send notification with data from user %s", who.UserProfile.LoginName)
err = r.ParseForm()
if err != nil {
http.Error(w, err.Error(), 400)
return
}
nc := NotificationContent{}
if len(r.Form["title"]) > 0 {
nc.Title = r.Form["title"][0]
}
if len(r.Form["subtitle"]) > 0 {
nc.Subtitle = r.Form["subtitle"][0]
}
if len(r.Form["body"]) > 0 {
nc.Body = r.Form["body"][0]
}
if nc.Title == "" && nc.Body == "" {
// This notification would have no content
log.Printf("..notification has none of: title, body")
http.Error(w, "Notification must have content", 400)
return
}
sendNotification(w, who.UserProfile.ID, nc)
})
mux.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
})
mux.HandleFunc("POST /sendJSON", func(w http.ResponseWriter, r *http.Request) {
// Send notification to APNs
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
log.Printf("Request to send notification with JSON from user %s", who.UserProfile.LoginName)
var nc NotificationContent
err = json.NewDecoder(r.Body).Decode(&nc)
if err != nil {
log.Printf("..invalid JSON")
http.Error(w, err.Error(), 400)
return
}
if nc.Title == "" && nc.Body == "" {
// This notification would have no content
log.Printf("..notification has none of: title, body")
http.Error(w, "Notification must have content", 400)
return
}
sendNotification(w, who.UserProfile.ID, nc)
})
mux.HandleFunc("/sendJSON", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
})
// TODO: Potential future endpoints to eliminate notifications when viewed on other devices
// https://stackoverflow.com/questions/34549453/how-to-sync-push-notifications-across-multiple-ios-devices
// MARK: - run
log.Printf("[6/6] Launching server")
go func() {
log.Printf("HTTP listener exited with error: %s", http.Serve(httpListener, mux).Error())
}()
log.Fatalf("HTTPS listener exited with error: %s", http.Serve(httpsListener, mux).Error())
}