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
53 field' :: Parser (ByteString, [ByteString])
55 f <- "\n" *> take 2 <* " "
56 a <- takeTill isEndOfLine
58 let as' = case DL.length as > 0 of
61 return (f, [a] ++ as')
63 wosFields' :: Parser [(ByteString, [ByteString])]
64 wosFields' = many field'
66 wosFields :: Parser (Maybe [ByteString])
71 -- d <- field "DI" -- DOI
76 return $ DL.lookup "UT" ws
77 -- return $ HyperdataDocument
85 wosLines :: Parser [ByteString]
88 line :: Parser ByteString
89 line = "\n " *> takeTill isEndOfLine
91 runParser :: ParserType -> ByteString -> Either String [Maybe [WosDoc]]
92 runParser p x = parseOnly parser x
96 _ -> error "Not implemented yet"
98 -- isTokenChar :: Word8 -> Bool
99 -- isTokenChar = inClass "!#$%&'()*+./0-9:<=>?@a-zA-Z[]^_`{|}~-\n"
102 zipFiles :: FilePath -> IO [ByteString]
104 path <- resolveFile' fp
105 entries <- withArchive path (DM.keys <$> getEntries)
106 bs <- mapConcurrently (\s -> withArchive path (getEntry s)) entries
110 parseFile :: ParserType -> ByteString -> IO Int
111 parseFile p x = case runParser p x of
113 Right r -> pure $ length r
115 parseWos :: FilePath -> IO [Int]
116 parseWos fp = join $ mapConcurrently (parseFile WOS) <$> zipFiles fp