~singpolyma/cheogram

cheogram/Main.hs -rw-r--r-- 121.2 KiB
9b9e950eStephen Paul Weber block a few more spam patterns 3 days ago
                                                                                
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NamedFieldPuns #-}
import Prelude (show, read)
import BasicPrelude hiding (show, read, forM, mapM, forM_, mapM_, getArgs, log)
import System.IO (stdout, stderr, hSetBuffering, BufferMode(LineBuffering))
import Data.Char
import Control.Concurrent
import Control.Concurrent.STM
import Data.Foldable (forM_, mapM_, toList)
import Data.Traversable (forM, mapM)
import System.Directory (getFileSize)
import System.Environment (getArgs)
import System.Exit (die)
import Control.Error (readZ, MaybeT(..), hoistMaybe, headZ, justZ, hush, atZ, rightZ)
import Data.Time (UTCTime, addUTCTime, diffUTCTime, getCurrentTime)
import Network.Socket (PortNumber)
import Network.URI (parseURI, uriPath, escapeURIString, isUnescapedInURI)
import System.Random (Random(randomR), getStdRandom)
import System.Random.Shuffle (shuffleM)
import Data.Digest.Pure.SHA (sha1, bytestringDigest, showDigest)
import Network.StatsD (openStatsD)
import qualified Network.StatsD as StatsD
import Magic (Magic, MagicFlag(MagicMimeType), magicOpen, magicLoadDefault, magicFile)
import Network.Mime (defaultMimeMap)
import Crypto.Hash (Digest, SHA1, SHA256, SHA512)

import "monads-tf" Control.Monad.Error (catchError) -- ick
import Data.XML.Types as XML (Element(..), Node(NodeContent, NodeElement), Content(ContentText), isNamed, hasAttributeText, elementText, elementChildren, attributeText, attributeContent, hasAttribute, nameNamespace)
import UnexceptionalIO (Unexceptional, UIO)
import qualified UnexceptionalIO as UIO
import qualified Data.ByteArray as ByteArray
import qualified Dhall
import qualified Jingle
import qualified Jingle.StoreChunks as Jingle
import qualified Codec.Picture as Picture
import qualified Codec.Picture.Blurhash as Blurhash
import qualified Data.CaseInsensitive as CI
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Map as Map
import qualified Data.Map.Strict as SMap
import qualified Data.UUID as UUID ( toString, toText )
import qualified Data.UUID.V1 as UUID ( nextUUID )
import qualified Data.ByteString.Lazy as LZ
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Builder as Builder
import qualified Database.Redis as Redis
import qualified Data.Bool.HT as HT
import qualified Text.Regex.PCRE.Light as PCRE
import qualified Network.Http.Client as HTTP
import qualified System.IO.Streams as Streams
import Network.Protocol.XMPP as XMPP -- should import qualified

import Util
import IQManager
import qualified ConfigureDirectMessageRoute
import qualified JidSwitch
import qualified Config
import qualified DB
import qualified Tapback
import qualified VCard4
import Adhoc (adhocBotSession, commandList, queryCommandList)
import StanzaRec

instance Ord JID where
	compare x y = compare (show x) (show y)

-- Do not use uncommon file extensions for ambiguous MIME types
badExts :: [Text]
badExts = [
		s"mpg4", s"mp4v",
		s"mpga", s"m2a", s"m3a", s"mp2", s"mp2a",
		s"m1v", s"m2v", s"mpe"
	]

mimeToExtMap :: SMap.Map String Text
mimeToExtMap = SMap.fromList $
	(\xs -> ("audio/amr", s"amr") : ("audio/AMR", s"amr") : xs) $
	mapMaybe (\(ext, mimeBytes) ->
		if ext `elem` badExts then
			Nothing
		else
			Just (textToString (decodeUtf8 mimeBytes), ext)
	) $ SMap.toList defaultMimeMap

queryDisco to from = (:[]) . mkStanzaRec <$> queryDiscoWithNode Nothing to from

queryDiscoWithNode node to from = do
	uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
	return $ (queryDiscoWithNode' node to from) {
		iqID = uuid
	}

fillFormField var value form = form {
		elementNodes = map (\node ->
			case node of
				NodeElement el
					| elementName el == fromString "{jabber:x:data}field" &&
					  (attributeText (fromString "{jabber:x:data}var") el == Just var ||
					  attributeText (fromString "var") el == Just var) ->
						NodeElement $ el { elementNodes = [
							NodeElement $ Element (fromString "{jabber:x:data}value") []
								[NodeContent $ ContentText value]
						]}
				x -> x
		) (elementNodes form)
	}

data Invite = Invite {
	inviteMUC :: JID,
	inviteFrom :: JID,
	inviteText :: Maybe Text,
	invitePassword :: Maybe Text
} deriving (Show)

getMediatedInvitation m = do
	from <- messageFrom m
	x <- listToMaybe $ isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< messagePayloads m
	invite <- listToMaybe $ isNamed (fromString "{http://jabber.org/protocol/muc#user}invite") =<< elementChildren x
	inviteFrom <- parseJID =<< attributeText (fromString "from") invite
	return Invite {
		inviteMUC = from,
		inviteFrom = inviteFrom,
		inviteText = do
			txt <- mconcat . elementText <$> listToMaybe
				(isNamed (fromString "{http://jabber.org/protocol/muc#user}reason") =<< elementChildren invite)
			guard (not $ T.null txt)
			return txt,
		invitePassword =
			mconcat . elementText <$> listToMaybe
			(isNamed (fromString "{http://jabber.org/protocol/muc#user}password") =<< elementChildren x)
	}

getDirectInvitation m = do
	x <- listToMaybe $ isNamed (fromString "{jabber:x:conference}x") =<< messagePayloads m
	Invite <$>
		(parseJID =<< attributeText (fromString "jid") x) <*>
		messageFrom m <*>
		Just (do
			txt <- attributeText (fromString "reason") x
			guard (not $ T.null txt)
			return txt
		) <*>
		Just (attributeText (fromString "password") x)

nickFor db componentJid jid existingRoom
	| fmap bareTxt existingRoom == Just bareFrom = return $ fromMaybe (s"nonick") resourceFrom
	| jidDomain componentJid == jidDomain jid,
	  Just tel <- mfilter isE164 (strNode <$> jidNode jid) = do
		mnick <- DB.get db (DB.byNode jid ["nick"])
		case mnick of
			Just nick -> return (tel <> s" \"" <> nick <> s"\"")
			Nothing -> return tel
	| otherwise = return bareFrom
	where
	bareFrom = bareTxt jid
	resourceFrom = strResource <$> jidResource jid

code str status =
	hasAttributeText (fromString "{http://jabber.org/protocol/muc#user}code") (== fromString str) status
	<>
	hasAttributeText (fromString "code") (== fromString str) status

-- When we're talking to the adhoc bot we'll get a command from stuff\40example.com@cheogram.com
-- When they're talking to us directly, we'll get the command from stuff@example.com
-- In either case, we want to use the same key and understand it as coming from the same user
maybeUnescape componentJid userJid
	| jidDomain userJid == jidDomain componentJid,
	  Just node <- jidNode userJid =
		let resource = maybe mempty strResource $ jidResource userJid
		in
		-- If we can't parse the thing we unescaped, just return the original
		fromMaybe userJid $ parseJID (unescapeJid (strNode node) ++ if T.null resource then mempty else s"/" ++ resource)
	| otherwise = userJid

cheogramDiscoInfo db componentJid sendIQ from q = do
	canVoice <- isJust <$> getSipProxy db componentJid sendIQ from
	return $ Element (s"{http://jabber.org/protocol/disco#info}query")
		(map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [ContentText node])) $ maybeToList $ nodeAttribute =<< q)
		(catMaybes [
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [
				(s"category", [ContentText $ s"gateway"]),
				(s"type", [ContentText $ s"sms"]),
				(s"name", [ContentText $ s"Cheogram"])
				] [],
			mfilter (const canVoice) $ Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [
				(s"category", [ContentText $ s"gateway"]),
				(s"type", [ContentText $ s"pstn"]),
				(s"name", [ContentText $ s"Cheogram"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"http://jabber.org/protocol/commands"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"jabber:iq:gateway"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"jabber:iq:register"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"urn:xmpp:ping"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"vcard-temp"])
			] [],
			Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [
				(s"var", [ContentText $ s"http://jabber.org/protocol/address"])
			] []
		])

cheogramAvailable db componentJid sendIQ from to = do
	disco <- cheogramDiscoInfo db componentJid sendIQ to Nothing
	let ver = T.decodeUtf8 $ Base64.encode $ discoToCapsHash disco
	return $ (emptyPresence PresenceAvailable) {
			presenceTo = Just to,
			presenceFrom = Just from,
			presencePayloads = [
				Element (s"{http://jabber.org/protocol/caps}c") [
					(s"{http://jabber.org/protocol/caps}hash", [ContentText $ fromString "sha-1"]),
					(s"{http://jabber.org/protocol/caps}node", [ContentText $ fromString "xmpp:cheogram.com"]),
					(s"{http://jabber.org/protocol/caps}ver", [ContentText ver])
				] []
			]
		}

telDiscoFeatures = [
		s"http://jabber.org/protocol/muc",
		s"jabber:x:conference",
		s"urn:xmpp:ping",
		s"urn:xmpp:receipts",
		s"vcard-temp",
		s"urn:xmpp:jingle:1",
		s"urn:xmpp:jingle:apps:file-transfer:3",
		s"urn:xmpp:jingle:apps:file-transfer:5",
		s"urn:xmpp:jingle:transports:s5b:1",
		s"urn:xmpp:jingle:transports:ibb:1"
	]

getSipProxy :: DB.DB -> JID -> (IQ -> UIO (STM (Maybe IQ))) -> JID -> IO (Maybe Text)
getSipProxy db componentJid sendIQ jid = do
	maybeProxy <- DB.get db (DB.byJid jid ["sip-proxy"])
	case maybeProxy of
		Just proxy -> return $ Just proxy
		Nothing ->
			(extractSip =<<) <$> routeQueryStateful db componentJid sendIQ jid Nothing query
	where
	query jidTo jidFrom = return $ (emptyIQ IQGet) {
			iqTo = Just jidTo,
			iqFrom = Just jidFrom,
			iqPayload = Just $ XML.Element (s"{urn:xmpp:extdisco:2}services") [
				(s"type", [XML.ContentText $ s"sip"])
			] []
		}
	extractSip (IQ { iqPayload = payload }) =
		headZ $
		(mapMaybe (attributeText (s"host")) $
		filter (\el -> attributeText (s"type") el == Just (s"sip")) $
		isNamed (s"{urn:xmpp:extdisco:2}service") =<<
		elementChildren =<< (justZ payload))

