Skip to content

Commit

Permalink
Merge pull request #168 from ankitpws/release-6.0.0
Browse files Browse the repository at this point in the history
file upload added to release-6.0.0
  • Loading branch information
aks30 authored Feb 22, 2024
2 parents e6c567a + 8f7a2ca commit 791d2e3
Show file tree
Hide file tree
Showing 10 changed files with 352 additions and 132 deletions.
4 changes: 3 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,6 @@ CLOUD_STORAGE_REGION = "ap-south-1"
CLOUD_STORAGE_PROJECT = "sl-dev-project" // CSP project Id (required for gcloud CSP)
CLOUD_ENDPOINT = https://a**.compat.objectstorage.ap-hyderabad-1.oraclecloud.com // CSP endpoint (required for oci)

VALIDATE_ENTITIES = ON/OFF //validate entities with location search enable disable
VALIDATE_ENTITIES = ON/OFF //validate entities with location search enable disable

PUBLIC_BASE_URL = "http://sunbird.org" // Public Base Url for presigned Url
2 changes: 1 addition & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ var expressValidator = require('express-validator');
//To enable cors
app.use(cors());
app.use(expressValidator())

app.use(bodyParser.raw({ type: 'application/octet-stream' }));
app.use(fileUpload());
app.use(bodyParser.json({ limit: '50MB' }));
app.use(bodyParser.urlencoded({ limit: '50MB', extended: false }));
Expand Down
16 changes: 16 additions & 0 deletions config/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,22 @@ module.exports = function () {
}
});

// Create Public/asstes for Upload File

if (!fs.existsSync(ROOT_PATH + "/public")) {
fs.mkdirSync(ROOT_PATH + "/public");

// Ensure /public/assets directory exists
if (!fs.existsSync(ROOT_PATH + "/public/assets")) {
fs.mkdirSync(ROOT_PATH + "/public/assets");
}
} else {
// If /public directory exists, ensure /public/assets directory exists
if (!fs.existsSync(ROOT_PATH + "/public/assets")) {
fs.mkdirSync(ROOT_PATH + "/public/assets");
}
}

//define cache as global variable
global.cache = require(ROOT_PATH+"/generics/helpers/cache");

Expand Down
127 changes: 99 additions & 28 deletions controllers/v1/cloud-services/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@

// dependencies
let filesHelpers = require(ROOT_PATH+"/module/cloud-services/files/helper");

const path = require("path");
const fs = require("fs");
const moment = require("moment-timezone");
/**
* Files service.
* @class
Expand Down Expand Up @@ -89,37 +91,30 @@ module.exports = class Files {
* @returns {JSON} Response with status and message.
*/

async preSignedUrls(req) {
return new Promise(async (resolve, reject) => {

try {

let signedUrl =
await filesHelpers.preSignedUrls(
req.body.request,
req.body.ref,
req.userDetails ? req.userDetails.userId : ""
async preSignedUrls(req) {
return new Promise(async (resolve, reject) => {
try {
let signedUrl = await filesHelpers.preSignedUrls(
req.body.request,
req.body.ref,
req.userDetails ? req.userDetails.userId : "",
req.query.serviceUpload == "true"? true : false
);

signedUrl["result"] = signedUrl["data"];
return resolve(signedUrl);

} catch (error) {

} catch (error) {
return reject({
status:
error.status ||
httpStatusCode["internal_server_error"].status,

message:
error.message
|| httpStatusCode["internal_server_error"].message,

errorObject: error
})
}
})
}
status:
error.status || httpStatusCode["internal_server_error"].status,

message:
error.message || httpStatusCode["internal_server_error"].message,

errorObject: error,
});
}
});
}

/**
* @api {post} /kendra/api/v1/cloud-services/files/getDownloadableUrl
Expand Down Expand Up @@ -184,5 +179,81 @@ module.exports = class Files {

}

/**
* upload the file to the cloud .
* @method
* @name upload
* @param {Request} req request body.
* @returns {JSON} Response with status .
* @apiParamExample {json} Response:
* {
"status": 200
}
*/

async upload(req) {
return new Promise(async (resolve, reject) => {
try {
let currentMoment = moment(new Date());
let formattedDate = currentMoment.format("DD-MM-YYYY");
if (!fs.existsSync(`${ROOT_PATH}/public/assets/${formattedDate}`)) {
fs.mkdirSync(`${ROOT_PATH}/public/assets/${formattedDate}`);
}
let filename = path.basename(req.query.file);
let localFilePath = `${ROOT_PATH}/public/assets/${formattedDate}/${filename}`;
let uploadStatus
// Use the Promise version of fs.writeFile

if (req.headers["content-type"] === "application/octet-stream") {
const binaryData = Buffer.from(req.body);
await fs.promises.writeFile(localFilePath, binaryData);
uploadStatus = await filesHelpers.upload(localFilePath, req.query.file);

if(uploadStatus.status == 200){
return resolve({
status: httpStatusCode["ok"].status,
});
}
} else if(req.headers["content-type"].split(";")[0] === "multipart/form-data"){
const fileKey = Object.keys(req.files)[0];
if (filename === req.files[fileKey].name) {
await fs.promises.writeFile(localFilePath, req.files[fileKey].data);
uploadStatus = await filesHelpers.upload(
localFilePath,
req.query.file
);
if(uploadStatus.status == 200){
return resolve({
status: httpStatusCode["ok"].status,
});
}

} else {
return reject({
status: httpStatusCode["internal_server_error"].status,

message: constants.apiResponses.FAILED_TO_VALIDATE_FILE,
});
}
} else{
return reject({
status: httpStatusCode["internal_server_error"].status,

message: constants.apiResponses.FAILED_TO_VALIDATE_FILE,
});
}
} catch (error) {
return reject({
status:
error.status || httpStatusCode["internal_server_error"].status,

message:
error.message || httpStatusCode["internal_server_error"].message,

errorObject: error,
});
}
});
}
};

4 changes: 4 additions & 0 deletions envVariables.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ let enviromentVariables = {
"optional" : true,
"default" : "+05:30"
},
PUBLIC_BASE_URL: {
"message" : "Public Base Url required",
"optional" : true,
},
"VALIDATE_ENTITIES" : {
"message" : "Requires Validate Entity Key for validating Entities",
"optional" : false,
Expand Down
1 change: 1 addition & 0 deletions generics/constants/api-responses.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,5 @@ module.exports = {
"FAILED_TO_CREATE_DOWNLOADABLEURL" : "Failed to generate downloadableUrl",
"KEYS_INDEXED_SUCCESSFULLY": 'Keys indexed successfully',
"KEYS_ALREADY_INDEXED": 'Keys already indexed',
"FAILED_TO_VALIDATE_FILE": "Could not validate fileName",
};
3 changes: 2 additions & 1 deletion generics/constants/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,6 @@ module.exports = {
SIGNEDURL: "signedUrl",
WRITE: "write",
READ: "read",
OFF: "OFF"
OFF: "OFF",
UPLOAD_FILE:"api/cloud-services/mlcore/v1/files/upload"
};
Loading

0 comments on commit 791d2e3

Please sign in to comment.