2021-08-21 09:45:37 +02:00
|
|
|
{-# LANGUAGE ScopedTypeVariables #-}
|
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
|
|
|
|
|
|
module Web.Announcements
|
2021-08-21 09:49:30 +02:00
|
|
|
(sendAnnouncement,
|
2021-08-21 10:08:41 +02:00
|
|
|
formatLink,
|
|
|
|
AnnouncementHook(..),
|
|
|
|
toAnnouncementHook)
|
2021-08-21 09:45:37 +02:00
|
|
|
where
|
|
|
|
|
|
|
|
import Data.Text
|
|
|
|
import qualified Data.Text.Encoding as DTE
|
|
|
|
import Data.Maybe
|
|
|
|
import Network.HTTP.Req as R
|
|
|
|
import Prelude
|
|
|
|
import Data.Aeson
|
|
|
|
import Data.Default
|
|
|
|
|
2021-08-21 10:48:34 +02:00
|
|
|
data AnnouncementHook = SlackWebHook Text | DiscordWebHook Text
|
2021-08-21 09:45:37 +02:00
|
|
|
|
2021-08-21 10:08:41 +02:00
|
|
|
toAnnouncementHook :: Text -> AnnouncementHook
|
|
|
|
toAnnouncementHook url
|
|
|
|
| ".slack." `isInfixOf` url = SlackWebHook url
|
2021-08-21 10:48:34 +02:00
|
|
|
| "discord.com" `isInfixOf` url = DiscordWebHook url
|
|
|
|
| otherwise = error $ unpack $ "unknown hook type '" <> url <> "'"
|
2021-08-21 10:08:41 +02:00
|
|
|
|
|
|
|
sendAnnouncement :: AnnouncementHook -> Text -> IO ()
|
2021-08-21 10:48:34 +02:00
|
|
|
sendAnnouncement (SlackWebHook hook) message = sendAnnouncementViaJson hook "text" message
|
|
|
|
sendAnnouncement (DiscordWebHook hook) message = sendAnnouncementViaJson hook "content" message
|
|
|
|
|
|
|
|
sendAnnouncementViaJson :: Text -> Text -> Text -> IO ()
|
|
|
|
sendAnnouncementViaJson hook fieldName message = do
|
2021-08-21 09:45:37 +02:00
|
|
|
let (Just (hookUrl, _)) = parseUrlHttps $ DTE.encodeUtf8 hook
|
|
|
|
|
|
|
|
R.runReq def $ do
|
2021-08-21 10:48:34 +02:00
|
|
|
let payload = object [ fieldName .= message ]
|
2021-08-21 09:45:37 +02:00
|
|
|
(_ :: IgnoreResponse) <- R.req R.POST
|
|
|
|
hookUrl
|
|
|
|
(R.ReqBodyJson payload)
|
|
|
|
R.ignoreResponse
|
|
|
|
mempty
|
|
|
|
return ()
|
|
|
|
|
2021-08-21 10:08:41 +02:00
|
|
|
formatLink :: Maybe AnnouncementHook -> Text -> Text -> Text
|
|
|
|
formatLink (Just (SlackWebHook _)) url title = "<" <> url <> "|" <> title <> ">"
|
2021-08-21 10:48:34 +02:00
|
|
|
formatLink (Just (DiscordWebHook _)) url title = formatLinkWithAngleBrackets url title
|
|
|
|
formatLink Nothing url title = formatLinkWithAngleBrackets url title
|
|
|
|
|
|
|
|
formatLinkWithAngleBrackets :: Text -> Text -> Text
|
|
|
|
formatLinkWithAngleBrackets url title = title <> " <" <> url <> ">"
|