getTelFeatures db componentJid sendIQ jid = do
	maybeProxy <- getSipProxy db componentJid sendIQ jid
	log "TELFEATURES" (jid, maybeProxy)
	return $ maybe [] (const $ [s"urn:xmpp:jingle:transports:ice-udp:1", s"urn:xmpp:jingle:apps:dtls:0", s"urn:xmpp:jingle:apps:rtp:1", s"urn:xmpp:jingle:apps:rtp:audio", s"urn:xmpp:jingle-message:0"]) maybeProxy

telCapsStr extraVars =
	s"client/sms//Cheogram<" ++ mconcat (intersperse (s"<") (sort (nub (telDiscoFeatures ++ extraVars)))) ++ s"<"

telAvailable from to disco =
	(emptyPresence PresenceAvailable) {
		presenceTo = Just to,
		presenceFrom = Just fromWithResource,
		presencePayloads = [
			Element (s"{http://jabber.org/protocol/caps}c") [
				(s"{http://jabber.org/protocol/caps}hash", [ContentText $ fromString "sha-1"]),
				(s"{http://jabber.org/protocol/caps}node", [ContentText $ fromString "xmpp:cheogram.com"]),
				(s"{http://jabber.org/protocol/caps}ver", [ContentText hash])
			] []
		]
	}
	where
	fromWithResource
		| Nothing <- jidResource from,
		  Just newFrom <- parseJID (bareTxt from ++ s"/tel") = newFrom
		| otherwise = from
	hash = T.decodeUtf8 $ Base64.encode $ LZ.toStrict $ bytestringDigest $ sha1 $ LZ.fromStrict $ T.encodeUtf8 $ telCapsStr disco

nodeAttribute el =
	attributeText (s"{http://jabber.org/protocol/disco#info}node") el <|>
	attributeText (s"node") el

telDiscoInfo q id from to disco =
	(emptyIQ IQResult) {
		iqTo = Just to,
		iqFrom = Just from,
		iqID = Just id,
		iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/disco#info}query")
			(map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [ContentText node])) $ maybeToList $ nodeAttribute q) $
			[
				NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [
					(s"{http://jabber.org/protocol/disco#info}category", [ContentText $ s"client"]),
					(s"{http://jabber.org/protocol/disco#info}type", [ContentText $ s"sms"]),
					(s"{http://jabber.org/protocol/disco#info}name", [ContentText $ s"Cheogram"])
				] []
			] ++ map (\var ->
				NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
					(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText var])
				] []
			) (sort $ nub $ telDiscoFeatures ++ disco)
	}

routeQueryOrReply db componentJid from smsJid resource query reply = do
	maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"])
	case (maybeRoute, maybeRouteFrom) of
		(Just route, Just routeFrom) ->
				let routeTo = fromMaybe componentJid $ parseJID $ (maybe mempty (++ s"@") $ strNode <$> jidNode smsJid) ++ route in
				query routeTo routeFrom
		_ -> return [mkStanzaRec $ reply]
	where
	maybeRouteFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/" ++ (fromString resource)

routeQueryStateful db componentJid sendIQ from targetNode query = hasLocked "routeQueryStateful" $ do
	maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"])
	case (maybeRoute, maybeRouteFrom) of
		(Just route, Just routeFrom) -> do
			let Just routeTo = parseJID $ (maybe mempty (++ s"@") $ strNode <$> targetNode) ++ route
			iqToSend <- query routeTo routeFrom
			result <- atomicUIO =<< UIO.lift (sendIQ iqToSend)
			return $ mfilter ((==IQResult) . iqType) result
		_ -> return Nothing
	where
	maybeRouteFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/IQMANAGER"

routeDiscoStateful db componentJid sendIQ from targetNode node =
	routeQueryStateful db componentJid sendIQ from targetNode (queryDiscoWithNode node)

routeDiscoOrReply db componentJid from smsJid resource node reply =
	routeQueryOrReply db componentJid from smsJid resource (fmap (pure . mkStanzaRec) .: queryDiscoWithNode node) reply

deliveryReceipt id from to =
	(emptyMessage MessageNormal) {
		messageFrom = Just from,
		messageTo = Just to,
		messagePayloads = [
			Element (s"{urn:xmpp:receipts}received")
				[(s"{urn:xmpp:receipts}id", [ContentText id])] []
		]
	}

iqNotImplemented iq =
	iq {
		iqTo = iqFrom iq,
		iqFrom = iqTo iq,
		iqType = IQError,
		iqPayload = Just $ Element (s"{jabber:component:accept}error")
			[(s"{jabber:component:accept}type", [ContentText $ fromString "cancel"])]
			[NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}feature-not-implemented") [] []]
	}

stripOptionalSuffix suffix text =
	fromMaybe text $ T.stripSuffix suffix text

-- https://otr.cypherpunks.ca/Protocol-v3-4.0.0.html
stripOtrWhitespaceOnce body =
	foldl' (\body' suffix -> stripOptionalSuffix suffix body') body [
		s"\x20\x20\x09\x09\x20\x20\x09\x09",
		s"\x20\x20\x09\x09\x20\x20\x09\x20",
		s"\x20\x09\x20\x09\x20\x20\x09\x20",
		s"\x20\x09\x20\x20\x09\x09\x09\x09",
		s"\x20\x09\x20\x09\x20\x09\x20\x20"
	]

stripOtrWhitespace = stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce

mapBody f (m@Message { messagePayloads = payloads }) =
	m { messagePayloads =
		map (\payload ->
			case isNamed (s"{jabber:component:accept}body") payload of
				[] -> payload
				_ -> payload { elementNodes = [NodeContent $ ContentText $ f (concat (elementText payload))] }
		) payloads
	}

deleteDirectMessageRoute db userJid = do
	DB.del db (DB.byJid userJid ["direct-message-route"])
	mcheoJid <- fmap (parseJID =<<) $ DB.get db (DB.byJid userJid ["cheoJid"])
	forM_ mcheoJid $ \cheoJid -> do
		DB.del db (DB.byJid userJid ["cheoJid"])
		DB.srem db (DB.byNode cheoJid ["owners"]) [bareTxt userJid]

unregisterDirectMessageRoute db componentJid userJid route = do
	maybeCheoJid <- (parseJID =<<) <$> DB.get db (DB.byJid userJid ["cheoJid"])
	forM_ maybeCheoJid $ \cheoJid -> do
		DB.del db (DB.byJid userJid ["cheoJid"])
		DB.srem db (DB.byNode cheoJid ["owners"]) [bareTxt userJid]

	uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
	return $ (emptyIQ IQSet) {
			iqTo = Just route,
			iqFrom = parseJID $ escapeJid (bareTxt userJid) ++ s"@" ++ formatJID componentJid ++ s"/CHEOGRAM%removed",
			iqID = uuid,
			iqPayload = Just $ Element (s"{jabber:iq:register}query") [] [
				NodeElement $ Element (s"{jabber:iq:register}remove") [] []
			]
		}

toRouteOrFallback db componentJid from smsJid m fallback = do
	maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"])
	case (maybeRoute, parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ resourceSuffix) of
		(Just route, Just routeFrom) -> do
			return [mkStanzaRec $ m {
				messageFrom = Just routeFrom,
				messageTo = parseJID $ (fromMaybe mempty $ strNode <$> jidNode smsJid) ++ s"@" ++ route
			}]
		_ -> fallback
	where
	resourceSuffix = maybe mempty (s"/"++) (strResource <$> jidResource from)

componentMessage db componentJid (m@Message { messageType = MessageError }) _ from smsJid body = do
	log "MESSAGE ERROR"  m
	toRouteOrFallback db componentJid from smsJid m $ do
		log "DIRECT FROM GATEWAY" smsJid
		return [mkStanzaRec $ m { messageTo = Just smsJid, messageFrom = Just componentJid }]
componentMessage db componentJid m@(Message { messageTo = Just to@JID{ jidNode = Just _ } }) existingRoom _ smsJid _
	| Just invite <- getMediatedInvitation m <|> getDirectInvitation m = do
		forM_ (invitePassword invite) $ \password ->
			DB.set db (DB.byNode to [textToString $ formatJID $ inviteMUC invite, "muc_roomsecret"]) password
		existingInvite <- (parseJID =<<) <$> DB.get db (DB.byNode to ["invited"])
		nick <- nickFor db componentJid (inviteFrom invite) existingRoom
		let txt = mconcat [
				fromString "* ",
				nick,
				fromString " has invited you to a group",
				maybe mempty (\t -> fromString ", saying \"" <> t <> fromString "\"") (inviteText invite),
				fromString "\nYou can switch to this group by replying with /join"
			]
		if (existingRoom /= Just (inviteMUC invite) && existingInvite /= Just (inviteMUC invite)) then do
			DB.set db (DB.byNode to ["invited"]) (formatJID $ inviteMUC invite)
			regJid <- (parseJID =<<) <$> DB.get db (DB.byNode to ["registered"])
			fmap (((mkStanzaRec $ mkSMS componentJid smsJid txt):) . concat . toList)
				(forM regJid $ \jid -> sendInvite db jid (invite { inviteFrom = to }))
		else
			return []
componentMessage _ componentJid (m@Message { messageType = MessageGroupChat }) existingRoom from smsJid (Just body) = do
	if fmap bareTxt existingRoom == Just (bareTxt from) && (
	   existingRoom /= Just from ||
	   not (fromString "CHEOGRAM%" `T.isPrefixOf` fromMaybe mempty (messageID m))) then
		return [mkStanzaRec $ mkSMS componentJid smsJid txt]
	else do
		log "MESSAGE FROM WRONG GROUP" (fmap bareTxt existingRoom, from, m)
		return []
	where
	txt = mconcat [fromString "(", fromMaybe (fromString "nonick") (strResource <$> jidResource from), fromString ") ", body]
