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.
16 -------------------------------------------------------------------
17 -- TODO-ACCESS: access by admin only.
18 -- At first let's just have an isAdmin check.
19 -- Later: check userId CanDeleteNodes Nothing
20 -- TODO-EVENTS: DeletedNodes [NodeId]
21 -- {"tag": "DeletedNodes", "nodes": [Int*]}
25 {-# OPTIONS_GHC -fno-warn-orphans #-}
27 {-# LANGUAGE DataKinds #-}
28 {-# LANGUAGE DeriveGeneric #-}
29 {-# LANGUAGE FlexibleContexts #-}
30 {-# LANGUAGE FlexibleInstances #-}
31 {-# LANGUAGE NoImplicitPrelude #-}
32 {-# LANGUAGE OverloadedStrings #-}
33 {-# LANGUAGE RankNTypes #-}
34 {-# LANGUAGE ScopedTypeVariables #-}
35 {-# LANGUAGE TemplateHaskell #-}
36 {-# LANGUAGE TypeOperators #-}
38 module Gargantext.API.Node
41 import Control.Lens ((^.))
42 import Control.Monad ((>>))
43 import Control.Monad.IO.Class (liftIO)
44 import Data.Aeson (FromJSON, ToJSON)
47 import Data.Text (Text())
48 import Data.Time (UTCTime)
49 import GHC.Generics (Generic)
50 import Gargantext.API.Auth (withAccess, PathId(..))
51 import Gargantext.API.Metrics
52 import Gargantext.API.Ngrams (TabType(..), TableNgramsApi, apiNgramsTableCorpus, QueryParamR)
53 import Gargantext.API.Ngrams.NTree (MyTree)
54 import Gargantext.API.Search (SearchDocsAPI, searchDocs)
55 import Gargantext.API.Table
56 import Gargantext.API.Types
57 import Gargantext.Core.Types (NodeTableResult)
58 import Gargantext.Core.Types.Main (Tree, NodeTree, ListType)
59 import Gargantext.Database.Config (nodeTypeId)
60 import Gargantext.Database.Facet (FacetDoc, OrderBy(..))
61 import Gargantext.Database.Node.Children (getChildren)
62 import Gargantext.Database.Schema.Node ( getNodesWithParentId, getNodeWith, getNode, deleteNode, deleteNodes, mkNodeWithParent, JSONB, HasNodeError(..))
63 import Gargantext.Database.Schema.NodeNode (nodeNodesCategory)
64 import Gargantext.Database.Node.UpdateOpaleye (updateHyperdata)
65 import Gargantext.Database.Tree (treeDB)
66 import Gargantext.Database.Types.Node
67 import Gargantext.Database.Utils -- (Cmd, CmdM)
68 import Gargantext.Prelude
69 import Gargantext.Viz.Chart
70 import Gargantext.Viz.Phylo.API (PhyloAPI, phyloAPI)
72 import Test.QuickCheck (elements)
73 import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
74 import qualified Gargantext.Database.Node.Update as U (update, Update(..))
77 import qualified Gargantext.Text.List.Learn as Learn
78 import qualified Data.Vector as Vec
82 type NodesAPI = Delete '[JSON] Int
85 -- Be careful: really delete nodes
86 -- Access by admin only
87 nodesAPI :: [NodeId] -> GargServer NodesAPI
88 nodesAPI ids = deleteNodes ids
90 ------------------------------------------------------------------------
91 -- | TODO-ACCESS: access by admin only.
92 -- At first let's just have an isAdmin check.
93 -- Later: CanAccessAnyNode or (CanGetAnyNode, CanPutAnyNode)
94 -- To manage the Users roots
97 -- TODO needs design discussion.
98 type Roots = Get '[JSON] [Node HyperdataAny]
99 :<|> Put '[JSON] Int -- TODO
101 -- | TODO: access by admin only
102 roots :: GargServer Roots
103 roots = (liftIO (putStrLn ( "/user" :: Text)) >> getNodesWithParentId 0 Nothing)
104 :<|> pure (panic "not implemented yet") -- TODO use patch map to update what we need
106 -------------------------------------------------------------------
107 -- | Node API Types management
108 -- TODO-ACCESS : access by users
109 -- No ownership check is needed if we strictly follow the capability model.
111 -- CanGetNode (Node, Children, TableApi, TableNgramsApiGet, PairingApi, ChartApi,
113 -- CanRenameNode (or part of CanEditNode?)
114 -- CanCreateChildren (PostNodeApi)
115 -- CanEditNode / CanPutNode TODO not implemented yet
117 -- CanPatch (TableNgramsApi)
121 type NodeAPI a = Get '[JSON] (Node a)
122 :<|> "rename" :> RenameApi
123 :<|> PostNodeApi -- TODO move to children POST
124 :<|> ReqBody '[JSON] a :> Put '[JSON] Int
125 :<|> Delete '[JSON] Int
126 :<|> "children" :> ChildrenApi a
129 :<|> "table" :> TableApi
130 :<|> "ngrams" :> TableNgramsApi
131 -- :<|> "pairing" :> PairingApi
133 :<|> "category" :> CatApi
134 :<|> "search" :> SearchDocsAPI
137 :<|> "metrics" :> ScatterAPI
138 :<|> "chart" :> ChartApi
140 :<|> "tree" :> TreeApi
141 :<|> "phylo" :> PhyloAPI
142 -- :<|> "add" :> NodeAddAPI
144 -- TODO-ACCESS: check userId CanRenameNode nodeId
145 -- TODO-EVENTS: NodeRenamed RenameNode or re-use some more general NodeEdited...
146 type RenameApi = Summary " Rename Node"
147 :> ReqBody '[JSON] RenameNode
150 type PostNodeApi = Summary " PostNode Node with ParentId as {id}"
151 :> ReqBody '[JSON] PostNode
152 :> Post '[JSON] [NodeId]
154 type ChildrenApi a = Summary " Summary children"
155 :> QueryParam "type" NodeType
156 :> QueryParam "offset" Int
157 :> QueryParam "limit" Int
158 -- :> Get '[JSON] [Node a]
159 :> Get '[JSON] (NodeTableResult a)
161 ------------------------------------------------------------------------
162 type NodeNodeAPI a = Get '[JSON] (Node a)
164 nodeNodeAPI :: forall proxy a. (JSONB a, ToJSON a)
169 -> GargServer (NodeNodeAPI a)
170 nodeNodeAPI p uId cId nId = withAccess (Proxy :: Proxy (NodeNodeAPI a)) Proxy uId (PathNodeNode cId nId) nodeNodeAPI'
172 nodeNodeAPI' :: GargServer (NodeNodeAPI a)
173 nodeNodeAPI' = getNodeWith nId p
175 ------------------------------------------------------------------------
176 -- TODO: make the NodeId type indexed by `a`, then we no longer need the proxy.
177 nodeAPI :: forall proxy a. (JSONB a, FromJSON a, ToJSON a) => proxy a -> UserId -> NodeId -> GargServer (NodeAPI a)
178 nodeAPI p uId id = withAccess (Proxy :: Proxy (NodeAPI a)) Proxy uId (PathNode id) nodeAPI'
180 nodeAPI' :: GargServer (NodeAPI a)
181 nodeAPI' = getNodeWith id p
185 :<|> deleteNodeApi id
186 :<|> getChildren id p
190 :<|> apiNgramsTableCorpus id
191 -- :<|> getPairing id
192 -- :<|> getTableNgramsDoc id
203 -- :<|> nodeAddAPI id
204 -- :<|> postUpload id
206 deleteNodeApi id' = do
208 if _node_typename node == nodeTypeId NodeUser
209 then panic "not allowed" -- TODO add proper Right Management Type
212 ------------------------------------------------------------------------
213 data RenameNode = RenameNode { r_name :: Text }
216 -- TODO unPrefix "r_" FromJSON, ToJSON, ToSchema, adapt frontend.
217 instance FromJSON RenameNode
218 instance ToJSON RenameNode
219 instance ToSchema RenameNode
220 instance Arbitrary RenameNode where
221 arbitrary = elements [RenameNode "test"]
222 ------------------------------------------------------------------------
223 data PostNode = PostNode { pn_name :: Text
224 , pn_typename :: NodeType}
227 -- TODO unPrefix "pn_" FromJSON, ToJSON, ToSchema, adapt frontend.
228 instance FromJSON PostNode
229 instance ToJSON PostNode
230 instance ToSchema PostNode
231 instance Arbitrary PostNode where
232 arbitrary = elements [PostNode "Node test" NodeCorpus]
234 ------------------------------------------------------------------------
235 type CatApi = Summary " To Categorize NodeNodes: 0 for delete, 1/null neutral, 2 favorite"
236 :> ReqBody '[JSON] NodesToCategory
239 data NodesToCategory = NodesToCategory { ntc_nodesId :: [NodeId]
240 , ntc_category :: Int
244 -- TODO unPrefix "ntc_" FromJSON, ToJSON, ToSchema, adapt frontend.
245 instance FromJSON NodesToCategory
246 instance ToJSON NodesToCategory
247 instance ToSchema NodesToCategory
249 catApi :: CorpusId -> GargServer CatApi
252 putCat :: CorpusId -> NodesToCategory -> Cmd err [Int]
253 putCat cId cs' = nodeNodesCategory $ map (\n -> (cId, n, ntc_category cs')) (ntc_nodesId cs')
255 ------------------------------------------------------------------------
256 -- TODO adapt FacetDoc -> ListDoc (and add type of document as column)
257 type PairingApi = Summary " Pairing API"
258 :> QueryParam "view" TabType
259 -- TODO change TabType -> DocType (CorpusId for pairing)
260 :> QueryParam "offset" Int
261 :> QueryParam "limit" Int
262 :> QueryParam "order" OrderBy
263 :> Get '[JSON] [FacetDoc]
265 ------------------------------------------------------------------------
266 type ChartApi = Summary " Chart API"
267 :> QueryParam "from" UTCTime
268 :> QueryParam "to" UTCTime
269 :> Get '[JSON] (ChartMetrics Histo)
271 type PieApi = Summary " Chart API"
272 :> QueryParam "from" UTCTime
273 :> QueryParam "to" UTCTime
274 :> QueryParamR "ngramsType" TabType
275 :> Get '[JSON] (ChartMetrics Histo)
277 type TreeApi = Summary " Tree API"
278 :> QueryParam "from" UTCTime
279 :> QueryParam "to" UTCTime
280 :> QueryParamR "ngramsType" TabType
281 :> QueryParamR "listType" ListType
282 :> Get '[JSON] (ChartMetrics [MyTree])
284 -- Depending on the Type of the Node, we could post
285 -- New documents for a corpus
286 -- New map list terms
287 -- :<|> "process" :> MultipartForm MultipartData :> Post '[JSON] Text
289 ------------------------------------------------------------------------
292 NOTE: These instances are not necessary. However, these messages could be part
293 of a display function for NodeError/TreeError.
294 instance HasNodeError ServantErr where
295 _NodeError = prism' mk (const Nothing) -- panic "HasNodeError ServantErr: not a prism")
297 e = "Gargantext NodeError: "
298 mk NoListFound = err404 { errBody = e <> "No list found" }
299 mk NoRootFound = err404 { errBody = e <> "No Root found" }
300 mk NoCorpusFound = err404 { errBody = e <> "No Corpus found" }
301 mk NoUserFound = err404 { errBody = e <> "No User found" }
303 mk MkNode = err500 { errBody = e <> "Cannot mk node" }
304 mk NegativeId = err500 { errBody = e <> "Node with negative Id" }
305 mk UserNoParent = err500 { errBody = e <> "Should not have parent"}
306 mk HasParent = err500 { errBody = e <> "NodeType has parent" }
307 mk NotImplYet = err500 { errBody = e <> "Not implemented yet" }
308 mk ManyParents = err500 { errBody = e <> "Too many parents" }
309 mk ManyNodeUsers = err500 { errBody = e <> "Many userNode/user" }
311 instance HasTreeError ServantErr where
312 _TreeError = prism' mk (const Nothing) -- panic "HasTreeError ServantErr: not a prism")
315 mk NoRoot = err404 { errBody = e <> "Root node not found" }
316 mk EmptyRoot = err500 { errBody = e <> "Root node should not be empty" }
317 mk TooManyRoots = err500 { errBody = e <> "Too many root nodes" }
320 type TreeAPI = Get '[JSON] (Tree NodeTree)
322 treeAPI :: NodeId -> GargServer TreeAPI
325 ------------------------------------------------------------------------
326 -- | Check if the name is less than 255 char
327 rename :: NodeId -> RenameNode -> Cmd err [Int]
328 rename nId (RenameNode name') = U.update (U.Rename nId name')
330 postNode :: HasNodeError err
335 postNode uId pId (PostNode nodeName nt) = do
336 nodeUser <- getNodeWith (NodeId uId) HyperdataUser
337 let uId' = nodeUser ^. node_userId
338 mkNodeWithParent nt (Just pId) uId' nodeName
340 putNode :: forall err a. (HasNodeError err, JSONB a, ToJSON a)
344 putNode n h = fromIntegral <$> updateHyperdata n h
345 -------------------------------------------------------------