2 module Data.Gargantext.Utils.SaveGetHash where
4 import System.FilePath (addExtension, joinPath)
5 import Data.ByteString.Lazy.Internal (ByteString)
6 import Data.List (elem, intersperse, insert)
7 import Data.List.Extra (chunksOf)
8 import Data.Digest.Pure.MD5 (md5)
9 import System.Directory (getDirectoryContents, createDirectory, findFile, createDirectoryIfMissing)
10 import Control.Monad (foldM)
12 import Data.List (splitAt)
13 import Data.ByteString.Lazy.Internal (packChars)
14 import qualified Data.ByteString.Lazy as BL
16 import Codec.Compression.Zlib (compress, decompress)
18 data Config = Config {
30 chunkUrl :: Int -> ByteString -> [[Char]]
31 chunkUrl a url = chunksOf a $ show $ md5 url
33 -- replace it with createDirectoryIfMissing
34 existOrCreate :: [[Char]] -> FilePath -> IO [[Char]]
35 existOrCreate path_ dir = do
36 let path = joinPath path_
37 let returnPath = return $ path_ ++ [dir]
39 is <- elem dir <$> getDirectoryContents path -- ?
44 createDirectory $ path ++ "/" ++ dir
47 doPath :: [[Char]] -> [FilePath] -> IO [[Char]]
48 doPath root path = foldM (\x y -> existOrCreate x y) root path
51 splitAt' :: Int -> Int -> [Char] -> ([Char], [Char], [Char])
52 splitAt' i1 i2 x = (a, b, c) where
53 (a, a') = splitAt i1 x
54 (b, c) = splitAt i2 a'
57 -- ne pas écraser le fichier s'il existe
58 -- spliter l'url proprement
59 saveFile :: ByteString -> String -> IO String
60 saveFile url'' file = do
61 let url' = chunkUrl (chunkSize conf) url''
64 -- add extension according to the filetype
65 let filename = Prelude.foldl addExtension (last url') ["html", "zlib"]
67 doPath [(root conf)] url
69 let path = (root conf) ++ "/" ++ joinPath url ++ "/" ++ filename
71 --case (findFile ["/tmp/sdfs"] "file.hmtl.zib"
74 case (compression conf) of
75 True -> BL.writeFile path (compress $ packChars file)
76 False -> writeFile path file
80 getFile :: FilePath -> IO ByteString
82 case (compression conf) of
83 True -> decompress <$> BL.readFile path
84 False -> packChars <$> Prelude.readFile path
91 -- levensthein distance...