componentMessage db componentJid m@(Message { messageTo = Just to, messagePayloads = payloads }) existingRoom from smsJid body
	| [reactions] <- XML.isNamed (s"{urn:xmpp:reactions:0}reactions") =<< payloads,
	  Just rid <- XML.attributeText (s"id") reactions,
	  Nothing <- Tapback.parse =<< body = do
		log "REACTION" (from, rid)
		case XML.isNamed (s"{urn:xmpp:reactions:0}reaction") =<< XML.elementChildren reactions of
			[reaction] -> do
				mrbody <- DB.get db (DB.byJid from ["body", textToString rid])
				log "REACTION" (from, reaction, mrbody)
				case mrbody of
					Nothing -> return [
							mkStanzaRec $ m { messageTo = Just from, messageFrom = Just to, messageType = MessageError, messagePayloads =
								(Element (s"{jabber:component:accept}error")
										[(s"{jabber:component:accept}type", [ContentText $ fromString "cancel"])]
										[
											NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable") [] [],
											NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}text")
												[(fromString "xml:lang", [ContentText $ fromString "en"])]
												[NodeContent $ ContentText $ s"Could not find message to react to"]
										]
								) : payloads
							}
						]
					Just rbody -> do
						log "REACTION" (from, "sending")
						componentMessage db componentJid (m {
							messagePayloads =
								(XML.Element (s"{jabber:component:accept}body") [] []) :
								XML.Element (s"{urn:xmpp:fallback:0}fallback") [(s"for", [s"urn:xmpp:reactions:0"])] [
									XML.NodeElement $ mkElement (s"{urn:xmpp:fallback:0}body") (s"")
								] : payloads
						}) existingRoom from smsJid $ Just $
							Tapback.smsBody $ Tapback.fromReaction (mconcat $ XML.elementText reaction) rbody
			_ -> do
				log "REACTION" (from, "tried multi reaction")
				return [
						mkStanzaRec $ m { messageTo = Just from, messageFrom = Just to, messageType = MessageError, messagePayloads =
							(Element (s"{jabber:component:accept}error")
									[(s"{jabber:component:accept}type", [ContentText $ fromString "cancel"])]
									[
										NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}not-acceptable") [] [],
										NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}text")
											[(fromString "xml:lang", [ContentText $ fromString "en"])]
											[NodeContent $ ContentText $ s"Tapback must be exactly one reaction"]
									]
							) : payloads
						}
					]
componentMessage db componentJid m@(Message { messageTo = Just to }) existingRoom from smsJid (Just body) = do
	ack <- case isNamed (fromString "{urn:xmpp:receipts}request") =<< messagePayloads m of
		(_:_) ->
			routeDiscoOrReply db componentJid from smsJid ("CHEOGRAM%query-then-send-ack%" ++ extra) Nothing
				(deliveryReceipt (fromMaybe mempty $ messageID m) to from)
		[] -> return []

	fmap (++ack) $ toRouteOrFallback db componentJid from smsJid strippedM $
		case PCRE.match autolinkRegex (encodeUtf8 body) [] of
			Just _ -> do
				log "WHISPER URL" m
				return [mkStanzaRec $ m {
					messageFrom = Just to,
					messageTo = Just from,
					messageType = MessageError,
					messagePayloads = messagePayloads m ++ [
						Element (fromString "{jabber:component:accept}error")
						[(fromString "{jabber:component:accept}type", [ContentText $ fromString "auth"])]
						[NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}forbidden") [] []]
					]
				}]
			Nothing -> do
				nick <- nickFor db componentJid from existingRoom
				let txt = mconcat [s"<", nick, s" says> ", strippedBody]
				let sms = mkSMS componentJid smsJid txt
				let thread = (maybe id (\t f -> f ++ s" " ++ t) (getThread "jabber:component:accept" m)) (bareTxt from)
				return [mkStanzaRec $ sms { messagePayloads = (Element (s"{jabber:component:accept}thread") [] [NodeContent $ ContentText thread]) : messagePayloads sms } ]
	where
	strippedM = mapBody (const strippedBody) m
	strippedBody = stripOtrWhitespace body
	extra = T.unpack $ escapeJid $ T.pack $ show (fromMaybe mempty (messageID m), maybe mempty strResource $ jidResource from)
componentMessage _ _ m _ _ _ _ = do
	log "UNKNOWN MESSAGE" m
	return []

handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads join
	| join,
	  [x] <- isNamed (s"{http://jabber.org/protocol/muc#user}x") =<< payloads,
	  not $ null $ code "110" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do
		existingInvite <- (parseJID =<<) <$> DB.get db (DB.byNode to ["invited"])
		when (existingInvite == parseJID bareMUC) $
			DB.del db (DB.byNode to ["invited"])
		DB.set db (DB.byNode to ["joined"]) (formatJID from)
		DB.sadd db (DB.byNode to ["bookmarks"]) [bareMUC]

		presences <- syncCall toRoomPresences $ GetRoomPresences to from
		atomically $ writeTChan toRoomPresences $ RecordSelfJoin to from (Just to)

		atomically $ writeTChan toRejoinManager $ Joined from

		case presences of
			[] -> do -- No one in the room, so we "created"
				uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
				let fullid = if (resourceFrom `elem` map fst presences) then uuid else "CHEOGRAMCREATE%" <> uuid
				return [mkStanzaRec $ (emptyIQ IQGet) {
					iqTo = Just room,
					iqFrom = Just to,
					iqID = Just $ fromString fullid,
					iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/muc#owner}query") [] []
				}]
			(_:_) | isNothing (lookup resourceFrom presences) -> do
				fmap ((mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [
						s"* You have joined ", bareMUC,
						s" as ", resourceFrom,
						s" along with\n",
						intercalate (s", ") (filter (/= resourceFrom) $ map fst presences)
					]):)
					(queryDisco room to)
			_ -> do
				log "JOINED" (to, from, "FALSE PRESENCE")
				queryDisco room to
	| not join,
	  [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads,
	  (_:_) <- code "303" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do
		let mnick = attributeText (fromString "nick") =<<
			listToMaybe (isNamed (fromString "{http://jabber.org/protocol/muc#user}item") =<< elementChildren x)
		toList <$> forM mnick (\nick -> do
			atomically $ writeTChan toRoomPresences $ RecordNickChanged to from nick
			return $ mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [
					fromString "* ",
					resourceFrom,
					fromString " has changed their nick to ",
					nick
				]
			)
	| not join,
	  [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads,
	  (_:_) <- code "332" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do
		log "SERVER RESTART, clear join status" (to, from)
		void $ atomically (writeTChan toRejoinManager $ JoinError from)
		return []
	| not join && existingRoom == Just from = do
		DB.del db (DB.byNode to ["joined"])
		atomically $ writeTChan toRoomPresences $ RecordPart to from
		atomically $ writeTChan toRoomPresences $ Clear to from
		return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "* You have left " <> bareMUC)]
	| fmap bareTxt existingRoom == Just bareMUC && join = do
		atomically $ writeTChan toJoinPartDebouncer $ DebounceJoin to from (participantJid payloads)
		return []
	| fmap bareTxt existingRoom == Just bareMUC && not join = do
		atomically $ writeTChan toJoinPartDebouncer $ DebouncePart to from
		return []
	| join,
	  (_:_) <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads = do
		log "UNKNOWN JOIN" (existingRoom, from, to, payloads, join)
		atomically $ writeTChan toRoomPresences $ RecordJoin to from (participantJid payloads)
		return []
	| (_:_) <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads = do
		log "UNKNOWN NOT JOIN" (existingRoom, from, to, payloads, join)
		atomically $ writeTChan toRoomPresences $ RecordPart to from
		return []
	| otherwise =
		-- This is just presence. It's not marked as MUC or from the room this user is in
		return []
	where
	resourceFrom = fromMaybe mempty (strResource <$> jidResource from)
	Just room = parseJID bareMUC
	bareMUC = bareTxt from

handleRegister db componentJid iq@(IQ { iqType = IQGet, iqFrom = Just from }) _ = do
	maybeExistingRoute <- (parseJID =<<) <$> DB.get db (DB.byJid from ["direct-message-route"])
	return [mkStanzaRec $ iq {
		iqTo = iqFrom iq,
		iqFrom = iqTo iq,
		iqType = IQResult,
		iqPayload = Just $ Element (s"{jabber:iq:register}query") []
			([
				NodeElement $ Element (s"{jabber:iq:register}instructions") [] [
					NodeContent $ ContentText $ s"To register, please use the Register command."
				],
				NodeElement $ Element (s"{jabber:x:oob}x") [] [
					NodeElement $ Element (s"{jabber:x:oob}url") [] [
						NodeContent $ ContentText $ s"xmpp:" ++ formatJID componentJid ++ s"?command;node=jabber:iq:register"
					]
				]
			] ++ (if isJust maybeExistingRoute then [
				NodeElement $ Element (s"{jabber:iq:register}registered") [] []
			] else []))
	}]
handleRegister db componentJid iq@(IQ { iqTo = Just to, iqFrom = Just from, iqType = IQSet }) query
	| [_] <- isNamed (fromString "{jabber:iq:register}remove") =<< elementChildren query = do
		maybeExistingRoute <- (parseJID =<<) <$> DB.get db (DB.byJid from ["direct-message-route"])
		deleteDirectMessageRoute db from
		fmap ([
				mkStanzaRec $
					iqReply
					(Just $ Element (fromString "{jabber:iq:register}query") [] [])
					iq
			] ++) $ mapM (fmap mkStanzaRec . unregisterDirectMessageRoute db componentJid from) (justZ maybeExistingRoute)
handleRegister _ _ iq@(IQ { iqType = typ }) _
	| typ `elem` [IQGet, IQSet] = do
		log "HANDLEREGISTER return error" iq
		return [mkStanzaRec $ iq {
			iqTo = iqFrom iq,
			iqFrom = iqTo iq,
			iqType = IQError,
			iqPayload = Just $ Element (fromString "{jabber:component:accept}error")
				[(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])]
				[NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}feature-not-implemented") [] []]
		}]
handleRegister _ _ iq _ = do
	log "HANDLEREGISTER UNKNOWN" iq
	return []

data ComponentContext = ComponentContext {
	db :: DB.DB,
	pushStatsd :: [StatsD.Stat] -> IO (),
	smsJid :: Maybe JID,
	adhocBotMessage :: Message -> STM (),
	ctxCacheOOB :: (XMPP.Message -> Maybe XMPP.Message) -> Bool -> Message -> UIO Message,
	toRoomPresences :: TChan RoomPresences,
	toRejoinManager :: TChan RejoinManagerCommand,
	toJoinPartDebouncer :: TChan JoinPartDebounce,
	processDirectMessageRouteConfig :: IQ -> IO (Maybe IQ),
	componentJid :: JID,
	sendIQ :: IQ -> UIO (STM (Maybe IQ)),
	maybeAvatar :: Maybe Avatar
}

