1 {-# LANGUAGE OverloadedStrings #-}
3 module Data.Gargantext.Parsers.WOS where
5 import Prelude hiding (takeWhile, take, concat, readFile)
6 import qualified Data.List as DL
8 import Data.Attoparsec.ByteString
9 import Data.Attoparsec.ByteString.Char8 (anyChar, isEndOfLine)
10 import Data.ByteString (ByteString)
11 import Data.ByteString.Char8 (pack)
13 import Data.Either.Extra(Either(..))
14 import Control.Applicative
16 import Control.Monad (join)
18 -- To be removed just for Tests
20 -- import Codec.Archive.LibZip (withArchive, fileNames, sourceFile, addFile)
21 --import Codec.Archive.LibZip.Types (ZipSource, OpenFlag (CreateFlag))
23 import Control.Concurrent.Async as CCA (mapConcurrently)
25 import Codec.Archive.Zip
26 import Path.IO (resolveFile')
27 -- import qualified Data.ByteString.Lazy as B
28 import Control.Applicative ( (<$>) )
30 -- type Parser a = a -> Text -> [Document]
31 data ParserType = WOS | CSV
33 type WosDoc = ByteString
36 wosParser :: Parser [Maybe [WosDoc]]
38 -- TODO Warning if version /= 1.0
39 -- FIXME anyChar (string ..) /= exact string "\nVR 1.0" ?
40 _ <- manyTill anyChar (string $ pack "\nVR 1.0")
41 ns <- many1 wosNotice <* (string $ pack "\nEF")
44 wosNotice :: Parser (Maybe [WosDoc])
45 wosNotice = startNotice *> wosFields <* endNotice
47 endNotice :: Parser [Char]
48 endNotice = manyTill anyChar (string $ pack "\nER\n")
50 startNotice :: Parser ByteString
51 startNotice = "\nPT " *> takeTill isEndOfLine
54 field' :: Parser (ByteString, [ByteString])
56 f <- "\n" *> take 2 <* " "
57 a <- takeTill isEndOfLine
59 let as' = case DL.length as > 0 of
62 return (f, [a] ++ as')
64 wosFields' :: Parser [(ByteString, [ByteString])]
65 wosFields' = many field'
67 wosFields :: Parser (Maybe [ByteString])
72 -- d <- field "DI" -- DOI
77 return $ DL.lookup "UT" ws
78 -- return $ HyperdataDocument
86 wosLines :: Parser [ByteString]
89 line :: Parser ByteString
90 line = "\n " *> takeTill isEndOfLine
92 runParser :: ParserType -> ByteString -> Either String [Maybe [WosDoc]]
93 runParser p x = parseOnly parser x
97 _ -> error "Not implemented yet"
99 -- isTokenChar :: Word8 -> Bool
100 -- isTokenChar = inClass "!#$%&'()*+./0-9:<=>?@a-zA-Z[]^_`{|}~-\n"
103 zipFiles :: FilePath -> IO [ByteString]
105 path <- resolveFile' fp
106 entries <- withArchive path (DM.keys <$> getEntries)
107 bs <- mapConcurrently (\s -> withArchive path (getEntry s)) entries
111 parseFile :: ParserType -> ByteString -> IO Int
112 parseFile p x = case runParser p x of
114 Right r -> pure $ length r
116 testWos :: FilePath -> IO [Int]
117 testWos fp = join $ mapConcurrently (parseFile WOS) <$> zipFiles fp