ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/ns_dev/Python/NinoCode/Tool_Box/RelativityLib.py
Revision: 618
Committed: Mon Oct 31 14:09:43 2016 UTC (9 years, 4 months ago) by nino.borges
Content type: text/x-python
File size: 12256 byte(s)
Log Message:
Added some support for the parent object, to populate the dictionaires correctly.

File Contents

# User Rev Content
1 nino.borges 570 """
2    
3     Relativity Library
4    
5     Created by
6     Emanuel Borges
7     05.22.2014
8    
9     This class will be my main Relativity library
10     Should DocumentTable and COTable be their own classes that subclass RelativityConnection?
11    
12    
13     TODO:
14     Make it so taht you van overide the site, username and pw. Right now it's created before you can overide.
15    
16     """
17    
18 nino.borges 618 import os,time
19 nino.borges 570 import requests,json
20    
21     class Relativity_Connection(object):
22     """An Advanced Relativity Connection Library and Toolkit"""
23 nino.borges 618 version = '0.3.0'
24 nino.borges 605
25     ## Prod
26     rootSite = 'https://relativity5.advanceddiscovery.com'
27     rootUserName = 'emanuel.borges@advanceddiscovery.com'
28     rootPassword = 'M@y_1255'
29    
30    
31     ## ## Dev
32     ## #rootSite = 'http://dev.mcdermottdiscovery.com'
33     ## #rootUserName = 'eborges@mwe.com'
34     ## #rootPassword = 'MWEreldev2@'
35     ##
36     ## ## Prod
37     ## rootSite = 'https://www.mcdermottdiscovery.com'
38     ## rootUserName = 'eborges@mwe.com'
39     ## rootPassword = 'QEst3kU2!'
40 nino.borges 570
41     def __init__(self, workSpace = None):
42     self.UpdateWorkspaceDict()
43     self.workSpace = workSpace
44     self.availableTables = None
45    
46     def UpdateWorkspaceDict(self):
47     """Updates the instance varible workSpaceDict with a {workspaceName:ID} dictionary"""
48     workSpaceDict = {}
49     r = requests.get(self.rootSite+'/Relativity.REST/Relativity/Workspace',auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword), headers={'X-CSRF-Header':""})
50     rawJson = r.json()
51     rawResults = rawJson['Results']
52     for i in rawResults:
53     workSpaceDict[i['Relativity Text Identifier']] = i['Artifact ID']
54    
55     self.workSpaceDict = workSpaceDict
56    
57     def GetAvilableTables(self):
58     """updates the list of available tables"""
59     pass
60    
61     def LoadWorkspace(self, workspaceName):
62     r = requests.get(self.rootSite+ '/Relativity.REST/Relativity/Workspace/%s'% self.workSpaceDict[workSpaceName],auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword), headers={'X-CSRF-Header':""})
63     self.workSpace = workSpaceName
64    
65    
66    
67     class DocumentTable(Relativity_Connection):
68    
69     def __init__ (self,workSpace):
70     self.workSpace = workSpace
71     super(DocumentTable,self).__init__(workSpace)
72     r = requests.get(self.rootSite+ '/Relativity.REST/Relativity/Workspace/%s/Document'% self.workSpaceDict[self.workSpace],auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword), headers={'X-CSRF-Header':""})
73     self.availableTables = r
74     #return r.__dict__
75    
76     def UpdateField(self,field):
77     d = {
78     "Artifact ID":1078252,"Artifact Type Name":"Tasks","Billing Time Used":5
79     }
80    
81     r = requests.put('https://dev.mcdermottdiscovery.com/Relativity.REST/Workspace/1016359/Tasks/1078252',
82     auth=requests.auth.HTTPBasicAuth('eborges@mwe.com','MWEreldev2@'),
83     headers={'X-CSRF-Header':"",'Content-Type':"application/json; charset=utf-8"},
84     data=json.dumps(d))
85    
86    
87    
88    
89     class CustomObjectTable(Relativity_Connection):
90     '''You can just insts this object if you already know the workspace # and objectName. Otherwise insts a sep rl object
91     to gather the workspace number and objectName'''
92     def __init__ (self, workSpace, objectName):
93     self.workSpace = workSpace
94     super(CustomObjectTable,self).__init__(workSpace)
95     r = requests.get(self.rootSite+ '/Relativity.REST/Workspace/%s/%s'% (self.workSpaceDict[self.workSpace],objectName),
96     auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword),
97     headers={'X-CSRF-Header':""})
98    
99     self.rlResponse = r.json()
100    
101     rlResponseCode = r.status_code
102     print rlResponseCode
103    
104     ## This is the ID of the workspace, which is needed when you update or create new items
105 nino.borges 618 ## Careful here, if the object that you are loading is a normal object the ID of the workspace will be the parent ID. BUT
106     ## If the object is a child table, liek contacts is child table of client in MCP, the parent ID will be the parent ID
107     ## of the last item in that database. So the parent id = client and not the workspace.
108 nino.borges 570 ## This will only work if there are already items in this table, got to fix this...
109     self.parentID = self.rlResponse['Results'][0]['Parent Artifact']['Artifact ID']
110    
111     ## You wont get the field list until after you return 1 item from the RDO
112     self.fieldMatrix = None
113    
114     ## Count of the results both in total and on this page.
115     self.totalResultCount = self.UpdateTotalResultCount()
116     self.pageResultCount = self.UpdateCurrentResultCount()
117    
118     ## The matrix if returned items with artifactID:name. Cant do other way around, since name can dupe.
119 nino.borges 618 self.itemMatrix = self.UpdateItemMatrix()
120     ## sets a matrix of the item and it's parent artifactID (name:parentArtifactID). when you grab from a table this has a
121     ## foreign key to another table.
122     self.relatedItemMatrix = self.UpdateRelatedItemMatrix()
123 nino.borges 570
124     ## The objectName stays the same, since you need a new instance for each table.
125     self.objectName = objectName
126    
127     ## Loading the item will update the field list and make that the active item
128     self.currentItems = None
129    
130     ## You may load 1 item using single item or query and get multiple items.
131     self.currentItemCount = None
132    
133    
134    
135     def LoadSingleItem(self, itemID):
136     '''loads a requested item into the instance and updates the field matrix'''
137     r = requests.get(self.rootSite+ '/Relativity.REST/Workspace/%s/%s/%s'% (self.workSpaceDict[self.workSpace],self.objectName,itemID),
138     auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword),
139     headers={'X-CSRF-Header':""})
140     rlResponse = r.json()
141     rlResponseCode = r.status_code
142     print rlResponseCode
143     self.currentItems = [rlResponse,]
144     self.UpdateFieldMatrix(self.currentItems[0]['__Fields'])
145     self.currentItemCount = len(self.currentItems)
146    
147     def QueryForItems(self,searchString):
148     '''takes a search string and brings back a matrix containing only those items that matched the search'''
149     payload = {
150     "condition":searchString,
151     "fields":["*"]
152     }
153     ## Note that it will give you a max of 100 here because I'm setting the page size.
154     r = requests.post(self.rootSite+ '/Relativity.REST/Workspace/%s/%s/QueryResult?pagesize=100'% (self.workSpaceDict[self.workSpace],self.objectName),
155     auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword),
156     headers={'X-CSRF-Header':"",'Content-Type':"application/json; charset=utf-8"},
157     data=json.dumps(payload))
158     rlResponse = r.json()
159     rlResponseCode = r.status_code
160     print rlResponseCode
161     self.currentItems = rlResponse['Results']
162     #print self.currentItems
163 nino.borges 579 if self.currentItems:
164     self.UpdateFieldMatrix(self.currentItems[0]['__Fields'])
165     self.currentItemCount = len(self.currentItems)
166    
167 nino.borges 570 return self.currentItems
168    
169     def UpdateItemMatrix(self):
170     ''' Updates the item matrix with ArtifactID:name and also puts all names in the itemlist'''
171     itemMatrix = {}
172     for i in self.rlResponse['Results']:
173     itemMatrix[i['Artifact ID']] = i['Relativity Text Identifier']
174     return itemMatrix
175 nino.borges 618
176     def UpdateRelatedItemMatrix(self):
177     ''' Updates the related item matrix with parentArtifactID:[names] for related tables'''
178     relatedItemMatrix = {}
179     #for i in self.rlResponse['Results']:
180     # relatedItemMatrix[i['Relativity Text Identifier']] = i['Parent Artifact']['Artifact ID']
181     #return relatedItemMatrix
182     for i in self.rlResponse['Results']:
183     if i['Parent Artifact']['Artifact ID'] in relatedItemMatrix.keys():
184     relatedItemMatrix[i['Parent Artifact']['Artifact ID']][i['Relativity Text Identifier']] = i['Artifact ID']
185     else:
186     relatedItemMatrix[i['Parent Artifact']['Artifact ID']]= {i['Relativity Text Identifier']:i['Artifact ID']}
187     return relatedItemMatrix
188 nino.borges 570
189     def UpdateTotalResultCount(self):
190     '''Returns the current totalResultCount'''
191     return self.rlResponse['TotalResultCount']
192    
193     def UpdateCurrentResultCount(self):
194     '''Returns the current result count for the page that you are on'''
195     return self.rlResponse['ResultCount']
196    
197     def UpdateFieldMatrix(self,rawFieldDict):
198     '''Returns the list of fields in the table object'''
199     fieldMatrix = {}
200     for i in rawFieldDict:
201     fieldMatrix[i['Name']] = i['Field Type']
202     self.fieldMatrix = fieldMatrix
203    
204    
205 nino.borges 618 def CreateNewItem(self, itemFieldMatrix, parentID = None):
206     '''Allows you to create a new item in the DO, by passing a matrix of fields and their values. If the Object that you are
207     writing in is a normal object, let it inherite self.parentID. If your object is a child object, like contact table that is
208     a child of a client table, overide the parentID here with the ID that you want to write to. So the associated records ID.
209     i.e. mcguirewoods parent ID'''
210     if parentID:
211     pass
212     else:
213     parentID = self.parentID
214     #print self.objectName
215 nino.borges 570 itemFieldMatrix["Artifact Type Name"] = self.objectName
216 nino.borges 618 #print self.parentID
217     itemFieldMatrix["Parent Artifact"] = {"Artifact ID":parentID}
218 nino.borges 570
219     r = requests.post(self.rootSite+ '/Relativity.REST/Workspace/%s/%s'% (self.workSpaceDict[self.workSpace],self.objectName),
220     auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword),
221     headers={'X-CSRF-Header':"",'Content-Type':"application/json; charset=utf-8"},
222     data=json.dumps(itemFieldMatrix))
223     rlResponse = r.json()
224     rlResponseCode = r.status_code
225     print rlResponseCode
226     artID = rlResponse['Results'][0]['ArtifactID']
227 nino.borges 618 ## This update wont work here because it's using the old response... if I need this one day, update.
228     #self.itemMatrix = self.UpdateItemMatrix()
229 nino.borges 570 ## Returning the artifact id?, not sure about this. maybe should return status and allow you to get at artifact...
230     return artID
231     #d = {
232     # "Name":"TEST","Artifact Type Name":"Tasks","Billing Time Used":5,"Parent Artifact":{"Artifact ID":1003663}
233     #}
234     #
235     #r = requests.post('https://dev.mcdermottdiscovery.com/Relativity.REST/Workspace/1016359/Tasks',
236     # auth=requests.auth.HTTPBasicAuth('eborges@mwe.com','MWEreldev2@'),
237     # headers={'X-CSRF-Header':"",'Content-Type':"application/json; charset=utf-8"},
238     # data=json.dumps(d))
239    
240    
241     def UpdateField(self,field):
242    
243     d = {
244     "Artifact ID":1078252,"Artifact Type Name":"Tasks","Billing Time Used":5,"Parent Artifact":{"Artifact ID":1003663}
245     }
246    
247     r = requests.put(self.rootSite+ '/Relativity.REST/Workspace/1016359/Tasks/1078252',
248     auth=requests.auth.HTTPBasicAuth(self.rootUserName,self.rootPassword),
249     headers={'X-CSRF-Header':"",'Content-Type':"application/json; charset=utf-8"},
250     data=json.dumps(d))
251 nino.borges 618
252     def DownLoadFile(self, fileName):
253     """Downloads a file to a epoch dir, under the temp dir, and returns a path to that."""
254     ## Test that this is win
255     ## Then
256     tempDir = os.getenv('TEMP')
257     epochTime = str(time.time())
258     fileTargetPath = os.path.join(tempDir,epochTime)
259     ## Test that it worked.
260     ## Then
261     fullFilePath = os.path.join(fileTargetPath,fileName)
262     return fullFilePath
263