-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
175 lines (153 loc) · 5.01 KB
/
handler.js
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
const downloadMedia = require("./downloadAndSaveFile.js");
const convertFile = require("./convert.js");
const { getPdfMetadata } = require("./convert.js");
const { uploadThumbnails } = require("./uploadToS3");
const jwt = require("./jwtValidation");
const path = require("path");
const DEFAULT_ATTEMPTS = process.env.DEFAULT_ATTEMPTS || 3;
const getErrorResponse = (statusCode = 0, errorMessage = "") => ({
statusCode: statusCode || 400,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type,Authorization",
},
body: JSON.stringify({
status: statusCode || 400,
message: "Validation Failed",
reasons: [
{ message: errorMessage || "We encountered an error. Please try again!" },
],
}),
});
/**
* Handles file download, conversion and upload
*
* Sample Event:
* {
* "headers": {
* "Authorization": "Bearer <JWT_TOKEN>"
* },
* "body": {
* "media_url": <MEDIA_URL>,
* "convert_to": "pdf"
* }
* }
*
* @param {Object} event - function invocation parameters
* - headers (required): the request headers
* - headers.Authorization (required): the JWT token
* - body (required): the request body
* - body.media_url (required): the URL of the file to convert
* - body.convert_to (optional): the file format of the converted type. Will be
* converted to pdf if not specified
* - body.num_attempts (optional): number of conversion attempts to make. If not
* specified, defaults to `DEFAULT_ATTEMPTS`
*
* @throws {Error} if any required param is missing
* or the 'convert_to' format is not supported
*
* @returns {Object} - the S3 URL of the converted file
*/
module.exports.handler = async (event) => {
try {
console.log("event", event);
// Set the response headers
// need to set the headers for AWS API Gateway
// also applies to rest of the objects like this
const response = {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Methods": "POST,GET,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type,Authorization",
},
};
if (!event.body) {
return getErrorResponse(
400,
"Invalid Body. Please check the request body and try again."
);
}
let body = {};
try {
body = JSON.parse(event.body);
} catch (err) {
return getErrorResponse(
400,
"Invalid Body. Please check the request body and try again."
);
}
// Check if the request is authorized
const checkToken = await jwt.validateJWT(event);
if (!(checkToken && checkToken.companyId)) {
return getErrorResponse(401, "Authentication Error");
}
const mediaUrl = body.media_url;
const numAttempts = body.num_attempts || DEFAULT_ATTEMPTS;
const convertTo = body.convert_to || "pdf";
// If 'convert_to' is specified in `event` then use that. Otherwise,
// attempt to infer it from `output_path`
const supportedTargetTypes = ["pdf"];
// [("pdf", "png", "jpg", "jpeg")];
if (!mediaUrl) {
return getErrorResponse(400, "Please specify a media_url to convert");
// throw new Error(`Please specify a media_url to convert.`);
}
if (!supportedTargetTypes.includes(convertTo)) {
return getErrorResponse(
400,
`We do not support the submitted Target file type - "${convertTo}". Check back later.`
);
}
const downloadPath = await downloadMedia(mediaUrl, "/tmp");
console.info(
`Successfully downloaded\n::->> ${mediaUrl} - at\n::->>${downloadPath}.`
);
let metaData = {};
const convertedPdfPath = downloadPath.includes(".pdf")
? downloadPath
: await convertFile(downloadPath, "/tmp", convertTo, numAttempts);
try {
metaData = await getPdfMetadata(convertedPdfPath);
} catch (er) {
// ignore
console.log("Error While Fetching Metadata", er);
}
// TODO: convert all the pages of PDF to images
// the param can not be jpg, it only supports jpeg
const imgPath = await convertFile(
convertedPdfPath,
"/tmp",
"jpeg",
numAttempts
);
// upload the converted pdf file to S3
const pdfLink = downloadPath.includes(".pdf")
? mediaUrl
: await uploadThumbnails([convertedPdfPath], checkToken.companyId);
// upload the converted image files to S3
const imgLinks = await uploadThumbnails(
[imgPath],
checkToken.companyId,
path.extname(imgPath).replace(".", "")
);
console.info(
`Successfully uploaded converted document to "${pdfLink} and ${imgLinks}".`
);
return {
...response,
statusCode: 200,
body: JSON.stringify({
metaData,
pdfLink,
imageLinks: imgLinks,
}),
};
} catch (err) {
console.log("errrrr");
console.log(err);
return getErrorResponse(400, err.message);
}
};