module Matterhorn.State.Links
  ( openLinkTarget
  )
where

import           Prelude ()
import           Matterhorn.Prelude

import           Control.Exception ( SomeException, catch )
import qualified Data.Text as T

import           Network.Mattermost.Exceptions
import           Network.Mattermost.Types

import           Matterhorn.State.Common
import {-# SOURCE #-} Matterhorn.State.Messages ( jumpToPost )
import           Matterhorn.Types
import           Matterhorn.Types.RichText ( unURL )


openLinkTarget :: LinkTarget -> MH ()
openLinkTarget :: LinkTarget -> MH ()
openLinkTarget LinkTarget
target = do
    Session
session <- MH Session
getSession
    case LinkTarget
target of
        LinkURL URL
url -> MH (Either MHError String) -> MH ()
openWithOpener (forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ Text -> String
T.unpack forall a b. (a -> b) -> a -> b
$ URL -> Text
unURL URL
url)
        LinkFileId FileId
fId -> MH (Either MHError String) -> MH ()
openWithOpener (FileId -> Session -> MH (Either MHError String)
fetchAttachment FileId
fId Session
session)
        LinkPermalink TeamURLName
_ PostId
pId -> PostId -> MH ()
jumpToPost PostId
pId

fetchAttachment :: FileId -> Session -> MH (Either MHError String)
fetchAttachment :: FileId -> Session -> MH (Either MHError String)
fetchAttachment FileId
fId Session
session =
    forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ (forall a b. b -> Either a b
Right forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FileId -> Session -> IO String
fetchFile FileId
fId Session
session)
        forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(MattermostError
e::MattermostError) -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ MattermostError -> MHError
ServerError MattermostError
e)
        forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
e::SomeException) -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ Text -> MHError
GenericError forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show SomeException
e)