aboutsummaryrefslogtreecommitdiff
path: root/src/Main.hs
blob: f9054af2ea0c26256860fc16e51db32abda61b0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
{-# LANGUAGE OverloadedStrings #-}

module Main
  ( main
  ) where

import HTTP

import Control.Applicative ((<$>))

import System.Environment (getArgs, getProgName)
import System.Directory (createDirectoryIfMissing)

import Data.List (intercalate)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Text.Encoding (encodeUtf8)
import Data.Aeson (eitherDecodeStrict)

import CommandLineOptions

import Model.URL
import Model.Json.Search
import Model.Perfume

import PerfumeParser (parsePerfumes)

main :: IO ()
main = do
  options@(Options materials ignoredMaterials) <- (parseOptions . map T.pack) <$> getArgs
  if null materials
    then do
      progName <- T.pack <$> getProgName
      T.putStrLn (T.concat ["Usage: ", progName, " materials… [--without materials…]"])
    else do
      eitherPerfumesSequences <- getPerfumesSequences materials
      eitherIgnoredPerfumesSequences <- getPerfumesSequences ignoredMaterials
      case (eitherPerfumesSequences, eitherIgnoredPerfumesSequences) of
        (Left error, _) ->
          T.putStrLn error
        (_, Left error) ->
          T.putStrLn error
        (Right perfumesSequences, Right ignoredPerfumesSequences) ->
          let commonPerfumes = mergePerfumes perfumesSequences ignoredPerfumesSequences
              outputDirectory = "output"
              outputName = outputDirectory ++ "/" ++ (T.unpack . fileName $ options) ++ ".csv"
          in  do
                createDirectoryIfMissing True outputDirectory
                T.writeFile outputName (csvPerfumes commonPerfumes)
                putStrLn ("Successfully generated " ++ outputName)

getPerfumesSequences :: [Text] -> IO (Either Text [[Perfume]])
getPerfumesSequences = fmap sequence <$> sequence . map getHtmlPerfumes

getHtmlPerfumes :: Text -> IO (Either Text [Perfume])
getHtmlPerfumes material = do
  eitherPage <- getPage (getIdURL material)
  case eitherPage of
    Left error ->
      return . Left $ error
    Right page ->
      case eitherDecodeStrict (encodeUtf8 page) :: Either String [Search] of
        Left error ->
          return . Left . T.pack $ error
        Right searches ->
          case getMaterialSearch searches of
            Nothing ->
              return . Left $ T.concat [ "No material identifier found for ", material ]
            Just (Search identifier _ name) -> do
              T.putStrLn $ T.concat [ "Found material « ", name, " » for ", material, "." ]
              fmap parsePerfumes <$> getPage (getMaterialURL identifier)