componentStanza :: ComponentContext -> ReceivedStanza -> IO [StanzaRec]
componentStanza (ComponentContext { db, adhocBotMessage, ctxCacheOOB, componentJid }) (ReceivedMessage (m@Message { messageTo = Just (JID { jidNode = Nothing }) }))
	| Just _ <- groupTextPorcelein (formatJID componentJid) m = do
		-- TODO: only when from direct message route
		-- TODO: only if target does not understand stanza addressing
		Just reply <- fmap (groupTextPorcelein (formatJID componentJid)) $ fmap addMarkable $ UIO.lift $ ctxCacheOOB (Just . addOOBFallbackBody) True m
		let mBody = fromMaybe mempty $ getBody "jabber:component:accept" m
		let replyBody = fromMaybe mempty $ getBody "jabber:component:accept" reply
		reply' <- rememberIncomingBody db (mapBody (const mBody) reply)
		return [mkStanzaRec $ mapBody (const replyBody) reply']
	| MessageError == messageType m = return []
	| Just _ <- getBody "jabber:component:accept" m = do
		hasLocked "adhocBotMessage" $ atomicUIO $ adhocBotMessage m
		return []
	| otherwise = log "WEIRD BODYLESS MESSAGE DIRECT TO COMPONENT" m >> return []
componentStanza (ComponentContext { db, componentJid, sendIQ, smsJid = Just smsJid }) (ReceivedMessage (m@Message { messageTo = Just to, messageFrom = Just from}))
	| [propose] <- isNamed (fromString "{urn:xmpp:jingle-message:0}propose") =<< messagePayloads m = do
		let sid = fromMaybe mempty $ XML.attributeText (s"id") propose
		telFeatures <- getTelFeatures db componentJid sendIQ from
		stanzas <- routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from telFeatures
		return $ (mkStanzaRec $ (XMPP.emptyMessage XMPP.MessageNormal) {
				XMPP.messageID = Just $ s"proceed%" ++ sid,
				XMPP.messageTo = Just from,
				XMPP.messageFrom = XMPP.parseJID $ bareTxt to ++ s"/tel",
				XMPP.messagePayloads = [
					XML.Element (s"{urn:xmpp:jingle-message:0}proceed")
						[(s"id", [XML.ContentText sid])] []
				]
			}) : stanzas
componentStanza _ (ReceivedMessage (m@Message { messageTo = Just to, messageFrom = Just from}))
	| [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< messagePayloads m,
	  not $ null $ code "104" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do
		queryDisco from to
componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid, ctxCacheOOB }) (ReceivedMessage (m@Message { messageTo = Just to@(JID { jidNode = Just _ }), messageFrom = Just from})) = do
	existingRoom <- (parseJID =<<) <$> DB.get db (DB.byNode to ["joined"])
	m' <- UIO.lift $ ctxCacheOOB (const Nothing) False m
	UIO.lift $ rememberOutgoingBody db m'
	componentMessage db componentJid m' existingRoom from smsJid $
		getBody "jabber:component:accept" m'
componentStanza (ComponentContext { smsJid = (Just smsJid), toRejoinManager, componentJid }) (ReceivedPresence p@(Presence { presenceType = PresenceError, presenceFrom = Just from, presenceTo = Just to, presenceID = Just id }))
	| fromString "CHEOGRAMREJOIN%" `T.isPrefixOf` id = do
		log "FAILED TO REJOIN, clear join state" p
		void $ atomically (writeTChan toRejoinManager $ JoinError from)
		return []
	| fromString "CHEOGRAMJOIN%" `T.isPrefixOf` id = do
		log "FAILED TO JOIN" p
		let errorText = maybe mempty (mconcat . (fromString "\n":) . elementText) $ listToMaybe $
			isNamed (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}text") =<<
			elementChildren =<< isNamed (fromString "{jabber:component:accept}error") =<< presencePayloads p
		return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "* Failed to join " <> bareTxt from <> errorText)]
	| otherwise = return [] -- presence error from a non-MUC, just ignore
componentStanza (ComponentContext { db, smsJid = (Just smsJid), toRoomPresences, toRejoinManager, toJoinPartDebouncer, componentJid }) (ReceivedPresence (Presence {
		presenceType = typ,
		presenceFrom = Just from,
		presenceTo = Just to@(JID { jidNode = Just _ }),
		presencePayloads = payloads
	})) | typ `elem` [PresenceAvailable, PresenceUnavailable] = do
		existingRoom <- (parseJID =<<) <$> DB.get db (DB.byNode to ["joined"])
		hasLocked "handleJoinPartRoom" $ handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads (typ == PresenceAvailable)
componentStanza (ComponentContext { db, componentJid, sendIQ, maybeAvatar }) (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do
	avail <- cheogramAvailable db componentJid sendIQ to from
	return $ [
			mkStanzaRec $ (emptyPresence PresenceSubscribed) {
				presenceTo = Just from,
				presenceFrom = Just to
			},
			mkStanzaRec $ (emptyPresence PresenceSubscribe) {
				presenceTo = Just from,
				presenceFrom = Just to
			},
			mkStanzaRec avail
		] ++ map (mkStanzaRec . (\payload -> ((emptyMessage MessageHeadline) {
			messageTo = Just from,
			messageFrom = Just to,
			messagePayloads = [payload]
		})) . avatarMetadata) (justZ maybeAvatar)
componentStanza _ (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just node } }))
	| Just (_:_:_) <- mapM localpartToURI (T.split (==',') $ strNode node) = do
	return $ [
			mkStanzaRec $ (emptyPresence PresenceSubscribed) {
				presenceTo = Just from,
				presenceFrom = Just to
			},
			mkStanzaRec $ (emptyPresence PresenceSubscribe) {
				presenceTo = Just from,
				presenceFrom = Just to
			},
			mkStanzaRec $ telAvailable to from []
		]
componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid }) (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do
	stanzas <- routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from []
	return $ [
			mkStanzaRec $ (emptyPresence PresenceSubscribed) {
				presenceTo = Just from,
				presenceFrom = Just to
			},
			mkStanzaRec $ (emptyPresence PresenceSubscribe) {
				presenceTo = Just from,
				presenceFrom = Just to
			}
		] ++ stanzas
componentStanza (ComponentContext { db, componentJid, sendIQ, maybeAvatar }) (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do
	avail <- cheogramAvailable db componentJid sendIQ to from
	return $
		[mkStanzaRec avail] ++
		map (mkStanzaRec . (\payload -> (emptyMessage (MessageHeadline)) {
			messageTo = Just from,
			messageFrom = Just to,
			messagePayloads = [payload]
		}) . avatarMetadata) (justZ maybeAvatar)
componentStanza _ (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just node } }))
	| Just (_:_:_) <- mapM localpartToURI (T.split (==',') $ strNode node) = do
	return $ [mkStanzaRec $ telAvailable to from []]
componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid }) (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do
	routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from []
componentStanza (ComponentContext { maybeAvatar = Just (Avatar hash _ b64) }) (ReceivedIQ (iq@IQ { iqType = IQGet, iqTo = Just to@JID { jidNode = Nothing }, iqFrom = Just from, iqID = Just id, iqPayload = Just p }))
	| [items] <- isNamed (s"{http://jabber.org/protocol/pubsub}items") =<<
		elementChildren =<<
		isNamed (s"{http://jabber.org/protocol/pubsub}pubsub") p,
	  attributeText (s"node") items == Just (s"urn:xmpp:avatar:data"),
	  item <- headZ $ isNamed (s"{http://jabber.org/protocol/pubsub}item") =<<
		elementChildren items,
	  isNothing item || (attributeText (s"id") =<< item) == Just hash =
		return [mkStanzaRec $ iqReply (Just $
			XML.Element (s"{http://jabber.org/protocol/pubsub}pubsub") [] [
				XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}items")
				[(s"node", [XML.ContentText $ s"urn:xmpp:avatar:data"])] [
					XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}item")
					[(s"id", [XML.ContentText hash])] [
						XML.NodeElement $ mkElement (s"{urn:xmpp:avatar:data}data") b64
					]
				]
			]
		) iq]
componentStanza (ComponentContext { processDirectMessageRouteConfig, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to }))
	| fmap strResource (jidResource to) == Just (s"CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName),
	  Just (fwdBy, onBehalf, iqId) <- readZ . T.unpack =<< iqID iq = do
		replyIQ <- processDirectMessageRouteConfig (iq { iqID = iqId })
		fmap (fromMaybe []) $ forM replyIQ $ \replyIQ -> do
			let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ)
			return [mkStanzaRec $ replyIQ {
				iqTo = if fmap bareTxt (iqTo replyIQ) == Just onBehalf then parseJID fwdBy else iqTo replyIQ,
				iqID = if iqType replyIQ == IQResult then iqID replyIQ else Just $ fromString $ show (fwdBy, onBehalf, iqID replyIQ),
				iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName)
			}]
componentStanza (ComponentContext { processDirectMessageRouteConfig, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = payload }))
	| (jidNode to == Nothing && fmap elementName payload == Just (s"{http://jabber.org/protocol/commands}command") && (attributeText (s"node") =<< payload) == Just ConfigureDirectMessageRoute.nodeName) ||
	  fmap strResource (jidResource to) == Just (s"CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName) = do
		replyIQ <- processDirectMessageRouteConfig iq
		fmap (fromMaybe []) $ forM replyIQ $ \replyIQ -> do
			let subscribe = if (attributeText (s"status") =<< iqPayload replyIQ) /= Just (s"completed") then [] else [
					mkStanzaRec $ (emptyPresence PresenceSubscribe) {
						presenceTo = parseJID =<< fmap (bareTxt . maybeUnescape componentJid) (iqFrom iq),
						presenceFrom = Just componentJid,
						presencePayloads = [
							Element (s"{jabber:component:accept}status") [] [
								NodeContent $ ContentText $ s"Add this contact and then you can SMS by sending messages to +1<phone-number>@" ++ formatJID componentJid ++ s" Jabber IDs."
							]
						]
					}
				]

			let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ)
			return $ subscribe ++ [mkStanzaRec $ replyIQ {
				iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName)
			}]
componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just (JID { jidNode = Nothing }), iqPayload = payload, iqFrom = Just from }))
	| fmap elementName payload == Just (s"{http://jabber.org/protocol/commands}command") && (attributeText (s"node") =<< payload) == Just JidSwitch.nodeName =
		let setJidSwitch newJid = do
			let from' = maybeUnescape componentJid from
			Just route <- (XMPP.parseJID <=< id) <$> DB.get db (DB.byJid from' ["direct-message-route"])
			let key = DB.byJid newJid ["jidSwitch"]
			DB.hset db key $ JidSwitch.toAssoc from' route
			-- I figure 30 days is a wide enough window to accept a JID switch
			DB.expire db key $ 60 * 60 * 24 * 30
			return (from', newJid, route)
		in
		map mkStanzaRec <$> JidSwitch.receiveIq componentJid setJidSwitch iq
componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = Just payload, iqFrom = Just from }))
	| jidNode to == Nothing,
	  elementName payload == s"{http://jabber.org/protocol/commands}command",
	  attributeText (s"node") payload == Just (s"sip-proxy-set"),
	  [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren payload,
	  Just proxy <- getFormField form (s"sip-proxy") = do
		if T.null proxy then
			DB.del db (DB.byJid from ["sip-proxy"])
		else
			DB.set db (DB.byJid from ["sip-proxy"]) proxy
		return [mkStanzaRec $ iqReply Nothing iq]
componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = Just payload, iqFrom = Just from }))
	| jidNode to == Nothing,
	  jidNode from == Nothing,
	  elementName payload == s"{http://jabber.org/protocol/commands}command",
	  attributeText (s"node") payload == Just (s"push-register"),
	  [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren payload,
	  Just pushRegisterTo <- XMPP.parseJID =<< getFormField form (s"to") = do
		DB.set db (DB.byJid pushRegisterTo ["possible-route"]) (XMPP.formatJID from)
		return [
				mkStanzaRec $ iqReply (
					Just $ Element (s"{http://jabber.org/protocol/commands}command")
					[
						(s"{http://jabber.org/protocol/commands}node", [ContentText $ s"push-register"]),
						(s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ s"all-done"]),
						(s"{http://jabber.org/protocol/commands}status", [ContentText $ s"completed"])
					]
					[
						NodeElement $ Element (fromString "{jabber:x:data}x") [
							(fromString "{jabber:x:data}type", [ContentText $ s"result"])
						] [
							NodeElement $ Element (fromString "{jabber:x:data}field") [
								(fromString "{jabber:x:data}type", [ContentText $ s"jid-single"]),
								(fromString "{jabber:x:data}var", [ContentText $ s"from"])
							] [
								NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ escapeJid (bareTxt pushRegisterTo) ++ s"@" ++ formatJID componentJid]
							]
						]
					]
				) iq,
				mkStanzaRec $ (XMPP.emptyMessage XMPP.MessageChat) {
					XMPP.messageTo = Just pushRegisterTo,
					XMPP.messageFrom = Just componentJid,
					XMPP.messagePayloads = [
						mkElement (s"{jabber:component:accept}body") $
							s"To start registration with " ++ XMPP.formatJID from ++ s" reply with: register " ++ XMPP.formatJID from ++
							s"\n(If you do not wish to start this registration, simply ignore this message.)",
						Element (s"{http://jabber.org/protocol/disco#items}query")
							[(s"node", [ContentText $ s"http://jabber.org/protocol/commands"])] [
								NodeElement $ Element (s"{http://jabber.org/protocol/disco#items}item") [
									(s"jid", [ContentText $ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName]),
									(s"node", [ContentText ConfigureDirectMessageRoute.nodeName]),
									(s"name", [ContentText $ s"register " ++ XMPP.formatJID from])
								] []
							]
					]
				}
			]
componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqFrom = Just _, iqTo = Just (JID { jidNode = Nothing }), iqPayload = Just p }))
	| iqType iq `elem` [IQGet, IQSet],
	  [query] <- isNamed (fromString "{jabber:iq:register}query") p = do
		handleRegister db componentJid iq query
	| iqType iq == IQGet,
	  [query] <- isNamed (s"{im.quicksy.synchronization:0}phone-book") p,
	  tels <- justZ . attributeText (s"number") =<< isNamed (s"{im.quicksy.synchronization:0}entry") =<< elementChildren query = do
		entries <- fmap catMaybes . forM tels $ \tel -> do
			owners <- filterM (\owner ->
					fromMaybe False <$> DB.getEnum db (DB.byJid owner ["allowJidDiscovery"])
				) . mapMaybe XMPP.parseJID =<< DB.smembers db (DB.byTel tel ["owners"])
			return $ if null owners then Nothing else
				Just $ XML.NodeElement $ XML.Element (s"{im.quicksy.synchronization:0}entry")
					[(s"number", [XML.ContentText tel])]
					(map (\jid -> XML.NodeElement $ XML.Element (s"{im.quicksy.synchronization:0}jid") [] [XML.NodeContent $ XML.ContentText $ XMPP.formatJID jid]) owners)
		return [mkStanzaRec $ iqReply (Just $ XML.Element (s"{im.quicksy.synchronization:0}phone-book") [] entries) iq]
componentStanza (ComponentContext { db, pushStatsd, componentJid, maybeAvatar, sendIQ }) (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = id, iqPayload = Just p }))
	| Nothing <- jidNode to,
	  [q] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do
		payload <- cheogramDiscoInfo db componentJid sendIQ from (Just q)
		return [mkStanzaRec $ (emptyIQ IQResult) {
				iqTo = Just from,
				iqFrom = Just to,
				iqID = id,
				iqPayload = Just payload
			}]
	| Nothing <- jidNode to,
	  [s"http://jabber.org/protocol/commands"] ==
	    mapMaybe (attributeText (s"node")) (isNamed (fromString "{http://jabber.org/protocol/disco#items}query") p) = do

		pushStatsd [StatsD.stat ["cmd-list", "fetch"] 1 "c" Nothing]

		routeQueryOrReply db componentJid from componentJid ("CHEOGRAM%query-then-send-command-list%" ++ extra) queryCommandList (commandList componentJid id to from [])
	| Nothing <- jidNode to,
	  [_] <- isNamed (s"{vcard-temp}vCard") p =
		return [mkStanzaRec $ (emptyIQ IQResult) {
			iqTo = Just from,
			iqFrom = Just to,
			iqID = id,
			iqPayload = Just $ Element (s"{vcard-temp}vCard") [] $
				[
					NodeElement $ Element (s"{vcard-temp}URL") [] [NodeContent $ ContentText $ s"https://cheogram.com"],
					NodeElement $ Element (s"{vcard-temp}DESC") [] [NodeContent $ ContentText $ s"Cheogram provides stable JIDs for PSTN identifiers, with routing through many possible backends.\n\n© Stephen Paul Weber, licensed under AGPLv3+.\n\nSource code for this gateway is available from the listed homepage.\n\nPart of the Soprani.ca project."]
				] ++ map (\(Avatar _ _ b64) -> NodeElement $ Element (s"{vcard-temp}PHOTO") [] [
						NodeElement $ mkElement (s"{vcard-temp}TYPE") (s"image/png"),
						NodeElement $ mkElement (s"{vcard-temp}BINVAL") b64
					]
				) (justZ maybeAvatar)
		}]
	where
	extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom)
	resourceFrom = strResource <$> jidResource from
componentStanza (ComponentContext { db, sendIQ, smsJid = (Just smsJid), componentJid }) (ReceivedIQ iq@(IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = Just id, iqPayload = Just p }))
	| Just _ <- jidNode to,
	  [q] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do
		maybeDiscoResult <- routeDiscoStateful db componentJid sendIQ from (jidNode smsJid) (nodeAttribute q)
		telFeatures <- getTelFeatures db componentJid sendIQ from
		case maybeDiscoResult of
			Just (IQ { iqPayload = Just discoResult }) -> return [
					mkStanzaRec $ telDiscoInfo q id to from $ (telFeatures ++) $ mapMaybe (attributeText (fromString "var")) $
					isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren discoResult
				]
			Nothing -> return [mkStanzaRec $ telDiscoInfo q id to from telFeatures]
	| Just tel <- strNode <$> jidNode to,
	  [items] <- isNamed (s"{http://jabber.org/protocol/pubsub}items") =<<
		elementChildren =<<
		isNamed (s"{http://jabber.org/protocol/pubsub}pubsub") p,
	  attributeText (s"node") items == Just (s"urn:xmpp:vcard4"),
	  itemId <- attributeText (s"id") =<< headZ (isNamed (s"{http://jabber.org/protocol/pubsub}item") =<< elementChildren items) = do
		owners <- filterM (\owner ->
				fromMaybe False <$> DB.getEnum db (DB.byJid owner ["allowJidDiscovery"])
			) . mapMaybe XMPP.parseJID =<< DB.smembers db (DB.byNode smsJid ["owners"])

		let tel = maybe mempty XMPP.strNode $ XMPP.jidNode smsJid
		quicksy <- (atomicUIO =<<) $ UIO.lift $ sendIQ $ (emptyIQ IQGet) {
				iqTo = XMPP.parseJID $ s"api.quicksy.im",
				iqFrom = XMPP.parseJID $ bareTxt componentJid ++ s"/IQMANAGER",
				iqPayload = Just $ XML.Element (s"{im.quicksy.synchronization:0}phone-book") [] [
						XML.NodeElement $ XML.Element (s"{im.quicksy.synchronization:0}entry") [(s"number", [XML.ContentText tel])] []
				]
			}
		log "QUICKSY RESPONSE" quicksy
		let quicksyOwners = mapMaybe (XMPP.parseJID . mconcat . XML.elementText) $ XML.elementChildren =<< filter (\entry -> XML.attributeText (s"number") entry == Just tel)
			(XML.isNamed (s"{im.quicksy.synchronization:0}entry") =<< XML.elementChildren =<< XML.isNamed (s"{im.quicksy.synchronization:0}phone-book") =<< justZ (XMPP.iqPayload =<< quicksy))
		log "VCARD4 OWNERS" (owners, quicksyOwners)

		return [mkStanzaRec $ iqReply (Just $
				XML.Element (s"{http://jabber.org/protocol/pubsub}pubsub") [] [
					XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}items")
					[(s"node", [XML.ContentText $ s"urn:xmpp:avatar:data"])] [
						XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}item")
						[(s"id", [XML.ContentText $ fromMaybe (s"current") itemId])] [
							XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}vcard") [] ([
								XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}tel") [] [
									XML.NodeElement $ mkElement (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") (s"tel:" ++ tel)
								]
							] ++ map (\jid ->
								XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}impp") [] [
									XML.NodeElement $ mkElement (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") (s"xmpp:" ++ formatJID jid)
								]
							) (nub $ owners ++ quicksyOwners))
						]
					]
				]
			) iq]
	where
	extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom)
	resourceFrom = strResource <$> jidResource from
componentStanza (ComponentContext { componentJid }) (ReceivedIQ (iq@IQ { iqType = IQSet, iqFrom = Just from, iqTo = Just (to@JID {jidNode = Nothing}), iqID = id, iqPayload = Just p }))
	| [query] <- isNamed (fromString "{jabber:iq:gateway}query") p,
	  [prompt] <- isNamed (fromString "{jabber:iq:gateway}prompt") =<< elementChildren query = do
		case telToJid (mconcat $ elementText prompt) (formatJID componentJid) of
			Just jid ->
				return [mkStanzaRec $ (emptyIQ IQResult) {
					iqTo = Just from,
					iqFrom = Just to,
					iqID = id,
					iqPayload = Just $ Element (fromString "{jabber:iq:gateway}query") []
						[NodeElement $ Element (fromString "{jabber:iq:gateway}jid") [ ] [NodeContent $ ContentText $ formatJID jid]]
				}]
			Nothing ->
				return [mkStanzaRec $ iq {
					iqTo = Just from,
					iqFrom = Just to,
					iqType = IQError,
					iqPayload = Just $ Element (fromString "{jabber:component:accept}error")
						[(fromString "{jabber:component:accept}type", [ContentText $ fromString "modify"])]
						[
							NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}not-acceptable") [] [],
							NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}text")
								[(fromString "xml:lang", [ContentText $ fromString "en"])]
								[NodeContent $ ContentText $ fromString "Only US/Canada telephone numbers accepted"]
						]
				}]
componentStanza _ (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just (to@JID {jidNode = Nothing}), iqID = id, iqPayload = Just p }))
	| [_] <- isNamed (fromString "{jabber:iq:gateway}query") p = do
		return [mkStanzaRec $ (emptyIQ IQResult) {
			iqTo = Just from,
			iqFrom = Just to,
			iqID = id,
			iqPayload = Just $ Element (fromString "{jabber:iq:gateway}query") []
				[
					NodeElement $ Element (fromString "{jabber:iq:gateway}desc") [ ] [NodeContent $ ContentText $ fromString "Please enter your contact's phone number"],
					NodeElement $ Element (fromString "{jabber:iq:gateway}prompt") [ ] [NodeContent $ ContentText $ fromString "Phone Number"]
				]
		}]
componentStanza (ComponentContext { db }) (ReceivedIQ (iq@IQ { iqType = IQError, iqFrom = Just from, iqTo = Just to }))
	| (strNode <$> jidNode to) == Just (fromString "create"),
	  Just resource <- strResource <$> jidResource to = do
		log "create@ ERROR" (from, to, iq)
		case T.splitOn (fromString "|") resource of
			(cheoJidT:_) | Just cheoJid <- parseJID cheoJidT -> do
				mnick <- DB.get db (DB.byNode cheoJid ["nick"])
				let nick = fromMaybe (maybe mempty strNode (jidNode cheoJid)) mnick
				let Just room = parseJID $ bareTxt from <> fromString "/" <> nick
				(++) <$>
					leaveRoom db cheoJid "Joined a different room." <*>
					joinRoom db cheoJid room
			_ -> return [] -- Invalid packet, ignore
componentStanza (ComponentContext { componentJid }) (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to }))
	| (strNode <$> jidNode to) == Just (fromString "create"),
	  Just resource <- strResource <$> jidResource to = do
		case T.splitOn (fromString "|") resource of
			(cheoJidT:name:[]) | Just cheoJid <- parseJID cheoJidT, Just tel <- strNode <$> jidNode cheoJid ->
				createRoom componentJid [strDomain $ jidDomain from] cheoJid (name <> fromString "_" <> tel)
			(cheoJidT:name:servers) | Just cheoJid <- parseJID cheoJidT ->
				createRoom componentJid servers cheoJid name
			_ -> return [] -- Invalid packet, ignore
componentStanza (ComponentContext { toRejoinManager }) (ReceivedIQ (IQ { iqType = IQResult, iqID = Just id, iqFrom = Just from }))
	| fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do
		atomically $ writeTChan toRejoinManager (PingReply from)
		return []
componentStanza (ComponentContext { toRejoinManager }) (ReceivedIQ (IQ { iqType = IQError, iqID = Just id, iqFrom = Just from }))
	| fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do
		atomically $ writeTChan toRejoinManager (PingError from)
		return []
componentStanza _ (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to, iqID = Just id, iqPayload = Just p }))
	| [query] <- isNamed (fromString "{http://jabber.org/protocol/muc#owner}query") p,
	  [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query = do
		uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
		let fullid = if fromString "CHEOGRAMCREATE%" `T.isPrefixOf` id then "CHEOGRAMCREATE%" <> uuid else uuid
		return [mkStanzaRec $ (emptyIQ IQSet) {
			iqTo = Just from,
			iqFrom = Just to,
			iqID = Just $ fromString fullid,
			iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/muc#owner}query") [] [
				NodeElement $
				fillFormField (fromString "muc#roomconfig_publicroom") (fromString "0") $
				fillFormField (fromString "muc#roomconfig_persistentroom") (fromString "1") $
				fillFormField (fromString "muc#roomconfig_allowinvites") (fromString "1") $
				fillFormField (fromString "muc#roomconfig_membersonly") (fromString "1")
				form { elementAttributes = [(fromString "{jabber:x:data}type", [ContentText $ fromString "submit"])] }
			]
		}]
componentStanza (ComponentContext { smsJid = (Just smsJid), componentJid }) (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to, iqID = Just id }))
	| fromString "CHEOGRAMCREATE%" `T.isPrefixOf` id = do
		fmap (((mkStanzaRec $ mkSMS componentJid smsJid (mconcat [fromString "* You have created ", bareTxt from])):) . concat . toList) $
			forM (parseJID $ bareTxt to <> fromString "/create") $
				queryDisco from
componentStanza (ComponentContext { componentJid }) (ReceivedIQ (IQ { iqType = typ, iqTo = Just to@(JID { jidNode = Just toNode }), iqPayload = Just p }))
	| typ `elem` [IQResult, IQError],
	  Just idAndResource <- T.stripPrefix (s"CHEOGRAM%query-then-send-command-list%") . strResource =<< jidResource to,
	  Just (iqId, resource) <- readZ $ T.unpack $ unescapeJid idAndResource,
	  Just routeTo <- parseJID (unescapeJid (strNode toNode) ++ if T.null resource then mempty else s"/" ++ resource) =
		if typ == IQError then do
			return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo []]
		else do
			let items = isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren p
			return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo items]
componentStanza (ComponentContext { db, componentJid, sendIQ }) (ReceivedIQ (IQ { iqType = IQError, iqTo = Just to@(JID { jidNode = Just toNode }), iqFrom = Just from }))
	| fmap strResource (jidResource to) == Just (s"CHEOGRAM%query-then-send-presence"),
	  Just routeTo <- parseJID (unescapeJid (strNode toNode)),
	  Just fromNode <- jidNode from,
	  Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) = do
		telFeatures <- getTelFeatures db componentJid sendIQ routeTo
		return [ mkStanzaRec $ telAvailable routeFrom routeTo telFeatures ]
componentStanza (ComponentContext { db, componentJid, sendIQ }) (ReceivedIQ (IQ { iqType = IQResult, iqTo = Just to@(JID { jidNode = Just toNode }), iqFrom = Just from, iqPayload = Just p }))
	| Just idAndResource <- T.stripPrefix (s"CHEOGRAM%query-then-send-ack%") . strResource =<< jidResource to,
	  Just (messageId, resource) <- readZ $ T.unpack $ unescapeJid idAndResource,
	  [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p,
	  Just routeTo <- parseJID (unescapeJid (strNode toNode) ++ if T.null resource then mempty else s"/" ++ resource),
	  Just fromNode <- jidNode from,
	  Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) =
		let features = mapMaybe (attributeText (fromString "var")) $ isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query in
		if (s"urn:xmpp:receipts") `elem` features then do
			return []
		else do
			return [mkStanzaRec $ deliveryReceipt messageId routeFrom routeTo]
	| fmap strResource (jidResource to) == Just (s"CHEOGRAM%query-then-send-presence"),
	  [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p,
	  Just routeTo <- parseJID (unescapeJid (strNode toNode)),
	  Just fromNode <- jidNode from,
	  Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) = do
		telFeatures <- getTelFeatures db componentJid sendIQ routeTo
		return [
				mkStanzaRec $ telAvailable routeFrom routeTo $ (telFeatures ++) $ mapMaybe (attributeText (fromString "var")) $
				isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query
			]
	| [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do
		let vars = mapMaybe (attributeText (fromString "var")) $
			isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query
		if s"muc_membersonly" `elem` vars then
			DB.setEnum db (DB.byJid from ["muc_membersonly"]) True
		else
			DB.del db (DB.byJid from ["muc_membersonly"])
		return []
componentStanza _ (ReceivedIQ (iq@IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqPayload = Just p }))
	| not $ null $ isNamed (fromString "{urn:xmpp:ping}ping") p = do
		return [mkStanzaRec $ iq {
			iqTo = Just from,
			iqFrom = Just to,
			iqType = IQResult,
			iqPayload = Nothing
		}]
componentStanza (ComponentContext { db, smsJid = maybeSmsJid, componentJid }) (ReceivedIQ (iq@IQ { iqType = typ, iqFrom = Just from }))
	| fmap strResource (jidResource =<< iqTo iq) /= Just (s"capsQuery") = do
	let resourceSuffix = maybe mempty (s"/"++) $ fmap strResource (jidResource from)
	maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"])
	case (maybeRoute, parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ resourceSuffix) of
		(Just route, Just routeFrom) | isJust maybeSmsJid -> do
			return [mkStanzaRec $ iq {
				iqFrom = Just routeFrom,
				iqTo = parseJID $ (maybe mempty (++s"@") $ strNode <$> (jidNode =<< maybeSmsJid)) ++ route
			}]
		_ | typ `elem` [IQGet, IQSet] -> do
			return [mkStanzaRec $ iqNotImplemented iq]
		_ | typ == IQError, Just smsJid <- maybeSmsJid -> do
			log "IQ ERROR" iq
			return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "Error while querying or configuring " <> formatJID from)]
		_ -> log "IGNORE BOGUS REPLY (no route)" iq >> return []
componentStanza _ _ = return []

participantJid payloads =
	listToMaybe $ mapMaybe (parseJID <=< attributeText (fromString "jid")) $
	isNamed (fromString "{http://jabber.org/protocol/muc#user}item") =<<
	elementChildren =<<
	isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads

-- Tapbacks reference messages using the whole body, so we need to remember message id, body pairs temporarily for them to work
rememberIncomingBody :: (Unexceptional m) => DB.DB -> Message -> m Message
rememberIncomingBody db m@(XMPP.Message { XMPP.messageTo = Just to, XMPP.messagePayloads = payloads })
	| Just body <- getBody "jabber:component:accept" m,
	  Just tapback <- Tapback.parse body = do
		mrid <- fmap (join . hush) $ UIO.fromIO $ DB.get db (DB.byJid to ["body", showDigest $ sha1 $ LZ.fromStrict $ encodeUtf8 $ Tapback.body tapback])
		case mrid of
			Nothing -> return m
			Just rid -> return $ m {
					XMPP.messagePayloads = payloads ++ [
						XML.Element (s"{urn:xmpp:reactions:0}reactions") [(s"id", [XML.ContentText rid])] [
							XML.NodeElement $ mkElement (s"{urn:xmpp:reactions:0}reaction") (Tapback.emoji tapback)
						]
					]
				}
