summary refs log tree commit diff
path: root/src/web/routes/link.test.js
blob: e8473f85ffc979ffb8768672e83ab4666b185a14 (plain) (blame)
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// @ts-check

const tryToCatch = require("try-to-catch")
const {router, test} = require("../../../test/web")
const {MatrixServerError} = require("../../matrix/mreq")
const {select, db} = require("../../passthrough")
const assert = require("assert").strict

test("web link space: access denied when not logged in to Discord", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Can't edit a guild you don't have Manage Server permissions in")
})

test("web link space: access denied when not logged in to Matrix", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Can't link with your Matrix space if you aren't logged in to Matrix")
})

test("web link space: access denied when bot was invited by different user", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@user:example.org"
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "You personally must invite OOYE to that space on Matrix")
})

test("web link space: access denied when guild is already in use", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["112760669178241024"],
			mxid: "@cadence:cadence.moe"
		},
		body: {
			space_id: "!jjmvBegULiLucuWEHU:cadence.moe",
			guild_id: "112760669178241024"
		}
	}))
	t.equal(error.data, "Guild ID 112760669178241024 or space ID !jjmvBegULiLucuWEHU:cadence.moe are already bridged and cannot be reused")
})

test("web link space: check that OOYE is joined", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@cadence:cadence.moe"
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				throw new MatrixServerError({errcode: "M_FORBIDDEN", error: "not allowed to join I guess"})
			}
		}
	}))
	t.equal(error.data, "Unable to join the requested Matrix space. Please invite the bridge to the space and try again. (Server said: M_FORBIDDEN - not allowed to join I guess)")
	t.equal(called, 1)
})

test("web link space: check that OOYE has PL 100 (not 50)", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@cadence:cadence.moe"
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				return roomID
			},
			async getStateEvent(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.power_levels")
				t.equal(key, "")
				return {users: {"@_ooye_bot:cadence.moe": 50}}
			},
			async getStateEventOuter(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@creator:cadence.moe",
					room_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "11"
					}
				}
			}
		}
	}))
	t.equal(error.data, "OOYE needs power level 100 (admin) in the target Matrix space")
	t.equal(called, 3)
})

test("web link space: check that inviting user has PL 50", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@cadence:cadence.moe"
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				return roomID
			},
			async getStateEvent(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.power_levels")
				t.equal(key, "")
				return {users: {"@_ooye_bot:cadence.moe": 100}, events: {"m.room.tombstone": 150}}
			},
			async getStateEventOuter(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@creator:cadence.moe",
					room_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "12"
					}
				}
			}
		}
	}))
	t.equal(error.data, "You need to be at least power level 50 (moderator) in the target Matrix space to set up OOYE, but you are currently power level 0.")
	t.equal(called, 3)
})

test("web link space: successfully adds entry to database and loads page", async t => {
	let called = 0
	await router.test("post", "/api/link-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@cadence:cadence.moe"
		},
		body: {
			space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				return roomID
			},
			async getStateEvent(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.power_levels")
				t.equal(key, "")
				return {users: {"@cadence:cadence.moe": 50}}
			},
			async getStateEventOuter(roomID, type, key) {
				called++
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@_ooye_bot:cadence.moe",
					room_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "12"
					}
				}
			}
		}
	})
	t.equal(called, 3)

	// check that the entry was added to the database
	t.equal(select("guild_space", "privacy_level", {guild_id: "665289423482519565", space_id: "!zTMspHVUBhFLLSdmnS:cadence.moe"}).pluck().get(), 0)

	// check that the guild info page now loads
	const html = await router.test("get", "/guild?guild_id=665289423482519565", {
		sessionData: {
			managedGuilds: ["665289423482519565"],
			mxid: "@cadence:cadence.moe"
		},
		api: {
			async getFullHierarchy(spaceID) {
				return []
			}
		}
	})
	t.has(html, `<h1 class="s-page-title--header">Data Horde</h1>`)
})

// *****

test("web link room: access denied when not logged in to Discord", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Can't edit a guild you don't have Manage Server permissions in")
})

