summaryrefslogtreecommitdiff
path: root/fig-web/src/Fig/Web/Module/Circle.hs
blob: 99285fdaad814f4e89d489fe760a340ec5aa7655 (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
module Fig.Web.Module.Circle
  ( public
  , publicWebsockets
  , publicBusEvents
  ) where

import Fig.Prelude

import qualified Control.Concurrent.MVar as MVar
import qualified Control.Concurrent.Chan as Chan

import qualified Data.Text as Text
import qualified Data.Set as Set

import qualified Network.WebSockets as WS

import Fig.Utils.SExpr
import Fig.Web.Utils
import Fig.Web.Types

public :: PublicModule
public a = do
  onGet "/api/circle" do
    live <- liftIO $ MVar.readMVar a.globals.currentlyLive
    respondText $ pretty . SExprList @Void $ SExprString <$> Set.toList live

publicWebsockets :: PublicWebsockets
publicWebsockets a =
  [ ( "/api/circle/events", \conn -> do
        c <- Chan.dupChan a.channels.live
        forever do
          ev <- liftIO $ Chan.readChan c
          WS.sendTextData conn $ case ev of
            LiveEventOnline online ->
              pretty $ SExprList @Void
              [ SExprString "online"
              , SExprList $ SExprString <$> Set.toList online
              ]
            LiveEventOffline offline ->
              pretty $ SExprList @Void
              [ SExprString "offline"
              , SExprList $ SExprString <$> Set.toList offline
              ]
    )
  ]

publicBusEvents :: PublicBusEvents
publicBusEvents a =
  [ ("fig monitor twitch stream online", \d -> do
        let dstr = decodeUtf8 d
        let live = Text.words dstr
        let new = Set.fromList live 
        old <- MVar.swapMVar a.globals.currentlyLive new
        let online = Set.difference new old
        let offline = Set.difference old new
        unless (Set.null online && Set.null offline) do
          log $ "Newly online: " <> Text.intercalate " " (Set.toList online) <> ", newly offline: " <> Text.intercalate " " (Set.toList offline)
        unless (Set.null online) . Chan.writeChan a.channels.live $ LiveEventOnline online
        unless (Set.null offline) . Chan.writeChan a.channels.live $ LiveEventOnline offline
    )
  ]