rememberIncomingBody db m@(XMPP.Message { XMPP.messageTo = Just to })
	| Just body <- getBody "jabber:component:accept" m = do
		mid <- midGenerator
		void $ UIO.fromIO $ do -- ignore db failure
			DB.set db (DB.byJid to ["body", textToString mid]) body
			DB.expire db (DB.byJid to ["body", textToString mid]) 43200
		return $ m { XMPP.messageID = Just mid }
	where
	midGenerator
		| Just originalId <- XMPP.messageID m = return originalId
		| otherwise = fromIO_ $ fmap (fromMaybe mempty) $ (fmap . fmap) UUID.toText UUID.nextUUID
rememberIncomingBody _ m = return m

rememberOutgoingBody :: (Unexceptional m) => DB.DB -> Message -> m ()
rememberOutgoingBody db m@(XMPP.Message { XMPP.messageFrom = Just from, XMPP.messageID = Just mid })
	| Just body <- getBody "jabber:component:accept" m =
		let
			hash = showDigest $ sha1 $ LZ.fromStrict $ encodeUtf8 body
		in
		void $ UIO.fromIO $ do -- ignore db failure
			DB.set db (DB.byJid from ["body", hash]) mid
			DB.expire db (DB.byJid from ["body", hash]) 43200
rememberOutgoingBody _ _ = return ()

cacheHTTP :: (Unexceptional m) => FilePath -> Text -> m (Either IOError (FilePath, Digest SHA1, Digest SHA256, Digest SHA512))
cacheHTTP jingleStore url =
	UIO.fromIO' (userError . show) $
	HTTP.get (encodeUtf8 url) $ \response body -> UIO.runEitherIO $
		if HTTP.getStatusCode response == 200 then
			Jingle.storeChunks Nothing jingleStore
			(reverse $ take 240 $ reverse $ escapeURIString isAlphaNum (textToString url))
			(hush <$> UIO.fromIO (fromMaybe mempty <$> Streams.read body))
		else
			return $ Left $ userError "Response was not 200 OK"

data ProtoSIMS = ProtoSIMS {
	protoSimsPath     :: FilePath,
	protoSimsName     :: Text,
	protoSimsMimeType :: Text,
	protoSimsSources  :: [Text],
	protoSimsSha1     :: Digest SHA1,
	protoSimsSha256   :: Digest SHA256,
	protoSimsSha512   :: Digest SHA512
} deriving (Show)