test("web link room: check that guild exists", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["1"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "1"
		}
	}))
	t.equal(error.data, "Discord guild does not exist or bot has not joined it")
})

test("web link room: check that channel exists", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "1",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Discord channel does not exist")
})

test("web link room: check that channel is part of guild", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "112760669178241024",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Channel ID 112760669178241024 is not part of guild 665289423482519565")
})

test("web link room: check that channel is not already linked", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["112760669178241024"]
		},
		body: {
			discord: "112760669178241024",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "112760669178241024"
		}
	}))
	t.equal(error.data, "Channel ID 112760669178241024 or room ID !NDbIqNpJyPvfKRnNcr:cadence.moe are already bridged and cannot be reused")
})

test("web link room: checks the autocreate setting if the space doesn't exist yet", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		createSpace: {
			async ensureSpace(guild) {
				called++
				t.equal(guild.id, "665289423482519565")
				// simulate what ensureSpace is intended to check
				const autocreate = 0
				assert.equal(autocreate, 1, "refusing to implicitly create a space for guild 665289423482519565. set the guild_active data first before calling ensureSpace/syncSpace.")
				return ""
			}
		}
	}))
	t.match(error.message, /refusing to implicitly create a space/)
	t.equal(called, 1)
})

test("web link room: check that room is part of space (not in hierarchy)", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async *generateFullHierarchy(spaceID) {
				called++
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
			}
		}
	}))
	t.equal(error.data, "Matrix room needs to be part of the bridged space")
	t.equal(called, 1)
})

test("web link room: check that bridge can join room (notices lack of via and asks for invite instead)", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				throw new MatrixServerError({errcode: "M_FORBIDDEN", error: "not allowed to join I guess"})
			},
			async *generateFullHierarchy(spaceID) {
				called++
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			}
		}
	}))
	t.equal(error.data, "Unable to join the requested Matrix room. Please invite the bridge to the room and try again. (Server said: M_FORBIDDEN - not allowed to join I guess)")
	t.equal(called, 2)
})

test("web link room: check that bridge can join room (uses via for join attempt)", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID, _, via) {
				called++
				t.deepEqual(via, ["cadence.moe", "hashi.re"])
				throw new MatrixServerError({errcode: "M_FORBIDDEN", error: "not allowed to join I guess"})
			},
			async *generateFullHierarchy(spaceID) {
				called++
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				yield {
					room_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
					children_state: [{
						type: "m.space.child",
						state_key: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
						sender: "@elliu:hashi.re",
						content: {
							via: ["cadence.moe", "hashi.re"]
						},
						origin_server_ts: 0
					}],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			}
		}
	}))
	t.equal(error.data, "M_FORBIDDEN - not allowed to join I guess")
	t.equal(called, 2)
})

test("web link room: check that bridge has PL 100 in target room", async t => {
	let called = 0
	const [error] = await tryToCatch(() => router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				return roomID
			},
			async *generateFullHierarchy(spaceID) {
				called++
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			},
			async getStateEvent(roomID, type, key) {
				called++
				t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
				t.equal(type, "m.room.power_levels")
				t.equal(key, "")
				return {users_default: 50}
			},
			async getStateEventOuter(roomID, type, key) {
				called++
				t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@creator:cadence.moe",
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "11"
					}
				}
			}
		}
	}))
	t.equal(error.data, "OOYE needs power level 100 (admin) in the target Matrix room")
	t.equal(called, 4)
})

