-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmass-case-association.ts
238 lines (200 loc) · 6.81 KB
/
mass-case-association.ts
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/* README
This is an example script for how to automatically create cases given a list of data vault directories from a CSV file. Refer to ExampleCsv.csv for an example on how to format the cases to create from your datavault directories.
To run the script, please look at package.json in dea-app.
Use the following command:
mass-case:only --username <username> --password <password> --datavaultulid <dataVaultUlid> --csvpath <your csv path>
For production use, you'll need to replace the credentials login with getting the Oauth2 cookie from your IDP provider if you are not using cognito.
Please note, this is only an example, adjustments will need to be made for production use.
*/
import * as fs from 'fs';
import * as path from 'path';
import { Credentials } from 'aws4-axios';
import { parse } from 'csv-parse';
import minimist from 'minimist';
import { getRequiredEnv } from '../../../lambda-http-helpers';
import { Oauth2Token } from '../../../models/auth';
import { DeaDataVaultFile } from '../../../models/data-vault-file';
import CognitoHelper from '../../../test-e2e/helpers/cognito-helper';
import { callDeaAPIWithCreds } from '../../../test-e2e/resources/test-helpers';
const args = minimist(process.argv.slice(2));
const massCaseAssociation = async (
directories: string[],
username: string,
password: string,
datavaultulid: string
) => {
let creds: Credentials;
let idToken: Oauth2Token;
const cognitoHelper: CognitoHelper = new CognitoHelper(password);
const deaApiUrl = getRequiredEnv('DEA_API_URL');
for (const directory of directories) {
[creds, idToken] = await cognitoHelper.getCredentialsForUser(username); // Refresh tokens per directory
const fileUlids = await getFileUlids(idToken, creds, deaApiUrl, directory, datavaultulid);
// Create case and return case ulid
const caseName = getDirectoryName(directory);
const currentCase = await createCase(caseName, idToken, creds, deaApiUrl);
// Break down file ulids into chunks, max 300 per case association
const fileUlidsChunks = getFileUlidChunks(fileUlids, 300);
for (const fileUlids of fileUlidsChunks) {
await associateFiles(currentCase.ulid, fileUlids, datavaultulid, idToken, creds, deaApiUrl);
}
console.log(`Case associations complete for case ${caseName}`);
}
};
const getFileUlidChunks = (fileUlids: string[], chunkSize: number): string[][] => {
const chunks: string[][] = [];
for (let i = 0; i < fileUlids.length; i += chunkSize) {
const chunk = fileUlids.slice(i, i + chunkSize);
chunks.push(chunk);
}
return chunks;
};
const parseCsv = async (csvpath: string) => {
const csvFilePath = path.resolve(__dirname, csvpath);
const fileContent = fs.readFileSync(csvFilePath, { encoding: 'utf-8' });
return new Promise<string[]>((resolve, reject) => {
let directories: string[] = [];
parse(
fileContent,
{
delimiter: ',',
skip_empty_lines: true,
},
(error, directory) => {
if (error) {
console.error(error);
reject(error);
return;
}
directories = directory;
}
);
setTimeout(() => {
resolve(directories);
}, 10000);
});
};
const getDirectoryName = (filePath: string) => {
const regExp = new RegExp(/\/([^/]+)\/$/);
const regMatch = String(filePath).match(regExp);
let caseName = '';
if (regMatch && regMatch[1]) {
caseName = regMatch[1];
}
return caseName;
};
const associateFiles = async (
caseUlid: string,
fileUlids: string[],
dataVaultUlid: string,
idToken: Oauth2Token,
creds: Credentials,
deaApiUrl: string
) => {
const response = await callDeaAPIWithCreds(
`${deaApiUrl}datavaults/${dataVaultUlid}/caseAssociations`,
'POST',
idToken,
creds,
{
caseUlids: [caseUlid],
fileUlids,
}
);
// Check if the case creation was successful
if (response.status === 200) {
console.log(`files associated successfully with case ${caseUlid}`);
} else {
console.error('Failed to associate files with case:', response.data);
}
return response.data;
};
const createCase = async (caseName: string, idToken: Oauth2Token, creds: Credentials, deaApiUrl: string) => {
const response = await callDeaAPIWithCreds(`${deaApiUrl}cases`, 'POST', idToken, creds, {
name: caseName,
status: 'ACTIVE',
});
// Check if the case creation was successful
if (response.status === 200) {
console.log(`case ${caseName} was created successfully`);
} else {
console.error('Failed to create case:', response.data);
}
return response.data;
};
const getFileUlids = async (
idToken: Oauth2Token,
creds: Credentials,
deaApiUrl: string,
directory: string,
datavaultulid: string,
nextToken?: string
): Promise<string[]> => {
let fileUlids: string[] = [];
try {
let url = `${deaApiUrl}datavaults/${datavaultulid}/files?filePath=${directory}`.replace(
/[^\x20-\x7E]/g,
''
);
if (nextToken) {
url += `&next=${encodeURIComponent(nextToken)}`;
}
const getResponse = await callDeaAPIWithCreds(url, 'GET', idToken, creds);
const files: DeaDataVaultFile[] = getResponse.data.files;
for (const file of files) {
if (file.isFile) {
fileUlids.push(file.ulid);
} else {
// folder entry, get ulids inside folder
const directoryFiles = await getFileUlids(
idToken,
creds,
deaApiUrl,
`${file.filePath}${file.fileName}/`,
datavaultulid
);
fileUlids = fileUlids.concat(directoryFiles);
}
}
// If there's a next token, recursively fetch more files
if (getResponse.data.next) {
const moreFileUlids = await getFileUlids(
idToken,
creds,
deaApiUrl,
directory,
datavaultulid,
getResponse.data.next
);
fileUlids = fileUlids.concat(moreFileUlids);
}
} catch (error) {
console.error('Error fetching file ulids:', error);
}
return fileUlids;
};
const createCases = async (username: string, password: string, datavaultulid: string, csvpath: string) => {
let directories: string[] = [];
try {
const response = await parseCsv(csvpath);
directories = [...new Set(response)]; // removes duplicates
} catch (error) {
console.error(error);
}
await massCaseAssociation(directories, username, password, datavaultulid);
};
const verifyRequiredParam = (name: string) => {
if (!args[name]) {
console.error(`required parameter '--${name}' is unspecified`);
process.exit(1);
}
};
verifyRequiredParam('username');
verifyRequiredParam('password');
verifyRequiredParam('datavaultulid');
verifyRequiredParam('csvpath');
void createCases(args.username, args.password, args.datavaultulid, args.csvpath);