module Network.SoundCloud.Util (
scSimpleGet,
scRecursiveGet,
scFetch,
scResourceType,
scResolve
) where
import Data.List
import Network.HTTP
import System.IO
import Network.SoundCloud.Const
scGet :: Bool -> String -> IO (Maybe String)
scGet followRedirections url =
do res <- simpleHTTP $ getRequest url
case res of
Left _ -> return Nothing
Right r ->
case rspCode r of
(2,_,_) -> return $ Just $ rspBody r
(3,_,_) ->
case findHeader HdrLocation r of
Nothing -> return Nothing
Just uri ->
if followRedirections
then scRecursiveGet uri
else return $ Just uri
_ -> return Nothing
scSimpleGet :: String -> IO (Maybe String)
scSimpleGet = scGet False
scRecursiveGet :: String -> IO (Maybe String)
scRecursiveGet = scGet True
scFetch :: String -> String -> IO ()
scFetch dUrl out =
do contents <- scRecursiveGet dUrl
case contents of
Nothing -> putStrLn "Could not fetch file contents."
Just c ->
do file <- openBinaryFile out WriteMode
hPutStr file c
hClose file
scResourceType :: String -> String
scResourceType url | tracksURL `isPrefixOf` url = "track"
| usersURL `isPrefixOf` url = "user"
| playlistsURL `isPrefixOf` url = "set"
| groupsURL `isPrefixOf` url = "group"
| commentsURL `isPrefixOf` url = "comment"
| appsURLS `isPrefixOf` url = "app"
| otherwise = "nothing"
scResolve :: String -> IO String
scResolve url =
do dat <- scSimpleGet resolveUrl
case dat of
Nothing -> return ""
Just d -> return d
where
resolveUrl = concat [resolveURL, ".json?url=", url, "&client_id=", clientId]