2 Module : Gargantext.API.Node
3 Description : Server API
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 -- TODO-SECURITY: Critical
12 -- TODO-ACCESS: CanGetNode
13 -- TODO-EVENTS: No events as this is a read only query.
15 -------------------------------------------------------------------
16 -- TODO-ACCESS: access by admin only.
17 -- At first let's just have an isAdmin check.
18 -- Later: check userId CanDeleteNodes Nothing
19 -- TODO-EVENTS: DeletedNodes [NodeId]
20 -- {"tag": "DeletedNodes", "nodes": [Int*]}
24 {-# OPTIONS_GHC -fno-warn-orphans #-}
26 {-# LANGUAGE DataKinds #-}
27 {-# LANGUAGE DeriveGeneric #-}
28 {-# LANGUAGE FlexibleContexts #-}
29 {-# LANGUAGE FlexibleInstances #-}
30 {-# LANGUAGE NoImplicitPrelude #-}
31 {-# LANGUAGE OverloadedStrings #-}
32 {-# LANGUAGE RankNTypes #-}
33 {-# LANGUAGE ScopedTypeVariables #-}
34 {-# LANGUAGE TemplateHaskell #-}
35 {-# LANGUAGE TypeOperators #-}
37 module Gargantext.API.Node
40 import Control.Lens ((^.))
41 import Data.Aeson (FromJSON, ToJSON)
44 import Data.Text (Text())
45 import Data.Time (UTCTime)
46 import GHC.Generics (Generic)
47 import Gargantext.API.Auth (withAccess, PathId(..))
48 import Gargantext.API.Metrics
49 import Gargantext.API.Ngrams (TabType(..), TableNgramsApi, apiNgramsTableCorpus, QueryParamR)
50 import Gargantext.API.Ngrams.NTree (MyTree)
51 import Gargantext.API.Search (SearchDocsAPI, searchDocs, SearchPairsAPI, searchPairs)
52 import Gargantext.API.Table
53 import Gargantext.API.Types
54 import Gargantext.Core.Types (NodeTableResult)
55 import Gargantext.Core.Types.Main (Tree, NodeTree, ListType)
56 import Gargantext.Database.Action.Query.Facet (FacetDoc, OrderBy(..))
57 import Gargantext.Database.Action.Flow.Pairing (pairing)
58 import Gargantext.Database.Action.Query.Node.Children (getChildren)
59 import Gargantext.Database.Action.Query.Node.UpdateOpaleye (updateHyperdata)
60 import Gargantext.Database.Action.Query.Node.User
61 import Gargantext.Database.Action.Query.Node hiding (postNode)
62 import Gargantext.Database.Action.Query
63 import Gargantext.Database.Action.Query.Tree (treeDB)
64 import Gargantext.Database.Admin.Config (nodeTypeId)
65 import Gargantext.Database.Admin.Types.Errors (HasNodeError(..))
66 import Gargantext.Database.Admin.Types.Node
67 import Gargantext.Database.Admin.Utils -- (Cmd, CmdM)
68 import Gargantext.Database.Schema.Node
69 import Gargantext.Database.Schema.NodeNode
70 import Gargantext.Prelude
71 import Gargantext.Viz.Chart
72 import Gargantext.Viz.Phylo.API (PhyloAPI, phyloAPI)
74 import Test.QuickCheck (elements)
75 import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
76 import qualified Gargantext.Database.Action.Query.Node.Update as U (update, Update(..))
79 import qualified Gargantext.Text.List.Learn as Learn
80 import qualified Data.Vector as Vec
83 type NodesAPI = Delete '[JSON] Int
86 -- Be careful: really delete nodes
87 -- Access by admin only
88 nodesAPI :: [NodeId] -> GargServer NodesAPI
89 nodesAPI ids = deleteNodes ids
91 ------------------------------------------------------------------------
92 -- | TODO-ACCESS: access by admin only.
93 -- At first let's just have an isAdmin check.
94 -- Later: CanAccessAnyNode or (CanGetAnyNode, CanPutAnyNode)
95 -- To manage the Users roots
98 -- TODO needs design discussion.
99 type Roots = Get '[JSON] [Node HyperdataUser]
100 :<|> Put '[JSON] Int -- TODO
102 -- | TODO: access by admin only
103 roots :: GargServer Roots
104 roots = getNodesWithParentId Nothing
105 :<|> pure (panic "not implemented yet") -- TODO use patch map to update what we need
107 -------------------------------------------------------------------
108 -- | Node API Types management
109 -- TODO-ACCESS : access by users
110 -- No ownership check is needed if we strictly follow the capability model.
112 -- CanGetNode (Node, Children, TableApi, TableNgramsApiGet, PairingApi, ChartApi,
114 -- CanRenameNode (or part of CanEditNode?)
115 -- CanCreateChildren (PostNodeApi)
116 -- CanEditNode / CanPutNode TODO not implemented yet
118 -- CanPatch (TableNgramsApi)
122 type NodeAPI a = Get '[JSON] (Node a)
123 :<|> "rename" :> RenameApi
124 :<|> PostNodeApi -- TODO move to children POST
125 :<|> ReqBody '[JSON] a :> Put '[JSON] Int
126 :<|> Delete '[JSON] Int
127 :<|> "children" :> ChildrenApi a
130 :<|> "table" :> TableApi
131 :<|> "ngrams" :> TableNgramsApi
133 :<|> "category" :> CatApi
134 :<|> "search" :> SearchDocsAPI
137 :<|> "pairwith" :> PairWith
138 :<|> "pairs" :> Pairs
139 :<|> "pairing" :> PairingApi
140 :<|> "searchPair" :> SearchPairsAPI
143 :<|> "metrics" :> ScatterAPI
144 :<|> "chart" :> ChartApi
146 :<|> "tree" :> TreeApi
147 :<|> "phylo" :> PhyloAPI
148 -- :<|> "add" :> NodeAddAPI
150 -- TODO-ACCESS: check userId CanRenameNode nodeId
151 -- TODO-EVENTS: NodeRenamed RenameNode or re-use some more general NodeEdited...
152 type RenameApi = Summary " Rename Node"
153 :> ReqBody '[JSON] RenameNode
156 type PostNodeApi = Summary " PostNode Node with ParentId as {id}"
157 :> ReqBody '[JSON] PostNode
158 :> Post '[JSON] [NodeId]
160 type ChildrenApi a = Summary " Summary children"
161 :> QueryParam "type" NodeType
162 :> QueryParam "offset" Int
163 :> QueryParam "limit" Int
164 -- :> Get '[JSON] [Node a]
165 :> Get '[JSON] (NodeTableResult a)
167 ------------------------------------------------------------------------
168 type NodeNodeAPI a = Get '[JSON] (Node a)
170 nodeNodeAPI :: forall proxy a. (JSONB a, ToJSON a)
175 -> GargServer (NodeNodeAPI a)
176 nodeNodeAPI p uId cId nId = withAccess (Proxy :: Proxy (NodeNodeAPI a)) Proxy uId (PathNodeNode cId nId) nodeNodeAPI'
178 nodeNodeAPI' :: GargServer (NodeNodeAPI a)
179 nodeNodeAPI' = getNodeWith nId p
181 ------------------------------------------------------------------------
182 -- TODO: make the NodeId type indexed by `a`, then we no longer need the proxy.
183 nodeAPI :: forall proxy a. (JSONB a, FromJSON a, ToJSON a) => proxy a -> UserId -> NodeId -> GargServer (NodeAPI a)
184 nodeAPI p uId id = withAccess (Proxy :: Proxy (NodeAPI a)) Proxy uId (PathNode id) nodeAPI'
186 nodeAPI' :: GargServer (NodeAPI a)
187 nodeAPI' = getNodeWith id p
191 :<|> deleteNodeApi id
192 :<|> getChildren id p
196 :<|> apiNgramsTableCorpus id
212 -- :<|> nodeAddAPI id
213 -- :<|> postUpload id
215 deleteNodeApi id' = do
217 if _node_typename node == nodeTypeId NodeUser
218 then panic "not allowed" -- TODO add proper Right Management Type
221 ------------------------------------------------------------------------
222 data RenameNode = RenameNode { r_name :: Text }
225 -- TODO unPrefix "r_" FromJSON, ToJSON, ToSchema, adapt frontend.
226 instance FromJSON RenameNode
227 instance ToJSON RenameNode
228 instance ToSchema RenameNode
229 instance Arbitrary RenameNode where
230 arbitrary = elements [RenameNode "test"]
231 ------------------------------------------------------------------------
232 data PostNode = PostNode { pn_name :: Text
233 , pn_typename :: NodeType}
236 -- TODO unPrefix "pn_" FromJSON, ToJSON, ToSchema, adapt frontend.
237 instance FromJSON PostNode
238 instance ToJSON PostNode
239 instance ToSchema PostNode
240 instance Arbitrary PostNode where
241 arbitrary = elements [PostNode "Node test" NodeCorpus]
243 ------------------------------------------------------------------------
244 type CatApi = Summary " To Categorize NodeNodes: 0 for delete, 1/null neutral, 2 favorite"
245 :> ReqBody '[JSON] NodesToCategory
248 data NodesToCategory = NodesToCategory { ntc_nodesId :: [NodeId]
249 , ntc_category :: Int
253 -- TODO unPrefix "ntc_" FromJSON, ToJSON, ToSchema, adapt frontend.
254 instance FromJSON NodesToCategory
255 instance ToJSON NodesToCategory
256 instance ToSchema NodesToCategory
258 catApi :: CorpusId -> GargServer CatApi
261 putCat :: CorpusId -> NodesToCategory -> Cmd err [Int]
262 putCat cId cs' = nodeNodesCategory $ map (\n -> (cId, n, ntc_category cs')) (ntc_nodesId cs')
264 ------------------------------------------------------------------------
265 -- TODO adapt FacetDoc -> ListDoc (and add type of document as column)
266 -- Pairing utilities to move elsewhere
267 type PairingApi = Summary " Pairing API"
268 :> QueryParam "view" TabType
269 -- TODO change TabType -> DocType (CorpusId for pairing)
270 :> QueryParam "offset" Int
271 :> QueryParam "limit" Int
272 :> QueryParam "order" OrderBy
273 :> Get '[JSON] [FacetDoc]
276 type Pairs = Summary "List of Pairs"
277 :> Get '[JSON] [AnnuaireId]
278 pairs :: CorpusId -> GargServer Pairs
280 ns <- getNodeNode cId
281 pure $ map _nn_node2_id ns
283 type PairWith = Summary "Pair a Corpus with an Annuaire"
284 :> "annuaire" :> Capture "annuaire_id" AnnuaireId
285 :> "list" :> Capture "list_id" ListId
288 pairWith :: CorpusId -> GargServer PairWith
289 pairWith cId aId lId = do
290 r <- pairing cId aId lId
291 _ <- insertNodeNode [ NodeNode cId aId Nothing Nothing]
294 ------------------------------------------------------------------------
295 type ChartApi = Summary " Chart API"
296 :> QueryParam "from" UTCTime
297 :> QueryParam "to" UTCTime
298 :> Get '[JSON] (ChartMetrics Histo)
300 type PieApi = Summary " Chart API"
301 :> QueryParam "from" UTCTime
302 :> QueryParam "to" UTCTime
303 :> QueryParamR "ngramsType" TabType
304 :> Get '[JSON] (ChartMetrics Histo)
306 type TreeApi = Summary " Tree API"
307 :> QueryParam "from" UTCTime
308 :> QueryParam "to" UTCTime
309 :> QueryParamR "ngramsType" TabType
310 :> QueryParamR "listType" ListType
311 :> Get '[JSON] (ChartMetrics [MyTree])
313 -- Depending on the Type of the Node, we could post
314 -- New documents for a corpus
315 -- New map list terms
316 -- :<|> "process" :> MultipartForm MultipartData :> Post '[JSON] Text
318 ------------------------------------------------------------------------
321 NOTE: These instances are not necessary. However, these messages could be part
322 of a display function for NodeError/TreeError.
323 instance HasNodeError ServantErr where
324 _NodeError = prism' mk (const Nothing) -- panic "HasNodeError ServantErr: not a prism")
326 e = "Gargantext NodeError: "
327 mk NoListFound = err404 { errBody = e <> "No list found" }
328 mk NoRootFound = err404 { errBody = e <> "No Root found" }
329 mk NoCorpusFound = err404 { errBody = e <> "No Corpus found" }
330 mk NoUserFound = err404 { errBody = e <> "No User found" }
332 mk MkNode = err500 { errBody = e <> "Cannot mk node" }
333 mk NegativeId = err500 { errBody = e <> "Node with negative Id" }
334 mk UserNoParent = err500 { errBody = e <> "Should not have parent"}
335 mk HasParent = err500 { errBody = e <> "NodeType has parent" }
336 mk NotImplYet = err500 { errBody = e <> "Not implemented yet" }
337 mk ManyParents = err500 { errBody = e <> "Too many parents" }
338 mk ManyNodeUsers = err500 { errBody = e <> "Many userNode/user" }
340 instance HasTreeError ServantErr where
341 _TreeError = prism' mk (const Nothing) -- panic "HasTreeError ServantErr: not a prism")
344 mk NoRoot = err404 { errBody = e <> "Root node not found" }
345 mk EmptyRoot = err500 { errBody = e <> "Root node should not be empty" }
346 mk TooManyRoots = err500 { errBody = e <> "Too many root nodes" }
349 type TreeAPI = QueryParams "type" NodeType :> Get '[JSON] (Tree NodeTree)
351 treeAPI :: NodeId -> GargServer TreeAPI
354 ------------------------------------------------------------------------
355 -- | Check if the name is less than 255 char
356 rename :: NodeId -> RenameNode -> Cmd err [Int]
357 rename nId (RenameNode name') = U.update (U.Rename nId name')
359 postNode :: HasNodeError err
364 postNode uId pId (PostNode nodeName nt) = do
365 nodeUser <- getNodeUser (NodeId uId)
366 let uId' = nodeUser ^. node_userId
367 mkNodeWithParent nt (Just pId) uId' nodeName
369 putNode :: forall err a. (HasNodeError err, JSONB a, ToJSON a)
373 putNode n h = fromIntegral <$> updateHyperdata n h
374 -------------------------------------------------------------