wnpClient/app/Main.hs

61 lines
1.7 KiB
Haskell
Raw Normal View History

2021-06-25 16:41:42 +02:00
module Main where
import Control.Monad
import Control.Exception
import System.IO
import System.Directory
import Network.HTTP.Client
import Network.HTTP.Simple
import Network.URI
import qualified Data.ByteString.Char8 as B8
import GHC.IO.Encoding (setLocaleEncoding)
import Lib
main :: IO ()
main = do
setLocaleEncoding utf8
forever $ do
line <- getLine
dispatch line
dispatch :: String -> IO ()
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 ()
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)
handleCover :: String -> IO ()
handleCover url= do
contents <- lines <$> readFile filename
when ((contents !! 3 ) /= url && url /= "") $ do
writeToFile (url) 3
request <- parseRequest url
let fileName = Prelude.last . pathSegments . getUri $ request
resp <- httpBS request
B8.writeFile coverName $ getResponseBody resp
filename :: FilePath
filename= "wnpClient.txt"
coverName :: FilePath
coverName="cover.jpg"