70 lines
1.7 KiB
Haskell
70 lines
1.7 KiB
Haskell
module Gemini where
|
|
|
|
import Data.ByteString.UTF8
|
|
import Data.Text
|
|
import Network.Mime
|
|
import System.Directory (doesFileExist, doesDirectoryExist)
|
|
import Text.Regex
|
|
import Text.Regex.PCRE
|
|
|
|
|
|
-- check :: FilePath -> IO Bool
|
|
-- check s = do
|
|
-- result <- doesFileExist
|
|
-- if result
|
|
-- then pure True
|
|
-- else pure False
|
|
|
|
-- return components of the url
|
|
-- gemini:// | hostname | uri | ? | query
|
|
parse_url :: String -> [[String]]
|
|
parse_url url =
|
|
(sanitize_uri url) =~ "^(gemini:\\/\\/)([^\\/]*)\\/?([^\\?]*)(\\?)?(.*)?(\\r\\n)$"
|
|
|
|
-- remove any .. in the uri that could escape the location
|
|
sanitize_uri :: String -> String
|
|
sanitize_uri path =
|
|
subRegex (mkRegex "\\.\\.\\/") path ""
|
|
|
|
|
|
-- return a file as a string
|
|
read_file :: String -> IO String
|
|
read_file path = do
|
|
text <- readFile path
|
|
pure text
|
|
|
|
-- read from stdin
|
|
get_request :: IO String
|
|
get_request = do
|
|
stdin <- getContents
|
|
pure stdin
|
|
|
|
data Gemini = MkGemini
|
|
{ domain :: String
|
|
, file :: String
|
|
, query :: String
|
|
, mime :: String
|
|
}
|
|
|
|
get_mime :: String -> String
|
|
get_mime filename
|
|
| (fileNameExtensions (pack filename)) == [(pack "gmi" :: Extension)] = "text/gemini"
|
|
| (fileNameExtensions (pack filename)) == [(pack "gemini" :: Extension)] = "text/gemini"
|
|
| otherwise = (toString (defaultMimeLookup (pack filename)))
|
|
|
|
|
|
parse_to_gemini :: [[String]] -> Gemini
|
|
parse_to_gemini tab =
|
|
MkGemini
|
|
{ domain = tab!!0!!2
|
|
, file = tab!!0!!3
|
|
, query = tab!!0!!5
|
|
, mime = get_mime (tab!!0!!3)
|
|
}
|
|
|
|
get_reply :: String -> Int -> String -> String
|
|
get_reply mime return lang
|
|
| lang /= "" = "20 " ++ mime ++ "; lang=" ++ lang ++ " \r\n"
|
|
| lang == "" = "20 " ++ mime ++ "; \r\n"
|
|
| otherwise = "50\r\n"
|