-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_viewing_packages.py
More file actions
212 lines (178 loc) · 8.38 KB
/
Copy pathcreate_viewing_packages.py
File metadata and controls
212 lines (178 loc) · 8.38 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
from time import sleep
import argparse
import requests
import re
from pathlib import Path
# Package ID, Display Name and Storage Handlers
# -------------------------
# Viewing package ID will be used as the source when creating new
# viewing sessions from the package
def basicFilesystemIdGenerator(path):
id = '_'.join(re.split("[./\\\\]", str(path)))
return id
# Display name is used to create the viewing package.
# display name is used to identify the session, display name used to create
# viewing package and viewing sessions should be consistent to keep markup
# associated with new viewing sessions
def basicFilesystemDisplayNameGenerator(path):
return str(path)
# The document collector is reponsible for gathering documents to be migrated from storage
# It should be used as an adapter for document storage
def collectFilesystemDocuments(filesource, idGenerator, displayNameGenerator):
filePath = Path(filesource)
documentsList = recursivelyGatherDocuments(filePath, idGenerator, displayNameGenerator)
return documentsList
def recursivelyGatherDocuments(path, idGenerator, displayNameGenerator):
documentList = []
if path.is_file():
docId = idGenerator(path)
displayName = displayNameGenerator(path)
with open(path, 'rb') as document:
rawDoc = document.read()
docData = {
'data': rawDoc,
'id': docId,
'displayName': displayName
}
documentList.append(docData)
elif path.is_dir():
for subPath in path.iterdir():
documentList.extend(recursivelyGatherDocuments(subPath, idGenerator, displayNameGenerator))
return documentList
# -------------------------
def runPackageCreation(args, collectDocuments, idGenerator, displayNameGenerator):
documentsList = collectDocuments(args.documents_folder, idGenerator, displayNameGenerator)
failureLog = []
for document in documentsList:
try:
createViewingPackage(document, args.pas_base_url, args.pas_secret_key)
except HttpException as e:
print(f'error creating package for document {document["displayName"]}: ')
if e.response.status_code > 299:
print(f'{e.response.status_code} returned from {e.response.url} due to {e.response.reason}')
else:
print(f'Error reported from {e.response.url}: {e.args[0]}')
failureLog.append((document["displayName"], e))
continue
if len(failureLog) > 0:
print('Failed documents:\n')
for log in failureLog:
print(log[0])
def createViewingPackage(document, pas_base_url, pas_secret_key):
requestHandler = Requestor(pas_base_url, pas_secret_key)
# parameters used for creating the viewing package, including display name, must be identical
# to the parameters used to create viewing sessions with the file.
# This allows Prizmdoc to correctly associate sessions created from the viewing package with the markup
packageId = requestHandler.createPdfPackage(document, document['id'], document['displayName'])
return packageId
# Requestor handles direct communication with PrizmDoc
# -------------------------
class Requestor:
def __init__(self, pas_base_url, pas_secret_key):
self.pas_base_url = pas_base_url
self.pas_secret_key = pas_secret_key
def createPdfPackage(self, documentData, documentId, documentDisplayName):
print(f"creating a viewing package for {documentDisplayName}: documentId = {documentId}")
creatorId = self.startPackageCreator(documentDisplayName, documentId)
if creatorId == None:
# Package already exists, OK
return documentId
self.uploadDocumentToPackageCreator(documentData, creatorId)
self.pollForPackageCreation(creatorId)
print("package creation complete!")
return documentId
def startPackageCreator(self, displayName, documentId):
# Make sure to set viewingPackageLifetime to 0 to make the
# viewing package content remain available perpetually.
PostPackageCreatorsData = {
"input": {
"source": {
"documentId": f"{documentId}",
"type": "upload",
"displayName": f"{displayName}",
"packageType": "pdf"
},
"viewingPackageLifetime": 0
}
}
PostPackageCreatorsHeaders = {
"Content-Type": "application/json",
"Accusoft-Secret": self.pas_secret_key,
}
PostPackageCreatorsEndpoint = '/'.join([self.pas_base_url, "v2", "viewingPackageCreators"])
with requests.post(PostPackageCreatorsEndpoint, json=PostPackageCreatorsData, headers=PostPackageCreatorsHeaders) as res:
if not res.ok:
if res.reason == "DocumentIdAlreadyInUse":
print(f"package '{documentId}' already exists")
return None
else:
print(res.request.body)
raise HttpException(res, f"error calling {PostPackageCreatorsEndpoint}: \n{res.status_code}\n{res.reason}")
else:
print("package creation process started!")
return res.json()["processId"]
def uploadDocumentToPackageCreator(self, documentData, creatorId):
endpoint = '/'.join([self.pas_base_url, "v2", "viewingPackageCreators", creatorId, "SourceFile"])
self.uploadDocument(documentData, endpoint)
def uploadDocument(self, documentData, endpoint):
headers = {
"Accusoft-Secret": self.pas_secret_key
}
with requests.put(endpoint, data=documentData["data"], headers=headers) as res:
if not res.ok:
raise Exception(f"error calling {endpoint}: \n{res.status_code}\n{res.reason}")
else:
print("upload successful!")
return res.ok
def pollForPackageCreation(self, packageCreationProcessId):
GetPackageCreatorsEndpoint = '/'.join([self.pas_base_url, "v2", "viewingPackageCreators", packageCreationProcessId])
GetPackageCreatorsHeaders = {
"Accusoft-Secret": self.pas_secret_key,
}
packageCreationComplete = False
attemptCount = 60
while packageCreationComplete is not True:
sleep(1)
if (attemptCount < 0):
raise HttpException(res, f"timed out polling for package creation")
attemptCount = attemptCount - 1
with requests.get(GetPackageCreatorsEndpoint, headers=GetPackageCreatorsHeaders) as res:
if not res.ok:
raise HttpException(res, f"error calling {GetPackageCreatorsEndpoint}: \n{res.status_code}\n{res.reason}")
respJson = res.json()
if respJson["state"] == "error":
raise HttpException(res, f"error calling {GetPackageCreatorsEndpoint}: \n{respJson["errorCode"]}")
packageCreationComplete = respJson["state"] == "complete"
# -------------------------
class HttpException(Exception):
def __init__(self, response, message):
super().__init__(message)
self.response = response
def parseArguments():
parser = argparse.ArgumentParser(
prog='create_viewing_packages.py',
)
parser.add_argument(
"-d",
"--documents_folder",
help="Path to the documents folder",
required=True
)
parser.add_argument(
"-u",
"--pas_base_url",
help="PAS base url, e.g. 'http://localhost:3000'",
required=True
)
parser.add_argument(
"-s",
"--pas_secret_key",
help="PAS secret key. See https://help.accusoft.com/PrizmDoc/v13.28/HTML/pas-configuration.html",
required=True
)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parseArguments()
# Storage, ID Generator, and Display Name generator functions can be substituted based on specific implementation details
runPackageCreation(args, collectFilesystemDocuments, basicFilesystemIdGenerator, basicFilesystemDisplayNameGenerator)