Types.purs 18.3 KB
Newer Older
1 2
module Gargantext.Types where

3
import Data.Argonaut (class DecodeJson, class EncodeJson, decodeJson, encodeJson, jsonEmptyObject, (.:), (:=), (~>))
4
import Data.Array as A
5
import Data.Either (Either(..))
6 7 8 9
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Eq (genericEq)
import Data.Generic.Rep.Ord (genericCompare)
import Data.Generic.Rep.Show (genericShow)
10
import Data.Int (toNumber)
11
import Data.Maybe (Maybe(..), maybe, fromMaybe)
12
import Effect.Aff (Aff)
13 14
import Gargantext.Prelude (class Read, read)
import Prelude
15
import Prim.Row (class Union)
James Laver's avatar
James Laver committed
16
import URI.Query (Query)
17

18 19 20
type ID     = Int
type Name   = String
type Reload = Int
21

22
newtype SessionId = SessionId String
23
type NodeID = Int
24 25 26 27 28 29 30 31 32

derive instance genericSessionId :: Generic SessionId _

instance eqSessionId :: Eq SessionId where
  eq = genericEq

instance showSessionId :: Show SessionId where
  show (SessionId s) = s

33
data TermSize = MonoTerm | MultiTerm
34

35 36
data Term = Term String TermList

37
derive instance eqTermSize :: Eq TermSize
38

James Laver's avatar
James Laver committed
39 40 41 42
-- | Converts a data structure to a query string
class ToQuery a where
  toQuery :: a -> Query

43
instance showTermSize :: Show TermSize where
44 45 46
  show MonoTerm  = "MonoTerm"
  show MultiTerm = "MultiTerm"

47 48 49 50 51
instance readTermSize :: Read TermSize where
  read :: String -> Maybe TermSize
  read "MonoTerm"  = Just MonoTerm
  read "MultiTerm" = Just MultiTerm
  read _           = Nothing
52

53 54
termSizes :: Array { desc :: String, mval :: Maybe TermSize }
termSizes = [ { desc: "All types",        mval: Nothing        }
55 56 57 58 59
            , { desc: "One-word terms",   mval: Just MonoTerm  }
            , { desc: "Multi-word terms", mval: Just MultiTerm }
            ]

data TermList = GraphTerm | StopTerm | CandidateTerm
60
-- TODO use generic JSON instance
61 62

derive instance eqTermList :: Eq TermList
63
derive instance ordTermList :: Ord TermList
64

65
instance encodeJsonTermList :: EncodeJson TermList where
66 67 68
  encodeJson GraphTerm     = encodeJson "GraphTerm"
  encodeJson StopTerm      = encodeJson "StopTerm"
  encodeJson CandidateTerm = encodeJson "CandidateTerm"
69

70
instance decodeJsonTermList :: DecodeJson TermList where
71 72 73
  decodeJson json = do
    s <- decodeJson json
    case s of
74 75 76
      "GraphTerm"     -> pure GraphTerm
      "StopTerm"      -> pure StopTerm
      "CandidateTerm" -> pure CandidateTerm
77
      _               -> Left "Unexpected list name"
78 79 80 81 82 83 84 85 86

type ListTypeId = Int

listTypeId :: TermList -> ListTypeId
listTypeId GraphTerm     = 1
listTypeId StopTerm      = 2
listTypeId CandidateTerm = 3

instance showTermList :: Show TermList where
87 88 89
  show GraphTerm     = "GraphTerm"
  show StopTerm      = "StopTerm"
  show CandidateTerm = "CandidateTerm"
90

91 92
-- TODO: Can we replace the show instance above with this?
termListName :: TermList -> String
93
termListName GraphTerm = "Map List"
94 95 96
termListName StopTerm = "Stop List"
termListName CandidateTerm = "Candidate List"

97 98 99 100 101 102
instance readTermList :: Read TermList where
  read :: String -> Maybe TermList
  read "GraphTerm"     = Just GraphTerm
  read "StopTerm"      = Just StopTerm
  read "CandidateTerm" = Just CandidateTerm
  read _               = Nothing
103 104 105