test("web link room: successfully calls createRoom", async t => {
	let called = 0
	await router.test("post", "/api/link", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			discord: "665310973967597573",
			matrix: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
			guild_id: "665289423482519565"
		},
		api: {
			async joinRoom(roomID) {
				called++
				return roomID
			},
			async *generateFullHierarchy(spaceID) {
				called++
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			},
			async getStateEvent(roomID, type, key) {
				if (type === "m.room.power_levels") {
					called++
					t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
					t.equal(key, "")
					return {users: {"@_ooye_bot:cadence.moe": 100}}
				} else if (type === "m.room.name") {
					called++
					t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
					return {}
				} else if (type === "m.room.avatar") {
					called++
					t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
					return {}
				} else if (type === "m.room.topic") {
					called++
					t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
					return {}
				}
			},
			async getStateEventOuter(roomID, type, key) {
				called++
				t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@creator:cadence.moe",
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "11"
					}
				}
			},
			async sendEvent(roomID, type, content) {
				called++
				t.equal(roomID, "!NDbIqNpJyPvfKRnNcr:cadence.moe")
				t.equal(type, "m.room.message")
				t.match(content.body, /👋/)
				return ""
			}
		},
		createRoom: {
			async syncRoom(channelID) {
				called++
				t.equal(channelID, "665310973967597573")
				return "!NDbIqNpJyPvfKRnNcr:cadence.moe"
			}
		}
	})
	t.equal(called, 9)
})

// *****

test("web unlink room: access denied if not logged in to Discord", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/unlink", {
		body: {
			channel_id: "665310973967597573",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Can't edit a guild you don't have Manage Server permissions in")
})

test("web unlink room: checks that guild exists", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/unlink", {
		sessionData: {
			managedGuilds: ["2"]
		},
		body: {
			channel_id: "665310973967597573",
			guild_id: "2"
		}
	}))
	t.equal(error.data, "Discord guild does not exist or bot has not joined it")
})

test("web unlink room: checks that the channel is part of the guild", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/unlink", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			channel_id: "112760669178241024",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Channel ID 112760669178241024 is not part of guild 665289423482519565")
})

test("web unlink room: successfully calls unbridgeChannel when the channel does exist", async t => {
	let called = 0
	await router.test("post", "/api/unlink", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			channel_id: "665310973967597573",
			guild_id: "665289423482519565"
		},
		createRoom: {
			async unbridgeChannel(channel) {
				called++
				t.equal(channel.id, "665310973967597573")
			}
		}
	})
	t.equal(called, 1)
})

test("web unlink room: successfully calls unbridgeChannel when the channel does not exist", async t => {
	let called = 0
	await router.test("post", "/api/unlink", {
		sessionData: {
			managedGuilds: ["112760669178241024"]
		},
		body: {
			channel_id: "489237891895768942",
			guild_id: "112760669178241024"
		},
		createRoom: {
			async unbridgeChannel(channel) {
				called++
				t.equal(channel.id, "489237891895768942")
			}
		}
	})
	t.equal(called, 1)
})

test("web unlink room: checks that the channel is bridged", async t => {
	const row = db.prepare("SELECT * FROM channel_room WHERE channel_id = '665310973967597573'").get()
	db.prepare("DELETE FROM channel_room WHERE channel_id = '665310973967597573'").run()

	const [error] = await tryToCatch(() => router.test("post", "/api/unlink", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			channel_id: "665310973967597573",
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Channel ID 665310973967597573 is not currently bridged")

	db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id, custom_topic) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(row.channel_id, row.room_id, row.name, row.nick, row.thread_parent, row.custom_avatar, row.last_bridged_pin_timestamp, row.speedbump_id, row.speedbump_checked, row.speedbump_webhook_id, row.guild_id, row.custom_topic)
	const new_row = db.prepare("SELECT * FROM channel_room WHERE channel_id = '665310973967597573'").get()
	t.deepEqual(row, new_row)
})

// *****

test("web unlink space: access denied if not logged in to Discord", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/unlink-space", {
		body: {
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Can't edit a guild you don't have Manage Server permissions in")
})

test("web unlink space: checks that guild exists", async t => {
	const [error] = await tryToCatch(() => router.test("post", "/api/unlink-space", {
		sessionData: {
			managedGuilds: ["2"]
		},
		body: {
			guild_id: "2"
		}
	}))
	t.equal(error.data, "Discord guild does not exist or bot has not joined it")
})

test("web unlink space: checks that a space is linked to the guild before trying to unlink the space", async t => {
	db.exec("BEGIN TRANSACTION")
	db.prepare("DELETE FROM guild_active WHERE guild_id = '665289423482519565'").run()

	const [error] = await tryToCatch(() => router.test("post", "/api/unlink-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			guild_id: "665289423482519565"
		}
	}))
	t.equal(error.data, "Discord guild has not been considered for bridging")

	db.exec("ROLLBACK") // ぬ
})

