made ytdl function way prettier

This commit is contained in:
Rachel Lambda Samuelsson 2021-07-09 18:16:55 +02:00
parent 9caf89817f
commit d7e5230c07

View File

@ -3,7 +3,6 @@ module YTDL (Resolution(..), ytdl) where
import Config
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Class
import Control.Concurrent (forkIO, threadDelay)
import Data.Digest.Pure.MD5
import qualified Data.ByteString.Lazy.UTF8 as BCU
@ -37,8 +36,7 @@ resToArgs (PMAX) = ["-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4", "--merge
resToArgs (Audio) = ["-x", "--audio-format", "mp3"]
ytdl :: String -> Resolution -> ReaderT ViddlConfig IO (Either String FilePath)
ytdl url res = do
cfg <- ask
ytdl url res = ReaderT $ \cfg -> do
let ext = case res of { Audio -> ".mp3"; _ -> ".mp4" }
@ -47,30 +45,30 @@ ytdl url res = do
let dir = concat [dlDir cfg, "/", ident]
let fileName = concat [dir, "/", ident, ext]
processed <- lift $ doesFileExist fileName
processed <- doesFileExist fileName
if processed
then do
lift $ putStrLn $ "Returning existing ident " <> ident
putStrLn $ "Returning existing ident " <> ident
pure (Right fileName)
else do
lift $ putStrLn $ "Processing new ident " <> ident
putStrLn $ "Processing new ident " <> ident
lift $ createDirectoryIfMissing True dir
createDirectoryIfMissing True dir
lift $ print (resToArgs res <> ["-o", fileName, url])
print (resToArgs res <> ["-o", fileName, url])
ytdlProc <- lift $ createProcess (proc "youtube-dl" (resToArgs res <> ["-o", fileName, url]))
ytdlProc <- createProcess (proc "youtube-dl" (resToArgs res <> ["-o", fileName, url]))
case ytdlProc of
(_, _, _, ph) -> do
exitCode <- lift $ waitForProcess ph
exitCode <- waitForProcess ph
case exitCode of
ExitSuccess -> do
exists <- lift $ doesFileExist fileName
exists <- doesFileExist fileName
if exists
then do
-- wait 5 minutes and then delete the directory
_ <- lift $ forkIO $ threadDelay 300000000 >> removeDirectoryRecursive dir
_ <- forkIO $ threadDelay 300000000 >> removeDirectoryRecursive dir
pure (Right fileName)
else do
-- removeDirectoryRecursive dir