termLists :: Array { desc :: String, mval :: Maybe TermList }
termLists = [ { desc: "All terms",   mval: Nothing      }
106
            , { desc: "Map terms",   mval: Just GraphTerm   }
107 108 109 110
            , { desc: "Stop terms",  mval: Just StopTerm  }
            , { desc: "Candidate terms", mval: Just CandidateTerm }
            ]

111 112 113
-- | Proof that row `r` is a subset of row `s`
class Optional (r :: # Type) (s :: # Type)
instance optionalInstance :: Union r t s => Optional r s
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

showTabType' :: TabType -> String
showTabType' (TabCorpus   t) = show t
showTabType' (TabDocument t) = show t
showTabType' (TabPairing t) = show t

data TabPostQuery = TabPostQuery {
    offset :: Int
  , limit :: Int
  , orderBy :: OrderBy
  , tabType :: TabType
  , query :: String
  }

instance encodeJsonTabPostQuery :: EncodeJson TabPostQuery where
  encodeJson (TabPostQuery post) =
        "view"       := showTabType' post.tabType
     ~> "offset"     := post.offset
     ~> "limit"      := post.limit
     ~> "orderBy"    := show post.orderBy
     ~> "query"      := post.query
     ~> jsonEmptyObject

data NodeType = NodeUser
138
              | Folder | FolderPrivate | FolderShared | FolderPublic
139 140 141
              | Annuaire
              | NodeContact
              | Corpus
142
              | Team
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
              | Url_Document
              | Dashboard
              | Error
              | Graph
              | Phylo
              | Individu
              | Node
              | Nodes
              | Tree
              | NodeList
              | Texts

derive instance eqNodeType :: Eq NodeType

instance showNodeType :: Show NodeType where
  show NodeUser      = "NodeUser"
159 160

  show Folder        = "NodeFolder"
161
  show FolderPrivate = "NodeFolderPrivate"  -- Node Private Worktop
Alexandre Delanoë's avatar
Alexandre Delanoë committed
162
  show FolderShared  = "NodeFolderShared"   -- Node Share Worktop
163
  show FolderPublic  = "NodeFolderPublic"   -- Node Public Worktop
164

165
  show Annuaire      = "NodeAnnuaire"
166 167 168 169 170 171 172 173 174 175 176
  show NodeContact   = "NodeContact"
  show Corpus        = "NodeCorpus"
  show Dashboard     = "NodeDashboard"
  show Url_Document  = "NodeDocument"
  show Error         = "NodeError"
  show Graph         = "NodeGraph"
  show Phylo         = "NodePhylo"
  show Individu      = "NodeIndividu"
  show Node          = "Node"
  show Nodes         = "Nodes"
  show Tree          = "NodeTree"
177
  show Team          = "NodeTeam"
178 179 180
  show NodeList      = "NodeList"
  show Texts         = "NodeTexts"

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
instance readNodeType :: Read NodeType where
  read "NodeUser"          = Just NodeUser
  read "NodeFolder"        = Just Folder
  read "NodeFolderPrivate" = Just FolderPrivate
  read "NodeFolderShared"  = Just FolderShared
  read "NodeFolderPublic"  = Just FolderPublic
  read "NodeAnnuaire"  = Just Annuaire
  read "NodeDashboard" = Just Dashboard
  read "Document"      = Just Url_Document
  read "NodeGraph"     = Just Graph
  read "NodePhylo"     = Just Phylo
  read "Individu"      = Just Individu
  read "Node"          = Just Node
  read "Nodes"         = Just Nodes
  read "NodeCorpus"    = Just Corpus
  read "NodeContact"   = Just NodeContact
  read "Tree"          = Just Tree
  read "NodeTeam"      = Just Team
  read "NodeList"      = Just NodeList
  read "NodeTexts"     = Just Texts
  read "Annuaire"      = Just Annuaire
  read _               = Nothing
203 204 205 206


fldr :: NodeType -> Boolean -> String
fldr NodeUser false = "fa fa-user-circle"
207 208
fldr NodeUser true  = "fa fa-user"
------------------------------------------------------
209 210
fldr Folder  false  = "fa fa-folder"
fldr Folder  true   = "fa fa-folder-open-o"
211
------------------------------------------------------
212
fldr FolderPrivate true  = "fa fa-lock"
213
fldr FolderPrivate false = "fa fa-lock-circle"
214

215
fldr FolderShared  true  = "fa fa-share-alt"
Alexandre Delanoë's avatar
Alexandre Delanoë committed
216
fldr FolderShared  false = "fa fa-share-circle"
217
fldr Team  true   = "fa fa-users"
218
fldr Team  false  = "fa fa-users-closed"
219

220 221
fldr FolderPublic true  = "fa fa-globe-circle"
fldr FolderPublic false = "fa fa-globe"
222
------------------------------------------------------
223

224
fldr Corpus true  = "fa fa-book"
Alexandre Delanoë's avatar
Alexandre Delanoë committed
225
fldr Corpus false = "fa fa-book-circle"
226 227 228 229 230 231 232 233

fldr Phylo _ = "fa fa-code-fork"

fldr Graph _ = "fa fa-hubzilla"
fldr Texts _ = "fa fa-newspaper-o"
fldr Dashboard _ = "fa fa-signal"
fldr NodeList _ = "fa fa-list"

234 235
fldr Annuaire true  = "fa fa-address-card-o"
fldr Annuaire false = "fa fa-address-card"
236 237 238 239

fldr NodeContact true  = "fa fa-address-card-o"
fldr NodeContact false = "fa fa-address-card"

240 241
fldr _        false  = "fa fa-folder-o"
fldr _        true   = "fa fa-folder-open"
242 243 244



245 246 247 248 249 250 251 252 253 254 255 256
{-
------------------------------------------------------------
instance ordNodeType :: Ord NodeType where
  compare n1 n2 = compare (show n1) (show n2)

instance eqNodeType :: Eq NodeType where
  eq n1 n2  = eq (show n1) (show n2)
-}
------------------------------------------------------------
instance decodeJsonNodeType :: DecodeJson NodeType where
  decodeJson json = do
    obj <- decodeJson json
257
    pure $ fromMaybe Error $ read obj
258 259 260 261 262

instance encodeJsonNodeType :: EncodeJson NodeType where
  encodeJson nodeType = encodeJson $ show nodeType

nodeTypePath :: NodeType -> String
263 264
nodeTypePath Folder    = "folder"
nodeTypePath FolderPrivate = "folderPrivate"
265
nodeTypePath FolderShared  = "folderShared"
266
nodeTypePath FolderPublic  = "folderPublic"
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
nodeTypePath Annuaire  = "annuaire"
nodeTypePath Corpus    = "corpus"
nodeTypePath Dashboard = "dashboard"
nodeTypePath Url_Document  = "document"
nodeTypePath Error     = "ErrorNodeType"
nodeTypePath Graph     = "graph"
nodeTypePath Phylo     = "phylo"
nodeTypePath Individu  = "individu"
nodeTypePath Node      = "node"
nodeTypePath Nodes     = "nodes"
nodeTypePath NodeUser  = "user"
nodeTypePath NodeContact = "contact"
nodeTypePath Tree      = "tree"
nodeTypePath NodeList  = "lists"
nodeTypePath Texts     = "texts"
282
nodeTypePath Team      = "team"
283 284 285 286
------------------------------------------------------------

type ListId = Int

287 288 289 290 291 292 293
data ScoreType = Occurrences

derive instance genericScoreType :: Generic ScoreType _

instance showScoreType :: Show ScoreType where
  show = genericShow

294 295
type SearchQuery = String

296 297 298 299 300 301 302 303
type NgramsGetOpts =
  { tabType        :: TabType
  , offset         :: Offset
  , limit          :: Limit
  , orderBy        :: Maybe OrderBy
  , listIds        :: Array ListId
  , termListFilter :: Maybe TermList
  , termSizeFilter :: Maybe TermSize
304
  , scoreType      :: ScoreType
305
  , searchQuery    :: SearchQuery
306 307
  }

308 309 310 311 312 313
type NgramsGetTableAllOpts =
  { tabType        :: TabType
  , listIds        :: Array ListId
  , scoreType      :: ScoreType
  }

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
type SearchOpts =
  { {-id :: Int
    , query    :: Array String
    ,-}
    listId   :: Int
  , limit    :: Limit
  , offset   :: Offset
  , orderBy  :: Maybe OrderBy
  }

type CorpusMetricOpts =
  { tabType :: TabType
  , listId  :: ListId
  , limit   :: Maybe Limit
  }

type ChartOpts =
  { chartType :: ChartType
  , tabType   :: TabType
  -- , listId  :: ListId
  -- , limit   :: Maybe Limit
  }

James Laver's avatar
James Laver committed
337
data NodePath = NodePath SessionId NodeType (Maybe Id)
338 339

nodePath :: NodePath -> String
James Laver's avatar
James Laver committed
340
nodePath (NodePath s t i) = nodeTypePath t <> "/" <> show s <> id
James Laver's avatar
James Laver committed
341
  where id = maybe "" (\j -> "/" <> show j) i
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

data ChartType = Histo | Scatter | ChartPie | ChartTree

instance showChartType :: Show ChartType
  where
    show Histo    = "chart"
    show Scatter  = "scatter"
    show ChartPie = "pie"
    show ChartTree = "tree"

type Id  = Int
type Limit  = Int
type Offset = Int
data OrderBy = DateAsc  | DateDesc
             | TitleAsc | TitleDesc
             | ScoreAsc | ScoreDesc
             | TermAsc  | TermDesc
             | SourceAsc | SourceDesc

derive instance genericOrderBy :: Generic OrderBy _

instance showOrderBy :: Show OrderBy where
  show = genericShow

------------------------------------------------------------
367 368 369
-- V0 is the dummy case (impossible)
data ApiVersion = V0 | V10 | V11

370
instance showApiVersion :: Show ApiVersion where
371
  show V0  = "v0"
372 373 374 375 376 377 378 379
  show V10 = "v1.0"
  show V11 = "v1.1"

instance eqApiVersion :: Eq ApiVersion where
  eq V10 V10 = true
  eq V11 V11 = true
  eq _ _ = false

380 381 382 383 384 385 386 387 388 389 390 391
instance encodeJsonApiVersion :: EncodeJson ApiVersion where
  encodeJson v = encodeJson (show v)

instance decodeJsonApiVersion :: DecodeJson ApiVersion where
  decodeJson json = do
    v <- decodeJson json
    case v of
         "v1.0" -> pure V10
         "v1.1" -> pure V11
         _      -> pure V0
------------------------------------------------------------

392 393
-- Types of ngrams. Used to display user-selectable tabs and is sent via API,
-- wrapped in `TabNgramType a :: TabSubType`
394 395 396
data CTabNgramType = CTabTerms | CTabSources | CTabAuthors | CTabInstitutes

derive instance eqCTabNgramType :: Eq CTabNgramType
397
derive instance ordCTabNgramType :: Ord CTabNgramType
398 399 400 401 402 403 404 405 406 407

instance showCTabNgramType :: Show CTabNgramType where
  show CTabTerms      = "Terms"
  show CTabSources    = "Sources"
  show CTabAuthors    = "Authors"
  show CTabInstitutes = "Institutes"

data PTabNgramType = PTabPatents | PTabBooks | PTabCommunication

derive instance eqPTabNgramType :: Eq PTabNgramType
408
derive instance ordPTabNgramType :: Ord PTabNgramType
409 410 411 412 413 414 415 416 417

instance showPTabNgramType :: Show PTabNgramType where
  show PTabPatents       = "Patents"
  show PTabBooks         = "Books"
  show PTabCommunication = "Communication"

data TabSubType a = TabDocs | TabNgramType a | TabTrash | TabMoreLikeFav | TabMoreLikeTrash

derive instance eqTabSubType :: Eq a => Eq (TabSubType a)
418
derive instance ordTabSubType :: Ord a => Ord (TabSubType a)
419 420 421 422 423 424 425 426 427 428 429 430 431 432

instance showTabSubType :: Show a => Show (TabSubType a) where
  show TabDocs          = "Docs"
  show (TabNgramType a) = show a
  show TabTrash         = "Trash"
  show TabMoreLikeFav   = "MoreFav"
  show TabMoreLikeTrash = "MoreTrash"

data TabType
  = TabCorpus   (TabSubType CTabNgramType)
  | TabPairing  (TabSubType PTabNgramType)
  | TabDocument (TabSubType CTabNgramType)    

derive instance eqTabType :: Eq TabType
433
derive instance ordTabType :: Ord TabType
434 435 436 437 438

derive instance genericTabType :: Generic TabType _

instance showTabType :: Show TabType where
  show = genericShow
439 440 441

type TableResult a = {count :: Int, docs :: Array a}
type AffTableResult a = Aff (TableResult a)
442

443 444 445 446
data Mode = Authors
          | Sources
          | Institutes
          | Terms
447 448 449 450 451 452 453

derive instance genericMode :: Generic Mode _
instance showMode :: Show Mode where
  show = genericShow
derive instance eqMode :: Eq Mode
instance ordMode :: Ord Mode where
  compare = genericCompare
454 455 456
instance encodeMode :: EncodeJson Mode where
  encodeJson x = encodeJson $ show x

457 458 459 460 461 462 463 464 465 466 467 468
modeTabType :: Mode -> CTabNgramType
modeTabType Authors    = CTabAuthors
modeTabType Sources    = CTabSources
modeTabType Institutes = CTabInstitutes
modeTabType Terms      = CTabTerms

modeFromString :: String -> Maybe Mode
modeFromString "Authors" = Just Authors
modeFromString "Sources" = Just Sources
modeFromString "Institutes" = Just Institutes
modeFromString "Terms" = Just Terms
modeFromString _ = Nothing
469

470 471 472
-- Async tasks

-- corresponds to /add/form/async or /add/query/async
473 474 475
data AsyncTaskType = Form
                   | GraphT
                   | Query
476
                   | AddNode
477
                   | UpdateNode
478

479
derive instance genericAsyncTaskType :: Generic AsyncTaskType _
480 481 482 483 484 485
instance eqAsyncTaskType :: Eq AsyncTaskType where
  eq = genericEq
instance showAsyncTaskType :: Show AsyncTaskType where
  show = genericShow
instance encodeJsonAsyncTaskType :: EncodeJson AsyncTaskType where
  encodeJson t     = encodeJson $ show t
486 487 488 489 490 491 492
instance decodeJsonAsyncTaskType :: DecodeJson AsyncTaskType where
  decodeJson json = do
    obj <- decodeJson json
    case obj of
      "Form"       -> pure Form
      "GraphT"     -> pure GraphT
      "Query"      -> pure Query
Alexandre Delanoë's avatar
Alexandre Delanoë committed
493
      "AddNode"    -> pure AddNode
494
      s            -> Left ("Unknown string " <> s)
495 496

asyncTaskTypePath :: AsyncTaskType -> String
497
asyncTaskTypePath Form   = "add/form/async/"
498 499
asyncTaskTypePath Query  = "query/"
asyncTaskTypePath GraphT = "async/"
500
asyncTaskTypePath AddNode = "async/nobody/"
501 502 503
asyncTaskTypePath UpdateNode = "async/nobody/"


504

505 506
type AsyncTaskID = String

507 508 509 510 511 512 513
data AsyncTaskStatus = Running
                     | Pending
                     | Received
                     | Started
                     | Failed
                     | Finished
                     | Killed
514
derive instance genericAsyncTaskStatus :: Generic AsyncTaskStatus _
515

516 517
instance showAsyncTaskStatus :: Show AsyncTaskStatus where
  show = genericShow
518
derive instance eqAsyncTaskStatus :: Eq AsyncTaskStatus
519

520 521
instance encodeJsonAsyncTaskStatus :: EncodeJson AsyncTaskStatus where
  encodeJson s = encodeJson $ show s
522

523 524 525
instance decodeJsonAsyncTaskStatus :: DecodeJson AsyncTaskStatus where
  decodeJson json = do
    obj <- decodeJson json
526 527 528 529 530 531 532 533 534 535 536
    pure $ fromMaybe Running $ read obj

instance readAsyncTaskStatus :: Read AsyncTaskStatus where
  read "IsFailure"  = Just Failed
  read "IsFinished" = Just Finished
  read "IsKilled"   = Just Killed
  read "IsPending"  = Just Pending
  read "IsReceived" = Just Received
  read "IsRunning"  = Just Running
  read "IsStarted"  = Just Started
  read _            = Nothing
537

538 539 540 541 542
newtype AsyncTask =
  AsyncTask { id     :: AsyncTaskID
            , status :: AsyncTaskStatus
            }

543
derive instance genericAsyncTask :: Generic AsyncTask _
544 545 546 547 548 549 550
instance eqAsyncTask :: Eq AsyncTask where
  eq = genericEq
instance encodeJsonAsyncTask :: EncodeJson AsyncTask where
  encodeJson (AsyncTask { id, status }) =
        "id"       := id
     ~> "status"   := status
     ~> jsonEmptyObject
551 552
instance decodeJsonAsyncTask :: DecodeJson AsyncTask where
  decodeJson json = do
553 554
    obj    <- decodeJson json
    id     <- obj .: "id"
555
    status <- obj .: "status"
556
    pure $ AsyncTask { id, status }
557 558 559 560 561

newtype AsyncTaskWithType = AsyncTaskWithType {
    task :: AsyncTask
  , typ  :: AsyncTaskType
  }
562 563 564 565 566 567 568 569
derive instance genericAsyncTaskWithType :: Generic AsyncTaskWithType _
instance eqAsyncTaskWithType :: Eq AsyncTaskWithType where
  eq = genericEq
instance encodeJsonAsyncTaskWithType :: EncodeJson AsyncTaskWithType where
  encodeJson (AsyncTaskWithType { task, typ }) =
        "task"       := task
     ~> "typ"        := typ
     ~> jsonEmptyObject
570 571
instance decodeJsonAsyncTaskWithType :: DecodeJson AsyncTaskWithType where
  decodeJson json = do
572
    obj  <- decodeJson json
573
    task <- obj .: "task"
574
    typ  <- obj .: "typ"
575 576
    pure $ AsyncTaskWithType { task, typ }

577 578 579 580 581 582 583 584
newtype AsyncProgress = AsyncProgress {
    id :: AsyncTaskID
  , log :: Array AsyncTaskLog
  , status :: AsyncTaskStatus
  }
derive instance genericAsyncProgress :: Generic AsyncProgress _
instance decodeJsonAsyncProgress :: DecodeJson AsyncProgress where
  decodeJson json = do
585 586 587
    obj    <- decodeJson json
    id     <- obj .: "id"
    log    <- obj .: "log"
588 589 590 591 592 593 594 595 596 597 598 599
    status <- obj .: "status"
    pure $ AsyncProgress {id, log, status}

newtype AsyncTaskLog = AsyncTaskLog {
    events :: Array String
  , failed :: Int
  , remaining :: Int
  , succeeded :: Int
  }
derive instance genericAsyncTaskLog :: Generic AsyncTaskLog _
instance decodeJsonAsyncTaskLog :: DecodeJson AsyncTaskLog where
  decodeJson json = do
600 601 602
    obj       <- decodeJson json
    events    <- obj .: "events"
    failed    <- obj .: "failed"
603 604 605 606 607
    remaining <- obj .: "remaining"
    succeeded <- obj .: "succeeded"
    pure $ AsyncTaskLog {events, failed, remaining, succeeded}

progressPercent :: AsyncProgress -> Number
608
progressPercent (AsyncProgress {log}) = perc
609
  where
610 611 612
    perc = case A.head log of
      Nothing -> 0.0
      Just (AsyncTaskLog {failed, remaining, succeeded}) -> 100.0*nom/denom
613
        where
614 615
          nom = toNumber $ failed + succeeded
          denom = toNumber $ failed + succeeded + remaining