├── .builds
└── guix.yml
├── .gitignore
├── Adhoc.hs
├── COPYING
├── CommandAction.hs
├── Config.hs
├── ConfigureDirectMessageRoute.hs
├── DB.hs
├── IQManager.hs
├── JidSwitch.hs
├── Main.hs
├── Makefile
├── README
├── RedisURL.hs
├── Setup.hs
├── StanzaRec.hs
├── UniquePrefix.hs
├── Util.hs
├── VCard4.hs
├── cheogram.cabal
├── guix.scm
└── manifest.scm
/.builds/guix.yml:
--------------------------------------------------------------------------------
1 | image: guix
2 | packages:
3 | - plzip
4 | sources:
5 | - https://git.sr.ht/~singpolyma/cheogram
6 | secrets:
7 | - 9ded4157-4cf9-42ae-b7d0-55eb6e52ea37
8 | - fd52c9ce-04e8-4684-af6c-1ab78d2e124a
9 | artifacts:
10 | - cheogram.scm
11 | - cheogram.nar.lz
12 | tasks:
13 | - bake: |
14 | printf "(define-module (cheogram))\n" >> cheogram.scm
15 | sed '/^;;;;$/q' cheogram/guix.scm >> cheogram.scm
16 | printf "(define-public cheogram\n\t" >> cheogram.scm
17 | cd cheogram
18 | printf '(load "%s/guix.scm")\n(write cheogram-baked)\n' "$(pwd)" | guix repl /dev/stdin >> ../cheogram.scm
19 | cd -
20 | printf ")\n" >> cheogram.scm
21 | rm -f cheogram/guix.scm
22 | [ "$BUILD_REASON" = patchset ] || rm -rf cheogram
23 | - build: |
24 | if [ "$BUILD_REASON" = patchset ]; then with_source="--with-source=$PWD/cheogram"; fi
25 | guix build $with_source --no-grafts -r out -L. cheogram
26 | - archive: |
27 | if [ -e signing-key.sec ]; then
28 | sudo mv signing-key.pub /etc/guix/
29 | sudo mv signing-key.sec /etc/guix/
30 | sudo chown root:root /etc/guix/signing-key.sec
31 | sudo chmod 0400 /etc/guix/signing-key.sec
32 | fi
33 | guix archive --export -r --no-grafts $(readlink -f out-*) > cheogram.nar
34 | plzip cheogram.nar
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 | report.html
3 | cheogram
4 | *.o
5 | *.hi
6 |
--------------------------------------------------------------------------------
/Adhoc.hs:
--------------------------------------------------------------------------------
1 | module Adhoc (adhocBotSession, commandList, queryCommandList) where
2 |
3 | import Prelude ()
4 | import BasicPrelude hiding (log)
5 | import Control.Concurrent (myThreadId, killThread)
6 | import Control.Concurrent.STM
7 | import Control.Error (hush, ExceptT, runExceptT, throwE, justZ)
8 | import Data.XML.Types as XML (Element(..), Node(NodeContent, NodeElement), Content(ContentText), isNamed, elementText, elementChildren, attributeText)
9 | import qualified Data.XML.Types as XML
10 |
11 | import Network.Protocol.XMPP (JID(..), parseJID, formatJID, IQ(..), IQType(..), emptyIQ, Message(..))
12 | import qualified Network.Protocol.XMPP as XMPP
13 |
14 | import qualified Data.CaseInsensitive as CI
15 | import qualified Control.Concurrent.STM.Delay as Delay
16 | import qualified Data.Attoparsec.Text as Atto
17 | import qualified Data.Bool.HT as HT
18 | import qualified Data.Set as Set
19 | import qualified Data.Text as T
20 | import qualified Data.UUID as UUID ( toString, toText )
21 | import qualified Data.UUID.V1 as UUID ( nextUUID )
22 | import qualified UnexceptionalIO.Trans ()
23 | import qualified UnexceptionalIO as UIO
24 |
25 | import CommandAction
26 | import StanzaRec
27 | import UniquePrefix
28 | import Util
29 | import qualified ConfigureDirectMessageRoute
30 | import qualified JidSwitch
31 | import qualified DB
32 |
33 | sessionLifespan :: Int
34 | sessionLifespan = 60 * 60 * seconds
35 | where
36 | seconds = 1000000
37 |
38 | addOriginUUID :: (UIO.Unexceptional m) => XMPP.Message -> m XMPP.Message
39 | addOriginUUID msg = maybe msg (addTag msg) <$> fromIO_ UUID.nextUUID
40 | where
41 | addTag msg uuid = msg { messagePayloads = Element (s"{urn:xmpp:sid:0}origin-id") [(s"id", [ContentText $ UUID.toText uuid])] [] : messagePayloads msg }
42 |
43 | botHelp :: Maybe Text -> IQ -> Maybe Message
44 | botHelp header (IQ { iqTo = Just to, iqFrom = Just from, iqPayload = Just payload }) =
45 | Just $ mkSMS from to $ maybe mempty (++ s"\n") header ++ (s"Help:\n\t") ++ intercalate (s"\n\t") (map (\item ->
46 | fromMaybe mempty (attributeText (s"node") item) ++ s": " ++
47 | fromMaybe mempty (attributeText (s"name") item)
48 | ) items)
49 | where
50 | items = isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren payload
51 | botHelp _ _ = Nothing
52 |
53 | -- This replaces certain commands that the SGX supports with our sugared versions
54 | maskCommands :: XMPP.JID -> [Element] -> [Element]
55 | maskCommands componentJid = map (\el ->
56 | if attributeText (s"node") el == Just ConfigureDirectMessageRoute.switchBackendNodeName then
57 | Element (s"{http://jabber.org/protocol/disco#items}item") [
58 | (s"jid", [ContentText $ formatJID componentJid ++ s"/CHEOGRAM%" ++ JidSwitch.nodeName]),
59 | (s"node", [ContentText JidSwitch.nodeName]),
60 | (s"name", [ContentText $ s"Change your Jabber ID"])
61 | ] []
62 | else
63 | el
64 | )
65 |
66 | commandList :: JID -> Maybe Text -> JID -> JID -> [Element] -> IQ
67 | commandList componentJid qid from to extras =
68 | (emptyIQ IQResult) {
69 | iqTo = Just to,
70 | iqFrom = Just from,
71 | iqID = qid,
72 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/disco#items}query")
73 | [(s"{http://jabber.org/protocol/disco#items}node", [ContentText $ s"http://jabber.org/protocol/commands"])]
74 | (extraItems ++ [
75 | NodeElement $ Element (s"{http://jabber.org/protocol/disco#items}item") [
76 | (s"jid", [ContentText $ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName]),
77 | (s"node", [ContentText $ ConfigureDirectMessageRoute.nodeName]),
78 | (s"name", [ContentText $ s"Register with backend"])
79 | ] []
80 | ])
81 | }
82 | where
83 | extraItems = map NodeElement $ maskCommands componentJid $ map (\el ->
84 | el {
85 | elementAttributes = map (\(aname, acontent) ->
86 | if aname == s"{http://jabber.org/protocol/disco#items}jid" || aname == s"jid" then
87 | (aname, [ContentText $ formatJID componentJid])
88 | else
89 | (aname, acontent)
90 | ) (elementAttributes el)
91 | }
92 | ) $ filter (\el ->
93 | attributeText (s"node") el /= Just (s"jabber:iq:register")
94 | ) extras
95 |
96 | withNext :: (UIO.Unexceptional m) =>
97 | m XMPP.Message
98 | -> Element
99 | -> (ExceptT [Element] m XMPP.Message -> ExceptT [Element] m [Element])
100 | -> m [Element]
101 | withNext getMessage field answerField
102 | | isRequired field && T.null (mconcat $ fieldValue field) = do
103 | either return return =<< runExceptT (answerField $ lift getMessage)
104 | | otherwise =
105 | either return return =<< runExceptT (answerField suspension)
106 | where
107 | suspension = do
108 | m <- lift getMessage
109 | if fmap CI.mk (getBody (s"jabber:component:accept") m) == Just (s"next") then
110 | throwE [field]
111 | else
112 | return m
113 |
114 | withCancel :: (UIO.Unexceptional m) => Int -> (Text -> m ()) -> m () -> STM XMPP.Message -> m XMPP.Message
115 | withCancel sessionLength sendText cancelSession getMessage = do
116 | delay <- fromIO_ $ Delay.newDelay sessionLength
117 | maybeMsg <- atomicUIO $
118 | (Delay.waitDelay delay *> pure Nothing)
119 | <|>
120 | Just <$> getMessage
121 | case maybeMsg of
122 | Just msg
123 | | (CI.mk <$> getBody (s"jabber:component:accept") msg) == Just (s"cancel") -> cancel $ s"cancelled"
124 | Just msg -> return msg
125 | Nothing -> cancel $ s"expired"
126 | where
127 | cancel t = do
128 | sendText t
129 | cancelSession
130 | fromIO_ $ myThreadId >>= killThread
131 | return $ error "Unreachable"
132 |
133 | queryCommandList :: JID -> JID -> IO [StanzaRec]
134 | queryCommandList to from = do
135 | uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID
136 | return [mkStanzaRec $ (queryCommandList' to from) {iqID = uuid}]
137 |
138 | untilParse :: (UIO.Unexceptional m) => m Message -> m () -> (Text -> Maybe b) -> m b
139 | untilParse getText onFail parser = do
140 | text <- (fromMaybe mempty . getBody "jabber:component:accept") <$> getText
141 | maybe parseFail return $ parser text
142 | where
143 | parseFail = do
144 | onFail
145 | untilParse getText onFail parser
146 |
147 | formatLabel :: (Text -> Maybe Text) -> Element -> Text
148 | formatLabel valueFormatter field = lbl ++ value ++ descSuffix
149 | where
150 | lbl = maybe (fromMaybe mempty $ attributeText (s"var") field) T.toTitle $ label field
151 | value = maybe mempty (\v -> s" [Current value " ++ v ++ s"]") $ valueFormatter <=< mfilter (not . T.null) $ Just $ intercalate (s", ") (fieldValue field)
152 | descSuffix = maybe mempty (\dsc -> s"\n(" ++ dsc ++ s")") $ desc field
153 |
154 | adhocBotAnswerFixed :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
155 | adhocBotAnswerFixed sendText _getMessage field = do
156 | let values = fmap (mconcat . elementText) $ isNamed (s"{jabber:x:data}value") =<< elementChildren field
157 | sendText $ formatLabel (const Nothing) field
158 | sendText $ unlines values
159 | return []
160 |
161 | adhocBotAnswerBoolean :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
162 | adhocBotAnswerBoolean sendText getMessage field = do
163 | case attributeText (s"var") field of
164 | Just var -> do
165 | sendText $ formatLabel (fmap formatBool . hush . Atto.parseOnly parser) field ++ s"\nYes or No?"
166 | value <- untilParse getMessage (sendText helperText) $ hush . Atto.parseOnly parser
167 | return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [
168 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ HT.if' value (s"true") (s"false")]
169 | ]]
170 | _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return []
171 | where
172 | helperText = s"I didn't understand your answer. Please send yes or no"
173 | parser = Atto.skipMany Atto.space *> (
174 | (True <$ Atto.choice (Atto.asciiCI <$> [s"true", s"t", s"1", s"yes", s"y", s"enable", s"enabled"])) <|>
175 | (False <$ Atto.choice (Atto.asciiCI <$> [s"false", s"f", s"0", s"no", s"n", s"disable", s"disabled"]))
176 | ) <* Atto.skipMany Atto.space <* Atto.endOfInput
177 | formatBool True = s"Yes"
178 | formatBool False = s"No"
179 |
180 | adhocBotAnswerTextSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
181 | adhocBotAnswerTextSingle sendText getMessage field = do
182 | case attributeText (s"var") field of
183 | Just var -> do
184 | sendText $ s"Enter " ++ formatLabel Just field
185 | value <- getMessage
186 | case getBody "jabber:component:accept" value of
187 | Just body -> return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [
188 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText body]
189 | ]]
190 | Nothing -> return []
191 | _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return []
192 |
193 | listOptionText :: (Foldable t) => t Text -> Text -> (Int, Element) -> Text
194 | listOptionText currentValues currentValueText (n, v) = tshow n ++ s". " ++ optionText v ++ selectedText v
195 | where
196 | selectedText option
197 | | mconcat (fieldValue option) `elem` currentValues = currentValueText
198 | | otherwise = mempty
199 |
200 | adhocBotAnswerJidSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
201 | adhocBotAnswerJidSingle sendText getMessage field = do
202 | case attributeText (s"var") field of
203 | Just var -> do
204 | sendText $ s"Enter " ++ formatLabel Just field
205 | value <- untilParse getMessage (sendText helperText) XMPP.parseJID
206 | return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [
207 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ formatJID value]
208 | ]]
209 | _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return []
210 | where
211 | helperText = s"I didn't understand your answer. Please send only a valid JID like person@example.com or perhaps just example.com"
212 |
213 | adhocBotAnswerListMulti :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
214 | adhocBotAnswerListMulti sendText getMessage field = do
215 | case attributeText (s"var") field of
216 | Just var -> do
217 | let options = zip [1..] $ isNamed(s"{jabber:x:data}option") =<< elementChildren field
218 | let currentValues = fieldValue field
219 | let optionsText = fmap (listOptionText currentValues (s" [Currently Selected]")) options
220 | sendText $ unlines $ [formatLabel (const Nothing) field] ++ optionsText ++ [s"Which numbers?"]
221 | values <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly parser)
222 | let selectedOptions = fmap snd $ filter (\(x, _) -> x `elem` values) options
223 | return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] $ flip fmap selectedOptions $ \option ->
224 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ mconcat $ fieldValue option]
225 | ]
226 | _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return []
227 | where
228 | parser = Atto.skipMany Atto.space *> Atto.sepBy Atto.decimal (Atto.skipMany $ Atto.choice [Atto.space, Atto.char ',']) <* Atto.skipMany Atto.space <* Atto.endOfInput
229 | helperText = s"I didn't understand your answer. Please send the numbers you want, separated by commas or spaces like \"1, 3\" or \"1 3\". Blank (or just spaces) to pick nothing."
230 |
231 | -- Technically an option can have multiple values, but in practice it probably won't
232 | data ListSingle = ListSingle { listLabel :: T.Text, listIsOpen :: Bool, listLookup :: (Int -> Maybe [T.Text]) }
233 | listSingleHelper :: Element -> ListSingle
234 | listSingleHelper field = ListSingle label open lookup
235 | where
236 | open = isOpenValidation (fieldValidation field)
237 | options = zip [1..] $ isNamed(s"{jabber:x:data}option") =<< elementChildren field
238 | currentValue = listToMaybe $ elementText =<< isNamed(s"{jabber:x:data}value") =<< elementChildren field
239 | optionsText = fmap (listOptionText currentValue (s" [Current Value]")) options
240 | currentValueText = (\func -> maybe [] func currentValue) $ \value ->
241 | if open && value `notElem` (map (mconcat . fieldValue . snd) options) then
242 | [s"[Current Value: " ++ value ++ s"]"]
243 | else
244 | []
245 | label = unlines $ [formatLabel (const Nothing) field] ++ optionsText ++ currentValueText
246 | lookup n = fmap (fieldValue . snd) $ find (\(x, _) -> x == n) options
247 |
248 | adhocBotAnswerListSingle :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m [Element]
249 | adhocBotAnswerListSingle sendText getMessage field = do
250 | case attributeText (s"var") field of
251 | Just var -> do
252 | let list = listSingleHelper field
253 | let open = listIsOpen list
254 | let prompt = s"Please enter a number from the list above" ++ if open then s", or enter a custom option" else s""
255 | sendText $ listLabel list ++ prompt
256 | maybeOption <- if open then do
257 | value <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly openParser)
258 | return $ Just $ case value of
259 | Left openValue -> [openValue]
260 | Right itemNumber -> maybe ([tshow itemNumber]) id $ listLookup list itemNumber
261 | else do
262 | value <- untilParse getMessage (sendText helperText) (hush . Atto.parseOnly parser)
263 | return $ listLookup list value
264 | case maybeOption of
265 | Just option -> return [Element (s"{jabber:x:data}field") [(s"var", [ContentText var])] [
266 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ mconcat option]
267 | ]]
268 | Nothing -> do
269 | sendText $ s"Please pick one of the given options"
270 | adhocBotAnswerListSingle sendText getMessage field
271 | _ -> log "ADHOC BOT FIELD WITHOUT VAR" field >> return []
272 | where
273 | helperText = s"I didn't understand your answer. Please just send the number of the one item you want to pick, like \"1\""
274 | parser = Atto.skipMany Atto.space *> Atto.decimal <* Atto.skipMany Atto.space <* Atto.endOfInput
275 | openParser = (Right <$> parser) <|> (Left <$> Atto.takeText)
276 |
277 | adhocBotAnswerForm :: (UIO.Unexceptional m) => (Text -> m ()) -> m XMPP.Message -> Element -> m Element
278 | adhocBotAnswerForm sendText getMessage form = do
279 | fields <- forM (filter (uncurry (||) . (isField &&& isInstructions)) $ elementChildren form) $ \field ->
280 | let sendText' = lift . sendText in
281 | withNext getMessage field $ \getMessage' ->
282 | HT.select (
283 | -- The spec says a field type we don't understand should be treated as text-single
284 | log "ADHOC BOT UNKNOWN FIELD" field >>
285 | adhocBotAnswerTextSingle sendText' getMessage' field
286 | ) [
287 | (isInstructions field,
288 | sendText' (mconcat $ elementText field) >> return []),
289 | (attributeText (s"type") field == Just (s"list-single"),
290 | adhocBotAnswerListSingle sendText' getMessage' field),
291 | (attributeText (s"type") field == Just (s"list-multi"),
292 | adhocBotAnswerListMulti sendText' getMessage' field),
293 | (attributeText (s"type") field == Just (s"jid-single"),
294 | adhocBotAnswerJidSingle sendText' getMessage' field),
295 | (attributeText (s"type") field == Just (s"hidden"),
296 | return [field]),
297 | (attributeText (s"type") field == Just (s"fixed"),
298 | adhocBotAnswerFixed sendText' getMessage' field),
299 | (attributeText (s"type") field == Just (s"boolean"),
300 | adhocBotAnswerBoolean sendText' getMessage' field),
301 | (attributeText (s"type") field `elem` [Just (s"text-single"), Nothing],
302 | -- The default if a type isn't specified is text-single
303 | adhocBotAnswerTextSingle sendText' getMessage' field)
304 | ]
305 | return $ Element (s"{jabber:x:data}x") [(s"type", [ContentText $ s"submit"])] $ NodeElement <$> mconcat fields
306 |
307 | formatReported :: Element -> (Text, [Text])
308 | formatReported =
309 | first (intercalate (s"\t")) . unzip .
310 | map (\field ->
311 | (
312 | formatLabel (const Nothing) field,
313 | fromMaybe mempty (attributeText (s"var") field)
314 | )
315 | ) . filter isField . elementChildren
316 |
317 | formatItem :: [Text] -> Element -> Text
318 | formatItem reportedVars item = intercalate (s"\t") $ map (\var ->
319 | intercalate (s", ") $ findFieldValue var
320 | ) reportedVars
321 | where
322 | findFieldValue var = maybe [] fieldValue $ find (\field ->
323 | attributeText (s"var") field == Just var
324 | ) fields
325 | fields = filter isField $ elementChildren item
326 |
327 | simpleResultField :: Text -> [Text] -> Text
328 | simpleResultField label [value] = concat [label, s": ", value, s"\n"]
329 | simpleResultField label values = concat [label, s":\n", unlines values]
330 |
331 | formatResultField :: Element -> Text
332 | formatResultField el = case maybe ("text-single") T.unpack $ attributeText (s"type") el of
333 | "hidden" -> mempty
334 | "list-single" -> listLabel $ listSingleHelper el
335 | "jid-single" -> simpleResultField label $ map (s"xmpp:" ++) $ fieldValue el
336 | _ -> simpleResultField label $ fieldValue el
337 | where
338 | label = formatLabel (const Nothing) el
339 |
340 | renderResultForm :: Element -> Text
341 | renderResultForm form =
342 | intercalate (s"\n") $ catMaybes $ snd $
343 | forAccumL [] (elementChildren form) $ \reportedVars el ->
344 | HT.select (reportedVars, Nothing) $ map (second $ second Just) [
345 | (isInstructions el, (reportedVars,
346 | mconcat $ elementText el)),
347 | (isField el, (reportedVars, formatResultField el)),
348 | (isReported el,
349 | swap $ formatReported el),
350 | (isItem el, (reportedVars,
351 | formatItem reportedVars el))
352 | ]
353 | where
354 | forAccumL z xs f = mapAccumL f z xs
355 |
356 | waitForAction :: (UIO.Unexceptional m) => [Action] -> (Text -> m ()) -> m XMPP.Message -> m Action
357 | waitForAction actions sendText getMessage = do
358 | m <- getMessage
359 | let ciBody = CI.mk <$> getBody (s"jabber:component:accept") m
360 | HT.select whatWasThat [
361 | (ciBody == Just (s"next"), return ActionNext),
362 | (ciBody == Just (s"back"), return ActionPrev),
363 | (ciBody == Just (s"cancel"), return ActionCancel),
364 | (ciBody == Just (s"finish"), return ActionComplete)
365 | ]
366 | where
367 | allowedCmds = map actionCmd (ActionCancel : actions)
368 | whatWasThat = do
369 | sendText $
370 | s"I didn't understand that. You can say one of: " ++
371 | intercalate (s", ") allowedCmds
372 | waitForAction actions sendText getMessage
373 |
374 | label :: Element -> Maybe Text
375 | label = attributeText (s"label")
376 |
377 | optionText :: Element -> Text
378 | optionText element = fromMaybe (mconcat $ fieldValue element) (label element)
379 |
380 | fieldValue :: Element -> [Text]
381 | fieldValue = fmap (mconcat . elementText) .
382 | isNamed (s"{jabber:x:data}value") <=< elementChildren
383 |
384 | fieldValidation :: Element -> Maybe Element
385 | fieldValidation =
386 | listToMaybe .
387 | (isNamed (s"{http://jabber.org/protocol/xdata-validate}validate") <=< elementChildren)
388 |
389 | isOpenValidation :: Maybe Element -> Bool
390 | isOpenValidation (Just el) =
391 | not $ null $
392 | isNamed (s"{http://jabber.org/protocol/xdata-validate}open")
393 | =<< elementChildren el
394 | isOpenValidation _ = False
395 |
396 | desc :: Element -> Maybe Text
397 | desc = mfilter (not . T.null) . Just . mconcat .
398 | (elementText <=< isNamed(s"{jabber:x:data}desc") <=< elementChildren)
399 |
400 | isField :: Element -> Bool
401 | isField el = elementName el == s"{jabber:x:data}field"
402 |
403 | isInstructions :: Element -> Bool
404 | isInstructions el = elementName el == s"{jabber:x:data}instructions"
405 |
406 | isReported :: Element -> Bool
407 | isReported el = elementName el == s"{jabber:x:data}reported"
408 |
409 | isItem :: Element -> Bool
410 | isItem el = elementName el == s"{jabber:x:data}item"
411 |
412 | isRequired :: Element -> Bool
413 | isRequired = not . null . (isNamed (s"{jabber:x:data}required") <=< elementChildren)
414 |
415 | registerShorthand :: Text -> Maybe JID
416 | registerShorthand body = do
417 | gatewayJID <- hush $ Atto.parseOnly (Atto.asciiCI (s"register") *> Atto.many1 Atto.space *> Atto.takeText) body
418 | parseJID gatewayJID
419 |
420 | getServerInfoForm :: [XML.Element] -> Maybe XML.Element
421 | getServerInfoForm = find (\el ->
422 | attributeText (s"type") el == Just (s"result") &&
423 | getFormField el (s"FORM_TYPE") == Just (s"http://jabber.org/network/serverinfo")
424 | ) . (isNamed (s"{jabber:x:data}x") =<<)
425 |
426 | sendHelp :: (UIO.Unexceptional m) =>
427 | DB.DB
428 | -> JID
429 | -> (XMPP.Message -> m ())
430 | -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ)))
431 | -> JID
432 | -> JID
433 | -> m ()
434 | sendHelp db componentJid sendMessage sendIQ from routeFrom = do
435 | maybeRoute <- (parseJID =<<) . (join . hush) <$> UIO.fromIO (DB.get db (DB.byJid from ["direct-message-route"]))
436 | case maybeRoute of
437 | Just route -> do
438 | replySTM <- UIO.lift $ sendIQ $ queryCommandList' route routeFrom
439 | discoInfoSTM <- UIO.lift $ sendIQ $ queryDiscoWithNode' Nothing route routeFrom
440 | (mreply, mDiscoInfo) <- atomicUIO $ (,) <$> replySTM <*> discoInfoSTM
441 |
442 | let helpMessage = botHelp
443 | (renderResultForm <$> (getServerInfoForm . elementChildren =<< iqPayload =<< mDiscoInfo)) $
444 | commandList componentJid Nothing componentJid from $
445 | isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren =<< maybeToList (XMPP.iqPayload =<< mfilter ((== XMPP.IQResult) . XMPP.iqType) mreply)
446 | case helpMessage of
447 | Just msg -> sendMessage msg
448 | Nothing -> log "INVALID HELP MESSAGE" mreply
449 | Nothing ->
450 | case botHelp Nothing $ commandList componentJid Nothing componentJid from [] of
451 | Just msg -> sendMessage msg
452 | Nothing -> log "INVALID HELP MESSAGE" ()
453 |
454 | adhocBotRunCommand :: (UIO.Unexceptional m) => DB.DB -> JID -> JID -> (XMPP.Message -> m ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> STM XMPP.Message -> JID -> Text -> [Element] -> m ()
455 | adhocBotRunCommand db componentJid routeFrom sendMessage sendIQ getMessage from body cmdEls = do
456 | let (nodes, cmds) = unzip $ mapMaybe (\el -> (,) <$> attributeText (s"node") el <*> pure el) cmdEls
457 |
458 | case (snd <$> find (\(prefixes, _) -> Set.member (CI.mk body) prefixes) (zip (uniquePrefix nodes) cmds), registerShorthand body) of
459 | (_, Just gatewayJID) -> do
460 | mResult <- (atomicUIO =<<) $ UIO.lift $ sendIQ $ (emptyIQ IQSet) {
461 | iqFrom = Just routeFrom,
462 | iqTo = Just componentJid,
463 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText ConfigureDirectMessageRoute.nodeName])] []
464 | }
465 | case attributeText (s"sessionid") =<< iqPayload =<< mResult of
466 | Just sessionid ->
467 | startWithIntro $ (emptyIQ IQSet) {
468 | iqFrom = Just routeFrom,
469 | iqTo = iqFrom =<< mResult,
470 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText ConfigureDirectMessageRoute.nodeName]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText $ s"next"])] [
471 | NodeElement $ Element (fromString "{jabber:x:data}x") [
472 | (fromString "{jabber:x:data}type", [ContentText $ s"submit"])
473 | ] [
474 | NodeElement $ Element (fromString "{jabber:x:data}field") [
475 | (fromString "{jabber:x:data}type", [ContentText $ s"jid-single"]),
476 | (fromString "{jabber:x:data}var", [ContentText $ s"gateway-jid"])
477 | ] [
478 | NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ formatJID gatewayJID]
479 | ]
480 | ]
481 | ]
482 | }
483 | Nothing -> sendHelp db componentJid sendMessage sendIQ from routeFrom
484 | (Just cmd, Nothing) ->
485 | startWithIntro $ (emptyIQ IQSet) {
486 | iqFrom = Just routeFrom,
487 | iqTo = parseJID =<< attributeText (s"jid") cmd,
488 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") cmd])] []
489 | }
490 | (Nothing, Nothing) -> sendHelp db componentJid sendMessage sendIQ from routeFrom
491 | where
492 | startWithIntro cmdIQ =
493 | sendAndRespondTo (Just $ intercalate (s"\n") [
494 | s"You can leave something at the current value by saying 'next'.",
495 | s"You can return to the main menu by saying 'cancel' at any time."
496 | ]) cmdIQ
497 | threadedMessage Nothing msg = msg
498 | threadedMessage (Just sessionid) msg = msg { messagePayloads = (Element (s"thread") [] [NodeContent $ ContentText sessionid]) : messagePayloads msg }
499 | continueExecution resultIQ responseBody
500 | | Just payload <- iqPayload resultIQ,
501 | Just sessionid <- attributeText (s"sessionid") payload,
502 | Just "executing" <- T.unpack <$> attributeText (s"status") payload = do
503 | let actions = listToMaybe $ isNamed(s"{http://jabber.org/protocol/commands}actions") =<< elementChildren payload
504 | -- The standard says if actions is present, with no "execute" attribute, that the default is "next"
505 | -- But if there is no actions, the default is "execute"
506 | let defaultAction = maybe (s"execute") (fromMaybe (s"next") . attributeText (s"execute")) actions
507 | let cmdIQ' = (emptyIQ IQSet) {
508 | iqFrom = Just routeFrom,
509 | iqTo = iqFrom resultIQ,
510 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") payload]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText defaultAction])] responseBody
511 | }
512 | sendAndRespondTo Nothing cmdIQ'
513 | continueExecution _ _ = return ()
514 | sendAndRespondTo intro cmdIQ = do
515 | mcmdResult <- atomicUIO =<< UIO.lift (sendIQ cmdIQ)
516 | case mcmdResult of
517 | Just resultIQ
518 | | IQResult == iqType resultIQ,
519 | Just payload <- iqPayload resultIQ,
520 | [form] <- isNamed (s"{jabber:x:data}x") =<< elementChildren payload,
521 | attributeText (s"type") form == Just (s"result") -> do
522 | let sendText = sendMessage . threadedMessage (attributeText (s"sessionid") payload) . mkSMS componentJid from
523 | sendText $ renderResultForm form
524 | continueExecution resultIQ []
525 | | IQResult == iqType resultIQ,
526 | Just payload <- iqPayload resultIQ,
527 | Just sessionid <- attributeText (s"sessionid") payload,
528 | Just cmd <- attributeText (s"node") payload,
529 | [form] <- isNamed (s"{jabber:x:data}x") =<< elementChildren payload -> do
530 | let cancelIQ = (emptyIQ IQSet) {
531 | iqFrom = Just routeFrom,
532 | iqTo = iqFrom resultIQ,
533 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText cmd]), (s"sessionid", [ContentText sessionid]), (s"action", [ContentText $ s"cancel"])] []
534 | }
535 | let cancel = void . atomicUIO =<< UIO.lift (sendIQ cancelIQ)
536 | let sendText = sendMessage . threadedMessage (Just sessionid) . mkSMS componentJid from
537 | let cancelText = sendText . ((cmd ++ s" ") ++)
538 | forM_ intro sendText
539 | returnForm <- adhocBotAnswerForm sendText (withCancel sessionLifespan cancelText cancel getMessage) form
540 | continueExecution resultIQ [NodeElement returnForm]
541 | | IQResult == iqType resultIQ,
542 | Just payload <- iqPayload resultIQ,
543 | notes@(_:_) <- isNamed (s"{http://jabber.org/protocol/commands}note") =<< elementChildren payload -> do
544 | let sendText = sendMessage . threadedMessage (attributeText (s"sessionid") payload) . mkSMS componentJid from
545 | forM_ notes $
546 | sendText . mconcat . elementText
547 | if (attributeText (s"status") payload == Just (s"executing")) then do
548 | let actions = mapMaybe (actionFromXMPP . XML.nameLocalName . elementName) $ elementChildren =<< isNamed (s"{http://jabber.org/protocol/commands}actions") =<< elementChildren payload
549 | let sessionid = maybe [] (\sessid -> [(s"sessionid", [ContentText sessid])]) $ attributeText (s"sessionid") payload
550 | sendText $
551 | s"You can say one of: " ++
552 | (intercalate (s", ") $ map actionCmd (ActionCancel : actions))
553 | action <- waitForAction actions sendText (atomicUIO getMessage)
554 | let cmdIQ' = (emptyIQ IQSet) {
555 | iqFrom = Just routeFrom,
556 | iqTo = iqFrom resultIQ,
557 | iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") ([(s"node", [ContentText $ fromMaybe mempty $ attributeText (s"node") payload]), (s"action", [actionContent action])] ++ sessionid) []
558 | }
559 | sendAndRespondTo Nothing cmdIQ'
560 | else when (
561 | attributeText (s"status") payload == Just (s"completed") &&
562 | attributeText (s"node") payload == Just ConfigureDirectMessageRoute.nodeName &&
563 | all (\n -> attributeText (s"type") n /= Just (s"error")) notes
564 | ) $
565 | sendHelp db componentJid sendMessage sendIQ from routeFrom
566 | | IQResult == iqType resultIQ,
567 | [cmd] <- isNamed (s"{http://jabber.org/protocol/commands}command") =<< (justZ $ iqPayload resultIQ),
568 | attributeText (s"status") cmd `elem` [Just (s"completed"), Just (s"canceled")] -> return ()
569 | | otherwise -> do
570 | log "COMMAND ERROR" resultIQ
571 | sendMessage $ mkSMS componentJid from (s"Command error")
572 | Nothing -> sendMessage $ mkSMS componentJid from (s"Command timed out")
573 |
574 | adhocBotSession :: (UIO.Unexceptional m) => DB.DB -> JID -> (XMPP.Message -> m ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> STM XMPP.Message -> XMPP.Message-> m ()
575 | adhocBotSession db componentJid sendMessage sendIQ getMessage message@(XMPP.Message { XMPP.messageFrom = Just from })
576 | | Just body <- getBody "jabber:component:accept" message = do
577 | maybeRoute <- (parseJID =<<) . (join . hush) <$> UIO.fromIO (DB.get db (DB.byJid from ["direct-message-route"]))
578 | case maybeRoute of
579 | Just route -> do
580 | mreply <- atomicUIO =<< (UIO.lift . sendIQ) (queryCommandList' route routeFrom)
581 | case iqPayload =<< mfilter ((==IQResult) . iqType) mreply of
582 | Just reply -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body $ maskCommands componentJid $ elementChildren reply ++ internalCommands
583 | Nothing -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body internalCommands
584 | Nothing -> adhocBotRunCommand db componentJid routeFrom sendMessage' sendIQ getMessage from body internalCommands
585 | | otherwise = sendHelp db componentJid sendMessage' sendIQ from routeFrom
586 | where
587 | internalCommands = elementChildren =<< maybeToList (iqPayload $ commandList componentJid Nothing componentJid from [])
588 | Just routeFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/adhocbot"
589 | sendMessage' = sendMessage <=< addOriginUUID
590 | adhocBotSession _ _ _ _ _ m = log "BAD ADHOC BOT MESSAGE" m
591 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/CommandAction.hs:
--------------------------------------------------------------------------------
1 | module CommandAction where
2 |
3 | import Data.XML.Types as XML (Element(..), Node(NodeContent, NodeElement), Content(ContentText), isNamed, elementText, elementChildren, attributeText)
4 |
5 | import qualified Data.Text as T
6 | import qualified Data.XML.Types as XML
7 |
8 | import Util
9 |
10 | data Action = ActionNext | ActionPrev | ActionCancel | ActionComplete
11 |
12 | actionContent :: Action -> Content
13 | actionContent ActionNext = ContentText $ s"next"
14 | actionContent ActionPrev = ContentText $ s"prev"
15 | actionContent ActionCancel = ContentText $ s"cancel"
16 | actionContent ActionComplete = ContentText $ s"complete"
17 |
18 | actionCmd :: Action -> T.Text
19 | actionCmd ActionNext = s"next"
20 | actionCmd ActionPrev = s"back"
21 | actionCmd ActionCancel = s"cancel"
22 | actionCmd ActionComplete = s"finish"
23 |
24 | actionFromXMPP :: T.Text -> Maybe Action
25 | actionFromXMPP xmpp
26 | | xmpp == s"next" = Just ActionNext
27 | | xmpp == s"prev" = Just ActionPrev
28 | | xmpp == s"complete" = Just ActionComplete
29 | | otherwise = Nothing
30 |
31 | actionToEl :: Action -> [Element]
32 | actionToEl ActionNext = [Element (s"{http://jabber.org/protocol/commands}next") [] []]
33 | actionToEl ActionPrev = [Element (s"{http://jabber.org/protocol/commands}prev") [] []]
34 | actionToEl ActionComplete = [Element (s"{http://jabber.org/protocol/commands}complete") [] []]
35 | actionToEl ActionCancel = []
36 |
--------------------------------------------------------------------------------
/Config.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE DeriveGeneric #-}
2 | {-# LANGUAGE DeriveAnyClass #-}
3 |
4 | module Config where
5 |
6 | import Prelude ()
7 | import BasicPrelude
8 | import Network.HostAndPort (maybeHostAndPort)
9 | import System.IO.Unsafe (unsafePerformIO)
10 | import Control.Error (headZ)
11 |
12 | import qualified Network.Socket as Socket
13 | import qualified Database.Redis as Redis
14 | import qualified Dhall
15 | import qualified Dhall.Core as Dhall
16 | import qualified Network.Protocol.XMPP as XMPP
17 |
18 | import Util
19 | import qualified RedisURL
20 |
21 | data ServerConfig = ServerConfig { host :: Socket.HostName, port :: Socket.PortNumber } deriving (Dhall.Generic, Dhall.FromDhall, Show)
22 |
23 | data Redis = Redis {
24 | presence :: Redis.ConnectInfo,
25 | state :: Redis.ConnectInfo
26 | } deriving (Dhall.Generic, Dhall.FromDhall, Show)
27 |
28 | data Config = Config {
29 | componentJid :: XMPP.JID,
30 | server :: ServerConfig,
31 | secret :: Text,
32 | backend :: Text,
33 | did :: Text,
34 | registrationJid :: XMPP.JID,
35 | conferenceServers :: [Text],
36 | s5bListenOn :: [Socket.SockAddr],
37 | s5bAdvertise :: ServerConfig,
38 | jingleStore :: FilePath,
39 | jingleStoreURL :: Text,
40 | redis :: Redis,
41 | statsd :: ServerConfig,
42 | avatar :: Maybe FilePath
43 | } deriving (Dhall.Generic, Dhall.FromDhall, Show)
44 |
45 | instance Dhall.FromDhall XMPP.JID where
46 | autoWith _ = Dhall.Decoder {
47 | Dhall.extract = \(Dhall.TextLit (Dhall.Chunks _ txt)) ->
48 | maybe (Dhall.extractError $ s"Invalid JID") pure $ XMPP.parseJID txt,
49 | Dhall.expected = pure Dhall.Text
50 | }
51 |
52 | instance Dhall.FromDhall Socket.PortNumber where
53 | autoWith _ = Dhall.Decoder {
54 | Dhall.extract = \(Dhall.NaturalLit nat) -> pure $ fromIntegral nat,
55 | Dhall.expected = pure Dhall.Natural
56 | }
57 |
58 | instance Dhall.FromDhall Socket.SockAddr where
59 | autoWith _ = Dhall.Decoder {
60 | Dhall.extract = (\(Dhall.TextLit (Dhall.Chunks _ txt)) -> maybe (Dhall.extractError $ s"Invalid Socket Address") pure $ do
61 | Just (host, Just port) <- return $ maybeHostAndPort (textToString txt)
62 | -- This is not a great idea, but I'm lazy today and I really just want to parse IP addresses, which is a pure operation
63 | unsafePerformIO $ fmap (fmap Socket.addrAddress . headZ) $ Socket.getAddrInfo Nothing (Just host) (Just port)
64 | ),
65 | Dhall.expected = pure Dhall.Text
66 | }
67 |
68 | instance Dhall.FromDhall Redis.ConnectInfo where
69 | autoWith _ = Dhall.Decoder {
70 | Dhall.extract = (\(Dhall.TextLit (Dhall.Chunks _ txt)) ->
71 | either (Dhall.extractError . tshow) pure $ RedisURL.parseConnectInfo $ textToString txt
72 | ),
73 | Dhall.expected = pure Dhall.Text
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/ConfigureDirectMessageRoute.hs:
--------------------------------------------------------------------------------
1 | module ConfigureDirectMessageRoute (main, nodeName, switchBackendNodeName) where
2 |
3 | import Prelude ()
4 | import BasicPrelude hiding (log)
5 | import Data.Foldable (toList)
6 | import Control.Concurrent
7 | import Control.Concurrent.STM
8 | import Data.Time (UTCTime, diffUTCTime, getCurrentTime)
9 | import Data.XML.Types (Element(..), Node(NodeContent, NodeElement), Name(..), Content(ContentText), isNamed, hasAttributeText, elementText, elementChildren, attributeText)
10 | import Control.Monad.Loops (iterateM_)
11 |
12 | import Data.Map (Map)
13 | import qualified Data.Map as Map
14 | import qualified Data.Text as T
15 | import Data.UUID (UUID)
16 | import qualified Data.UUID as UUID (toString, fromString)
17 | import qualified Data.UUID.V1 as UUID (nextUUID)
18 | import qualified Network.Protocol.XMPP as XMPP
19 | import qualified Data.Bool.HT as HT
20 | import qualified Data.XML.Types as XML
21 |
22 | import Util
23 |
24 | switchBackendNodeName :: Text
25 | switchBackendNodeName = s"https://ns.cheogram.com/sgx/jid-switch"
26 |
27 | newtype SessionID = SessionID UUID deriving (Ord, Eq, Show)
28 |
29 | type GetPossibleRoute = XMPP.JID -> IO (Maybe XMPP.JID)
30 | type GetPossibleSwitch = XMPP.JID -> IO (Maybe (XMPP.JID, XMPP.JID, XMPP.JID))
31 | type GetRouteJid = XMPP.JID -> IO (Maybe XMPP.JID)
32 | type SetRouteJid = XMPP.JID -> Maybe XMPP.JID -> IO ()
33 | type ClearSwitch = XMPP.JID -> IO ()
34 | type GetAllowJidDiscovery = XMPP.JID -> IO (Maybe Bool)
35 | type SetAllowJidDiscovery = XMPP.JID -> Bool -> IO ()
36 |
37 | main :: XMPP.Domain -> GetPossibleRoute -> GetPossibleSwitch -> GetRouteJid -> SetRouteJid -> ClearSwitch -> GetAllowJidDiscovery -> SetAllowJidDiscovery -> IO (XMPP.IQ -> IO (Maybe XMPP.IQ))
38 | main componentDomain getPossibleRoute getPossibleSwitch getRouteJid setRouteJid clearSwitch getAllowJidDiscovery setAllowJidDiscovery = do
39 | stanzas <- newTQueueIO
40 | void $ flip forkFinally (log "ConfigureDirectMessageRouteTOP") $ void $ iterateM_ (\sessions -> do
41 | (iq, reply) <- atomically (readTQueue stanzas)
42 | (sessions', response) <- processOneIQ componentDomain getPossibleRoute getPossibleSwitch getRouteJid setRouteJid clearSwitch getAllowJidDiscovery setAllowJidDiscovery sessions iq
43 | atomically $ reply response
44 | now <- getCurrentTime
45 | return $! Map.filter (\(_, _, time) -> now `diffUTCTime` time < 600) sessions'
46 | ) Map.empty
47 | return (\iq -> do
48 | result <- atomically newEmptyTMVar
49 | atomically $ writeTQueue stanzas (iq, putTMVar result)
50 | atomically $ readTMVar result
51 | )
52 |
53 | processOneIQ :: XMPP.Domain -> GetPossibleRoute -> GetPossibleSwitch -> GetRouteJid -> SetRouteJid -> ClearSwitch -> GetAllowJidDiscovery -> SetAllowJidDiscovery -> Map SessionID (Session, Maybe Bool, UTCTime) -> XMPP.IQ -> IO (Map SessionID (Session, Maybe Bool, UTCTime), Maybe XMPP.IQ)
54 | processOneIQ componentDomain getPossibleRoute getPossibleSwitch getRouteJid setRouteJid clearSwitch getAllowJidDiscovery setAllowJidDiscovery sessions iq@(XMPP.IQ { XMPP.iqID = Just iqID, XMPP.iqFrom = Just from, XMPP.iqPayload = realPayload })
55 | | Just sid <- sessionIDFromText . snd =<< T.uncons =<< T.stripPrefix (s"ConfigureDirectMessageRoute") iqID,
56 | XMPP.iqType iq == XMPP.IQResult || XMPP.iqType iq == XMPP.IQError =
57 | (fmap Just) <$> lookupAndStepSession setRouteJid clearSwitch setAllowJidDiscovery sessions componentDomain sid iqID from payload
58 | | elementName payload /= s"{http://jabber.org/protocol/commands}command" ||
59 | attributeText (s"node") payload /= Just nodeName = do
60 | log "ConfigureDirectMessageRoute.processOneIQ BAD INPUT" (elementName payload, attributeText (s"node") payload)
61 | if XMPP.iqType iq == XMPP.IQError then
62 | return (sessions, Nothing)
63 | else
64 | return (sessions, Just $ iqError (Just iqID) (Just from) "cancel" "feature-not-implemented" Nothing)
65 | | Just sid <- sessionIDFromText =<< attributeText (s"sessionid") payload =
66 | (fmap Just) <$> lookupAndStepSession setRouteJid clearSwitch setAllowJidDiscovery sessions componentDomain sid iqID from payload
67 | | otherwise = do
68 | now <- getCurrentTime
69 | existingRoute <- getRouteJid from
70 | possibleRoute <- getPossibleRoute from
71 | possibleSwitch <- getPossibleSwitch from
72 | allowJidDiscovery <- getAllowJidDiscovery from
73 | case possibleSwitch of
74 | Just (newJid, switchJid, switchRoute) -> do
75 | (sid, session) <- newSession $ switchStage2 switchJid switchRoute possibleRoute existingRoute
76 | return (Map.insert sid (session, allowJidDiscovery, now) sessions, Just $ switchStage1 newJid switchJid switchRoute possibleRoute existingRoute from iqID sid)
77 | _ -> do
78 | (sid, session) <- newSession stage2
79 | return (Map.insert sid (session, allowJidDiscovery, now) sessions, Just $ stage1 possibleRoute existingRoute from iqID sid)
80 | where
81 | payload
82 | | Just p <- realPayload,
83 | XMPP.iqType iq == XMPP.IQError && elementName p == s"{jabber:component:accept}error" = p
84 | | XMPP.iqType iq == XMPP.IQError =
85 | let Just p = XMPP.iqPayload $ iqError Nothing Nothing "cancel" "internal-server-error" Nothing in p
86 | | otherwise = fromMaybe (Element (s"no-payload") [] []) realPayload
87 | processOneIQ _ _ _ _ _ _ _ _ sessions iq@(XMPP.IQ { XMPP.iqID = iqID, XMPP.iqFrom = from }) = do
88 | log "ConfigureDirectMessageRoute.processOneIQ BAD INPUT" iq
89 | return (sessions, Just $ iqError iqID from "cancel" "feature-not-implemented" Nothing)
90 |
91 | lookupAndStepSession :: SetRouteJid -> ClearSwitch -> SetAllowJidDiscovery -> Map SessionID (Session, Maybe Bool, UTCTime) -> Session' (IO (Map SessionID (Session, Maybe Bool, UTCTime), XMPP.IQ))
92 | lookupAndStepSession setRouteJid clearSwitch setAllowJidDiscovery sessions componentDomain sid iqID from payload
93 | | Just (stepSession, allowJidDiscovery, _) <- Map.lookup sid sessions =
94 | case attributeText (s"action") payload of
95 | Just action | action == s"cancel" ->
96 | return (Map.delete sid sessions, (XMPP.emptyIQ XMPP.IQResult) {
97 | XMPP.iqID = Just iqID,
98 | XMPP.iqTo = Just from,
99 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command")
100 | [
101 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
102 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
103 | (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"canceled"])
104 | ] [
105 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}note") [
106 | (s"{http://jabber.org/protocol/commands}type", [ContentText $ s"info"])
107 | ] [
108 | NodeContent $ ContentText $ s"Register cancelled"
109 | ]
110 | ]
111 | })
112 | Just action | action == s"complete" ->
113 | return (Map.delete sid sessions, (XMPP.emptyIQ XMPP.IQResult) {
114 | XMPP.iqID = Just iqID,
115 | XMPP.iqTo = Just from,
116 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command")
117 | [
118 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
119 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
120 | (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"completed"])
121 | ] [
122 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}note") [
123 | (s"{http://jabber.org/protocol/commands}type", [ContentText $ s"info"])
124 | ] [
125 | NodeContent $ ContentText $ s"Saved route configuration."
126 | ]
127 | ]
128 | })
129 | _ ->
130 | let (session', iq) = stepSession allowJidDiscovery componentDomain sid iqID from payload in
131 | fmap (flip (,) iq) $ case session' of
132 | SessionNext s -> do
133 | now <- getCurrentTime
134 | return $! Map.insert sid (s, allowJidDiscovery, now) sessions
135 | SessionCancel -> return $! Map.delete sid sessions
136 | SessionSaveAndNext userJid gatewayJid s -> do
137 | now <- getCurrentTime
138 | userJid `setRouteJid` (Just gatewayJid)
139 | return $! Map.insert sid (s, allowJidDiscovery, now) sessions
140 | SessionAllowJidDiscovery userJid allow maybeNext -> do
141 | now <- getCurrentTime
142 | userJid `setAllowJidDiscovery` allow
143 | return $! Map.alter (const $ fmap (\s -> (s, allowJidDiscovery, now)) maybeNext) sid sessions
144 | SessionClearSwitchAndNext userJid s -> do
145 | now <- getCurrentTime
146 | clearSwitch userJid
147 | return $! Map.insert sid (s, allowJidDiscovery, now) sessions
148 | SessionCompleteSwitch userJid oldJid gatewayJid -> do
149 | userJid `setRouteJid` Just gatewayJid
150 | oldJid `setRouteJid` Nothing
151 | clearSwitch userJid
152 | return $! Map.delete sid sessions
153 | SessionComplete userJid gatewayJid -> do
154 | userJid `setRouteJid` gatewayJid
155 | return $! Map.delete sid sessions
156 | | otherwise = do
157 | log "ConfigureDirectMessageRoute.processOneIQ NO SESSION FOUND" (sid, iqID, from, payload)
158 | return (sessions, iqError (Just iqID) (Just from) "modify" "bad-request" (Just "bad-sessionid"))
159 |
160 | data SessionResult = SessionNext Session | SessionCancel | SessionSaveAndNext XMPP.JID XMPP.JID Session | SessionClearSwitchAndNext XMPP.JID Session | SessionCompleteSwitch XMPP.JID XMPP.JID XMPP.JID | SessionComplete XMPP.JID (Maybe XMPP.JID) | SessionAllowJidDiscovery XMPP.JID Bool (Maybe Session)
161 | type Session' a = XMPP.Domain -> SessionID -> Text -> XMPP.JID -> Element -> a
162 | type Session = Maybe Bool -> Session' (SessionResult, XMPP.IQ)
163 |
164 | data RegisterFormType = DataForm | LegacyRegistration
165 |
166 | jidDiscoveryOptInParse :: (Text -> XMPP.IQ) -> Maybe Session -> Session
167 | jidDiscoveryOptInParse nextIQ nextS _ _ sid iqID from command
168 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
169 | Just allow <- parseBool =<< getFormField form (s"allow_jid_discovery") = (SessionAllowJidDiscovery from allow nextS, nextIQ iqID)
170 | | otherwise = (SessionCancel, iqError (Just iqID) (Just from) "modify" "bad-request" (Just "bad-payload"))
171 |
172 | jidDiscoveryOptIn :: (Text -> XMPP.IQ) -> Maybe Session -> XMPP.JID -> SessionID -> Text -> Maybe Bool -> (Session, XMPP.IQ)
173 | jidDiscoveryOptIn nextIQ nextS iqTo sid iqID allowJidDiscovery = (jidDiscoveryOptInParse nextIQ nextS, (XMPP.emptyIQ XMPP.IQResult) {
174 | XMPP.iqTo = Just iqTo,
175 | XMPP.iqID = Just iqID,
176 | XMPP.iqPayload = Just $ commandStage sid False $
177 | Element (fromString "{jabber:x:data}x") [
178 | (fromString "{jabber:x:data}type", [ContentText $ s"form"])
179 | ] [
180 | NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ s"Jabber ID Discoverability Opt-in"],
181 | NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [
182 | NodeContent $ ContentText $ concat [
183 | s"You may want to allow other users to discover your Jabber ID when all they know is your phone number. ",
184 | s"This can allow upgrading your contacts to end-to-end encryption, video calling, and other benefits of Jabber over time."
185 | ]
186 | ],
187 | NodeElement $ Element (fromString "{jabber:x:data}field") [
188 | (fromString "{jabber:x:data}type", [ContentText $ s"boolean"]),
189 | (fromString "{jabber:x:data}var", [ContentText $ s"allow_jid_discovery"]),
190 | (fromString "{jabber:x:data}label", [ContentText $ s"Allow others to discover your Jabber ID based on your phone number"])
191 | ] [
192 | NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ if allowJidDiscovery == Just False then s"false" else s"true"]
193 | ]
194 | ]
195 | })
196 |
197 | stage5 :: Text -> XMPP.JID -> Session
198 | stage5 stage4iqID stage4from allowJidDiscovery _ sid iqID from error
199 | | elementName error == s"{jabber:component:accept}error" =
200 | (SessionCancel, (XMPP.emptyIQ XMPP.IQError) {
201 | XMPP.iqID = Just stage4iqID,
202 | XMPP.iqTo = Just stage4from,
203 | XMPP.iqPayload = Just error
204 | })
205 | | otherwise =
206 | let (next, iq) = jidDiscoveryOptIn (\iqID' -> (XMPP.emptyIQ XMPP.IQResult) {
207 | XMPP.iqID = Just iqID',
208 | XMPP.iqTo = Just stage4from,
209 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command")
210 | [
211 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
212 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
213 | (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"completed"])
214 | ]
215 | [
216 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}note") [
217 | (s"{http://jabber.org/protocol/commands}type", [ContentText $ s"info"])
218 | ] [
219 | NodeContent $ ContentText $ s"Registration complete."
220 | ]
221 | ]
222 | }) Nothing stage4from sid stage4iqID allowJidDiscovery
223 | in
224 | (SessionSaveAndNext stage4from from next, iq)
225 |
226 | stage4 :: RegisterFormType -> XMPP.JID -> Session
227 | stage4 formType gatewayJid _ componentDomain sid iqID from command
228 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command =
229 | (SessionNext $ stage5 iqID from, (XMPP.emptyIQ XMPP.IQSet) {
230 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute4" ++ sessionIDToText sid),
231 | XMPP.iqTo = Just gatewayJid,
232 | XMPP.iqFrom = Just sendFrom, -- domain gets rewritten by main cheogram program
233 | XMPP.iqPayload = Just $
234 | case formType of
235 | DataForm -> Element (s"{jabber:iq:register}query") [] [NodeElement form]
236 | LegacyRegistration -> convertFormToLegacyRegistration form
237 | })
238 | | otherwise = (SessionCancel, iqError (Just iqID) (Just from) "modify" "bad-request" (Just "bad-payload"))
239 | where
240 | sendFrom = sendFromForBackend componentDomain from
241 |
242 | stage3 :: Text -> XMPP.JID -> Session
243 | stage3 stage2iqID stage2from _ _ sid iqID from query
244 | | elementName query == s"{jabber:component:accept}error" =
245 | (SessionCancel, (XMPP.emptyIQ XMPP.IQError) {
246 | XMPP.iqID = Just stage2iqID,
247 | XMPP.iqTo = Just stage2from,
248 | XMPP.iqPayload = Just query
249 | })
250 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query = processForm DataForm form
251 | | otherwise = processForm LegacyRegistration (convertQueryToForm query)
252 | where
253 | registered = not $ null $ isNamed (fromString "{jabber:iq:register}registered") =<< elementChildren query
254 | sessionNext
255 | | registered =
256 | SessionSaveAndNext stage2from from
257 | | otherwise = SessionNext
258 | processForm typ form =
259 | (sessionNext $ stage4 typ from, (XMPP.emptyIQ XMPP.IQResult) {
260 | XMPP.iqID = Just stage2iqID,
261 | XMPP.iqTo = Just stage2from,
262 | XMPP.iqPayload = Just $ commandStage sid registered form
263 | })
264 |
265 | stage2 :: Session
266 | stage2 _ componentDomain sid iqID from command
267 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
268 | Just gatewayJid <- XMPP.parseJID =<< getFormField form (s"gateway-jid"),
269 | XMPP.jidNode gatewayJid == Nothing && XMPP.jidResource gatewayJid == Nothing =
270 | (
271 | SessionNext $ commandOrIBR gatewayJid,
272 | (queryCommandList' gatewayJid sendFrom) {
273 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute2" ++ sessionIDToText sid)
274 | }
275 | )
276 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
277 | getFormField form (s"gateway-jid") `elem` [Nothing, Just mempty] =
278 | (SessionComplete from Nothing, (XMPP.emptyIQ XMPP.IQResult) {
279 | XMPP.iqID = Just iqID,
280 | XMPP.iqTo = Just from,
281 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command")
282 | [
283 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
284 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
285 | (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"completed"])
286 | ]
287 | [
288 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}note") [
289 | (s"{http://jabber.org/protocol/commands}type", [ContentText $ s"info"])
290 | ] [
291 | NodeContent $ ContentText $ s"Direct message route removed."
292 | ]
293 | ]
294 | })
295 | | otherwise = (SessionCancel, iqError (Just iqID) (Just from) "modify" "bad-request" (Just "bad-payload"))
296 | where
297 | sendFrom = sendFromForBackend componentDomain from
298 | commandOrIBR gatewayJid _ _ _ _ _ command'
299 | | (s"jabber:iq:register") `elem` mapMaybe (attributeText (s"node")) (isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren command') =
300 | (SessionNext $ proxyAdHocFromGateway iqID from, (XMPP.emptyIQ XMPP.IQSet) {
301 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute2" ++ sessionIDToText sid),
302 | XMPP.iqTo = Just gatewayJid,
303 | XMPP.iqFrom = Just sendFrom,
304 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText $ s"jabber:iq:register"])] []
305 | })
306 | | otherwise =
307 | (SessionNext $ stage3 iqID from, (XMPP.emptyIQ XMPP.IQGet) {
308 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute2" ++ sessionIDToText sid),
309 | XMPP.iqTo = Just gatewayJid,
310 | XMPP.iqFrom = Just sendFrom, -- domain gets rewritten by main cheogram program
311 | XMPP.iqPayload = Just $ Element (s"{jabber:iq:register}query") [] []
312 | })
313 |
314 | -- Use SessionNext and SessionSaveAndNext to allow the proxied session to continue for prev
315 | -- Rely on expiry for cleanup
316 | proxyAdHocFromGateway :: Text -> XMPP.JID -> Session
317 | proxyAdHocFromGateway prevIqID userJid allowJidDiscovery _ sid iqID from command
318 | | attributeText (s"status") command == Just (s"canceled") = (SessionNext next, proxied prevIqID)
319 | | attributeText (s"status") command == Just (s"completed") =
320 | if (s"error") `elem` mapMaybe (attributeText (s"type")) (XML.isNamed (s"{http://jabber.org/protocol/commands}note") =<< XML.elementChildren command) then
321 | (SessionNext next, proxied prevIqID)
322 | else
323 | let (next', iq) = jidDiscoveryOptIn (\iqid ->
324 | (proxied iqid) {
325 | XMPP.iqPayload = fmap (\elem ->
326 | elem {
327 | XML.elementNodes = XML.elementNodes elem ++ [
328 | XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/commands}note")
329 | [(s"type", [XML.ContentText $ s"info"])]
330 | [XML.NodeContent $ XML.ContentText $ s"Registration complete."]
331 | ]
332 | }
333 | ) (XMPP.iqPayload $ proxied iqid)
334 | }
335 | ) (Just next) userJid sid prevIqID allowJidDiscovery
336 | in
337 | (SessionSaveAndNext userJid from next', iq)
338 | | otherwise = (SessionNext next, proxied prevIqID)
339 | where
340 | next = proxyAdHocFromUser iqID otherSID from
341 | proxied iqid =
342 | (XMPP.emptyIQ XMPP.IQResult) {
343 | XMPP.iqID = Just iqid,
344 | XMPP.iqTo = Just userJid,
345 | XMPP.iqPayload = Just $ command {
346 | XML.elementAttributes = map (\attr@(name, _) ->
347 | HT.select attr [
348 | (name == s"node", (name, [ContentText nodeName])),
349 | (name == s"sessionid", (name, [ContentText $ sessionIDToText sid]))
350 | ]
351 | ) (XML.elementAttributes command)
352 | }
353 | }
354 | otherSID = fromMaybe mempty $ XML.attributeText (s"sessionid") command
355 |
356 | proxyAdHocFromUser :: Text -> Text -> XMPP.JID -> Session
357 | proxyAdHocFromUser prevIqID otherSID gatewayJid _ componentDomain _ iqID from command = (
358 | SessionNext $ proxyAdHocFromGateway iqID from,
359 | (XMPP.emptyIQ XMPP.IQSet) {
360 | XMPP.iqID = Just prevIqID,
361 | XMPP.iqTo = Just gatewayJid,
362 | XMPP.iqFrom = Just sendFrom,
363 | XMPP.iqPayload = Just $ command {
364 | XML.elementAttributes = map (\attr@(name, _) ->
365 | HT.select attr [
366 | (name == s"node", (name, [s"jabber:iq:register"])),
367 | (name == s"sessionid", (name, [ContentText otherSID]))
368 | ]
369 | ) (XML.elementAttributes command)
370 | }
371 | }
372 | )
373 | where
374 | sendFrom = sendFromForBackend componentDomain from
375 |
376 | switchStage1 :: XMPP.JID -> XMPP.JID -> XMPP.JID -> Maybe XMPP.JID -> Maybe XMPP.JID -> XMPP.JID -> Text -> SessionID -> XMPP.IQ
377 | switchStage1 newJid switchJid switchRoute possibleRoute existingRoute iqTo iqID sid = (XMPP.emptyIQ XMPP.IQResult) {
378 | XMPP.iqTo = Just iqTo,
379 | XMPP.iqID = Just iqID,
380 | XMPP.iqPayload = Just $ commandStage sid False $
381 | Element (fromString "{jabber:x:data}x") [
382 | (fromString "{jabber:x:data}type", [ContentText $ s"form"])
383 | ] [
384 | NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ s"Accept Jabber ID Change"],
385 | NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [
386 | NodeContent $ ContentText $ concat [
387 | s"It appears that the Jabber ID \"",
388 | bareTxt switchJid,
389 | s"\" has requested a migration to this Jabber ID (",
390 | bareTxt newJid,
391 | s"). If this isn't expected, respond no to the following to register normally"
392 | ]
393 | ],
394 | NodeElement $ Element (fromString "{jabber:x:data}field") [
395 | (fromString "{jabber:x:data}type", [ContentText $ s"boolean"]),
396 | (fromString "{jabber:x:data}var", [ContentText $ s"confirm"]),
397 | (fromString "{jabber:x:data}label", [ContentText $ s"Do you accept the migration?"])
398 | ] []
399 | ]
400 | }
401 |
402 | switchStage2 :: XMPP.JID -> XMPP.JID -> Maybe XMPP.JID -> Maybe XMPP.JID -> Session
403 | switchStage2 switchJid switchRoute possibleRoute existingRoute _ componentDomain sid iqID from command
404 | | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
405 | Just True <- parseBool =<< getFormField form (s"confirm") =
406 | (
407 | SessionNext $ switchStage3 switchJid switchRoute iqID from,
408 | (XMPP.emptyIQ XMPP.IQSet) {
409 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute2" ++ sessionIDToText sid),
410 | XMPP.iqTo = Just switchRoute,
411 | XMPP.iqFrom = Just $ sendFromForBackend componentDomain switchJid,
412 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [(s"node", [ContentText switchBackendNodeName])] []
413 | }
414 | )
415 | | otherwise =
416 | (
417 | SessionClearSwitchAndNext from stage2,
418 | stage1 possibleRoute existingRoute from iqID sid
419 | )
420 |
421 | switchStage3 :: XMPP.JID -> XMPP.JID -> Text -> XMPP.JID -> Session
422 | switchStage3 switchJid switchRoute stage2ID stage2From _ componentDomain sid iqID from command
423 | | Just backendSid <- attributeText (s"sessionid") command,
424 | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
425 | isJust $ getFormField form $ s"jid" =
426 | (
427 | SessionNext $ switchStage4 switchJid switchRoute stage2ID stage2From,
428 | (XMPP.emptyIQ XMPP.IQSet) {
429 | XMPP.iqTo = Just from,
430 | XMPP.iqFrom = Just $ sendFromForBackend componentDomain switchJid,
431 | XMPP.iqID = Just (s"ConfigureDirectMessageRoute3" ++ sessionIDToText sid),
432 | XMPP.iqPayload = Just $ Element (s"{http://jabber.org/protocol/commands}command") [
433 | (s"node", [ContentText switchBackendNodeName]),
434 | (s"sessionid", [ContentText $ backendSid])
435 | ] [
436 | NodeElement $ Element (fromString "{jabber:x:data}x") [
437 | (fromString "{jabber:x:data}type", [ContentText $ s"submit"])
438 | ] [
439 | NodeElement $ Element (fromString "{jabber:x:data}field") [
440 | (fromString "{jabber:x:data}var", [ContentText $ s"jid"])
441 | ] [
442 | NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ bareTxt $ sendFromForBackend componentDomain stage2From]
443 | ]
444 | ]
445 | ]
446 | }
447 | )
448 | | otherwise = (SessionCancel, iqError (Just stage2ID) (Just stage2From) "cancel" "internal-server-error" Nothing)
449 |
450 | switchStage4 :: XMPP.JID -> XMPP.JID -> Text -> XMPP.JID -> Session
451 | switchStage4 switchJid switchRoute stage2ID stage2From _ componentDomain sid iqID from command
452 | | attributeText (s"status") command == Just (s"canceled") = (SessionCancel, proxied)
453 | | attributeText (s"status") command == Just (s"completed") =
454 | if (s"error") `elem` mapMaybe (attributeText (s"type")) (XML.isNamed (s"{http://jabber.org/protocol/commands}note") =<< XML.elementChildren command) then
455 | (SessionCancel, proxied)
456 | else
457 | (SessionCompleteSwitch stage2From switchJid switchRoute, proxied)
458 | where
459 | proxied =
460 | (XMPP.emptyIQ XMPP.IQResult) {
461 | XMPP.iqID = Just stage2ID,
462 | XMPP.iqTo = Just stage2From,
463 | XMPP.iqPayload = Just $ command {
464 | XML.elementAttributes = map (\attr@(name, _) ->
465 | HT.select attr [
466 | (name == s"node", (name, [ContentText nodeName])),
467 | (name == s"sessionid", (name, [ContentText $ sessionIDToText sid]))
468 | ]
469 | ) (XML.elementAttributes command)
470 | }
471 | }
472 |
473 | stage1 :: Maybe XMPP.JID -> Maybe XMPP.JID -> XMPP.JID -> Text -> SessionID -> XMPP.IQ
474 | stage1 possibleRoute existingRoute iqTo iqID sid = (XMPP.emptyIQ XMPP.IQResult) {
475 | XMPP.iqTo = Just iqTo,
476 | XMPP.iqID = Just iqID,
477 | XMPP.iqPayload = Just $ commandStage sid False $
478 | Element (fromString "{jabber:x:data}x") [
479 | (s"{jabber:x:data}type", [s"form"])
480 | ] (catMaybes [
481 | Just $ NodeElement $ Element (s"{jabber:x:data}title") [] [NodeContent $ s"Configure Direct Message Route"],
482 | Just $ NodeElement $ Element (s"{jabber:x:data}instructions") [] [
483 | NodeContent $ ContentText $ s"Enter the gateway to use for routing your direct messages over SMS."
484 | ],
485 | flip fmap possibleRoute $ \route -> NodeElement $ Element (s"{jabber:x:data}instructions") [] [
486 | NodeContent $ ContentText $ s"To continue your registration with " ++ XMPP.formatJID route ++ s" please enter " ++ XMPP.formatJID route
487 | ],
488 | Just $ NodeElement $ Element (s"{jabber:x:data}field") [
489 | (s"{jabber:x:data}type", [s"list-single"]),
490 | (s"{jabber:x:data}var", [s"gateway-jid"]),
491 | (s"{jabber:x:data}label", [s"Gateway"])
492 | ] [
493 | NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ ContentText $ maybe mempty XMPP.formatJID existingRoute],
494 | NodeElement $ Element (s"{http://jabber.org/protocol/xdata-validate}validate")
495 | [(s"datatype", [s"xs:string"])]
496 | [NodeElement $ Element (s"{http://jabber.org/protocol/xdata-validate}open") [] []],
497 | NodeElement $ Element (s"{jabber:x:data}option")
498 | [(s"label", [s"JMP"])]
499 | [NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ s"jmp.chat"]],
500 | NodeElement $ Element (s"{jabber:x:data}option")
501 | [(s"label", [s"Vonage SGX"])]
502 | [NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ s"vonage.sgx.soprani.ca"]],
503 | NodeElement $ Element (s"{jabber:x:data}option")
504 | [(s"label", [s"Twilio SGX"])]
505 | [NodeElement $ Element (s"{jabber:x:data}value") [] [NodeContent $ s"twilio.sgx.soprani.ca"]]
506 | ]
507 | ])
508 | }
509 |
510 | sendFromForBackend :: XMPP.Domain -> XMPP.JID -> XMPP.JID
511 | sendFromForBackend componentDomain from
512 | | XMPP.jidDomain from == componentDomain = from
513 | | otherwise = sendFrom
514 | where
515 | Just sendFrom = XMPP.parseJID $ (escapeJid $ bareTxt from) ++ s"@" ++ XMPP.strDomain componentDomain
516 |
517 | commandStage :: SessionID -> Bool -> Element -> Element
518 | commandStage sid allowComplete el = Element (s"{http://jabber.org/protocol/commands}command")
519 | [
520 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
521 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
522 | (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"executing"])
523 | ]
524 | [
525 | NodeElement actions,
526 | NodeElement el
527 | ]
528 | where
529 | actions
530 | | allowComplete =
531 | Element (s"{http://jabber.org/protocol/commands}actions") [
532 | (s"{http://jabber.org/protocol/commands}execute", [ContentText $ s"complete"])
533 | ] [
534 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}next") [] [],
535 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}complete") [] []
536 | ]
537 | | otherwise =
538 | Element (s"{http://jabber.org/protocol/commands}actions") [
539 | (s"{http://jabber.org/protocol/commands}execute", [ContentText $ s"next"])
540 | ] [
541 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}next") [] []
542 | ]
543 |
544 | newSession :: Session -> IO (SessionID, Session)
545 | newSession nextStage = UUID.nextUUID >>= go
546 | where
547 | go (Just uuid) = return (SessionID uuid, nextStage)
548 | go Nothing = do
549 | log "ConfigureDirectMessageRoute.newSession" "UUID generation failed"
550 | UUID.nextUUID >>= go
551 |
552 | sessionIDFromText :: Text -> Maybe SessionID
553 | sessionIDFromText txt = SessionID <$> UUID.fromString (textToString txt)
554 |
555 | sessionIDToText :: SessionID -> Text
556 | sessionIDToText (SessionID uuid) = fromString $ UUID.toString uuid
557 |
558 | nodeName :: Text
559 | nodeName = s"register"
560 |
561 | iqError :: Maybe Text -> Maybe XMPP.JID -> String -> String -> Maybe String -> XMPP.IQ
562 | iqError iqID to typ xmpp command = (XMPP.emptyIQ XMPP.IQError) {
563 | XMPP.iqID = iqID,
564 | XMPP.iqTo = to,
565 | XMPP.iqPayload = Just $
566 | Element (s"{jabber:component:accept}error")
567 | [(s"{jabber:component:accept}type", [ContentText $ fromString typ])]
568 | (
569 | (NodeElement $ Element (fromString $ "{urn:ietf:params:xml:ns:xmpp-stanzas}" ++ xmpp) [] []) :
570 | map (\name ->
571 | NodeElement $ Element (fromString $ "{http://jabber.org/protocol/commands}" ++ name) [] []
572 | ) (toList command)
573 | )
574 | }
575 |
576 | convertFormToLegacyRegistration :: Element -> Element
577 | convertFormToLegacyRegistration form =
578 | Element (s"{jabber:iq:register}query") [] $
579 | map (NodeElement . uncurry legacyEl . varAndValue) fields
580 | where
581 | legacyEl var value = Element (fromString $ "{jabber:iq:register}" ++ T.unpack var) [] [NodeContent $ ContentText value]
582 | varAndValue field = (
583 | fromMaybe mempty $ attributeText (s"var") field,
584 | mconcat $ elementText =<< isNamed (s"{jabber:x:data}value") =<< elementChildren field
585 | )
586 | fields = isNamed (s"{jabber:x:data}field") =<< elementChildren form
587 |
588 | convertQueryToForm :: Element -> Element
589 | convertQueryToForm query =
590 | Element (s"{jabber:x:data}x") [
591 | (s"{jabber:x:data}type", [ContentText $ s"form"])
592 | ] ([
593 | NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ s"Register"],
594 | NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [NodeContent $ ContentText instructions]
595 | ] ++ map (NodeElement . uncurry field) vars)
596 | where
597 | field var text =
598 | Element (fromString "{jabber:x:data}field") [
599 | (s"{jabber:x:data}type", [ContentText $ if var == s"password" then s"text-private" else s"text-single"]),
600 | (s"{jabber:x:data}var", [ContentText var]),
601 | (s"{jabber:x:data}label", [ContentText var])
602 | ] [
603 | NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText text]
604 | ]
605 | instructions = mconcat $ elementText =<< isNamed (s"{jabber:iq:register}instructions") =<< elementChildren query
606 | vars =
607 | map snd $
608 | filter (\(ns, (var, _)) -> ns == s"jabber:iq:register" && var `notElem` [s"registered", s"instructions"]) $
609 | mapMaybe (\el -> let name = elementName el in (,) <$> nameNamespace name <*> pure (nameLocalName name, mconcat $ elementText el)) $
610 | elementChildren query
611 |
--------------------------------------------------------------------------------
/DB.hs:
--------------------------------------------------------------------------------
1 | module DB (DB, Key(..), byJid, byNode, mk, get, getEnum, del, set, expire, setEnum, sadd, srem, smembers, foldKeysM, hset, hdel, hgetall) where
2 |
3 | import Prelude ()
4 | import BasicPrelude
5 |
6 | import GHC.Stack (HasCallStack)
7 | import Network.Protocol.XMPP (JID(..), strNode)
8 |
9 | import qualified Database.Redis as Redis
10 | import qualified Data.ByteString as BS
11 | import qualified Data.Text.Encoding as T
12 |
13 | import Util
14 |
15 | data DB = DB {
16 | redis :: Redis.Connection
17 | }
18 |
19 | newtype Key = Key [String] deriving (Eq)
20 |
21 | mk :: Redis.ConnectInfo -> IO DB
22 | mk redisCI = DB <$> Redis.checkedConnect redisCI
23 |
24 | -- | 0xFF is invalid everywhere in UTF8 and is the CBOR "break" byte
25 | redisKey :: Key -> ByteString
26 | redisKey (Key key) = intercalate (BS.singleton 0xff) $ map (encodeUtf8 . fromString) key
27 |
28 | redisParseKey :: ByteString -> Key
29 | redisParseKey = Key . map (textToString . T.decodeUtf8) . BS.split 0xff
30 |
31 | -- | Run Redis action and if the reply is an error, send that to an IO exception
32 | runRedisChecked :: (HasCallStack) => DB -> Redis.Redis (Either Redis.Reply a) -> IO a
33 | runRedisChecked db action =
34 | either (ioError . userError . show) return =<<
35 | Redis.runRedis (redis db) action
36 |
37 | get :: (HasCallStack) => DB -> Key -> IO (Maybe Text)
38 | get db key = (fmap.fmap) T.decodeUtf8 $
39 | runRedisChecked db (Redis.get (redisKey key))
40 |
41 | getEnum :: (HasCallStack, Enum a) => DB -> Key -> IO (Maybe a)
42 | getEnum db key = (fmap.fmap) (toEnum . read . T.decodeUtf8) $
43 | runRedisChecked db (Redis.get (redisKey key))
44 |
45 | del :: (HasCallStack) => DB -> Key -> IO ()
46 | del db key = void $ runRedisChecked db $ Redis.del [redisKey key]
47 |
48 | set :: (HasCallStack) => DB -> Key -> Text -> IO ()
49 | set db key val = do
50 | Redis.Ok <- runRedisChecked db $ Redis.set (redisKey key) (encodeUtf8 val)
51 | return ()
52 |
53 | expire :: (HasCallStack) => DB -> Key -> Integer -> IO ()
54 | expire db key seconds = do
55 | -- True if set, False if key didn't exist, but actually I don't care
56 | _ <- runRedisChecked db $ Redis.expire (redisKey key) seconds
57 | return ()
58 |
59 | setEnum :: (HasCallStack, Enum a) => DB -> Key -> a -> IO ()
60 | setEnum db key val = do
61 | Redis.Ok <- runRedisChecked db $ Redis.set (redisKey key) (encodeUtf8 $ tshow $ fromEnum val)
62 | return ()
63 |
64 | sadd :: (HasCallStack) => DB -> Key -> [Text] -> IO ()
65 | sadd _ _ [] = return ()
66 | sadd db key new =
67 | void $ runRedisChecked db $ Redis.sadd (redisKey key) (map encodeUtf8 new)
68 |
69 | srem :: (HasCallStack) => DB -> Key -> [Text] -> IO ()
70 | srem db key toremove =
71 | void $ runRedisChecked db $ Redis.srem (redisKey key) (map encodeUtf8 toremove)
72 |
73 | smembers :: (HasCallStack) => DB -> Key -> IO [Text]
74 | smembers db key =
75 | map T.decodeUtf8 <$> runRedisChecked db (Redis.smembers (redisKey key))
76 |
77 | -- | Encode Just txt as UTF8 txt and Nothing as "\xf6"
78 | -- This is invalid UTF8, so there is no overlap. It is also the CBOR value for null
79 | redisMaybe :: Maybe Text -> ByteString
80 | redisMaybe (Just txt) = encodeUtf8 txt
81 | redisMaybe Nothing = BS.singleton 0xf6
82 |
83 | readRedisMaybe :: ByteString -> Maybe Text
84 | readRedisMaybe bytes
85 | | bytes == BS.singleton 0xf6 = Nothing
86 | | otherwise = Just $ T.decodeUtf8 bytes
87 |
88 | hset :: (HasCallStack) => DB -> Key -> [(Text, Maybe Text)] -> IO ()
89 | hset _ _ [] = return ()
90 | hset db key newitems =
91 | void $ runRedisChecked db (Redis.hmset (redisKey key) (map (encodeUtf8 *** redisMaybe) newitems))
92 |
93 | hdel :: (HasCallStack) => DB -> Key -> [Text] -> IO ()
94 | hdel db key toremove =
95 | void $ runRedisChecked db (Redis.hdel (redisKey key) (map encodeUtf8 toremove))
96 |
97 | hgetall :: (HasCallStack) => DB -> Key -> IO [(Text, Maybe Text)]
98 | hgetall db key =
99 | map (T.decodeUtf8 *** readRedisMaybe) <$>
100 | runRedisChecked db (Redis.hgetall (redisKey key))
101 |
102 | foldKeysM :: (HasCallStack) => DB -> Key -> b -> (b -> Key -> IO b) -> IO b
103 | foldKeysM db (Key prefix) z f = go Redis.cursor0 z
104 | where
105 | pattern = redisKey $ Key $ prefix ++ ["*"]
106 | go cursor acc = do
107 | (cursor', keys) <- runRedisChecked db $ Redis.scanOpts cursor (Redis.ScanOpts (Just pattern) (Just 100))
108 | acc' <- foldM f acc $ map redisParseKey keys
109 | if cursor' == Redis.cursor0 then return acc' else
110 | go cursor' acc'
111 |
112 | byJid :: JID -> [String] -> Key
113 | byJid jid subkey = Key $ (textToString $ bareTxt jid) : subkey
114 |
115 | -- | Used when we know the JID is @cheogram.com, for example
116 | -- So usually this is ByTel, really
117 | byNode :: (HasCallStack) => JID -> [String] -> Key
118 | byNode (JID { jidNode = Just node }) subkey =
119 | Key $ (textToString $ strNode node) : subkey
120 | byNode jid _ = error $ "JID without node used in byNode: " ++ show jid
121 |
--------------------------------------------------------------------------------
/IQManager.hs:
--------------------------------------------------------------------------------
1 | module IQManager (iqManager) where
2 |
3 | import Prelude ()
4 | import BasicPrelude
5 | import Control.Concurrent.STM (
6 | STM, TMVar, TVar, modifyTVar', newEmptyTMVar, newTVar, orElse,
7 | readTVar, takeTMVar, tryPutTMVar, writeTVar
8 | )
9 | import Control.Concurrent.STM.Delay (newDelay, waitDelay)
10 | import UnexceptionalIO.Trans (Unexceptional)
11 | import qualified Data.Map.Strict as Map
12 | import qualified Network.Protocol.XMPP as XMPP
13 | import qualified Data.UUID as UUID
14 | import qualified Data.UUID.V4 as UUID
15 |
16 | import Util
17 |
18 | type ResponseMap = Map.Map (Maybe Text) (TMVar XMPP.IQ)
19 |
20 | iqSendTimeoutMicroseconds :: Int
21 | iqSendTimeoutMicroseconds = 20 * 1000000
22 |
23 | iqDefaultID :: (Unexceptional m) => XMPP.IQ -> m XMPP.IQ
24 | iqDefaultID iq@XMPP.IQ { XMPP.iqID = Just _ } = return iq
25 | iqDefaultID iq = do
26 | uuid <- fromIO_ UUID.nextRandom
27 | return $ iq {
28 | XMPP.iqID = Just $ UUID.toText uuid
29 | }
30 |
31 | iqSenderUnexceptional :: (Unexceptional m) =>
32 | (XMPP.IQ -> m ())
33 | -> TVar ResponseMap
34 | -> XMPP.IQ
35 | -> m (STM (Maybe XMPP.IQ))
36 | iqSenderUnexceptional sender responseMapVar iq = do
37 | iqToSend <- iqDefaultID iq
38 | timeout <- fromIO_ $ newDelay iqSendTimeoutMicroseconds
39 | iqResponseVar <- atomicUIO newEmptyTMVar
40 | atomicUIO $ modifyTVar' responseMapVar $
41 | Map.insert (XMPP.iqID iqToSend) iqResponseVar
42 | sender iqToSend
43 | return (
44 | (waitDelay timeout *> pure Nothing)
45 | `orElse`
46 | fmap Just (takeTMVar iqResponseVar)
47 | )
48 |
49 | iqReceiver :: (Unexceptional m) => TVar ResponseMap -> XMPP.IQ -> m ()
50 | iqReceiver responseMapVar receivedIQ
51 | | XMPP.iqType receivedIQ `elem` [XMPP.IQResult, XMPP.IQError] = do
52 | maybeIqResponseVar <- atomicUIO $ do
53 | responseMap <- readTVar responseMapVar
54 | let (maybeIqResponseVar, responseMap') =
55 | Map.updateLookupWithKey
56 | (const $ const Nothing)
57 | (XMPP.iqID receivedIQ) responseMap
58 | writeTVar responseMapVar $! responseMap'
59 | return maybeIqResponseVar
60 | forM_ maybeIqResponseVar $ \iqResponseVar ->
61 | atomicUIO $ tryPutTMVar iqResponseVar receivedIQ
62 | | otherwise = return () -- TODO: log or otherwise signal error?
63 |
64 | iqManager :: (Unexceptional m1, Unexceptional m2, Unexceptional m3) =>
65 | (XMPP.IQ -> m2 ()) ->
66 | m1 (XMPP.IQ -> m2 (STM (Maybe XMPP.IQ)), XMPP.IQ -> m3 ())
67 | iqManager sender = do
68 | responseMapVar <- atomicUIO $ newTVar Map.empty
69 | return (
70 | iqSenderUnexceptional sender responseMapVar,
71 | iqReceiver responseMapVar
72 | )
73 |
--------------------------------------------------------------------------------
/JidSwitch.hs:
--------------------------------------------------------------------------------
1 | module JidSwitch where
2 |
3 | import Prelude ()
4 | import BasicPrelude hiding (log)
5 | import Data.UUID (UUID)
6 | import qualified Data.UUID as UUID (toString, fromString)
7 | import qualified Data.UUID.V1 as UUID (nextUUID)
8 | import Data.XML.Types (Element(..), Node(NodeContent, NodeElement), Name(..), Content(ContentText), isNamed, hasAttributeText, elementText, elementChildren, attributeText)
9 | import qualified Network.Protocol.XMPP as XMPP
10 |
11 | import Util
12 | import CommandAction
13 | import StanzaRec
14 |
15 | import qualified ConfigureDirectMessageRoute
16 | import qualified DB
17 |
18 | nodeName :: Text
19 | nodeName = s"change jabber id"
20 |
21 | newtype SessionID = SessionID UUID deriving (Ord, Eq, Show)
22 |
23 | sessionIDFromText :: Text -> Maybe SessionID
24 | sessionIDFromText txt = SessionID <$> UUID.fromString (textToString txt)
25 |
26 | sessionIDToText :: SessionID -> Text
27 | sessionIDToText (SessionID uuid) = fromString $ UUID.toString uuid
28 |
29 | type FromJID = XMPP.JID
30 | type Route = XMPP.JID
31 |
32 | fromAssoc :: [(Text, Maybe Text)] -> Maybe (FromJID, Route)
33 | fromAssoc assoc = (,) <$> (XMPP.parseJID =<< join (lookup (s"from") assoc)) <*> (XMPP.parseJID =<< join (lookup (s"route") assoc))
34 |
35 | toAssoc :: FromJID -> Route -> [(Text, Maybe Text)]
36 | toAssoc from route = [(s"from", Just $ bareTxt from), (s"route", Just $ bareTxt route)]
37 |
38 | newSession :: IO SessionID
39 | newSession = UUID.nextUUID >>= go
40 | where
41 | go (Just uuid) = return $ SessionID uuid
42 | go Nothing = do
43 | log "JidSwitch.newSession" "UUID generation failed"
44 | UUID.nextUUID >>= go
45 |
46 | receiveIq componentJid setJidSwitch iq@(XMPP.IQ { XMPP.iqFrom = Just from, XMPP.iqPayload = Just realPayload })
47 | | [command] <- isNamed (fromString "{http://jabber.org/protocol/commands}command") =<< [realPayload],
48 | Just action <- attributeText (s"action") command,
49 | action `elem` [s"complete", s"execute"],
50 | Just sid <- sessionIDFromText =<< attributeText (s"sessionid") command,
51 | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren command,
52 | Just newJid <- XMPP.parseJID =<< getFormField form (s"new-jid") = do
53 | (from', newJid', _) <- setJidSwitch newJid
54 | return [
55 | mkStanzaRec $ (XMPP.emptyMessage XMPP.MessageChat) {
56 | XMPP.messageTo = Just newJid,
57 | XMPP.messageFrom = Just componentJid,
58 | XMPP.messagePayloads = [
59 | mkElement (s"{jabber:component:accept}body") $ concat [
60 | bareTxt from',
61 | s" has requested a Jabber ID change to ",
62 | bareTxt newJid',
63 | s". To complete this request send \"register\""
64 | ],
65 | Element (s"{http://jabber.org/protocol/disco#items}query")
66 | [(s"node", [ContentText $ s"http://jabber.org/protocol/commands"])] [
67 | NodeElement $ Element (s"{http://jabber.org/protocol/disco#items}item") [
68 | (s"jid", [ContentText $ XMPP.formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName]),
69 | (s"node", [ContentText ConfigureDirectMessageRoute.nodeName]),
70 | (s"name", [ContentText $ s"register"])
71 | ] []
72 | ]
73 | ]
74 | },
75 | mkStanzaRec $ flip iqReply iq $ Just $ commandStage sid [] (s"completed") [
76 | Element (s"{http://jabber.org/protocol/commands}note") [
77 | (s"{http://jabber.org/protocol/commands}type", [ContentText $ s"info"])
78 | ] [
79 | NodeContent $ ContentText $ s"Please check for a message on " ++ bareTxt newJid'
80 | ]
81 | ]]
82 | | [command] <- isNamed (fromString "{http://jabber.org/protocol/commands}command") =<< [realPayload],
83 | Just sid <- sessionIDFromText =<< attributeText (s"sessionid") command =
84 | return [mkStanzaRec $ flip iqReply iq $ Just $ commandStage sid [ActionComplete] (s"canceled") []]
85 | | otherwise = do
86 | sid <- newSession
87 | return [mkStanzaRec $ stage1 sid iq]
88 |
89 | stage1 sid iq = flip iqReply iq $ Just $ commandStage sid [ActionComplete] (s"executing") [
90 | Element (fromString "{jabber:x:data}x") [
91 | (fromString "{jabber:x:data}type", [ContentText $ s"form"])
92 | ] [
93 | NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ s"Change Jabber ID"],
94 | NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [
95 | NodeContent $ ContentText $ s"Enter the Jabber ID you'd like to move your account to"
96 | ],
97 | NodeElement $ Element (fromString "{jabber:x:data}field") [
98 | (fromString "{jabber:x:data}type", [ContentText $ s"jid-single"]),
99 | (fromString "{jabber:x:data}var", [ContentText $ s"new-jid"]),
100 | (fromString "{jabber:x:data}label", [ContentText $ s"New Jabber ID"])
101 | ] []
102 | ]
103 | ]
104 |
105 | commandStage :: SessionID -> [Action] -> Text -> [Element] -> Element
106 | commandStage sid acceptedActions status el = Element (s"{http://jabber.org/protocol/commands}command")
107 | [
108 | (s"{http://jabber.org/protocol/commands}node", [ContentText nodeName]),
109 | (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ sessionIDToText sid]),
110 | (s"{http://jabber.org/protocol/commands}status", [ContentText status])
111 | ]
112 | (actions ++ map NodeElement el)
113 | where
114 | actions
115 | | null acceptedActions = []
116 | | otherwise = [
117 | NodeElement $ Element (s"{http://jabber.org/protocol/commands}actions") [
118 | (s"{http://jabber.org/protocol/commands}execute", [actionContent $ head acceptedActions])
119 | ] (map NodeElement $ concatMap actionToEl acceptedActions)
120 | ]
121 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | GHCFLAGS=-Wall -Wno-tabs -Wno-orphans -Wno-name-shadowing -XHaskell2010 -O -threaded
2 | HLINTFLAGS=-XHaskell2010 -XCPP -i 'Use camelCase' -i 'Use String' -i 'Use head' -i 'Use string literal' -i 'Use list comprehension'
3 |
4 | .PHONY: all shell clean
5 |
6 | all: report.html cheogram
7 |
8 | cheogram: Main.hs Adhoc.hs Config.hs ConfigureDirectMessageRoute.hs DB.hs IQManager.hs RedisURL.hs StanzaRec.hs UniquePrefix.hs Util.hs JidSwitch.hs VCard4.hs
9 | ghc -dynamic -package monads-tf -o cheogram $(GHCFLAGS) Main.hs
10 |
11 | report.html: Main.hs Adhoc.hs Config.hs ConfigureDirectMessageRoute.hs DB.hs IQManager.hs RedisURL.hs StanzaRec.hs UniquePrefix.hs Util.hs JidSwitch.hs VCard4.hs
12 | -hlint $(HLINTFLAGS) --report $^
13 |
14 | shell:
15 | ghci $(GHCFLAGS)
16 |
17 | clean:
18 | find -name '*.o' -o -name '*.hi' | xargs $(RM)
19 | $(RM) cheogram report.html
20 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | Part of the soprani.ca family of projects.
2 |
3 | Please report bugs and send patches to dev@singpolyma.net or join us in xmpp:discuss@conference.soprani.ca?join
4 |
5 | To build, run:
6 |
7 | guix shell
8 | make
9 |
--------------------------------------------------------------------------------
/RedisURL.hs:
--------------------------------------------------------------------------------
1 | {-
2 | Copyright (c)2011, Falko Peters
3 | Some modifications by Stephen Paul Weber
4 |
5 | All rights reserved.
6 |
7 | Redistribution and use in source and binary forms, with or without
8 | modification, are permitted provided that the following conditions are met:
9 |
10 | * Redistributions of source code must retain the above copyright
11 | notice, this list of conditions and the following disclaimer.
12 |
13 | * Redistributions in binary form must reproduce the above
14 | copyright notice, this list of conditions and the following
15 | disclaimer in the documentation and/or other materials provided
16 | with the distribution.
17 |
18 | * Neither the name of Falko Peters nor the names of other
19 | contributors may be used to endorse or promote products derived
20 | from this software without specific prior written permission.
21 |
22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 | -}
34 | module RedisURL (parseConnectInfo) where
35 |
36 | import Prelude ()
37 | import BasicPrelude
38 | import Control.Error.Util (note)
39 | import Control.Monad (guard)
40 | import Data.Monoid ((<>))
41 | import Database.Redis (ConnectInfo(..), defaultConnectInfo, PortID(..))
42 | import Network.HTTP.Base
43 | import Network.HTTP.Types (parseSimpleQuery)
44 | import Network.URI (URI, parseURI, uriPath, uriScheme, uriQuery)
45 | import Text.Read (readMaybe)
46 |
47 | import qualified Data.ByteString.Char8 as C8
48 |
49 | parseConnectInfo :: String -> Either String ConnectInfo
50 | parseConnectInfo url = do
51 | uri <- note "Invalid URI" $ parseURI url
52 | case uriScheme uri of
53 | "redis:" -> parseRedisScheme uri
54 | "unix:" -> parseUnixScheme uri
55 | _ -> Left "Invalid scheme"
56 |
57 | parseUnixScheme :: URI -> Either String ConnectInfo
58 | parseUnixScheme uri =
59 | return defaultConnectInfo
60 | { connectHost = ""
61 | , connectPort = UnixSocket path
62 | , connectAuth = C8.pack <$> (password =<< uriAuth)
63 | , connectDatabase = db
64 | }
65 | where
66 | path = case uriPath uri of
67 | ('/':_) -> uriPath uri
68 | _ -> '/' : uriPath uri
69 | db = fromMaybe 0 $ readMaybe . textToString . decodeUtf8 =<<
70 | lookup (encodeUtf8 $ fromString "db") query
71 | query = parseSimpleQuery (encodeUtf8 $ fromString $ uriQuery uri)
72 | uriAuth = parseURIAuthority $ uriToAuthorityString uri
73 |
74 | parseRedisScheme :: URI -> Either String ConnectInfo
75 | parseRedisScheme uri = do
76 | uriAuth <- note "Missing or invalid Authority"
77 | $ parseURIAuthority
78 | $ uriToAuthorityString uri
79 |
80 | let h = host uriAuth
81 | let dbNumPart = dropWhile (== '/') (uriPath uri)
82 |
83 | db <- if null dbNumPart
84 | then return $ connectDatabase defaultConnectInfo
85 | else note ("Invalid port: " <> dbNumPart) $ readMaybe dbNumPart
86 |
87 | return defaultConnectInfo
88 | { connectHost = if null h
89 | then connectHost defaultConnectInfo
90 | else h
91 | , connectPort = maybe (connectPort defaultConnectInfo)
92 | (PortNumber . fromIntegral) $ port uriAuth
93 | , connectAuth = C8.pack <$> password uriAuth
94 | , connectDatabase = db
95 | }
96 |
--------------------------------------------------------------------------------
/Setup.hs:
--------------------------------------------------------------------------------
1 | import Distribution.Simple
2 |
3 | main = defaultMain
4 |
--------------------------------------------------------------------------------
/StanzaRec.hs:
--------------------------------------------------------------------------------
1 | module StanzaRec (StanzaRec(..), mkStanzaRec, ensureId) where
2 |
3 | import Prelude ()
4 | import BasicPrelude
5 | import qualified Data.UUID as UUID (toText)
6 | import qualified Data.UUID.V1 as UUID (nextUUID)
7 | import qualified Data.XML.Types as XML
8 | import qualified Network.Protocol.XMPP as XMPP
9 | import Network.Protocol.XMPP.Internal (Stanza(..))
10 |
11 | import Util
12 |
13 | data StanzaRec = StanzaRec (Maybe XMPP.JID) (Maybe XMPP.JID) (Maybe Text) (Maybe Text) [XML.Element] XML.Element deriving (Show)
14 |
15 | instance Stanza StanzaRec where
16 | stanzaTo (StanzaRec to _ _ _ _ _) = to
17 | stanzaFrom (StanzaRec _ from _ _ _ _) = from
18 | stanzaID (StanzaRec _ _ sid _ _ _) = sid
19 | stanzaLang (StanzaRec _ _ _ lang _ _) = lang
20 | stanzaPayloads (StanzaRec _ _ _ _ payloads _) = payloads
21 | stanzaToElement (StanzaRec _ _ _ _ _ element) = element
22 |
23 | mkStanzaRec :: (Stanza s) => s -> StanzaRec
24 | mkStanzaRec x = StanzaRec (stanzaTo x) (stanzaFrom x) (stanzaID x) (stanzaLang x) (stanzaPayloads x) (stanzaToElement x)
25 |
26 | ensureId :: StanzaRec -> IO StanzaRec
27 | ensureId (StanzaRec to from Nothing lang payloads element) = do
28 | uuid <- (fmap.fmap) UUID.toText UUID.nextUUID
29 | return $ StanzaRec to from uuid lang payloads $ element {
30 | XML.elementAttributes =
31 | (s"id", [XML.ContentText $ fromMaybe mempty uuid]) :
32 | XML.elementAttributes element
33 | }
34 | ensureId s = return s
35 |
--------------------------------------------------------------------------------
/UniquePrefix.hs:
--------------------------------------------------------------------------------
1 | module UniquePrefix where
2 |
3 | import Data.List
4 | import qualified Data.Set as S
5 | import qualified Data.Text as T
6 | import qualified Data.CaseInsensitive as CI
7 |
8 | uniquePrefix txts = helper [] $ map (S.fromList . map CI.mk . tail . T.inits) txts
9 |
10 | helper done (prefixes:otherPrefixes) =
11 | (foldl' S.difference prefixes (done ++ otherPrefixes)) : helper (prefixes:done) otherPrefixes
12 | helper _ [] = []
13 |
14 | --ALT: https://pastebin.com/hFKdZw2g
15 |
--------------------------------------------------------------------------------
/Util.hs:
--------------------------------------------------------------------------------
1 | module Util where
2 |
3 | import Prelude ()
4 | import BasicPrelude
5 | import Control.Concurrent
6 | import Control.Concurrent.STM (STM, atomically)
7 | import System.Exit (ExitCode)
8 | import GHC.Stack (HasCallStack)
9 | import Data.Word (Word16)
10 | import Data.Bits (shiftL, (.|.))
11 | import Data.Char (isDigit)
12 | import Control.Applicative (many)
13 | import Control.Error (hush)
14 | import Data.Time (getCurrentTime)
15 | import Data.XML.Types as XML (Name(Name), Element(..), Node(NodeElement, NodeContent), Content(ContentText), isNamed, elementText, elementChildren, attributeText)
16 | import Crypto.Random (getSystemDRG, withRandomBytes)
17 | import Data.ByteString.Base58 (bitcoinAlphabet, encodeBase58)
18 | import Data.Digest.Pure.SHA (sha1, bytestringDigest)
19 | import Data.Void (absurd)
20 | import UnexceptionalIO (Unexceptional)
21 | import qualified UnexceptionalIO as UIO
22 | import qualified Control.Exception as Ex
23 | import qualified Data.Text as T
24 | import qualified Data.Text.Encoding as T
25 | import qualified Network.Protocol.XMPP as XMPP
26 | import qualified Data.Attoparsec.Text as Atto
27 | import qualified Data.ByteString.Lazy as LZ
28 | import qualified Text.Regex.PCRE.Light as PCRE
29 |
30 | instance Unexceptional XMPP.XMPP where
31 | lift = liftIO . UIO.lift
32 |
33 | log :: (HasCallStack, Show a, Unexceptional m) => String -> a -> m ()
34 | log tag x = fromIO_ $ do
35 | time <- getCurrentTime
36 | putStr (tshow time ++ s" " ++ fromString tag ++ s" :: ") >> print x >> putStrLn mempty
37 |
38 | s :: (IsString a) => String -> a
39 | s = fromString
40 |
41 | (.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
42 | (.:) = (.) . (.)
43 |
44 | fromIO_ :: (HasCallStack, Unexceptional m) => IO a -> m a
45 | fromIO_ = fmap (either absurd id) . UIO.fromIO' (error . show)
46 |
47 | atomicUIO :: (HasCallStack, Unexceptional m) => STM a -> m a
48 | atomicUIO = fromIO_ . atomically
49 |
50 | escapeJid :: Text -> Text
51 | escapeJid txt = mconcat result
52 | where
53 | Right result = Atto.parseOnly (many (
54 | slashEscape <|>
55 | replace ' ' "\\20" <|>
56 | replace '"' "\\22" <|>
57 | replace '&' "\\26" <|>
58 | replace '\'' "\\27" <|>
59 | replace '/' "\\2f" <|>
60 | replace ':' "\\3a" <|>
61 | replace '<' "\\3c" <|>
62 | replace '>' "\\3e" <|>
63 | replace '@' "\\40" <|>
64 | fmap T.singleton Atto.anyChar
65 | ) <* Atto.endOfInput) txt
66 | replace c str = Atto.char c *> pure (fromString str)
67 | -- XEP-0106 says to only escape \ when absolutely necessary
68 | slashEscape =
69 | fmap (s"\\5c"++) $
70 | Atto.char '\\' *> Atto.choice escapes
71 | escapes = map (Atto.string . fromString) [
72 | "20", "22", "26", "27", "2f", "3a", "3c", "3e", "40", "5c"
73 | ]
74 |
75 | unescapeJid :: Text -> Text
76 | unescapeJid txt = fromString result
77 | where
78 | Right result = Atto.parseOnly (many (
79 | (Atto.char '\\' *> Atto.choice unescapes) <|>
80 | Atto.anyChar
81 | ) <* Atto.endOfInput) txt
82 | unescapes = map (\(str, c) -> Atto.string (fromString str) *> pure c) [
83 | ("20", ' '), ("22", '"'), ("26", '&'), ("27", '\''), ("2f", '/'), ("3a", ':'), ("3c", '<'), ("3e", '>'), ("40", '@'), ("5c", '\\')
84 | ]
85 |
86 | -- Matches any URL-ish text, but not x@x.tld forms
87 | autolinkRegex :: PCRE.Regex
88 | autolinkRegex = PCRE.compile (encodeUtf8 $ s"(? Maybe Text
91 | sanitizeSipLocalpart localpart
92 | | Just ('+', tel) <- T.uncons candidate,
93 | T.all isDigit tel = Just candidate
94 | | T.length candidate < 3 =
95 | Just $ s"13;phone-context=anonymous.phone-context.soprani.ca"
96 | | candidate == s"Restricted" =
97 | Just $ s"14;phone-context=anonymous.phone-context.soprani.ca"
98 | | candidate == s"anonymous" =
99 | Just $ s"15;phone-context=anonymous.phone-context.soprani.ca"
100 | | candidate == s"Anonymous" =
101 | Just $ s"16;phone-context=anonymous.phone-context.soprani.ca"
102 | | candidate == s"unavailable" =
103 | Just $ s"17;phone-context=anonymous.phone-context.soprani.ca"
104 | | candidate == s"Unavailable" =
105 | Just $ s"18;phone-context=anonymous.phone-context.soprani.ca"
106 | | otherwise = Nothing
107 | where
108 | candidate = fst $ T.breakOn (s"@") $ unescapeJid localpart
109 |
110 | showAvailableness :: String -> Word8
111 | showAvailableness "chat" = 5
112 | showAvailableness "" = 4
113 | showAvailableness "away" = 3
114 | showAvailableness "dnd" = 2
115 | showAvailableness "xa" = 1
116 | showAvailableness _ = 0
117 |
118 | priorityAvailableness :: Integer -> Word8
119 | priorityAvailableness priority
120 | | priority > 127 = 0xff
121 | | priority < -128 = 0x00
122 | | otherwise = fromIntegral (priority + 128)
123 |
124 | availableness :: Text -> Integer -> Word16
125 | availableness sshow priority =
126 | (fromIntegral (showAvailableness (textToString sshow)) `shiftL` 8) .|.
127 | (fromIntegral (priorityAvailableness priority))
128 |
129 | parsePhoneContext :: Text -> Maybe (Text, Text)
130 | parsePhoneContext txt = hush $ Atto.parseOnly (
131 | (,) <$> Atto.takeWhile isDigit <* Atto.string (s";phone-context=") <*> Atto.takeTill (Atto.inClass " ;")
132 | <* Atto.endOfInput
133 | ) txt
134 |
135 | bareTxt :: XMPP.JID -> Text
136 | bareTxt (XMPP.JID (Just node) domain _) = mconcat [XMPP.strNode node, s"@", XMPP.strDomain domain]
137 | bareTxt (XMPP.JID Nothing domain _) = XMPP.strDomain domain
138 |
139 | getFormField :: XML.Element -> Text -> Maybe Text
140 | getFormField form var =
141 | listToMaybe $ mapMaybe (\node ->
142 | case node of
143 | NodeElement el
144 | | elementName el == s"{jabber:x:data}field" &&
145 | (attributeText (s"{jabber:x:data}var") el == Just var ||
146 | attributeText (s"var") el == Just var) ->
147 | Just $ mconcat $
148 | elementText =<< isNamed (s"{jabber:x:data}value") =<< elementChildren el
149 | _ -> Nothing
150 | ) (elementNodes form)
151 |
152 | genToken :: Int -> IO Text
153 | genToken n = do
154 | g <- getSystemDRG
155 | return $ fst $ withRandomBytes g n (T.decodeUtf8 . encodeBase58 bitcoinAlphabet)
156 |
157 | child :: (XMPP.Stanza s) => Name -> s -> Maybe Element
158 | child name = listToMaybe .
159 | (isNamed name <=< XMPP.stanzaPayloads)
160 |
161 | attrOrBlank :: XML.Name -> XML.Element -> Text
162 | attrOrBlank name el = fromMaybe mempty $ XML.attributeText name el
163 |
164 | discoCapsIdentities :: XML.Element -> [Text]
165 | discoCapsIdentities query =
166 | sort $
167 | map (\identity -> mconcat $ intersperse (s"/") [
168 | attrOrBlank (s"category") identity,
169 | attrOrBlank (s"type") identity,
170 | attrOrBlank (s"xml:lang") identity,
171 | attrOrBlank (s"name") identity
172 | ]) $
173 | XML.isNamed (s"{http://jabber.org/protocol/disco#info}identity") =<<
174 | XML.elementChildren query
175 |
176 | discoVars :: XML.Element -> [Text]
177 | discoVars query =
178 | sort $
179 | mapMaybe (XML.attributeText (s"var")) $
180 | XML.isNamed (s"{http://jabber.org/protocol/disco#info}feature") =<<
181 | XML.elementChildren query
182 |
183 | data DiscoForm = DiscoForm Text [(Text, [Text])] deriving (Show, Ord, Eq)
184 |
185 | oneDiscoForm :: XML.Element -> DiscoForm
186 | oneDiscoForm form =
187 | DiscoForm form_type (filter ((/= s"FORM_TYPE") . fst) fields)
188 | where
189 | form_type = mconcat $ fromMaybe [] $ lookup (s"FORM_TYPE") fields
190 | fields = sort $ map (\field ->
191 | (
192 | attrOrBlank (s"var") field,
193 | sort (map (mconcat . XML.elementText) $ XML.isNamed (s"{jabber:x:data}value") =<< XML.elementChildren form)
194 | )
195 | ) $
196 | XML.isNamed (s"{jabber:x:data}field") =<<
197 | XML.elementChildren form
198 |
199 | discoForms :: XML.Element -> [DiscoForm]
200 | discoForms query =
201 | sort $
202 | map oneDiscoForm $
203 | XML.isNamed (s"{jabber:x:data}x") =<<
204 | XML.elementChildren query
205 |
206 | discoCapsForms :: XML.Element -> [Text]
207 | discoCapsForms query =
208 | concatMap (\(DiscoForm form_type fields) ->
209 | form_type : concatMap (uncurry (:)) fields
210 | ) (discoForms query)
211 |
212 | discoToCaps :: XML.Element -> Text
213 | discoToCaps query =
214 | (mconcat $ intersperse (s"<") (discoCapsIdentities query ++ discoVars query ++ discoCapsForms query)) ++ s"<"
215 |
216 | discoToCapsHash :: XML.Element -> ByteString
217 | discoToCapsHash query =
218 | LZ.toStrict $ bytestringDigest $ sha1 $ LZ.fromStrict $ T.encodeUtf8 $ discoToCaps query
219 |
220 | getBody :: String -> XMPP.Message -> Maybe Text
221 | getBody ns = listToMaybe . fmap (mconcat . XML.elementText) . (XML.isNamed (XML.Name (fromString "body") (Just $ fromString ns) Nothing) <=< XMPP.messagePayloads)
222 |
223 | getThread :: String -> XMPP.Message -> Maybe Text
224 | getThread ns = listToMaybe . fmap (mconcat . XML.elementText) . (XML.isNamed (XML.Name (fromString "thread") (Just $ fromString ns) Nothing) <=< XMPP.messagePayloads)
225 |
226 | mkSMS :: XMPP.JID -> XMPP.JID -> Text -> XMPP.Message
227 | mkSMS from to txt = (XMPP.emptyMessage XMPP.MessageChat) {
228 | XMPP.messageTo = Just to,
229 | XMPP.messageFrom = Just from,
230 | XMPP.messagePayloads = [mkElement (s"{jabber:component:accept}body") txt]
231 | }
232 |
233 | castException :: (Ex.Exception e1, Ex.Exception e2) => e1 -> Maybe e2
234 | castException = Ex.fromException . Ex.toException
235 |
236 | -- Re-throws all by ThreadKilled async to parent thread
237 | -- Makes sync child exceptions async in parent, which is a bit sloppy
238 | forkXMPP :: XMPP.XMPP () -> XMPP.XMPP ThreadId
239 | forkXMPP kid = do
240 | parent <- liftIO myThreadId
241 | forkFinallyXMPP kid (either (handler parent) (const $ return ()))
242 | where
243 | handler parent e
244 | | Just Ex.ThreadKilled <- castException e = return ()
245 | | Just (Ex.SomeAsyncException _) <- castException e = throwTo parent e
246 | | Just e <- castException e = throwTo parent (e :: ExitCode)
247 | | otherwise = throwTo parent (ChildThreadError e)
248 |
249 | forkFinallyXMPP :: XMPP.XMPP () -> (Either SomeException () -> IO ()) -> XMPP.XMPP ThreadId
250 | forkFinallyXMPP kid handler = do
251 | session <- XMPP.getSession
252 | liftIO $ forkFinally (void $ XMPP.runXMPP session kid) handler
253 |
254 | newtype ChildThreadError = ChildThreadError SomeException deriving (Show, Typeable)
255 |
256 | instance Ex.Exception ChildThreadError where
257 | toException = Ex.asyncExceptionToException
258 | fromException = Ex.asyncExceptionFromException
259 |
260 | mkElement :: XML.Name -> Text -> XML.Element
261 | mkElement name txt = XML.Element name [] [XML.NodeContent $ XML.ContentText txt]
262 |
263 | nickname :: Text -> XML.Element
264 | nickname nick = XML.Element (s"{http://jabber.org/protocol/nick}nick") [] [
265 | XML.NodeContent $ XML.ContentText nick
266 | ]
267 |
268 | addNickname :: Text -> XMPP.Message -> XMPP.Message
269 | addNickname nick m@(XMPP.Message { XMPP.messagePayloads = p }) = m {
270 | XMPP.messagePayloads = (nickname nick) : p
271 | }
272 |
273 | mapReceivedMessageM :: (Applicative f) =>
274 | (XMPP.Message -> f XMPP.Message)
275 | -> XMPP.ReceivedStanza
276 | -> f XMPP.ReceivedStanza
277 | mapReceivedMessageM f (XMPP.ReceivedMessage m) = XMPP.ReceivedMessage <$> f m
278 | mapReceivedMessageM _ s = pure s
279 |
280 | iqReply :: Maybe XML.Element -> XMPP.IQ -> XMPP.IQ
281 | iqReply payload iq = iq {
282 | XMPP.iqType = XMPP.IQResult,
283 | XMPP.iqFrom = XMPP.iqTo iq,
284 | XMPP.iqTo = XMPP.iqFrom iq,
285 | XMPP.iqPayload = payload
286 | }
287 |
288 | queryCommandList' :: XMPP.JID -> XMPP.JID -> XMPP.IQ
289 | queryCommandList' to from = (XMPP.emptyIQ XMPP.IQGet) {
290 | XMPP.iqTo = Just to,
291 | XMPP.iqFrom = Just from,
292 | XMPP.iqPayload = Just $ XML.Element (s"{http://jabber.org/protocol/disco#items}query") [
293 | (s"{http://jabber.org/protocol/disco#items}node", [XML.ContentText $ s"http://jabber.org/protocol/commands"])
294 | ] []
295 | }
296 |
297 | queryDiscoWithNode' :: Maybe Text -> XMPP.JID -> XMPP.JID -> XMPP.IQ
298 | queryDiscoWithNode' node to from =
299 | (XMPP.emptyIQ XMPP.IQGet) {
300 | XMPP.iqTo = Just to,
301 | XMPP.iqFrom = Just from,
302 | XMPP.iqPayload = Just $ XML.Element
303 | (s"{http://jabber.org/protocol/disco#info}query")
304 | (map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [XML.ContentText node])) $ maybeToList node)
305 | []
306 | }
307 |
308 | parseBool :: Text -> Maybe Bool
309 | parseBool input
310 | | s"true" == input = Just True
311 | | s"1" == input = Just True
312 | | s"false" == input = Just False
313 | | s"0" == input = Just False
314 | | otherwise = Nothing
315 |
316 | hasLocked :: String -> IO a -> IO a
317 | hasLocked msg action =
318 | action `Ex.catches`
319 | [ Ex.Handler $ \exc@Ex.BlockedIndefinitelyOnMVar -> Util.log "[MVar]" msg >> Ex.throwIO exc
320 | , Ex.Handler $ \exc@Ex.BlockedIndefinitelyOnSTM -> Util.log "[STM]" msg >> Ex.throwIO exc
321 | ]
322 |
--------------------------------------------------------------------------------
/VCard4.hs:
--------------------------------------------------------------------------------
1 | module VCard4 (fetch) where
2 |
3 | import Prelude ()
4 | import BasicPrelude
5 |
6 | import Control.Concurrent.STM (STM)
7 | import UnexceptionalIO.Trans (Unexceptional)
8 | import Network.Protocol.XMPP (IQ(..), emptyIQ, IQType(IQResult, IQGet), JID, parseJID)
9 | import qualified Data.XML.Types as XML
10 | import qualified Data.Bool.HT as HT
11 |
12 | import Util
13 |
14 | fetch :: (Unexceptional m) => (IQ -> m (STM (Maybe IQ))) -> JID -> Maybe JID -> m (Maybe XML.Element)
15 | fetch sendIQ to from = do
16 | vcard4stm <- sendIQ (fetchVCard4 { iqTo = Just to, iqFrom = routeFrom })
17 | nickstm <- sendIQ (fetchNick { iqTo = Just to, iqFrom = routeFrom })
18 | vcardTempstm <- sendIQ (fetchVCardTemp { iqTo = Just to, iqFrom = routeFrom })
19 |
20 | vcard4 <- (parseVCard4Result =<<) <$> atomicUIO vcard4stm
21 | nick <- (parseNickResult =<<) <$> atomicUIO nickstm
22 | vcardTemp <- (parseVCardTempResult =<<) <$> atomicUIO vcardTempstm
23 |
24 | case concat $ mapMaybe (fmap XML.elementNodes) [vcard4, nick, vcardTemp] of
25 | els@(_:_) -> return $ Just $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}vcard") [] els
26 | _ -> return Nothing
27 | where
28 | routeFrom = parseJID =<< fmap (\jid -> bareTxt jid ++ s"/IQMANAGER") from
29 |
30 | fetchVCard4 :: IQ
31 | fetchVCard4 = (emptyIQ IQGet) {
32 | iqPayload = Just $ XML.Element (s"{http://jabber.org/protocol/pubsub}pubsub") [] [
33 | XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}items")
34 | [(s"node", [XML.ContentText $ s"urn:xmpp:vcard4"])] []
35 | ]
36 | }
37 |
38 | parseVCard4Result :: IQ -> Maybe XML.Element
39 | parseVCard4Result IQ { iqType = IQResult, iqPayload = Just payload } =
40 | listToMaybe $
41 | XML.isNamed (s"{urn:ietf:params:xml:ns:vcard-4.0}vcard") =<< XML.elementChildren =<<
42 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}item") =<< XML.elementChildren =<<
43 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}items") =<< XML.elementChildren =<<
44 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}pubsub") payload
45 | parseVCard4Result _ = Nothing
46 |
47 | fetchNick :: IQ
48 | fetchNick = (emptyIQ IQGet) {
49 | iqPayload = Just $ XML.Element (s"{http://jabber.org/protocol/pubsub}pubsub") [] [
50 | XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}items")
51 | [(s"node", [XML.ContentText $ s"http://jabber.org/protocol/nick"])] []
52 | ]
53 | }
54 |
55 | parseNickResult :: IQ -> Maybe XML.Element
56 | parseNickResult IQ { iqType = IQResult, iqPayload = Just payload } =
57 | fmap (\nickEl ->
58 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}vcard") [] [
59 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}nickname") [] [
60 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
61 | (map XML.NodeContent $ XML.elementContent nickEl)
62 | ]
63 | ]
64 | ) $ listToMaybe $
65 | XML.isNamed (s"{http://jabber.org/protocol/nick}nick") =<< XML.elementChildren =<<
66 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}item") =<< XML.elementChildren =<<
67 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}items") =<< XML.elementChildren =<<
68 | XML.isNamed (s"{http://jabber.org/protocol/pubsub}pubsub") payload
69 | parseNickResult _ = Nothing
70 |
71 | fetchVCardTemp :: IQ
72 | fetchVCardTemp = (emptyIQ IQGet) {
73 | iqPayload = Just $ XML.Element (s"{vcard-temp}vCard") [] []
74 | }
75 |
76 | parseVCardTempResult :: IQ -> Maybe XML.Element
77 | parseVCardTempResult IQ { iqType = IQResult, iqPayload = Just payload }
78 | | [vcard] <- XML.isNamed (s"{vcard-temp}vCard") payload =
79 | Just $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}vcard") [] $
80 | flip map (XML.elementChildren vcard) $ XML.NodeElement . \el ->
81 | HT.select el [
82 | (
83 | s"{vcard-temp}FN" == XML.elementName el,
84 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}fn") []
85 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
86 | (map XML.NodeContent $ XML.elementContent el)]
87 | ),
88 | (
89 | s"{vcard-temp}N" == XML.elementName el,
90 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}n") [] $
91 | flip map (XML.elementChildren el) $ XML.NodeElement . \subel ->
92 | HT.select el [
93 | (
94 | s"{vcard-temp}FAMILY" == XML.elementName subel,
95 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}surname") []
96 | (map XML.NodeContent $ XML.elementContent subel)
97 | ),
98 | (
99 | s"{vcard-temp}GIVEN" == XML.elementName subel,
100 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}given") []
101 | (map XML.NodeContent $ XML.elementContent subel)
102 | ),
103 | (
104 | s"{vcard-temp}MIDDLE" == XML.elementName subel,
105 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}additional") []
106 | (map XML.NodeContent $ XML.elementContent subel)
107 | ),
108 | (
109 | s"{vcard-temp}PREFIX" == XML.elementName subel,
110 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}prefix") []
111 | (map XML.NodeContent $ XML.elementContent subel)
112 | ),
113 | (
114 | s"{vcard-temp}SUFFIX" == XML.elementName subel,
115 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}suffix") []
116 | (map XML.NodeContent $ XML.elementContent subel)
117 | )
118 | ]
119 | ),
120 | (
121 | s"{vcard-temp}NICKNAME" == XML.elementName el,
122 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}nickname") []
123 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
124 | (map XML.NodeContent $ XML.elementContent el)]
125 | ),
126 | (
127 | s"{vcard-temp}PHOTO" == XML.elementName el,
128 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}photo") []
129 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") [] $
130 | case (
131 | XML.isNamed (s"{vcard-temp}TYPE") =<< XML.elementChildren el,
132 | XML.isNamed (s"{vcard-temp}EXTVAL") =<< XML.elementChildren el,
133 | XML.isNamed (s"{vcard-temp}BINVAL") =<< XML.elementChildren el
134 | ) of
135 | (_, [extval], _) -> map XML.NodeContent $ XML.elementContent extval
136 | (typ, _, [binval]) -> map XML.NodeContent $
137 | (XML.ContentText (s"data:") : concatMap XML.elementContent typ) ++
138 | (XML.ContentText (s";base64,") : XML.elementContent binval)
139 | _ -> []
140 | ]
141 | ),
142 | (
143 | s"{vcard-temp}BDAY" == XML.elementName el,
144 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}bday") []
145 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}date") []
146 | (map XML.NodeContent $ XML.elementContent el)]
147 | ),
148 | (
149 | s"{vcard-temp}ADR" == XML.elementName el,
150 | let
151 | home = not $ null $ XML.isNamed (s"{vcard-temp}HOME") =<< XML.elementChildren el
152 | work = not $ null $ XML.isNamed (s"{vcard-temp}WORK") =<< XML.elementChildren el
153 | pref = not $ null $ XML.isNamed (s"{vcard-temp}PREF") =<< XML.elementChildren el
154 | in
155 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}adr") [] $
156 | ((if home || work || pref then
157 | [
158 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}parameters") [] (map XML.NodeElement $ concat [
159 | if home || work then
160 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}type") [] [
161 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") [] [
162 | XML.NodeContent $ XML.ContentText $ if home then s"home" else s"work"]]]
163 | else [],
164 | if pref then
165 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}pref") [] [
166 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}integer") [] [
167 | XML.NodeContent $ XML.ContentText $ s"1"]]]
168 | else []
169 | ])
170 | ]
171 | else []) ++) $
172 | flip map (XML.elementChildren el) $ XML.NodeElement . \subel ->
173 | HT.select el [
174 | (
175 | s"{vcard-temp}POBOX" == XML.elementName subel,
176 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}pobox") []
177 | (map XML.NodeContent $ XML.elementContent subel)
178 | ),
179 | (
180 | s"{vcard-temp}EXTADD" == XML.elementName subel,
181 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}ext") []
182 | (map XML.NodeContent $ XML.elementContent subel)
183 | ),
184 | (
185 | s"{vcard-temp}STREET" == XML.elementName subel,
186 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}street") []
187 | (map XML.NodeContent $ XML.elementContent subel)
188 | ),
189 | (
190 | s"{vcard-temp}LOCALITY" == XML.elementName subel,
191 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}locality") []
192 | (map XML.NodeContent $ XML.elementContent subel)
193 | ),
194 | (
195 | s"{vcard-temp}REGION" == XML.elementName subel,
196 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}region") []
197 | (map XML.NodeContent $ XML.elementContent subel)
198 | ),
199 | (
200 | s"{vcard-temp}PCODE" == XML.elementName subel,
201 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}code") []
202 | (map XML.NodeContent $ XML.elementContent subel)
203 | ),
204 | (
205 | s"{vcard-temp}CTRY" == XML.elementName subel,
206 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}country") []
207 | (map XML.NodeContent $ XML.elementContent subel)
208 | )
209 | ]
210 | ),
211 | (
212 | s"{vcard-temp}TEL" == XML.elementName el,
213 | let
214 | home = not $ null $ XML.isNamed (s"{vcard-temp}HOME") =<< XML.elementChildren el
215 | work = not $ null $ XML.isNamed (s"{vcard-temp}WORK") =<< XML.elementChildren el
216 | text = not $ null $ XML.isNamed (s"{vcard-temp}TEXT") =<< XML.elementChildren el
217 | voice = not $ null $ XML.isNamed (s"{vcard-temp}VOICE") =<< XML.elementChildren el
218 | fax = not $ null $ XML.isNamed (s"{vcard-temp}FAX") =<< XML.elementChildren el
219 | cell = not $ null $ XML.isNamed (s"{vcard-temp}CELL") =<< XML.elementChildren el
220 | video = not $ null $ XML.isNamed (s"{vcard-temp}VIDEO") =<< XML.elementChildren el
221 | pager = not $ null $ XML.isNamed (s"{vcard-temp}pager") =<< XML.elementChildren el
222 | textphone = not $ null $ XML.isNamed (s"{vcard-temp}TEXTPHONE") =<< XML.elementChildren el
223 | pref = not $ null $ XML.isNamed (s"{vcard-temp}PREF") =<< XML.elementChildren el
224 | in
225 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}tel") [] $
226 | (if home || work || text || voice || fax || cell || video || pager || textphone || pref then
227 | [
228 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}parameters") [] (map XML.NodeElement $ concat [
229 | if home || work || text || voice || fax || cell || video || pager || textphone then
230 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}type") [] [
231 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") [] [
232 | XML.NodeContent $ XML.ContentText $ HT.select (s"unknown") [
233 | (home, s"home"),
234 | (work, s"work"),
235 | (text, s"text"),
236 | (voice, s"voice"),
237 | (fax, s"fax"),
238 | (cell, s"cell"),
239 | (video, s"video"),
240 | (pager, s"pager"),
241 | (textphone, s"texphone")
242 | ]]]]
243 | else [],
244 | if pref then
245 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}pref") [] [
246 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}integer") [] [
247 | XML.NodeContent $ XML.ContentText $ s"1"]]]
248 | else []
249 | ])
250 | ]
251 | else []) ++
252 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") [] $
253 | XML.NodeContent (XML.ContentText $ s"tel:") :
254 | map XML.NodeContent (XML.elementContent =<< XML.isNamed (s"{vcard-temp}NUMBER") =<< XML.elementChildren el)]
255 | ),
256 | (
257 | s"{vcard-temp}EMAIL" == XML.elementName el,
258 | let
259 | home = not $ null $ XML.isNamed (s"{vcard-temp}HOME") =<< XML.elementChildren el
260 | work = not $ null $ XML.isNamed (s"{vcard-temp}WORK") =<< XML.elementChildren el
261 | pref = not $ null $ XML.isNamed (s"{vcard-temp}PREF") =<< XML.elementChildren el
262 | in
263 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}email") [] $
264 | (if home || work || pref then
265 | [
266 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}parameters") [] (map XML.NodeElement $ concat [
267 | if home || work then
268 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}type") [] [
269 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") [] [
270 | XML.NodeContent $ XML.ContentText $ HT.select (s"unknown") [
271 | (home, s"home"),
272 | (work, s"work")
273 | ]]]]
274 | else [],
275 | if pref then
276 | [XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}pref") [] [
277 | XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}integer") [] [
278 | XML.NodeContent $ XML.ContentText $ s"1"]]]
279 | else []
280 | ])
281 | ]
282 | else []) ++
283 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") [] $
284 | map XML.NodeContent (XML.elementContent =<< XML.isNamed (s"{vcard-temp}USERID") =<< XML.elementChildren el)]
285 | ),
286 | (
287 | s"{vcard-temp}JABBERID" == XML.elementName el,
288 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}impp") []
289 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") []
290 | (XML.NodeContent (XML.ContentText $ s"xmpp:") : map XML.NodeContent (XML.elementContent el))]
291 | ),
292 | (
293 | s"{vcard-temp}TZ" == XML.elementName el,
294 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}tz") []
295 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
296 | (map XML.NodeContent (XML.elementContent el))]
297 | ),
298 | (
299 | s"{vcard-temp}GEO" == XML.elementName el,
300 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}geo") []
301 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") [] $
302 | (XML.NodeContent (XML.ContentText $ s"geo:") :
303 | map XML.NodeContent (XML.elementContent =<< XML.isNamed (s"{vcard-temp}LAT") =<< XML.elementChildren el)) ++
304 | (XML.NodeContent (XML.ContentText $ s",") :
305 | map XML.NodeContent (XML.elementContent =<< XML.isNamed (s"{vcard-temp}LON") =<< XML.elementChildren el))]
306 | ),
307 | (
308 | s"{vcard-temp}TITLE" == XML.elementName el,
309 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}title") []
310 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
311 | (map XML.NodeContent (XML.elementContent el))]
312 | ),
313 | (
314 | s"{vcard-temp}ROLE" == XML.elementName el,
315 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}role") []
316 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
317 | (map XML.NodeContent (XML.elementContent el))]
318 | ),
319 | (
320 | s"{vcard-temp}LOGO" == XML.elementName el,
321 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}logo") []
322 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") [] $
323 | case (
324 | XML.isNamed (s"{vcard-temp}TYPE") =<< XML.elementChildren el,
325 | XML.isNamed (s"{vcard-temp}EXTVAL") =<< XML.elementChildren el,
326 | XML.isNamed (s"{vcard-temp}BINVAL") =<< XML.elementChildren el
327 | ) of
328 | (_, [extval], _) -> map XML.NodeContent $ XML.elementContent extval
329 | (typ, _, [binval]) -> map XML.NodeContent $
330 | (XML.ContentText (s"data:") : concatMap XML.elementContent typ) ++
331 | (XML.ContentText (s";base64,") : XML.elementContent binval)
332 | _ -> []
333 | ]
334 | ),
335 | (
336 | s"{vcard-temp}ORG" == XML.elementName el,
337 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}org") []
338 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") [] $
339 | map XML.NodeContent (XML.elementContent =<< XML.isNamed (s"{vcard-temp}ORGNAME") =<< XML.elementChildren el)]
340 | ),
341 | (
342 | s"{vcard-temp}CATEGORIES" == XML.elementName el,
343 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}categories") []
344 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
345 | (map XML.NodeContent (XML.elementContent el))]
346 | ),
347 | (
348 | s"{vcard-temp}NOTE" == XML.elementName el,
349 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}note") []
350 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
351 | (map XML.NodeContent (XML.elementContent el))]
352 | ),
353 | (
354 | s"{vcard-temp}PRODID" == XML.elementName el,
355 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}prodid") []
356 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
357 | (map XML.NodeContent (XML.elementContent el))]
358 | ),
359 | (
360 | s"{vcard-temp}REV" == XML.elementName el,
361 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}rev") []
362 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}timestamp") []
363 | (map XML.NodeContent (XML.elementContent el))]
364 | ),
365 | (
366 | s"{vcard-temp}SORT-STRING" == XML.elementName el,
367 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}sort-as") []
368 | (map XML.NodeContent (XML.elementContent el))
369 | ),
370 | (
371 | s"{vcard-temp}SOUND" == XML.elementName el,
372 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}sound") []
373 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") [] $
374 | case (
375 | XML.isNamed (s"{vcard-temp}EXTVAL") =<< XML.elementChildren el,
376 | XML.isNamed (s"{vcard-temp}BINVAL") =<< XML.elementChildren el
377 | ) of
378 | ([extval], _) -> map XML.NodeContent $ XML.elementContent extval
379 | (_, [binval]) -> map XML.NodeContent $
380 | XML.ContentText (s"data:udio/basic;base64,") :
381 | XML.elementContent binval
382 | _ -> []
383 | ]
384 | ),
385 | (
386 | s"{vcard-temp}UID" == XML.elementName el,
387 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uid") []
388 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") []
389 | (map XML.NodeContent (XML.elementContent el))]
390 | ),
391 | (
392 | s"{vcard-temp}URL" == XML.elementName el,
393 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}url") []
394 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}uri") []
395 | (map XML.NodeContent (XML.elementContent el))]
396 | ),
397 | (
398 | s"{vcard-temp}KEY" == XML.elementName el,
399 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}key") []
400 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
401 | (map XML.NodeContent (XML.elementContent el))]
402 | ),
403 | (
404 | s"{vcard-temp}DESC" == XML.elementName el,
405 | XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}note") []
406 | [XML.NodeElement $ XML.Element (s"{urn:ietf:params:xml:ns:vcard-4.0}text") []
407 | (map XML.NodeContent (XML.elementContent el))]
408 | )
409 | ]
410 | parseVCardTempResult _ = Nothing
411 |
412 | --
413 |
--------------------------------------------------------------------------------
/cheogram.cabal:
--------------------------------------------------------------------------------
1 | name: cheogram
2 | version: 0.0.1
3 | cabal-version: >= 1.14
4 | license: OtherLicense
5 | license-file: COPYING
6 | category: Network
7 | copyright: © Stephen Paul Weber
8 | author: Stephen Paul Weber
9 | maintainer: Stephen Paul Weber
10 | stability: experimental
11 | tested-with: GHC == 7.6.3
12 | synopsis: Groupchat for everyone!
13 | homepage: https://git.singpolyma.net/cheogram
14 | bug-reports: mailto:dev@singpolyma.net
15 | build-type: Simple
16 | description:
17 | Bridge between XMPP MUC and SMS.
18 |
19 | extra-source-files:
20 | README
21 |
22 | executable cheogram
23 | main-is: Main.hs
24 | other-modules: ConfigureDirectMessageRoute, Util, RedisURL, IQManager, UniquePrefix, StanzaRec, Adhoc, Config, DB, JidSwitch, VCard4
25 | default-language: Haskell2010
26 | ghc-options: -Wall -Wno-tabs -Wno-orphans -Wno-name-shadowing -O -threaded
27 |
28 | build-depends:
29 | base == 4.*,
30 | basic-prelude,
31 | attoparsec,
32 | base58-bytestring,
33 | base64-bytestring,
34 | bytestring >= 0.10.0.0,
35 | case-insensitive,
36 | containers,
37 | cryptonite,
38 | dhall >= 1.33 && < 1.40,
39 | errors,
40 | hedis,
41 | HostAndPort,
42 | HTTP,
43 | http-types,
44 | http-streams,
45 | hstatsd,
46 | io-streams,
47 | jingle,
48 | magic,
49 | monad-loops,
50 | monads-tf,
51 | mime-types >= 0.1,
52 | network,
53 | network-uri,
54 | network-protocol-xmpp >= 0.4.9,
55 | pcre-light,
56 | random,
57 | random-shuffle,
58 | SHA,
59 | stm >= 2.4,
60 | stm-delay,
61 | text,
62 | time,
63 | uuid,
64 | unexceptionalio,
65 | unexceptionalio-trans,
66 | utility-ht,
67 | xml-types,
68 | mmorph
69 |
70 | source-repository head
71 | type: git
72 | location: https://git.singpolyma.net/cheogram
73 |
--------------------------------------------------------------------------------
/guix.scm:
--------------------------------------------------------------------------------
1 | (use-modules
2 | ((guix licenses) #:prefix license:)
3 | (guix packages)
4 | (guix download)
5 | (guix git-download)
6 | (guix build-system gnu)
7 | (guix build-system haskell)
8 | (gnu packages pkg-config)
9 | (gnu packages compression)
10 | (gnu packages tls)
11 | (gnu packages gsasl)
12 | (gnu packages gnupg)
13 | (gnu packages kerberos)
14 | (gnu packages libidn)
15 | (gnu packages xml)
16 | (gnu packages dhall)
17 | (gnu packages haskell)
18 | (gnu packages haskell-check)
19 | (gnu packages haskell-crypto)
20 | (gnu packages haskell-web)
21 | (gnu packages haskell-xyz)
22 | (ice-9 rdelim)
23 | (ice-9 popen)
24 | )
25 |
26 | (define-public ghc-unexceptionalio-trans
27 | (package
28 | (name "ghc-unexceptionalio-trans")
29 | (version "0.5.1")
30 | (source
31 | (origin
32 | (method url-fetch)
33 | (uri (hackage-uri "unexceptionalio-trans" version))
34 | (sha256
35 | (base32 "100sfbrpaldz37a176qpfkk1nx5acyh8pchjmb8g5vhzbhyrqniz"))))
36 | (build-system haskell-build-system)
37 | (inputs (list ghc-unexceptionalio))
38 | (arguments
39 | `(#:cabal-revision
40 | ("1" "0f15n8hqqczwjrcqxwjp2mrd9iycv53sylv407c95nb6d4hw93ci")))
41 | (home-page "https://github.com/singpolyma/unexceptionalio-trans")
42 | (synopsis "A wrapper around UnexceptionalIO using monad transformers")
43 | (description
44 | "UnexceptionalIO provides a basic type to witness having caught all exceptions you can safely handle. This library builds on that with transformers like ExceptT to provide a more ergonomic tool for many cases. . It is intended that you use qualified imports with this library. . > import UnexceptionalIO.Trans (UIO) > import qualified UnexceptionalIO.Trans as UIO")
45 | (license #f)))
46 |
47 | (define-public ghc-cache
48 | (package
49 | (name "ghc-cache")
50 | (version "0.1.3.0")
51 | (source
52 | (origin
53 | (method url-fetch)
54 | (uri (string-append
55 | "https://hackage.haskell.org/package/cache/cache-"
56 | version
57 | ".tar.gz"))
58 | (sha256
59 | (base32 "0d75257kvjpnv95ja50x5cs77pj8ccfr0nh9q5gzvcps83qdksa2"))))
60 | (build-system haskell-build-system)
61 | (inputs
62 | `(("ghc-clock" ,ghc-clock)
63 | ("ghc-hashable" ,ghc-hashable)
64 | ("ghc-unordered-containers" ,ghc-unordered-containers)))
65 | (native-inputs
66 | `(("ghc-hspec" ,ghc-hspec)
67 | ("hspec-discover" ,hspec-discover)))
68 | (home-page "https://github.com/hverr/haskell-cache#readme")
69 | (synopsis "An in-memory key/value store with expiration support")
70 | (description
71 | "An in-memory key/value store with expiration support, similar to patrickmn/go-cache for Go. . The cache is a shared mutable HashMap implemented using STM and with support for expiration times.")
72 | (license license:bsd-3)))
73 |
74 | (define-public ghc-scanner
75 | (package
76 | (name "ghc-scanner")
77 | (version "0.3.1")
78 | (source
79 | (origin
80 | (method url-fetch)
81 | (uri (string-append
82 | "https://hackage.haskell.org/package/scanner/scanner-"
83 | version
84 | ".tar.gz"))
85 | (sha256
86 | (base32 "1mhqh94qra08zidqfsq0gxi83cgflqldnk9rr53haynbgmd5y82k"))))
87 | (build-system haskell-build-system)
88 | (inputs `(("ghc-fail" ,ghc-fail)))
89 | (native-inputs
90 | `(("ghc-hspec" ,ghc-hspec)
91 | ("pkg-config" ,pkg-config)))
92 | (home-page "https://github.com/Yuras/scanner")
93 | (synopsis
94 | "Fast non-backtracking incremental combinator parsing for bytestrings")
95 | (description
96 | "Parser combinator library designed to be fast. It doesn't support backtracking.")
97 | (license license:bsd-3)))
98 |
99 | (define-public ghc-hedis
100 | (package
101 | (name "ghc-hedis")
102 | (version "0.12.11")
103 | (source
104 | (origin
105 | (method url-fetch)
106 | (uri (string-append
107 | "https://hackage.haskell.org/package/hedis/hedis-"
108 | version
109 | ".tar.gz"))
110 | (sha256
111 | (base32 "1n83zwg011n9w2v1zz4mwpms9jh3c8mk700zya4as1jg83748xww"))))
112 | (build-system haskell-build-system)
113 | (arguments
114 | `(#:phases
115 | (modify-phases %standard-phases
116 | (replace 'check
117 | (lambda _
118 | ; The main tests require redis-server running, but not doctest
119 | (invoke "runhaskell" "Setup.hs" "test" "doctest")
120 | #t)))))
121 | (inputs
122 | `(("ghc-scanner" ,ghc-scanner)
123 | ("ghc-async" ,ghc-async)
124 | ("ghc-bytestring-lexing" ,ghc-bytestring-lexing)
125 | ("ghc-unordered-containers" ,ghc-unordered-containers)
126 | ("ghc-network" ,ghc-network)
127 | ("ghc-resource-pool" ,ghc-resource-pool)
128 | ("ghc-tls" ,ghc-tls)
129 | ("ghc-vector" ,ghc-vector)
130 | ("ghc-http" ,ghc-http)
131 | ("ghc-errors" ,ghc-errors)
132 | ("ghc-network-uri" ,ghc-network-uri)))
133 | (native-inputs
134 | `(("ghc-hunit" ,ghc-hunit)
135 | ("ghc-test-framework" ,ghc-test-framework)
136 | ("ghc-test-framework-hunit" ,ghc-test-framework-hunit)
137 | ("ghc-doctest" ,ghc-doctest)))
138 | (home-page "https://github.com/informatikr/hedis")
139 | (synopsis
140 | "Client library for the Redis datastore: supports full command set, pipelining.")
141 | (description
142 | "Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. This library is a Haskell client for the Redis datastore. Compared to other Haskell client libraries it has some advantages: . [Compatibility with Latest Stable Redis:] Hedis is intended to be used with the latest stable version of Redis (currently 5.0). Most redis commands () are available as haskell functions, although MONITOR and SYNC are intentionally omitted. Additionally, a low-level API is exposed that makes it easy for the library user to implement further commands, such as new commands from an experimental Redis version. . [Automatic Optimal Pipelining:] Commands are pipelined () as much as possible without any work by the user. See for a technical explanation of automatic optimal pipelining. . [Enforced Pub\\/Sub semantics:] When subscribed to the Redis Pub\\/Sub server (), clients are not allowed to issue commands other than subscribing to or unsubscribing from channels. This library uses the type system to enforce the correct behavior. . [Connect via TCP or Unix Domain Socket:] TCP sockets are the default way to connect to a Redis server. For connections to a server on the same machine, Unix domain sockets offer higher performance than the standard TCP connection. . For detailed documentation, see the \"Database.Redis\" module. .")
143 | (license license:bsd-3)))
144 |
145 | (define-public ghc-libxml-sax
146 | (package
147 | (name "ghc-libxml-sax")
148 | (version "0.7.5")
149 | (source
150 | (origin
151 | (method url-fetch)
152 | (uri (string-append
153 | "https://hackage.haskell.org/package/libxml-sax/libxml-sax-"
154 | version
155 | ".tar.gz"))
156 | (sha256
157 | (base32 "0lbdq6lmiyrnzk6gkx09vvp928wj8qnqnqfzy14mfv0drj21f54r"))))
158 | (build-system haskell-build-system)
159 | (inputs
160 | `(("ghc-xml-types" ,ghc-xml-types)
161 | ("libxml2" ,libxml2)))
162 | (native-inputs `(("pkg-config" ,pkg-config)))
163 | (home-page "https://john-millikin.com/software/haskell-libxml/")
164 | (synopsis "Bindings for the libXML2 SAX interface")
165 | (description "")
166 | (license license:expat)))
167 |
168 | (define-public gsasl-1
169 | (package
170 | (name "gsasl")
171 | (version "1.10.0")
172 | (source (origin
173 | (method url-fetch)
174 | (uri (string-append "mirror://gnu/gsasl/gsasl-" version
175 | ".tar.gz"))
176 | (sha256
177 | (base32
178 | "1lv8fp01aq4jjia9g4vkx90zacl8rgmjhfi6f1wdwnh9ws7bvg45"))))
179 | (build-system gnu-build-system)
180 | (arguments
181 | `(#:configure-flags '("--with-gssapi-impl=mit"
182 | "--disable-static")))
183 | (inputs
184 | (list libgcrypt libidn libntlm mit-krb5 zlib))
185 | (native-inputs
186 | (list ;; Needed for cross compiling.
187 | libgcrypt))
188 | (propagated-inputs
189 | ;; Propagate GnuTLS because libgnutls.la reads `-lnettle', and Nettle is a
190 | ;; propagated input of GnuTLS.
191 | (list gnutls))
192 | (synopsis "Simple Authentication and Security Layer library")
193 | (description
194 | "GNU SASL is an implementation of the Simple Authentication and
195 | Security Layer framework. On network servers such as IMAP or SMTP servers,
196 | SASL is used to handle client/server authentication. This package contains
197 | both a library and a command-line tool to access the library.")
198 | (license license:gpl3+)
199 | (home-page "https://www.gnu.org/software/gsasl/")))
200 |
201 | (define-public ghc-gsasl
202 | (package
203 | (name "ghc-gsasl")
204 | (version "0.3.7")
205 | (source
206 | (origin
207 | (method url-fetch)
208 | (uri (string-append
209 | "https://hackage.haskell.org/package/gsasl/gsasl-"
210 | version
211 | ".tar.gz"))
212 | (sha256
213 | (base32 "11i12r9s30jrq8hkgqagf2fd129r6ya607s9ibw549ablsxgr507"))))
214 | (build-system haskell-build-system)
215 | (arguments
216 | `(#:cabal-revision
217 | ("1" "1c806a82qd1hkxxfh1mwk0i062bz6fkaap5ys3n4x9n6wjv7ilin")))
218 | (inputs
219 | `(("ghc-monad-loops" ,ghc-monad-loops)
220 | ("gsasl" ,gsasl-1)))
221 | (native-inputs `(("pkg-config" ,pkg-config)))
222 | (home-page "https://git.sr.ht/~singpolyma/gsasl-haskell")
223 | (synopsis "Bindings for GNU libgsasl")
224 | (description "")
225 | (license license:gpl3)))
226 |
227 | (define-public ghc-gnutls
228 | (package
229 | (name "ghc-gnutls")
230 | (version "0.2")
231 | (source
232 | (origin
233 | (method url-fetch)
234 | (uri (string-append
235 | "https://hackage.haskell.org/package/gnutls/gnutls-"
236 | version
237 | ".tar.gz"))
238 | (sha256
239 | (base32 "1c5pm0d80wpgh2bkcgbvmc72agf89h8ghfnrn1m1x3fljbgzvrn0"))))
240 | (build-system haskell-build-system)
241 | (inputs
242 | `(("ghc-monads-tf" ,ghc-monads-tf)
243 | ("gnutls" ,gnutls)))
244 | (native-inputs `(("pkg-config" ,pkg-config)))
245 | (home-page "https://john-millikin.com/software/haskell-gnutls/")
246 | (synopsis "Bindings for GNU libgnutls")
247 | (description
248 | "You almost certainly don't want to depend on this release. . This is a pre-alpha, almost useless release; its only purpose is to enable TLS support in some of my other libraries. More complete bindings for GNU TLS will be released at a later date.")
249 | (license license:gpl3)))
250 |
251 | (define-public ghc-gnuidn
252 | (package
253 | (name "ghc-gnuidn")
254 | (version "0.2.2")
255 | (source
256 | (origin
257 | (method url-fetch)
258 | (uri (string-append
259 | "https://hackage.haskell.org/package/gnuidn/gnuidn-"
260 | version
261 | ".tar.gz"))
262 | (sha256
263 | (base32 "0vxrcp9xz5gsvx60k12991zn5c9nk3fgg0yw7dixbsjcfqgnnd31"))))
264 | (build-system haskell-build-system)
265 | (arguments
266 | `(#:phases
267 | (modify-phases %standard-phases
268 | (add-after 'unpack 'less-strict-dependencies
269 | (lambda _
270 | (substitute* "gnuidn.cabal"
271 | (("chell >= 0.4 && < 0.5") "chell <0.6"))
272 | #t)))))
273 | (inputs `(("libidn" ,libidn)))
274 | (native-inputs
275 | `(("ghc-chell" ,ghc-chell)
276 | ("ghc-c2hs" ,ghc-c2hs)
277 | ("ghc-chell-quickcheck" ,ghc-chell-quickcheck)
278 | ("ghc-quickcheck" ,ghc-quickcheck)
279 | ("pkg-config" ,pkg-config)))
280 | (home-page "https://john-millikin.com/software/haskell-gnuidn/")
281 | (synopsis "Bindings for GNU IDN")
282 | (description "")
283 | (license license:gpl3)))
284 |
285 | (define-public ghc-network-simple
286 | (package
287 | (name "ghc-network-simple")
288 | (version "0.4.5")
289 | (source
290 | (origin
291 | (method url-fetch)
292 | (uri (hackage-uri "network-simple" version))
293 | (sha256
294 | (base32 "17hpgcwrsx2h8lrb2wwzy0anp33mn80dnwcgnqmb8prajwjvz807"))))
295 | (build-system haskell-build-system)
296 | (inputs (list ghc-network ghc-network-bsd ghc-safe-exceptions ghc-socks))
297 | (home-page "https://github.com/k0001/network-simple")
298 | (synopsis "Simple network sockets usage patterns.")
299 | (description
300 | "This module exports functions that abstract simple network socket usage patterns. . See the @changelog.md@ file in the source distribution to learn about any important changes between versions.")
301 | (license license:bsd-3)))
302 |
303 | (define-public ghc-base58-bytestring
304 | (package
305 | (name "ghc-base58-bytestring")
306 | (version "0.1.0")
307 | (source
308 | (origin
309 | (method url-fetch)
310 | (uri (hackage-uri "base58-bytestring" version))
311 | (sha256
312 | (base32 "1ls05nzswjr6aw0wwk3q7cpv1hf0lw7vk16a5khm6l21yfcgbny2"))))
313 | (build-system haskell-build-system)
314 | (native-inputs
315 | (list ghc-quickcheck-assertions
316 | ghc-quickcheck-instances
317 | ghc-tasty
318 | ghc-tasty-quickcheck))
319 | (home-page "https://bitbucket.org/s9gf4ult/base58-bytestring")
320 | (synopsis "Implementation of BASE58 transcoding for ByteStrings")
321 | (description
322 | "Implementation of BASE58 transcoding copy-pasted from haskoin package")
323 | (license license:public-domain)))
324 |
325 | (define-public ghc-network-protocol-xmpp
326 | (package
327 | (name "ghc-network-protocol-xmpp")
328 | (version "0.4.10")
329 | (source
330 | (origin
331 | (method url-fetch)
332 | (uri (string-append
333 | "https://hackage.haskell.org/package/network-protocol-xmpp/network-protocol-xmpp-"
334 | version
335 | ".tar.gz"))
336 | (sha256
337 | (base32 "03xlw8337lzwp7f5jvbvgirf546pfmfsfjvnik08qjjy1rfn5jji"))))
338 | (build-system haskell-build-system)
339 | (inputs
340 | `(("ghc-gnuidn" ,ghc-gnuidn)
341 | ("ghc-gnutls" ,ghc-gnutls)
342 | ("ghc-gsasl" ,ghc-gsasl)
343 | ("ghc-libxml-sax" ,ghc-libxml-sax)
344 | ("ghc-monads-tf" ,ghc-monads-tf)
345 | ("ghc-network" ,ghc-network)
346 | ("ghc-network-simple" ,ghc-network-simple)
347 | ("ghc-xml-types" ,ghc-xml-types)))
348 | (home-page "https://git.sr.ht/~singpolyma/network-protocol-xmpp")
349 | (synopsis "Client library for the XMPP protocol.")
350 | (description "")
351 | (license license:gpl3)))
352 |
353 | (define-public ghc-hstatsd
354 | (package
355 | (name "ghc-hstatsd")
356 | (version "0.1")
357 | (source
358 | (origin
359 | (method url-fetch)
360 | (uri (hackage-uri "hstatsd" version))
361 | (sha256
362 | (base32 "092q52yyb1xdji1y72bdcgvp8by2w1z9j717sl1gmh2p89cpjrs4"))))
363 | (build-system haskell-build-system)
364 | (arguments
365 | `(#:phases
366 | (modify-phases %standard-phases
367 | (add-after 'unpack 'fix-for-network-3
368 | (lambda _
369 | (substitute* "src/Network/StatsD.hs"
370 | (("sClose") "close"))
371 | #t)))))
372 | (inputs (list ghc-network))
373 | (home-page "https://github.com/mokus0/hstatsd")
374 | (synopsis "Quick and dirty statsd interface")
375 | (description "Quick and dirty statsd interface")
376 | (license license:public-domain)))
377 |
378 | (define-public ghc-random-shuffle
379 | (package
380 | (name "ghc-random-shuffle")
381 | (version "0.0.4")
382 | (source
383 | (origin
384 | (method url-fetch)
385 | (uri (hackage-uri "random-shuffle" version))
386 | (sha256
387 | (base32 "0586bnlh0g2isc44jbjvafkcl4yw6lp1db8x6vr0pza0y08l8w2j"))))
388 | (build-system haskell-build-system)
389 | (inputs (list ghc-random ghc-monadrandom))
390 | (home-page "http://hackage.haskell.org/package/random-shuffle")
391 | (synopsis "Random shuffle implementation.")
392 | (description
393 | "Random shuffle implementation, on immutable lists. Based on `perfect shuffle' implementation by Oleg Kiselyov, available on http://okmij.org/ftp/Haskell/perfect-shuffle.txt")
394 | (license license:bsd-3)))
395 |
396 | (define-public ghc-stm-delay
397 | (package
398 | (name "ghc-stm-delay")
399 | (version "0.1.1.1")
400 | (source
401 | (origin
402 | (method url-fetch)
403 | (uri (hackage-uri "stm-delay" version))
404 | (sha256
405 | (base32 "0cla21v89gcvmr1iwzibq13v1yq02xg4h6k9l6kcprj7mhd5hcmi"))))
406 | (build-system haskell-build-system)
407 | (home-page "https://github.com/joeyadams/haskell-stm-delay")
408 | (synopsis "Updatable one-shot timer polled with STM")
409 | (description
410 | "This library lets you create a one-shot timer, poll it using STM, and update it to ring at a different time than initially specified. . It uses GHC event manager timeouts when available (GHC 7.2+, @-threaded@, non-Windows OS), yielding performance similar to @threadDelay@ and @registerDelay@. Otherwise, it falls back to forked threads and @threadDelay@. . [0.1.1] Add tryWaitDelayIO, improve performance for certain cases of @newDelay@ and @updateDelay@, and improve example.")
411 | (license license:bsd-3)))
412 |
413 | (define-public ghc-hostandport
414 | (package
415 | (name "ghc-hostandport")
416 | (version "0.2.0")
417 | (source
418 | (origin
419 | (method url-fetch)
420 | (uri (hackage-uri "HostAndPort" version))
421 | (sha256
422 | (base32 "1rjv6c7j6fdy6gnn1zr5jnfmiqiamsmjfw9h3bx119giw3sjb9hm"))))
423 | (build-system haskell-build-system)
424 | (native-inputs
425 | (list ghc-hspec ghc-doctest))
426 | (home-page "https://github.com/bacher09/hostandport")
427 | (synopsis "Parser for host and port pairs like localhost:22")
428 | (description
429 | "Simple parser for parsing host and port pairs. Host can be either ipv4, ipv6 or domain name and port are optional. . IPv6 address should be surrounded by square brackets. . Examples: . * localhost . * localhost:8080 . * 127.0.0.1 . * 127.0.0.1:8080 . * [::1] . * [::1]:8080")
430 | (license license:expat)))
431 |
432 | (define-public ghc-binary-varint
433 | (package
434 | (name "ghc-binary-varint")
435 | (version "0.1.0.0")
436 | (source
437 | (origin
438 | (method url-fetch)
439 | (uri (hackage-uri "binary-varint" version))
440 | (sha256
441 | (base32 "1i183ab4bbq3yarijnb2pwgbi9k1w1nc0fs6ph8d8xnysj6ws8l8"))))
442 | (build-system haskell-build-system)
443 | (home-page "https://github.com/oscoin/ipfs")
444 | (synopsis "VarInt encoding/decoding via Data.Binary")
445 | (description "")
446 | (license license:bsd-3)))
447 |
448 | (define-public ghc-multihash-cryptonite
449 | (package
450 | (name "ghc-multihash-cryptonite")
451 | (version "0.1.0.0")
452 | (source
453 | (origin
454 | (method url-fetch)
455 | (uri (hackage-uri "multihash-cryptonite" version))
456 | (sha256
457 | (base32 "0gl13kjqz14lnwz7x162fad3j99qs1xa3zabpr30q53pkzk8adsi"))))
458 | (build-system haskell-build-system)
459 | (inputs (list ghc-binary-varint ghc-cryptonite ghc-hashable ghc-memory))
460 | (native-inputs (list ghc-hedgehog ghc-doctest ghc-cabal-doctest))
461 | (home-page "https://github.com/oscoin/ipfs")
462 | (synopsis
463 | "Self-identifying hashes, implementation of ")
464 | (description "")
465 | (license license:bsd-3)))
466 |
467 | (define-public ghc-cpu
468 | (package
469 | (name "ghc-cpu")
470 | (version "0.1.2")
471 | (source
472 | (origin
473 | (method url-fetch)
474 | (uri (hackage-uri "cpu" version))
475 | (sha256
476 | (base32 "0x19mlanmkg96h6h1i04w2i631z84y4rbk22ki4zhgsajysgw9sn"))))
477 | (build-system haskell-build-system)
478 | (home-page "http://github.com/vincenthz/hs-cpu")
479 | (synopsis "Cpu information and properties helpers.")
480 | (description
481 | "Lowlevel cpu routines to get basic properties of the cpu platform, like endianness and architecture.")
482 | (license license:bsd-3)))
483 |
484 | (define-public ghc-base32-z-bytestring
485 | (package
486 | (name "ghc-base32-z-bytestring")
487 | (version "1.0.0.0")
488 | (source
489 | (origin
490 | (method url-fetch)
491 | (uri (hackage-uri "base32-z-bytestring" version))
492 | (sha256
493 | (base32 "1r0235a2qqnavsm7jl807m555yd2k2vi2kfacw878v83zdr5qyix"))))
494 | (build-system haskell-build-system)
495 | (arguments
496 | `(#:phases
497 | (modify-phases %standard-phases
498 | (add-after 'unpack 'fix-internal-reference
499 | (lambda _
500 | (substitute* "base32-z-bytestring.cabal"
501 | (("z-base32-bytestring") "base32-z-bytestring"))
502 | #t)))))
503 | (inputs (list ghc-cpu))
504 | (native-inputs
505 | (list ghc-hedgehog
506 | ghc-tasty
507 | ghc-tasty-fail-fast
508 | ghc-tasty-hedgehog
509 | ghc-tasty-hspec))
510 | (home-page "https://github.com/oscoin/z-base32-bytestring")
511 | (synopsis "Fast z-base32 and z-base32hex codec for ByteStrings")
512 | (description
513 | "base32 and base32hex codec according to RFC4648 , extended to support z-base32 encoding according to . The package API is similar to base64-bytestring.")
514 | (license license:bsd-3)))
515 |
516 | (define-public ghc-formatting
517 | (package
518 | (name "ghc-formatting")
519 | (version "7.1.3")
520 | (source
521 | (origin
522 | (method url-fetch)
523 | (uri (hackage-uri "formatting" version))
524 | (sha256
525 | (base32 "1vrc2i1b6lxx2aq5hysfl3gl6miq2wbhxc384axvgrkqjbibnqc0"))))
526 | (build-system haskell-build-system)
527 | (inputs
528 | (list ghc-clock ghc-old-locale ghc-scientific ghc-double-conversion))
529 | (native-inputs (list ghc-hspec))
530 | (home-page "https://github.com/AJChapman/formatting#readme")
531 | (synopsis
532 | "Combinator-based type-safe formatting (like printf() or FORMAT)")
533 | (description
534 | "Combinator-based type-safe formatting (like printf() or FORMAT), modelled from the HoleyMonoids package. . See the README at for more info.")
535 | (license license:bsd-3)))
536 |
537 | (define-public ghc-tasty-tap
538 | (package
539 | (name "ghc-tasty-tap")
540 | (version "0.1.0")
541 | (source
542 | (origin
543 | (method url-fetch)
544 | (uri (hackage-uri "tasty-tap" version))
545 | (sha256
546 | (base32 "16i7pd0xis1fyqgmsy4mq04y87ny61dh2lddnjijcf1s9jz9b6x8"))))
547 | (build-system haskell-build-system)
548 | (inputs (list ghc-tasty))
549 | (native-inputs (list ghc-tasty-hunit ghc-tasty-golden))
550 | (home-page "https://github.com/michaelxavier/tasty-tap")
551 | (synopsis "TAP (Test Anything Protocol) Version 13 formatter for tasty")
552 | (description "A tasty ingredient to output test results in TAP 13 format.")
553 | (license license:expat)))
554 |
555 | (define-public ghc-tasty-fail-fast
556 | (package
557 | (name "ghc-tasty-fail-fast")
558 | (version "0.0.3")
559 | (source
560 | (origin
561 | (method git-fetch)
562 | (uri (git-reference
563 | (url "https://github.com/MichaelXavier/tasty-fail-fast")
564 | (commit "68d7f182f4d1f7b97a724c26f554e5da27fe9413")))
565 | (file-name (git-file-name name version))
566 | (sha256
567 | (base32 "05x4ly5sfj5fmjsxxrfys20qc6n078vwaxxzlk2l354l7kng5512"))))
568 | (build-system haskell-build-system)
569 | (inputs (list ghc-tasty ghc-tagged))
570 | (native-inputs (list ghc-tasty-hunit ghc-tasty-golden ghc-tasty-tap))
571 | (home-page "http://github.com/MichaelXavier/tasty-fail-fast#readme")
572 | (synopsis
573 | "Adds the ability to fail a tasty test suite on first test failure")
574 | (description
575 | "tasty-fail-fast wraps any ingredient to fail as soon as the first test fails. For example: . @ defaultMainWithIngredients (map failFast defaultIngredients) tests @ . Your test suite will now get a @--fail-fast@ flag.")
576 | (license license:bsd-3)))
577 |
578 | (define-public ghc-multibase
579 | (package
580 | (name "ghc-multibase")
581 | (version "0.1.2")
582 | (source
583 | (origin
584 | (method url-fetch)
585 | (uri (hackage-uri "multibase" version))
586 | (sha256
587 | (base32 "036caj0dzhzp065dhy05flz2j5qml5pirs1y95np4hf2xv9jk32h"))))
588 | (build-system haskell-build-system)
589 | (inputs
590 | (list ghc-aeson
591 | ghc-base16-bytestring
592 | ghc-base32-z-bytestring
593 | ghc-base58-bytestring
594 | ghc-base64-bytestring
595 | ghc-formatting
596 | ghc-hashable
597 | ghc-sandi
598 | ghc-serialise
599 | ghc-tagged))
600 | (native-inputs (list ghc-doctest ghc-quickcheck ghc-cabal-doctest))
601 | (home-page "https://github.com/oscoin/ipfs")
602 | (synopsis
603 | "Self-identifying base encodings, implementation of ")
604 | (description "")
605 | (license license:bsd-3)))
606 |
607 | (define-public ghc-ipld-cid
608 | (package
609 | (name "ghc-ipld-cid")
610 | (version "0.1.0.0")
611 | (source
612 | (origin
613 | (method url-fetch)
614 | (uri (hackage-uri "ipld-cid" version))
615 | (sha256
616 | (base32 "1y08j0ibcrpfcm0zv1h17zdgbl3hm3sjvm0w9bk1lzdipd6p6cwj"))))
617 | (build-system haskell-build-system)
618 | (inputs
619 | (list ghc-binary-varint
620 | ghc-cryptonite
621 | ghc-hashable
622 | ghc-multibase
623 | ghc-multihash-cryptonite))
624 | (native-inputs (list ghc-hedgehog))
625 | (home-page "https://github.com/oscoin/ipfs")
626 | (synopsis "IPLD Content-IDentifiers ")
627 | (description "")
628 | (license license:bsd-3)))
629 |
630 | (define-public ghc-jingle
631 | (package
632 | (name "ghc-jingle")
633 | (version "4c93bbd")
634 | (source
635 | (origin
636 | (method git-fetch)
637 | (uri (git-reference
638 | (recursive? #t)
639 | (url "https://git.singpolyma.net/jingle-xmpp")
640 | (commit version)))
641 | (file-name (git-file-name name version))
642 | (sha256
643 | (base32 "09y3wbskv11dg5vcvgw5zlii0brijr0rd5m1s8r6ws5h53k53n7r"))))
644 | (build-system haskell-build-system)
645 | (inputs
646 | (list
647 | ghc-base64-bytestring
648 | ghc-basic-prelude
649 | ghc-cache
650 | ghc-clock
651 | ghc-cryptonite
652 | ghc-errors
653 | ghc-ipld-cid
654 | ghc-network
655 | ghc-network-protocol-xmpp
656 | ghc-multihash-cryptonite
657 | ghc-socks
658 | ghc-unexceptionalio))
659 | (home-page "https://github.com/bacher09/hostandport")
660 | (synopsis "Parser for host and port pairs like localhost:22")
661 | (description
662 | "Simple parser for parsing host and port pairs. Host can be either ipv4, ipv6 or domain name and port are optional. . IPv6 address should be surrounded by square brackets. . Examples: . * localhost . * localhost:8080 . * 127.0.0.1 . * 127.0.0.1:8080 . * [::1] . * [::1]:8080")
663 | (license license:expat)))
664 |
665 | ;;;;
666 |
667 | (define %source-dir (dirname (current-filename)))
668 | (define %git-dir (string-append %source-dir "/.git"))
669 |
670 | ; double-escaped template of the cheogram sexp
671 | ; This allows us to bake the expression without doing a full eval to a record,
672 | ; so it can be written
673 | (define-public cheogram-template
674 | '(package
675 | (name "cheogram")
676 | (version (read-line (open-pipe* OPEN_READ "git" "--git-dir" %git-dir "describe" "--always" "--dirty")))
677 | (source
678 | `(origin
679 | (method git-fetch)
680 | (uri (git-reference
681 | (recursive? #t)
682 | (url "https://git.singpolyma.net/cheogram")
683 | (commit ,(read-line (open-pipe* OPEN_READ "git" "--git-dir" %git-dir "rev-parse" "HEAD")))))
684 | (file-name (git-file-name name version))
685 | (sha256
686 | (base32
687 | ,(read-line (open-pipe* OPEN_READ "guix" "hash" "-rx" %source-dir))))))
688 | (build-system 'haskell-build-system)
689 | (inputs
690 | '(list
691 | dhall
692 | ghc-attoparsec
693 | ghc-base58-bytestring
694 | ghc-base64-bytestring
695 | ghc-basic-prelude
696 | ghc-cache
697 | ghc-clock
698 | ghc-errors
699 | ghc-hedis
700 | ghc-hostandport
701 | ghc-hstatsd
702 | ghc-http
703 | ghc-http-streams
704 | ghc-http-types
705 | ghc-jingle
706 | ghc-magic
707 | ghc-mmorph
708 | ghc-monad-loops
709 | ghc-monads-tf
710 | ghc-mime-types
711 | ghc-network
712 | ghc-network-protocol-xmpp
713 | ghc-network-uri
714 | ghc-pcre-light
715 | ghc-random-shuffle
716 | ghc-safe
717 | ghc-sha
718 | ghc-stm-delay
719 | ghc-unexceptionalio-trans
720 | ghc-utility-ht
721 | ghc-uuid
722 | ghc-xml-types))
723 | (home-page "https://git.singpolyma.net/cheogram")
724 | (synopsis "")
725 | (description "")
726 | (license 'license:agpl3)))
727 |
728 | ; Baked version of cheogram-template with leaves eval'd
729 | (define-public cheogram-baked
730 | (cons
731 | (car cheogram-template)
732 | (map
733 | (lambda (x) (list (car x) (eval (cadr x) (current-module))))
734 | (cdr cheogram-template))))
735 |
736 | ; Build clean from git the version from a local clone
737 | ; To build whatever is sitting in local use:
738 | ; guix build --with-source=$PWD -f guix.scm
739 |
740 | (eval cheogram-baked (current-module))
741 |
--------------------------------------------------------------------------------
/manifest.scm:
--------------------------------------------------------------------------------
1 | (define cheogram (load "./guix.scm"))
2 |
3 | (concatenate-manifests
4 | (list
5 | (specifications->manifest
6 | '("hlint"))
7 | (package->development-manifest cheogram)))
8 |
--------------------------------------------------------------------------------