test("web unlink space: correctly abort unlinking if some linked channels remain after trying to unlink them all", async t => {
	let unbridgedChannel = false

	const [error] = await tryToCatch(() => router.test("post", "/api/unlink-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			guild_id: "665289423482519565",
		},
		createRoom: {
			async unbridgeChannel(channel, guildID) {
				unbridgedChannel = true
				t.ok(["1438284564815548418", "665310973967597573"].includes(channel.id))
				t.equal(guildID, "665289423482519565")
				// Do not actually delete the link from DB, should trigger error later in check
			}
		},
		api: {
			async *generateFullHierarchy(spaceID) {
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			},
		}
	}))

	t.equal(error.data, "Failed to unlink some rooms. Please try doing it manually, or report a bug. The space will not be unlinked until all rooms are.")
	t.equal(unbridgedChannel, true)
})

test("web unlink space: successfully calls unbridgeChannel on linked channels in space, self-downgrade power level, leave space, and delete link from DB", async t => {
	const {reg} = require("../../matrix/read-registration")
	const me = `@${reg.sender_localpart}:${reg.ooye.server_name}`

	const getLinkRowQuery = "SELECT * FROM guild_space WHERE guild_id = '665289423482519565'"

	const row = db.prepare(getLinkRowQuery).get()
	t.equal(row.space_id, "!zTMspHVUBhFLLSdmnS:cadence.moe")

	let unbridgedChannel = false
	let downgradedPowerLevel = false
	let leftRoom = false
	await router.test("post", "/api/unlink-space", {
		sessionData: {
			managedGuilds: ["665289423482519565"]
		},
		body: {
			guild_id: "665289423482519565",
		},
		createRoom: {
			async unbridgeChannel(channel, guildID) {
				unbridgedChannel = true
				t.ok(["1438284564815548418", "665310973967597573"].includes(channel.id))
				t.equal(guildID, "665289423482519565")

				// In order to not simulate channel deletion and not trigger the post unlink channels, pre-unlink space check
				db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(channel.id)
			}
		},
		snow: {
			user: {
				// @ts-ignore - snowtransfer or discord-api-types broken, 204 No Content should be mapped to void but is actually mapped to never
				async leaveGuild(guildID) {
					t.equal(guildID, "665289423482519565")
				}
			}
		},
		api: {
			async *generateFullHierarchy(spaceID) {
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				yield {
					room_id: "!NDbIqNpJyPvfKRnNcr:cadence.moe",
					children_state: [],
					guest_can_join: false,
					num_joined_members: 2
				}
				/* c8 ignore next */
			},

			async getStateEvent(roomID, type, key) { // getting power levels from space to apply to room
				t.equal(type, "m.room.power_levels")
				t.equal(key, "")
				return {users: {"@_ooye_bot:cadence.moe": 100, "@example:matrix.org": 50}, events: {"m.room.tombstone": 100}}
			},

			async getStateEventOuter(roomID, type, key) {
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.create")
				t.equal(key, "")
				return {
					type: "m.room.create",
					state_key: "",
					sender: "@_ooye_bot:cadence.moe",
					room_id: "!zTMspHVUBhFLLSdmnS:cadence.moe",
					event_id: "$create",
					origin_server_ts: 0,
					content: {
						room_version: "11"
					}
				}
			},

			async sendState(roomID, type, key, content) {
				downgradedPowerLevel = true
				t.equal(roomID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
				t.equal(type, "m.room.power_levels")
				t.notOk(me in content.users, `got ${JSON.stringify(content)} but expected bot user to not be present`)
				return ""
			},

			async leaveRoom(spaceID) {
				leftRoom = true
				t.equal(spaceID, "!zTMspHVUBhFLLSdmnS:cadence.moe")
			},
		}
	})

	t.equal(unbridgedChannel, true)
	t.equal(downgradedPowerLevel, true)
	t.equal(leftRoom, true)

	const missed_row = db.prepare(getLinkRowQuery).get()
	t.equal(missed_row, undefined)
})