-
-
Save ga2arch/3d00eb64a7492455753e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} | |
| module Main where | |
| import Data.ByteString (ByteString) | |
| import System.IO.Streams (InputStream, OutputStream) | |
| import Network.Http.Client | |
| import Text.Printf (printf) | |
| import qualified Data.ByteString as B | |
| import qualified Data.ByteString.Char8 as C8 | |
| import qualified System.IO.Streams as S | |
| withProgressBar :: Integer | |
| -> OutputStream ByteString | |
| -> Int -> ByteString -> IO Int | |
| withProgressBar fileSize outS blocksRead block = do | |
| let currentBlocks = blocksRead + B.length block | |
| let percentage = fromIntegral (currentBlocks * 100) / fromIntegral fileSize | |
| printf "%10d [%3.2f%%]\r" currentBlocks (percentage :: Double) | |
| S.write (Just block) outS | |
| return currentBlocks | |
| downloadFile :: URL -> FilePath -> IO () | |
| downloadFile url name = get url $ \response inStream -> | |
| case getStatusCode response of | |
| 200 -> let fileSize = maybe 0 (\fs -> read (C8.unpack fs) :: Integer) | |
| (getHeader response "Content-Length") | |
| in S.withFileAsOutput name $ dl fileSize inStream | |
| code -> error $ "Failed to download " | |
| ++ name | |
| ++ ": http response returned " | |
| ++ show code | |
| where | |
| dl fileSize inStream outS = do | |
| S.foldM (withProgressBar fileSize outS) 0 inStream >> return () | |
| main :: IO () | |
| main = do | |
| let url = "http://audacity.googlecode.com/files/audacity-macosx-ub-2.0.3.dmg" | |
| print $ "Downloading " ++ url | |
| downloadFile (C8.pack url) "audacity.dmg" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment