summaryrefslogtreecommitdiff
path: root/dht/Presence/LocalChat.hs
blob: eab54a03ff69dcef8e7d4d230f607788062166bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{-# LANGUAGE CPP #-}
module LocalChat
    ( module Chat
    , module LocalChat
    ) where

import Debug.Trace
import Control.Concurrent.STM
import Control.Monad
import Data.Function
import Data.List
import qualified Data.Map as Map
         ;import Data.Map (Map)
import qualified Data.Text as T
         ;import Data.Text (Text)

#ifdef THREAD_DEBUG
import Control.Concurrent.Lifted.Instrument
#else
import Control.Concurrent.Lifted
import GHC.Conc                  (labelThread)
#endif

import DPut
import DebugTag
import Chat
import MUC

forkUntilSignaled :: String -> STM (IO ()) -> IO (IO ())
forkUntilSignaled lbl action = do
    quitSignal <- newTVarIO False
    t <- forkIO $ do
        fix $ \loop -> join $ atomically
            $ orElse (do readTVar quitSignal >>= check
                         return $ return ())
                     (fmap (>> loop) $ action)
    labelThread t lbl
    return $ atomically (writeTVar quitSignal True)


chatevents rsvar = do
    rs <- readTVar rsvar
    if Map.null rs
      then retry
      else do
        ios <- forM rs $ \r -> do
            ps <- roomPending r
            trace ("roomPending " ++ show ps) $ return ()
            case Map.toList ps of
                (k,t):ts -> do
                    roomCommit r k t
                    return $ do
                        dput XJabber $ "committed " ++ show (length ts,k,t)
                _ -> retry
        return $ foldl1 (>>) ios

forkLocalChat :: MUC -> IO (IO ())
forkLocalChat muc = do
    (chan, rs) <- atomically $ do
        c <- dupTChan (mucChan muc)
        rs <- newTVar Map.empty
        return (c,rs)
    forkUntilSignaled "localchat" $ orElse (chatevents rs) $ do
        e <- readTChan chan
        case e of
            MUCCreate room jid nick r -> modifyTVar' rs $ Map.insert room r
        return $ case e of
            MUCCreate room jid nick _ ->
                dput XJabber $ unwords $ map T.unpack
                    [ "MUCCreate", room, jid, nick ]