forked from singpolyma/cheogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.hs
1745 lines (1632 loc) · 84.8 KB
/
Main.hs
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
{-# LANGUAGE PackageImports #-}
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.Environment (getArgs)
import Control.Error (readZ, syncIO, runExceptT, MaybeT(..), hoistMaybe)
import Data.Time (UTCTime, addUTCTime, diffUTCTime, getCurrentTime)
import Network (PortID(PortNumber))
import System.Random (Random(randomR), getStdRandom)
import System.Random.Shuffle (shuffleM)
import Data.Digest.Pure.SHA (sha1, bytestringDigest)
import "monads-tf" Control.Monad.Error (catchError) -- ick
import Data.XML.Types (Element(..), Node(NodeContent, NodeElement), Name(Name), Content(ContentText), isNamed, hasAttributeText, elementText, elementChildren, attributeText)
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.UUID as UUID ( toString )
import qualified Data.UUID.V1 as UUID ( nextUUID )
import qualified Data.ByteString.Lazy as LZ
import qualified Data.ByteString.Base64 as Base64
import qualified Database.TokyoCabinet as TC
import Network.Protocol.XMPP -- should import qualified
import Util
import qualified ConfigureDirectMessageRoute
instance Ord JID where
compare x y = compare (show x) (show y)
data StanzaRec = StanzaRec (Maybe JID) (Maybe JID) (Maybe Text) (Maybe Text) [Element] Element deriving (Show)
mkStanzaRec x = StanzaRec (stanzaTo x) (stanzaFrom x) (stanzaID x) (stanzaLang x) (stanzaPayloads x) (stanzaToElement x)
instance Stanza StanzaRec where
stanzaTo (StanzaRec to _ _ _ _ _) = to
stanzaFrom (StanzaRec _ from _ _ _ _) = from
stanzaID (StanzaRec _ _ id _ _ _) = id
stanzaLang (StanzaRec _ _ _ lang _ _) = lang
stanzaPayloads (StanzaRec _ _ _ _ payloads _) = payloads
stanzaToElement (StanzaRec _ _ _ _ _ element) = element
mkSMS from to txt = (emptyMessage MessageChat) {
messageTo = Just to,
messageFrom = Just from,
messagePayloads = [Element (fromString "{jabber:component:accept}body") [] [NodeContent $ ContentText txt]]
}
tcKey jid key = fmap (\node -> (T.unpack $ strNode node) <> "\0" <> key) (jidNode jid)
tcGetJID db jid key = liftIO $ case tcKey jid key of
Just tck -> (parseJID . fromString =<<) <$> TC.runTCM (TC.get db tck)
Nothing -> return Nothing
tcPutJID db cheoJid key jid = tcPut db cheoJid key $ T.unpack $ formatJID jid
tcPut db cheoJid key val = liftIO $ do
let Just tck = tcKey cheoJid key
True <- TC.runTCM (TC.put db tck val)
return ()
getBody ns = listToMaybe . fmap (mconcat . elementText) . (isNamed (Name (fromString "body") (Just $ fromString ns) Nothing) <=< messagePayloads)
queryDisco to from = do
uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
return [mkStanzaRec $ (emptyIQ IQGet) {
iqTo = Just to,
iqFrom = Just from,
iqID = uuid,
iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/disco#info}query") [] []
}]
queryCommandList to from = do
uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
return [mkStanzaRec $ (emptyIQ IQGet) {
iqTo = Just to,
iqFrom = Just from,
iqID = uuid,
iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/disco#items}query") [
(s"{http://jabber.org/protocol/disco#items}node", [ContentText $ s"http://jabber.org/protocol/commands"])
] []
}]
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)
forkXMPP :: XMPP () -> XMPP ThreadId
forkXMPP kid = do
session <- getSession
liftIO $ forkIO $ void $ runXMPP session kid
nickFor db jid existingRoom
| fmap bareTxt existingRoom == Just bareFrom = return $ fromMaybe (fromString "nonick") resourceFrom
| Just tel <- normalizeTel =<< strNode <$> jidNode jid = do
mnick <- maybe (return Nothing) (TC.runTCM .TC.get db) (tcKey jid "nick")
case mnick of
Just nick -> return (tel <> fromString " \"" <> fromString nick <> fromString "\"")
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
cheogramAvailable from to =
(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"]),
-- gateway/sms//Cheogram<http://jabber.org/protocol/commands<jabber:iq:gateway<jabber:iq:register<urn:xmpp:ping<vcard-temp<
(s"{http://jabber.org/protocol/caps}ver", [ContentText $ fromString "JSm4zri7yzqWhI0D9gKJHQd9Gdg="])
] []
]
}
telDiscoFeatures = [
s"http://jabber.org/protocol/muc",
s"jabber:x:conference",
s"urn:xmpp:ping",
s"urn:xmpp:receipts",
s"vcard-temp"
]
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 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 hash])
] []
]
}
where
hash = T.decodeUtf8 $ Base64.encode $ LZ.toStrict $ bytestringDigest $ sha1 $ LZ.fromStrict $ T.encodeUtf8 $ telCapsStr disco
telDiscoInfo 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") [] $
[
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)
}
commandList componentJid id from to extras =
(emptyIQ IQResult) {
iqTo = Just to,
iqFrom = Just from,
iqID = id,
iqPayload = Just $ Element (s"{http://jabber.org/protocol/disco#items}query")
[(s"{http://jabber.org/protocol/disco#items}node", [ContentText $ s"http://jabber.org/protocol/commands"])]
([
NodeElement $ Element (s"{http://jabber.org/protocol/disco#items}item") [
(s"{http://jabber.org/protocol/disco#items}jid", [ContentText $ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName]),
(s"{http://jabber.org/protocol/disco#items}node", [ContentText $ ConfigureDirectMessageRoute.nodeName]),
(s"{http://jabber.org/protocol/disco#items}name", [ContentText $ s"Configure direct message route"])
] []
] ++ extraItems)
}
where
extraItems = map (\el ->
NodeElement $ el {
elementAttributes = map (\(aname, acontent) ->
if aname == s"{http://jabber.org/protocol/disco#items}jid" || aname == s"jid" then
(aname, [ContentText $ formatJID componentJid])
else
(aname, acontent)
) (elementAttributes el)
}
) extras
routeQueryOrReply db componentJid from smsJid resource query reply = do
maybeRoute <- TC.runTCM $ TC.get db (T.unpack (bareTxt from) ++ "\0direct-message-route")
case (fmap fromString 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)
routeDiscoOrReply db componentJid from smsJid resource reply =
routeQueryOrReply db componentJid from smsJid resource queryDisco 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
}
unregisterDirectMessageRoute db componentJid userJid route = do
maybeCheoJid <- (parseJID . fromString =<<) <$> TC.runTCM (TC.get db (T.unpack (bareTxt userJid) ++ "\0cheoJid"))
forM_ maybeCheoJid $ \cheoJid -> do
TC.runTCM $ TC.out db (T.unpack (bareTxt userJid) ++ "\0cheoJid")
owners <- (fromMaybe [] . (readZ =<<)) <$>
maybe (return Nothing) (TC.runTCM . TC.get db) (tcKey cheoJid "owners")
tcPut db cheoJid "owners" (show $ (filter (/= bareTxt userJid)) owners)
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 bareFrom resourceFrom smsJid m fallback = do
maybeRoute <- TC.runTCM $ TC.get db (T.unpack bareFrom ++ "\0direct-message-route")
case (fmap fromString maybeRoute, parseJID $ escapeJid bareFrom ++ s"@" ++ formatJID componentJid ++ resourceSuffix) of
(Just route, Just routeFrom) -> do
log "TO DIRECT ROUTE" route
return [mkStanzaRec $ m {
messageFrom = Just routeFrom,
messageTo = parseJID $ (fromMaybe mempty $ strNode <$> jidNode smsJid) ++ s"@" ++ route
}]
_ -> fallback
where
resourceSuffix = maybe mempty (s"/"++) resourceFrom
componentMessage db componentJid (m@Message { messageType = MessageError }) _ bareFrom resourceFrom smsJid body = do
log "MESSAGE ERROR" m
toRouteOrFallback db componentJid bareFrom resourceFrom 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 }) existingRoom _ _ smsJid _
| Just invite <- getMediatedInvitation m <|> getDirectInvitation m = do
log "GOT INVITE" (invite, m)
forM_ (invitePassword invite) $ \password ->
tcPut db to (T.unpack (formatJID $ inviteMUC invite) <> "\0muc_roomsecret") (T.unpack password)
existingInvite <- tcGetJID db to "invited"
nick <- nickFor db (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
tcPutJID db to "invited" (inviteMUC invite)
regJid <- tcGetJID db 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 bareFrom resourceFrom smsJid (Just body) = do
log "MESSAGE FROM GROUP" (existingRoom, body)
if fmap bareTxt existingRoom == Just bareFrom && (
existingRoom /= parseJID (bareFrom <> fromString "/" <> fromMaybe mempty resourceFrom) ||
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, bareFrom, m)
return []
where
txt = mconcat [fromString "(", fromMaybe (fromString "nonick") resourceFrom, fromString ") ", body]
componentMessage db componentJid m@(Message { messageFrom = Just from, messageTo = Just to }) existingRoom bareFrom resourceFrom smsJid (Just body) = do
log "WHISPER" (from, smsJid, strippedBody)
ack <- case isNamed (fromString "{urn:xmpp:receipts}request") =<< messagePayloads m of
(_:_) ->
routeDiscoOrReply db componentJid from smsJid ("CHEOGRAM%query-then-send-ack%" ++ extra)
(deliveryReceipt (fromMaybe mempty $ messageID m) to from)
[] -> return []
fmap (++ack) $ toRouteOrFallback db componentJid bareFrom resourceFrom smsJid strippedM $ do
nick <- nickFor db from existingRoom
let txt = mconcat [fromString "(", nick, fromString " whispers) ", strippedBody]
return [mkStanzaRec $ mkSMS componentJid smsJid txt]
where
strippedM = mapBody (const strippedBody) m
strippedBody = stripOtrWhitespace body
extra = T.unpack $ escapeJid $ T.pack $ show (fromMaybe mempty (messageID m), fromMaybe mempty resourceFrom)
componentMessage _ _ m _ _ _ _ _ = do
log "UNKNOWN MESSAGE" m
return []
handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads join
| join,
[x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads,
not $ null $ code "110" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do
log "JOINED" (to, from)
existingInvite <- tcGetJID db to "invited"
when (existingInvite == parseJID bareMUC) $ do
let Just invitedKey = tcKey to "invited"
True <- TC.runTCM $ TC.out db invitedKey
log "JOINED" (to, from, "INVITE CLEARED")
return ()
tcPutJID db to "joined" from
let Just bookmarksKey = tcKey to "bookmarks"
bookmarks <- fmap (fromMaybe [] . (readZ =<<)) (TC.runTCM $ TC.get db bookmarksKey)
tcPut db to "bookmarks" (show $ sort $ nub $ T.unpack bareMUC : bookmarks)
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"
log "JOINED" (to, from, "CREATED")
uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
let fullid = if (T.unpack 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 (T.unpack resourceFrom) presences) -> do
log "JOINED" (to, from, resourceFrom, presences, "YOU HAVE JOINED")
fmap ((mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [
fromString "* You have joined ", bareMUC,
fromString " as ", resourceFrom,
fromString " along with\n",
fromString $ intercalate ", " (filter (/= T.unpack 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
log "CHANGED NICK" (to, x)
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, rejoin in 5s" (to, from)
void $ forkIO $ threadDelay 5000000 >> atomically (writeTChan toRejoinManager $ ForceRejoin from to)
return []
| not join && existingRoom == Just from = do
log "YOU HAVE LEFT" (to, existingRoom)
let Just joinedKey = tcKey to "joined"
True <- TC.runTCM $ TC.out db joinedKey
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 = do
log "UNKNOWN JOIN" (existingRoom, from, to, payloads, join)
atomically $ writeTChan toRoomPresences $ RecordJoin to from (participantJid payloads)
return []
| otherwise = do
log "UNKNOWN NOT JOIN" (existingRoom, from, to, payloads, join)
atomically $ writeTChan toRoomPresences $ RecordPart to from
return []
where
resourceFrom = fromMaybe mempty (strResource <$> jidResource from)
Just room = parseJID bareMUC
bareMUC = bareTxt from
verificationResponse =
Element (fromString "{jabber:iq:register}query") []
[
NodeElement $ Element (fromString "{jabber:iq:register}instructions") [] [
NodeContent $ ContentText $ fromString "Enter the verification code CheoGram texted you."
],
NodeElement $ Element (fromString "{jabber:iq:register}password") [] [],
NodeElement $ Element (fromString "{jabber:x:data}x") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "form"])
] [
NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ fromString "Verify Phone Number"],
NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [
NodeContent $ ContentText $ fromString "Enter the verification code CheoGram texted you."
],
NodeElement $ Element (fromString "{jabber:x:data}field") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "hidden"]),
(fromString "{jabber:x:data}var", [ContentText $ fromString "FORM_TYPE"])
] [
NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ fromString "jabber:iq:register"]
],
NodeElement $ Element (fromString "{jabber:x:data}field") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "text-single"]),
(fromString "{jabber:x:data}var", [ContentText $ fromString "password"]),
(fromString "{jabber:x:data}label", [ContentText $ fromString "Verification code"])
] []
]
]
data RegistrationCode = RegistrationCode { regCode :: Int, cheoJid :: Text, expires :: UTCTime } deriving (Show, Read)
registerVerification db componentJid to iq = do
log "REGISTERVERIFIFCATION" (to, iq)
code <- getStdRandom (randomR (123457::Int,987653))
time <- getCurrentTime
True <- TC.runTCM $ TC.put db ((maybe mempty T.unpack $ bareTxt <$> iqFrom iq) <> "\0registration_code") $ show $ RegistrationCode code (formatJID to) time
return [
mkStanzaRec $ mkSMS componentJid to $ fromString ("Enter this verification code to complete registration: " <> show code),
mkStanzaRec $ iq {
iqTo = iqFrom iq,
iqFrom = iqTo iq,
iqType = IQResult,
iqPayload = Just verificationResponse
}
]
handleVerificationCode db componentJid password iq = do
time <- getCurrentTime
codeAndTime <- fmap (readZ =<<) $ TC.runTCM $ TC.get db regKey
log "HANDLEVERIFICATIONCODE" (password, iq, time, codeAndTime)
case codeAndTime of
Just (RegistrationCode { regCode = code, cheoJid = cheoJidT })
| fmap expires codeAndTime > Just ((-300) `addUTCTime` time) ->
case (show code == T.unpack password, iqTo iq, iqFrom iq, parseJID cheoJidT) of
(True, Just to, Just from, Just cheoJid) -> do
bookmarks <- fmap (fromMaybe [] . (readZ =<<)) (maybe (return Nothing) (TC.runTCM . TC.get db) (tcKey cheoJid "bookmarks"))
invites <- fmap concat $ forM (mapMaybe parseJID bookmarks) $ \bookmark ->
sendInvite db from (Invite bookmark cheoJid (Just $ fromString "Cheogram registration") Nothing)
let Just tel = T.unpack . strNode <$> jidNode cheoJid
True <- TC.runTCM $ TC.put db (T.unpack (bareTxt from) <> "\0registered") tel
tcPutJID db cheoJid "registered" from
stuff <- runMaybeT $ do
-- If there is a nick that doesn't end in _sms, add _sms
nick <- MaybeT . TC.runTCM . TC.get db =<< (hoistMaybe $ tcKey cheoJid "nick")
let nick' = (fromMaybe (fromString nick) $ T.stripSuffix (fromString "_sms") (fromString nick)) <> fromString "_sms"
tcPut db cheoJid "nick" (T.unpack nick')
room <- MaybeT ((parseJID <=< fmap bareTxt) <$> tcGetJID db cheoJid "joined")
toJoin <- hoistMaybe $ parseJID (bareTxt room <> fromString "/" <> nick')
liftIO $ joinRoom db cheoJid toJoin
return ((mkStanzaRec $ iq {
iqTo = iqFrom iq,
iqFrom = iqTo iq,
iqType = IQResult,
iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] []
}):invites)
_ ->
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 "auth"])]
[NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}not-authorized") [] []]
}]
_ -> do
void $ TC.runTCM $ TC.out db regKey
return []
where
regKey = (maybe mempty T.unpack $ bareTxt <$> iqFrom iq) <> "\0registration_code"
handleRegister db componentJid iq@(IQ { iqType = IQGet }) _ = do
time <- getCurrentTime
codeAndTime <- fmap (readZ =<<) $ TC.runTCM $ TC.get db ((maybe mempty T.unpack $ bareTxt <$> iqFrom iq) <> "\0registration_code")
log "HANDLEREGISTER IQGet" (time, codeAndTime, iq)
if fmap expires codeAndTime > Just ((-300) `addUTCTime` time) then
return [mkStanzaRec $ iq {
iqTo = iqFrom iq,
iqFrom = iqTo iq,
iqType = IQResult,
iqPayload = Just verificationResponse
}]
else
return [mkStanzaRec $ iq {
iqTo = iqFrom iq,
iqFrom = iqTo iq,
iqType = IQResult,
iqPayload = Just $ Element (fromString "{jabber:iq:register}query") []
[
NodeElement $ Element (fromString "{jabber:iq:register}instructions") [] [
NodeContent $ ContentText $ fromString "CheoGram can verify your phone number and add you to the private groups you previously texted."
],
NodeElement $ Element (fromString "{jabber:iq:register}phone") [] [],
NodeElement $ Element (fromString "{jabber:x:data}x") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "form"])
] [
NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ fromString "Associate Phone Number"],
NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [
NodeContent $ ContentText $ fromString "CheoGram can verify your phone number and add you to the private groups you previously texted."
],
NodeElement $ Element (fromString "{jabber:x:data}field") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "hidden"]),
(fromString "{jabber:x:data}var", [ContentText $ fromString "FORM_TYPE"])
] [
NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ fromString "jabber:iq:register"]
],
NodeElement $ Element (fromString "{jabber:x:data}field") [
(fromString "{jabber:x:data}type", [ContentText $ fromString "text-single"]),
(fromString "{jabber:x:data}var", [ContentText $ fromString "phone"]),
(fromString "{jabber:x:data}label", [ContentText $ fromString "Phone number"])
] []
]
]
}]
handleRegister db componentJid iq@(IQ { iqType = IQSet }) query
| [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query,
Just to <- ((`telToJid` formatJID componentJid) . T.filter isDigit) =<< getFormField form (fromString "phone") = do
log "HANDLEREGISTER IQSet jabber:x:data phone" iq
registerVerification db componentJid to iq
handleRegister db componentJid iq@(IQ { iqType = IQSet }) query
| [phoneEl] <- isNamed (fromString "{jabber:iq:register}phone") =<< elementChildren query,
Just to <- (`telToJid` formatJID componentJid) $ T.filter isDigit $ mconcat (elementText phoneEl) = do
log "HANDLEREGISTER IQSet jabber:iq:register phone" iq
registerVerification db componentJid to iq
handleRegister db componentJid iq@(IQ { iqType = IQSet }) query
| [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query,
Just password <- getFormField form (fromString "password") = do
log "HANDLEREGISTER IQSet jabber:x:data password" iq
handleVerificationCode db componentJid password iq
handleRegister db componentJid iq@(IQ { iqType = IQSet, iqPayload = Just payload }) query
| [passwordEl] <- isNamed (fromString "{jabber:iq:register}password") =<< elementChildren query = do
log "HANDLEREGISTER IQSet jabber:iq:register password" iq
handleVerificationCode db componentJid (mconcat $ elementText passwordEl) iq
handleRegister db componentJid iq@(IQ { iqType = IQSet }) query
| [_] <- isNamed (fromString "{jabber:iq:register}remove") =<< elementChildren query = do
log "HANDLEREGISTER IQSet jabber:iq:register remove" iq
tel <- maybe mempty T.pack <$> TC.runTCM (TC.get db $ T.unpack (maybe mempty bareTxt $ iqFrom iq) <> "\0registered")
forM_ (telToJid tel (formatJID componentJid) >>= \cheoJid -> tcKey cheoJid "registered") $ \regKey ->
TC.runTCM $ TC.out db regKey
void $ TC.runTCM $ TC.out db $ T.unpack (maybe mempty bareTxt $ iqFrom iq) <> "\0registered"
return [mkStanzaRec $ iq {
iqTo = iqFrom iq,
iqFrom = iqTo iq,
iqType = IQResult,
iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] []
}]
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 []
componentStanza db _ _ _ _ _ _ componentJid (ReceivedMessage (m@Message { messageTo = Just (JID { jidNode = Nothing }), messageFrom = Just from}))
| Just _ <- getBody "jabber:component:accept" m = return [
mkStanzaRec $ mkSMS componentJid from (s"Instead of sending messages to " ++ formatJID componentJid ++ s" directly, you can SMS your contacts by sending messages to +1<phone-number>@" ++ formatJID componentJid ++ s" Jabber IDs. Or, for support, come talk to us in xmpp:[email protected]?join")
]
| otherwise = log "WEIRD BODYLESS MESSAGE DIRECT TO COMPONENT" m >> return []
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
log "CODE104" (to, from)
queryDisco from to
componentStanza db (Just smsJid) _ _ _ _ _ componentJid (ReceivedMessage (m@Message { messageTo = Just to, messageFrom = Just from})) = do
log "RECEIVEDMESSAGE" m
existingRoom <- tcGetJID db to "joined"
componentMessage db componentJid m existingRoom (bareTxt from) resourceFrom smsJid $
getBody "jabber:component:accept" m
where
resourceFrom = strResource <$> jidResource from
componentStanza _ (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, try again in 10s" p
void $ forkIO $ threadDelay 10000000 >> atomically (writeTChan toRejoinManager $ ForceRejoin from to)
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 db (Just smsJid) _ toRoomPresences toRejoinManager toJoinPartDebouncer _ componentJid (ReceivedPresence (Presence {
presenceType = typ,
presenceFrom = Just from,
presenceTo = Just to,
presencePayloads = payloads
})) | typ `elem` [PresenceAvailable, PresenceUnavailable] = do
existingRoom <- tcGetJID db to "joined"
log "JOIN PART ROOM" (from, to, typ, existingRoom, payloads)
handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads (typ == PresenceAvailable)
componentStanza _ _ _ _ _ _ _ _ (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do
log "SUBSCRIBE GATEWAY" (from, to)
return [
mkStanzaRec $ (emptyPresence PresenceSubscribed) {
presenceTo = Just from,
presenceFrom = Just to
},
mkStanzaRec $ (emptyPresence PresenceSubscribe) {
presenceTo = Just from,
presenceFrom = Just to
},
mkStanzaRec $ cheogramAvailable to from
]
componentStanza db (Just smsJid) _ _ _ _ _ componentJid (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do
log "SUBSCRIBE TEL" (from, to)
stanzas <- routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" $ telAvailable to from []
return $ [
mkStanzaRec $ (emptyPresence PresenceSubscribed) {
presenceTo = Just from,
presenceFrom = Just to
},
mkStanzaRec $ (emptyPresence PresenceSubscribe) {
presenceTo = Just from,
presenceFrom = Just to
}
] ++ stanzas
componentStanza _ _ _ _ _ _ _ _ (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do
log "RESPOND TO PROBES" (from, to)
return [mkStanzaRec $ cheogramAvailable to from]
componentStanza db (Just smsJid) _ _ _ _ _ componentJid (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do
log "RESPOND TO TEL PROBES" smsJid
routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" $ telAvailable to from []
componentStanza _ _ registrationJids _ _ _ processDirectMessageRouteConfig componentJid (ReceivedIQ (IQ { iqType = IQSet, iqTo = Just to, iqFrom = Just from, iqID = Just id, iqPayload = Just p }))
| jidNode to == Nothing,
[iqEl] <- isNamed (s"{jabber:client}iq") =<< elementChildren =<< isNamed (s"{urn:xmpp:forward:0}forwarded") p,
[payload] <- isNamed (s"{http://jabber.org/protocol/commands}command") =<< elementChildren iqEl,
Just asFrom <- parseJID =<< attributeText (s"from") iqEl,
bareTxt from `elem` map bareTxt registrationJids = do
log "COMMAND ON BEHALF OF" (from, asFrom, payload)
replyIQ <- processDirectMessageRouteConfig $ (emptyIQ IQSet) {
iqID = Just id,
iqTo = Just to,
iqFrom = Just asFrom,
iqPayload = Just payload
}
let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ)
let subscribe = if attributeText (s"action") payload /= Just (s"complete") then [] else [
mkStanzaRec $ (emptyPresence PresenceSubscribe) {
presenceTo = Just asFrom,
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."
]
]
}
]
return $ subscribe ++ [mkStanzaRec $ replyIQ {
iqTo = if iqTo replyIQ == Just asFrom then Just from else iqTo replyIQ,
iqID = if iqType replyIQ == IQResult then iqID replyIQ else Just $ fromString $ show (formatJID from, formatJID asFrom, iqID replyIQ),
iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName)
}]
componentStanza _ _ _ _ _ _ processDirectMessageRouteConfig componentJid (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = payload }))
| fmap strResource (jidResource to) == Just (s"CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName),
Just (fwdBy, onBehalf, iqId) <- readZ . T.unpack =<< iqID iq = do
log "FWD BY" (fwdBy, onBehalf, iqId, iq)
replyIQ <- processDirectMessageRouteConfig (iq { iqID = iqId })
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,
iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName)
}]
componentStanza _ _ _ _ _ _ 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
log "PART OF COMMAND" iq
replyIQ <- processDirectMessageRouteConfig iq
let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ)
return [mkStanzaRec $ replyIQ {
iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName)
}]
componentStanza 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
log "LOOKS LIKE REGISTRATION" iq
return [mkStanzaRec $ iqNotImplemented iq]
componentStanza db _ _ _ _ _ _ componentJid (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = id, iqPayload = Just p }))
| Nothing <- jidNode to,
[_] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do
log "DISCO ON US" (from, to, p)
return [mkStanzaRec $ (emptyIQ IQResult) {
iqTo = Just from,
iqFrom = Just to,
iqID = id,
iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/disco#info}query") []
[
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}identity") [
(fromString "{http://jabber.org/protocol/disco#info}category", [ContentText $ fromString "gateway"]),
(fromString "{http://jabber.org/protocol/disco#info}type", [ContentText $ fromString "sms"]),
(fromString "{http://jabber.org/protocol/disco#info}name", [ContentText $ fromString "Cheogram"])
] [],
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText $ fromString "http://jabber.org/protocol/commands"])
] [],
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText $ fromString "jabber:iq:gateway"])
] [],
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText $ fromString "jabber:iq:register"])
] [],
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText $ fromString "urn:xmpp:ping"])
] [],
NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [
(fromString "{http://jabber.org/protocol/disco#info}var", [ContentText $ fromString "vcard-temp"])
] []
]
}]
| Nothing <- jidNode to,
[s"http://jabber.org/protocol/commands"] ==
mapMaybe (attributeText (s"node")) (isNamed (fromString "{http://jabber.org/protocol/disco#items}query") p) = do
log "componentStanza QUERY FOR COMMAND LIST" to
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."]
]
}]
where
extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom)
resourceFrom = strResource <$> jidResource from
componentStanza db (Just smsJid) _ _ _ _ _ componentJid (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = Just id, iqPayload = Just p }))
| Just _ <- jidNode to,
[_] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do
log "DISCO ON USER" (from, to, p)
routeDiscoOrReply db componentJid from smsJid ("CHEOGRAM%query-then-send-disco-info%" ++ extra) $
telDiscoInfo id to from []
| Just tel <- strNode <$> jidNode to,
[_] <- isNamed (s"{vcard-temp}vCard") p = do
--owners <- (fromMaybe [] . (readZ =<<)) <$>
-- maybe (return Nothing) (TC.runTCM . TC.get db) (tcKey smsJid "owners")
return [mkStanzaRec $ (emptyIQ IQResult) {
iqTo = Just from,
iqFrom = Just to,
iqID = Just id,
iqPayload = Just $ Element (s"{vcard-temp}vCard") [] (
[
NodeElement $ Element (s"{vcard-temp}TEL") [] [
NodeElement $ Element (s"{vcard-temp}NUMBER") [] [NodeContent $ ContentText tel]
]
]
--map (\owner -> NodeElement (Element (s"{vcard-temp}JABBERID") [] [NodeContent $ ContentText owner])) owners
)
}]
where
extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom)
resourceFrom = strResource <$> jidResource from
componentStanza _ _ _ _ _ _ _ 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
log "jabber:iq:gateway submit" (from, to, p)
case telToJid (T.filter isDigit $ 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
log "jabber:iq:gateway query" (from, to, p)
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 db _ _ _ _ _ _ componentJid (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 <- maybe (return Nothing) (TC.runTCM . TC.get db) (tcKey cheoJid "nick")
let nick = maybe (maybe mempty strNode (jidNode cheoJid)) fromString 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 _ _ _ _ _ _ _ componentJid (ReceivedIQ (iq@IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to }))
| (strNode <$> jidNode to) == Just (fromString "create"),
Just resource <- strResource <$> jidResource to = do
log "create@ RESULT" (from, to, iq)
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 _ _ _ _ toRejoinManager _ _ _ (ReceivedIQ (iq@IQ { iqType = IQResult, iqID = Just id, iqFrom = Just from }))
| fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do
log "PING RESULT" from
atomically $ writeTChan toRejoinManager (PingReply from)
return []
componentStanza _ _ _ _ toRejoinManager _ _ _ (ReceivedIQ (iq@IQ { iqType = IQError, iqID = Just id, iqFrom = Just from }))
| fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do
log "PING ERROR RESULT" from
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
log "MUC DISCO RESULT" (from, to, p)
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 _ (Just smsJid) _ _ _ _ _ componentJid (ReceivedIQ (iq@IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to, iqID = Just id }))
| fromString "CHEOGRAMCREATE%" `T.isPrefixOf` id = do
log "CHEOGRAMCREATE RESULT YOU HAVE CREATED" (from, to, iq)
fmap (((mkStanzaRec $ mkSMS componentJid smsJid (mconcat [fromString "* You have created ", bareTxt from])):) . concat . toList) $
forM (parseJID $ bareTxt to <> fromString "/create") $
queryDisco from
componentStanza db _ _ _ _ _ _ componentJid (ReceivedIQ iq@(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
log "ERROR FROM ROUTE, SEND DEFAULT COMMAND LIST" iq
return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo []]
else do
log "COMMANDS FROM ROUTE, MERGE WITH OURS AND SEND" iq
let items = isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren p
return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo items]
componentStanza db _ _ _ _ _ _ componentJid (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
log "DISCO RESULT, DO NOT SEND ACK" (from, to, features)
return []
else do
log "DISCO RESULT, NOW SEND ACK" (from, to, routeFrom, routeTo, features)
return [mkStanzaRec $ deliveryReceipt messageId routeFrom routeTo]
| Just idAndResource <- T.stripPrefix (s"CHEOGRAM%query-then-send-disco-info%") . strResource =<< jidResource to,
Just (iqID, 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) = do
log "DISCO RESULT, NOW SEND INFO ONWARD" (from, to, routeFrom, routeTo)