cacheOneOOB :: (Unexceptional m) => Magic -> ([StatsD.Stat] -> m ()) -> FilePath -> Text -> XML.Element -> m (Maybe (Text, Text), Maybe ProtoSIMS, XML.Element)
cacheOneOOB magic pushStatsd jingleStore jingleStoreURL oob
	| [url] <- (mconcat . XML.elementText) <$> urls = do
		cacheResult <- cacheHTTP jingleStore url
		case cacheResult of
			Left err -> do
				pushStatsd [StatsD.stat ["cache", "oob", "failure"] 1 "c" Nothing]
				log "cacheOneOOB" (err, oob)
				return (Nothing, Nothing, oob)
			Right (path, sha1, sha256, sha512) -> do
				pushStatsd [StatsD.stat ["cache", "oob", "success"] 1 "c" Nothing]
				mimeType <- fromIO_ $ magicFile magic path
				let extSuffix = maybe mempty (s"." ++) $ SMap.lookup mimeType mimeToExtMap
				let name = T.takeWhileEnd (/='/') url
				let url' = jingleStoreURL ++ (T.takeWhileEnd (/='/') $ fromString path) ++ extSuffix
				return (
						Just (url, url'),
						Just (ProtoSIMS path name (fromString mimeType) [url'] sha1 sha256 sha512),
						oob {
							XML.elementNodes =
								map XML.NodeElement
								(mkElement urlName url' : rest)
						}
					)
	| otherwise = do
		pushStatsd [StatsD.stat ["cache", "oob", "malformed"] 1 "c" Nothing]
		log "cacheOneOOB MALFORMED" oob
		return (Nothing, Nothing, oob)
	where
	urlName = s"{jabber:x:oob}url"
	(urls, rest) = partition (\el -> XML.elementName el == urlName) (elementChildren oob)

hashEl :: String -> Digest a -> XML.Element
hashEl algo digest = XML.Element (s"{urn:xmpp:hashes:2}hash")
	[(s"algo", [XML.ContentText $ fromString algo])]
	[XML.NodeContent $ XML.ContentText $ decodeUtf8 $ Base64.encode $ ByteArray.convert digest]

thumbEl :: Int -> Int -> Text -> Text -> XML.Element
thumbEl w h mime uri = XML.Element (s"{urn:xmpp:thumbs:1}thumbnail") [
		(s"width", [XML.ContentText $ tshow w]),
		(s"height", [XML.ContentText $ tshow h]),
		(s"media-type", [XML.ContentText mime]),
		(s"uri", [XML.ContentText uri])
	] []

mkSIMS :: (Unexceptional m) => ProtoSIMS -> m XML.Element
mkSIMS (ProtoSIMS path name mimeType sources sha1 sha256 sha512) = do
	size <- fmap (fmap tshow . rightZ) $ UIO.fromIO $ getFileSize path
	thumbs <- if s"image/" `T.isPrefixOf` mimeType then do
		img <- join . fmap rightZ . rightZ <$> UIO.fromIO (Picture.readImage path)
		return $ concatMap (\img ->
				let (w, h) = Picture.dynamicMap (\px -> (Picture.imageWidth px, Picture.imageHeight px)) img in
				thumbEl
					w h (s"image/blurhash") <$>
					(fmap ((s"data:image/blurhash,"++) . fromString . escapeURIString isUnescapedInURI . textToString . decodeUtf8 . LZ.toStrict) $ rightZ $ Blurhash.encodeDynamic img)
			) (img :: [Picture.DynamicImage])
	else return []
	return $ XML.Element (s"{urn:xmpp:reference:0}reference") [(s"type", [s"data"])] [
			XML.NodeElement $ XML.Element (s"{urn:xmpp:sims:1}media-sharing") [] [
				XML.NodeElement $ XML.Element (s"{urn:xmpp:jingle:apps:file-transfer:5}file") [] ([
					XML.NodeElement $ mkElement (s"{urn:xmpp:jingle:apps:file-transfer:5}name") name,
					XML.NodeElement $ mkElement (s"{urn:xmpp:jingle:apps:file-transfer:5}media-type") mimeType,
					XML.NodeElement $ hashEl "sha-1" sha1,
					XML.NodeElement $ hashEl "sha-256" sha256,
					XML.NodeElement $ hashEl "sha-512" sha512
				] ++ map XML.NodeElement thumbs ++ map (XML.NodeElement . mkElement (s"{urn:xmpp:jingle:apps:file-transfer:5}size")) size),
				XML.NodeElement $ XML.Element (s"{urn:xmpp:sims:1}sources") [] $ map (\source ->
					XML.NodeElement $ XML.Element (s"{urn:xmpp:reference:0}reference") [
						(s"type", [s"data"]),
						(s"uri", [XML.ContentText source])
					] []
				) sources
			]
		]

oobDescUrl :: XML.Element -> (Text, Text)
oobDescUrl oob = (
		mconcat (XML.elementText =<< XML.isNamed (s"{jabber:x:oob}desc") =<< XML.elementChildren oob),
		mconcat (XML.elementText =<< XML.isNamed (s"{jabber:x:oob}url") =<< XML.elementChildren oob)
	)

addOOBFallbackBody :: XMPP.Message -> XMPP.Message
addOOBFallbackBody m
	| null oobs = m
	| otherwise = m { messagePayloads = body' : fallbackEl : noBody }
	where
	body' = mkElement bodyName bodyText'
	bodyText' = intercalate (s"\n") $ catMaybes [bodyText, Just fallbackText]
	fallbackEl =
		XML.Element (s"{urn:xmpp:fallback:0}fallback") [(s"for", [s"jabber:x:oob"])] [
			XML.NodeElement $ XML.Element (s"{urn:xmpp:fallback:0}body") [
				(s"start", [XML.ContentText $ tshow $ maybe 0 (\t -> T.length t) bodyText]),
				(s"end", [XML.ContentText $ tshow $ T.length bodyText'])
			] []
		]
	fallbackText = T.dropWhileEnd (== ' ') $ intercalate (s"\n") $ concatMap (\oob ->
			let (desc, url) = oobDescUrl oob in
			if T.null desc then [url] else [desc, url]
		) oobs
	oobName = s"{jabber:x:oob}x"
	bodyName = s"{jabber:component:accept}body"
	bodyText = headZ $ map (T.dropWhileEnd (==' ') . mconcat . XML.elementText) body
	oobs = filter (\el -> XML.elementName el == oobName) noBody
	(body, noBody) = partition (\el -> XML.elementName el == bodyName) (XMPP.messagePayloads m)

cacheOOB :: (Unexceptional m) => Magic -> ([StatsD.Stat] -> m ()) -> FilePath -> Text -> (XMPP.Message -> Maybe XMPP.Message) -> Bool -> XMPP.Message -> m XMPP.Message
cacheOOB magic pushStatsd jingleStore jingleStoreURL generateFallbacks doSims m@(XMPP.Message { XMPP.messagePayloads = payloads }) = do
	(replacements, protoSIMS, oobs') <- unzip3 <$> mapM (cacheOneOOB magic pushStatsd jingleStore jingleStoreURL) oobs
	sims <- if doSims then mapM mkSIMS $ catMaybes protoSIMS else return []
	return $ fromMaybe m $ (generateFallbacks $ m { XMPP.messagePayloads = noOobs ++ sims ++ oobs' }) <|>
		(Just $ m { XMPP.messagePayloads =
			((mkElement bodyName .: foldl (\body (a, b) -> T.replace a b body)) <$>
				(map (T.dropWhileEnd (==' ') . mconcat . XML.elementText) body) <*> pure (catMaybes replacements)) ++
			noOobsNoBody ++ sims ++ oobs'
		})
	where
	oobName = s"{jabber:x:oob}x"
	bodyName = s"{jabber:component:accept}body"
	(body, noOobsNoBody) = partition (\el -> XML.elementName el == bodyName) noOobs
	(oobs, noOobs) = partition (\el -> XML.elementName el == oobName) payloads

component :: DB.DB
                     -> Redis.Connection
                     -> ([StatsD.Stat] -> UIO ())
                     -> Text
                     -> Text
                     -> Maybe Avatar
                     -> ((Message -> Maybe Message) -> Bool -> Message -> UIO Message)
                     -> (IQ -> UIO (STM (Maybe IQ)))
                     -> (IQ -> XMPP ())
                     -> (Message -> STM ())
                     -> TChan RoomPresences
                     -> TChan RejoinManagerCommand
                     -> TChan JoinPartDebounce
                     -> TChan StanzaRec
                     -> TChan ReceivedStanza
                     -> (IQ -> IO (Maybe IQ))
                     -> (IQ -> XMPP ())
                     -> JID
                     -> [Text]
                     -> XMPP ()
component db redis pushStatsd backendHost did maybeAvatar cacheOOB sendIQ iqReceiver adhocBotMessage toRoomPresences toRejoinManager toJoinPartDebouncer toComponent toStanzaProcessor processDirectMessageRouteConfig jingleHandler componentJid conferenceServers = do
	sendThread <- forkXMPP $ forever $ flip catchError (log "component EXCEPTION") $ do
		stanza <- liftIO $ hasLocked "read toComponent" $ atomically $ readTChan toComponent

		UIO.lift $ pushStatsd [StatsD.stat ["stanzas", "out"] 1 "c" Nothing]
		putStanza =<< (liftIO . ensureId) stanza

	recvThread <- forkXMPP $ forever $ flip catchError (\e -> do
		log "component read EXCEPTION" e
		liftIO $ case e of
			TransportError _ -> die "Component connection gone"
			InvalidStanza el | not $ null $ isNamed (s"{http://etherx.jabber.org/streams}error") el -> die "Component connection error"
			_ -> return ()
		) $
		(liftIO . hasLocked "write toStanzaProcessor" . atomicUIO . writeTChan toStanzaProcessor) =<< getStanza

	flip catchError (\e -> liftIO (log "component part 2 EXCEPTION" e >> killThread sendThread >> killThread recvThread)) $ forever $ do
		stanza <- liftIO $ hasLocked "read toStanzaProcessor" $ atomicUIO $ readTChan toStanzaProcessor
		UIO.lift $ pushStatsd [StatsD.stat ["stanzas", "in"] 1 "c" Nothing]
		liftIO $ forkIO $ case stanza of
			(ReceivedPresence p@(Presence { presenceType = PresenceAvailable, presenceFrom = Just from, presenceTo = Just to }))
				| Just returnFrom <- parseJID (bareTxt to ++ s"/capsQuery") ->
				let
					cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid
					caps = child (s"{http://jabber.org/protocol/caps}c") p
					show = maybe mempty mconcat $ elementText <$> child (s"{jabber:component:accept}show") p
					priority = fromMaybe 0 $ (readZ . textToString . mconcat =<< elementText <$> child (s"{jabber:component:accept}priority") p)
					pavailableness = availableness show priority
				in do
				-- Caps?
				case (XML.attributeText (s"ver") =<< caps, XML.attributeText (s"node") =<< caps) of
				-- Yes: write ver to <barejid>/resource and <cheoagramjid>/resource
					(Just ver, Just node) -> do
						let bver = Base64.decodeLenient $ encodeUtf8 ver
						let val = LZ.toStrict $ Builder.toLazyByteString (Builder.word16BE pavailableness ++ Builder.byteString bver)
						Right exists <- Redis.runRedis redis $ do
							Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
							Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
					-- ver in redis?
							Redis.exists bver
					-- Yes: done
					-- No: send disco query, with node
						when (not exists) $ sendToComponent . mkStanzaRec =<< queryDiscoWithNode (Just $ node ++ s"#" ++ ver) from returnFrom
				-- No: write only availableness to redis. send disco query, no node
					_ -> do
						let val = LZ.toStrict $ Builder.toLazyByteString (Builder.word16BE pavailableness)
						void $ Redis.runRedis redis $ do
							Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
							Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
						mapM_ sendToComponent =<< queryDisco from returnFrom
			(ReceivedPresence (Presence { presenceType = PresenceUnavailable, presenceFrom = Just from })) -> do
				let cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid
				-- Delete <barejid>/resource and <cheogramjid>/resource
				void $ Redis.runRedis redis $ do
					Redis.hdel (encodeUtf8 $ bareTxt from) [encodeUtf8 $ maybe mempty strResource $ jidResource from]
					Redis.hdel (encodeUtf8 $ cheogramBareJid) [encodeUtf8 $ maybe mempty strResource $ jidResource from]
			(ReceivedIQ iq@(IQ { iqType = IQResult, iqFrom = Just from }))
				| Just query <- child (s"{http://jabber.org/protocol/disco#info}query") iq -> do
				let cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid
				let bver = discoToCapsHash query
				-- Write <ver> with the list of features
				void $ Redis.runRedis redis $ do
					Redis.sadd bver (encodeUtf8 <$> discoVars query)
				-- Write ver to <barejid>/resource and <cheogramjid>/resource
					Right ravailableness <- (fmap . fmap) (maybe (BS.pack [0,0]) (BS.take 2)) $ Redis.hget (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from)
					let val = ravailableness ++ bver
					Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
					Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val
			_ -> return ()
		flip forkFinallyXMPP (either (log "RECEIVE ONE" . show) return) $ case (stanzaFrom $ receivedStanza stanza, stanzaTo $ receivedStanza stanza, mapToBackend backendHost =<< stanzaTo (receivedStanza stanza), fmap strNode . jidNode =<< stanzaTo (receivedStanza stanza), stanza) of
			(_, Just to, _, _, ReceivedIQ iq@(IQ { iqType = typ }))
				| typ `elem` [IQResult, IQError],
				  (strResource <$> jidResource to) `elem` map Just [s"adhocbot", s"IQMANAGER"] ->
					iqReceiver iq
			(Just from, Just to, _, _, ReceivedMessage (Message { messageType = MessageError }))
				| strDomain (jidDomain from) == backendHost,
				  to == componentJid ->
					log "backend error" stanza
			(Just from, Just to, _, _, ReceivedMessage m)
				| strDomain (jidDomain from) == backendHost,
				  to == componentJid,
				  [] <- isNamed (s"{http://jabber.org/protocol/address}addresses") =<< messagePayloads m,
				  Just txt <- getBody "jabber:component:accept" m,
				  Just cheoJid <- mapToComponent from,
				  fmap strNode (jidNode from) /= Just did ->
					liftIO (mapM_ sendToComponent =<< processSMS db componentJid conferenceServers from cheoJid txt (getThread "jabber:component:accept" m))
			(Just from, Just to, Nothing, Just localpart, ReceivedMessage m)
				| Just txt <- getBody "jabber:component:accept" m,
				  Just owner <- parseJID (unescapeJid localpart),
				  (T.length txt == 144 || T.length txt == 145) && (s"CHEOGRAM") `T.isPrefixOf` txt -> liftIO $ do -- the length of our token messages
					log "POSSIBLE TOKEN" (from, to, txt)
					maybeRoute <- DB.get db (DB.byJid owner ["direct-message-route"])
					when (Just (strDomain $ jidDomain from) == maybeRoute || bareTxt from == bareTxt owner) $ do
						maybeToken <- DB.get db (DB.byJid owner ["addtoken"])
						case (fmap (first parseJID) (readZ . textToString =<< maybeToken)) of
							(Just (Just cheoJid, token)) | (s"CHEOGRAM"++token) == txt -> do
								log "SET OWNER" (cheoJid, owner)

								DB.set db (DB.byJid owner ["cheoJid"]) (formatJID cheoJid)
								DB.sadd db (DB.byNode cheoJid ["owners"]) [bareTxt owner]

							_ -> log "NO TOKEN FOUND, or mismatch" maybeToken
			(Just from, Just to, Nothing, Just localpart, _)
				| Just multipleTo <- mapM localpartToURI (T.split (==',') localpart),
				  ReceivedMessage m <- stanza,
				  Just backendJid <- parseJID backendHost -> liftIO $ do
					m' <- UIO.lift $ cacheOOB (const Nothing) False $ m { messagePayloads = messagePayloads m ++ [
							Element (s"{http://jabber.org/protocol/address}addresses") [] $ map (\oneto ->
								NodeElement $ Element (s"{http://jabber.org/protocol/address}address") [
									(s"{http://jabber.org/protocol/address}type", [ContentText $ s"to"]),
									(s"{http://jabber.org/protocol/address}uri", [ContentText oneto])
								] []
							) multipleTo
						] }
					UIO.lift $ rememberOutgoingBody db m'
					-- TODO: should check if backend supports XEP-0033
					-- TODO: fallback for no-backend case should work
					mapM_ sendToComponent =<< componentMessage db componentJid m' Nothing from backendJid (getBody "jabber:component:accept" m')
				| (s"sip.cheogram.com") == strDomain (jidDomain from) -> liftIO $ do
					let (toResource, fromResource)
						| Just toResource <- T.stripPrefix (s"CHEOGRAM%outbound-sip%") =<< (strResource <$> jidResource to) = (toResource, s"tel")
						| otherwise = (fromMaybe mempty (strResource <$> jidResource to), s"sip:" ++ escapeJid (formatJID from))
					case (mapLocalpartToBackend (formatJID componentJid) =<< sanitizeSipLocalpart (maybe mempty strNode $ jidNode from), parseJID (unescapeJid localpart ++ s"/" ++ toResource)) of
						(Just componentFrom, Just routeTo) -> liftIO $ do
							Just componentFromSip <- return $ parseJID (formatJID componentFrom ++ s"/" ++ fromResource)
							sendToComponent $ mkStanzaRec $ receivedStanza $ receivedStanzaFromTo componentFromSip routeTo stanza
						_ ->
							mapM_ sendToComponent $ stanzaError stanza $
								Element (fromString "{jabber:component:accept}error")
								[(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])]
								[NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}item-not-found") [] []]
			(Just from, Just to, Nothing, Just localpart, _)
				| Nothing <- mapM localpartToURI (T.split (==',') $ fromMaybe mempty $ fmap strNode $ jidNode to),
				  Just routeTo <- parseJID (unescapeJid localpart ++ maybe mempty (s"/"++) (strResource <$> jidResource to)),
				  fmap (((s"CHEOGRAM%") `T.isPrefixOf`) . strResource) (jidResource to) /= Just True -> liftIO $ do
					maybeRoute <- DB.get db (DB.byJid routeTo ["direct-message-route"])
					case (maybeRoute, mapToComponent from) of
						(Just route, _)
							| route == bareTxt from,
							  ReceivedIQ iq <- stanza,
							  iqType iq == IQSet,
							  [query] <- isNamed (fromString "{jabber:iq:register}query") =<< maybeToList (iqPayload iq) -> do
								deleteDirectMessageRoute db routeTo
								sendToComponent $ mkStanzaRec $ iqReply
									(Just $ Element (