]> gitweb @ CieloNegro.org - Lucu.git/blob - Network/HTTP/Lucu/MIMEType/Guess.hs
5a10bb60bd7e16ee6ae008534c8c5cc914568cb5
[Lucu.git] / Network / HTTP / Lucu / MIMEType / Guess.hs
1 {-# LANGUAGE
2     UnboxedTuples
3   , UnicodeSyntax
4   #-}
5 -- |MIME Type guessing by a file extension. This is a poor man's way
6 -- of guessing MIME Types. It is simple and fast.
7 --
8 -- In general you don't have to use this module directly.
9 module Network.HTTP.Lucu.MIMEType.Guess
10     ( ExtMap
11     , guessTypeByFileName
12
13     , parseExtMapFile
14     , serializeExtMap
15     )
16     where
17 import qualified Data.ByteString.Lazy.Char8 as B
18 import qualified Data.Map as M
19 import Data.Map (Map)
20 import Data.Maybe
21 import Language.Haskell.Pretty
22 import Language.Haskell.Syntax
23 import Network.HTTP.Lucu.MIMEType
24 import Network.HTTP.Lucu.Parser.Http
25 import Network.HTTP.Lucu.Utils
26
27 -- |'Data.Map.Map' from extension to MIME Type.
28 type ExtMap = Map String MIMEType
29
30 -- |Guess the MIME Type of file.
31 guessTypeByFileName :: ExtMap -> FilePath -> Maybe MIMEType
32 guessTypeByFileName extMap fpath
33     = extMap `seq` fpath `seq`
34       let ext = last $ splitBy (== '.') fpath
35       in
36         M.lookup ext extMap >>= return
37
38 -- |Read an Apache mime.types and parse it.
39 parseExtMapFile :: FilePath -> IO ExtMap
40 parseExtMapFile fpath
41     = fpath `seq`
42       do file <- B.readFile fpath
43          case parse (allowEOF extMapP) file of
44            (# Success xs, _ #)
45                -> return $ compile xs
46
47            (# _, input' #)
48                -> let near = B.unpack $ B.take 100 input'
49                   in 
50                     fail ("Failed to parse: " ++ fpath ++ " (near: " ++ near ++ ")")
51
52
53 extMapP :: Parser [ (MIMEType, [String]) ]
54 extMapP = do xs <- many (comment <|> validLine <|> emptyLine)
55              eof
56              return $ catMaybes xs
57     where
58       spc = oneOf " \t"
59
60       comment = many spc >>
61                 char '#' >>
62                 ( many $ satisfy (/= '\n') ) >>
63                 return Nothing
64
65       validLine = do _    <- many spc
66                      mime <- mimeTypeP
67                      _    <- many spc
68                      exts <- sepBy token (many spc)
69                      return $ Just (mime, exts)
70
71       emptyLine = oneOf " \t\n" >> return Nothing
72
73
74 compile :: [ (MIMEType, [String]) ] -> Map String MIMEType
75 compile = M.fromList . foldr (++) [] . map tr
76     where
77       tr :: (MIMEType, [String]) -> [ (String, MIMEType) ]
78       tr (mime, exts) = [ (ext, mime) | ext <- exts ]
79
80 -- |@'serializeExtMap' extMap moduleName variableName@ generates a
81 -- Haskell source code which contains the following things:
82 --
83 -- * A definition of module named @moduleName@.
84 --
85 -- * @variableName :: 'ExtMap'@ whose content is a serialization of
86 --   @extMap@.
87 --
88 -- The module "Network.HTTP.Lucu.MIMEType.DefaultExtensionMap" is
89 -- surely generated using this function.
90 serializeExtMap :: ExtMap -> String -> String -> String
91 serializeExtMap extMap moduleName variableName
92     = let hsModule = HsModule undefined modName (Just exports) imports decls
93           modName  = Module moduleName
94           exports  = [HsEVar (UnQual (HsIdent variableName))]
95           imports  = [ HsImportDecl undefined (Module "Network.HTTP.Lucu.MIMEType") False Nothing (Just (False, []))
96                      , HsImportDecl undefined (Module "Network.HTTP.Lucu.MIMEType.Guess") False Nothing Nothing
97                      , HsImportDecl undefined (Module "Data.Map") True (Just (Module "M")) Nothing
98                      ]
99           decls    = [ HsTypeSig undefined [HsIdent variableName]
100                                      (HsQualType []
101                                       (HsTyCon (UnQual (HsIdent "ExtMap"))))
102                      , HsFunBind [HsMatch undefined (HsIdent variableName)
103                                   [] (HsUnGuardedRhs extMapExp) []]
104                      ]
105           extMapExp = HsApp (HsVar (Qual (Module "M") (HsIdent "fromList"))) (HsList records)
106           comment   =    "{- !!! WARNING !!!\n"
107                       ++ "   This file is automatically generated.\n"
108                       ++ "   DO NOT EDIT BY HAND OR YOU WILL REGRET -}\n\n"
109       in
110         comment ++ prettyPrint hsModule ++ "\n"
111     where
112       records :: [HsExp]
113       records = map record $ M.assocs extMap
114
115       record :: (String, MIMEType) -> HsExp
116       record (ext, mime)
117           = HsTuple [HsLit (HsString ext), mimeToExp mime]
118                     
119       mimeToExp :: MIMEType -> HsExp
120       mimeToExp mt
121           = HsApp (HsVar (UnQual (HsIdent "read"))) (HsLit (HsString $ show mt))