wnpClient/app/Main.hs

67 lines
2.0 KiB
Haskell
Raw Normal View History

2021-06-25 16:41:42 +02:00
module Main where
import Control.Exception
2021-06-27 11:36:46 +02:00
import Control.Monad
2021-06-25 16:41:42 +02:00
import qualified Data.ByteString.Char8 as B8
import GHC.IO.Encoding (setLocaleEncoding)
import Lib
2021-06-27 11:36:46 +02:00
import Network.HTTP.Client
import Network.HTTP.Simple
import Network.URI
import System.Directory
import System.FilePath
import System.IO
2021-06-25 16:41:42 +02:00
main :: IO ()
main = do
2021-06-27 11:36:46 +02:00
setLocaleEncoding utf8
createDirectoryIfMissing False =<< workingDir
join $ (writeFile <$> fileName) <*> pure ""
forever $ do
line <- getLine
dispatch line
2021-06-25 16:41:42 +02:00
dispatch :: String -> IO ()
2021-06-27 11:36:46 +02:00
dispatch ('T' : 'I' : 'T' : 'L' : 'E' : ':' : title) = writeToFile title 0
dispatch ('A' : 'R' : 'T' : 'I' : 'S' : 'T' : ':' : artist) = writeToFile artist 1
dispatch ('A' : 'L' : 'B' : 'U' : 'M' : ':' : album) = writeToFile album 2
dispatch ('C' : 'O' : 'V' : 'E' : 'R' : ':' : cover) = handleCover cover
dispatch _ = return ()
2021-06-25 16:41:42 +02:00
2021-06-27 11:36:46 +02:00
writeToFile :: String -> Int -> IO ()
writeToFile text position = do
contents <- lines <$> (readFile =<< fileName)
let newContent = unlines $ take position contents ++ [text] ++ drop (position + 1) contents
bracketOnError
(openTempFile "." "temp")
( \(tempName, tempHandle) -> do
hClose tempHandle
removeFile tempName
)
( \(tempName, tempHandle) -> do
hPutStr tempHandle newContent
hClose tempHandle
renameFile tempName =<< fileName
)
2021-06-25 16:41:42 +02:00
handleCover :: String -> IO ()
2021-06-27 11:36:46 +02:00
handleCover url = do
contents <- lines <$> (readFile =<< fileName)
if length contents > 3 && (contents !! 3) /= url && url /= ""
then do
writeToFile url 3
request <- parseRequest url
let coverFileName = Prelude.last . pathSegments . getUri $ request
join $ B8.writeFile <$> coverName <*> (getResponseBody <$> httpBS request)
else writeToFile url 3
2021-06-25 16:41:42 +02:00
2021-06-27 11:36:46 +02:00
-- B8.writeFile coverName $ getResponseBody resp
2021-06-25 16:41:42 +02:00
2021-06-27 11:36:46 +02:00
fileName :: IO FilePath
fileName = (</> "wnpClient.txt") <$> workingDir
2021-06-25 16:41:42 +02:00
2021-06-27 11:36:46 +02:00
coverName :: IO FilePath
coverName = (</> "cover.jpg") <$> workingDir
2021-06-25 16:41:42 +02:00
2021-06-27 11:36:46 +02:00
workingDir :: IO FilePath
workingDir = (</> ".wnpClient") <$> getHomeDirectory