uploading using async and AWS SDK v3

This commit is contained in:
Luke Berndt
2023-04-09 09:53:58 -04:00
parent a535511f16
commit 6e4cbb0ec8

View File

@@ -1,5 +1,3 @@
var db = require('../db');
var mkdirp = require('mkdirp');
var path = require('path'); var path = require('path');
var fs = require('fs'); var fs = require('fs');
var sysStats = require("../sys_stats"); var sysStats = require("../sys_stats");
@@ -7,53 +5,25 @@ var probe = require('node-ffprobe');
var mongoose = require("mongoose"); var mongoose = require("mongoose");
var System = require("../models/system"); var System = require("../models/system");
var Talkgroup = require("../models/talkgroup"); var Talkgroup = require("../models/talkgroup");
var Group = require("../models/group"); var { callModel: Call } = require("../models/call");
var {callModel:Call} = require("../models/call");
var secrets = require("../config/secrets"); var secrets = require("../config/secrets");
var util = require("util") var util = require("util")
var config = require('../config/config.json');
var s3_endpoint = process.env['S3_ENDPOINT'] != null ? process.env['S3_ENDPOINT'] : 'https://s3.us-west-1.wasabisys.com'; var s3_endpoint = process.env['S3_ENDPOINT'] != null ? process.env['S3_ENDPOINT'] : 'https://s3.us-west-1.wasabisys.com';
var s3_region = process.env['S3_REGION'] != null ? process.env['S3_REGION'] : 'us-west-1';
var s3_bucket = process.env['S3_BUCKET'] != null ? process.env['S3_BUCKET'] : 'openmhz-west'; var s3_bucket = process.env['S3_BUCKET'] != null ? process.env['S3_BUCKET'] : 'openmhz-west';
var s3_profile = process.env['S3_PROFILE'] != null ? process.env['S3_PROFILE'] : 'wasabi-account'; var s3_profile = process.env['S3_PROFILE'] != null ? process.env['S3_PROFILE'] : 'wasabi-account';
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
const wasabi = require('aws-sdk'); const client = new S3Client({
credentials: fromIni({ profile: s3_profile }),
const wasabiEndpoint = new wasabi.Endpoint(s3_endpoint); bucketEndpoint: s3_endpoint,
var wasabiCredentials = new wasabi.SharedIniFileCredentials({ region: s3_region,
profile: s3_profile maxAttempts: 1
});
wasabi.config.credentials = wasabiCredentials;
const wasabiS3 = new wasabi.S3({
endpoint: wasabiEndpoint,
maxRetries: 0
}); });
async function callLength(file) { exports.upload = async function (req, res, next) {
return new Promise((resolve, reject) => {
probe(file, function (err, probeData) {
if (err) {
reject(err);
} else {
resolve(Math.round(probeData.format.duration));
}
});
})
}
exports.upload = function (req, res, next) {
process.nextTick(function () {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
/** The original name of the uploaded file
stored in the variable "originalname". **/
var target_path = 'uploads/' + req.file.originalname;
if (!req.file && (path.extname(req.file.originalname)) != '.m4a') { if (!req.file && (path.extname(req.file.originalname)) != '.m4a') {
console.warn("[" + req.params.shortName + "] Error file name is wrong or file does not exist"); console.warn("[" + req.params.shortName + "] Error file name is wrong or file does not exist");
@@ -65,18 +35,16 @@ exports.upload = function (req, res, next) {
var apiKey = req.body.api_key; var apiKey = req.body.api_key;
try {
System.findOne({ const item = System.findOne({ 'shortName': shortName }, ["key", "ignoreUnknownTalkgroup"]);
'shortName': shortName } catch (err) {
}, ["key", "ignoreUnknownTalkgroup"], async function (err, item) {
if (err) {
console.warn("[" + req.params.shortName + "] Error /:shortName/upload - Error: " + err); console.warn("[" + req.params.shortName + "] Error /:shortName/upload - Error: " + err);
res.status(500); res.status(500);
res.send("Error, invalid shotName:\n" + err); res.send("Error, invalid shotName:\n" + err);
return; return;
} }
if (item === null) {
if (!item) {
console.warn("[" + req.params.shortName + "] Error /:shortName/upload ShortName does not exist"); console.warn("[" + req.params.shortName + "] Error /:shortName/upload ShortName does not exist");
res.status(500); res.status(500);
res.send("ShortName does not exist: " + shortName + "\n"); res.send("ShortName does not exist: " + shortName + "\n");
@@ -101,14 +69,11 @@ exports.upload = function (req, res, next) {
if (item.ignoreUnknownTalkgroup == true) { if (item.ignoreUnknownTalkgroup == true) {
//console.log("ignore unknown talkgroup ");
//await Talkgroup.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)
talkgroupExists = await Talkgroup.exists({ talkgroupExists = await Talkgroup.exists({
'shortName': shortName, 'shortName': shortName,
'num': talkgroupNum 'num': talkgroupNum
}); });
//console.log("In talkgroup: " + talkgroupExists);
//talkgroupExists = await Talkgroup.findOne({ 'shortName': shortName, 'num': talkgroupNum }).select({ _id: 1 }).lean().then(doc => !!doc).exec();
if (!talkgroupExists) { if (!talkgroupExists) {
try { try {
fs.unlinkSync(req.file.path) fs.unlinkSync(req.file.path)
@@ -147,19 +112,12 @@ exports.upload = function (req, res, next) {
res.status(200).end(); res.status(200).end();
var base_path = config.mediaDirectory;
var local_path = "/" + shortName + "/" + time.getFullYear() + "/" + (time.getMonth() + 1) + "/" + time.getDate() + "/"; var local_path = "/" + shortName + "/" + time.getFullYear() + "/" + (time.getMonth() + 1) + "/" + time.getDate() + "/";
var target_file = base_path + local_path + path.basename(req.file.originalname);
var object_key = "media/" + shortName + "-" + talkgroupNum + "-" + startTime + ".m4a"; var object_key = "media/" + shortName + "-" + talkgroupNum + "-" + startTime + ".m4a";
var endpoint = s3_endpoint; var endpoint = s3_endpoint;
var bucket = s3_bucket; var bucket = s3_bucket;
// If not a pro plan, use S3 storage
var url = s3_endpoint + "/" + s3_bucket + "/" + object_key; var url = s3_endpoint + "/" + s3_bucket + "/" + object_key;
var objectStore = true;
var call = new Call({ var call = new Call({
shortName: shortName, shortName: shortName,
@@ -183,34 +141,31 @@ exports.upload = function (req, res, next) {
if (req.body.call_length) { if (req.body.call_length) {
call.len = parseFloat(req.body.call_length); call.len = parseFloat(req.body.call_length);
} else { } else {
call.len = (stopTime - time) / 1000; //await callLength(req.file.path); call.len = (stopTime - time) / 1000;
}
} catch (err) {
console.error(err);
} }
var wasabiSrc = fs.createReadStream(req.file.path); var wasabiSrc = fs.createReadStream(req.file.path);
var wasabiParams = { const command = new PutObjectCommand({
Bucket: s3_bucket, Bucket: s3_bucket,
Key: object_key, Key: object_key,
Body: wasabiSrc, Body: wasabiSrc,
ACL: 'public-read' ACL: 'public-read'
}; });
try {
const response = await client.send(command);
console.log(response);
//var options = {partSize: 10 * 1024 * 1024, queueSize: 1};
/*var upload = new wasabiS3.ManagedUpload({
leavePartsOnError: true,
partSize: 10 * 1024 * 1024, queueSize: 1,
params: wasabiParams
});*/
wasabiS3.upload(wasabiParams, function (err, data) {
wasabiSrc.destroy(); wasabiSrc.destroy();
fs.unlink(req.file.path, (err) => { fs.unlink(req.file.path, async (err) => {
if (err) { if (err) {
console.error("[" + call.shortName + "]error deleting: " + req.file.path); console.error("[" + call.shortName + "]error deleting: " + req.file.path);
} }
call.save(); await call.save();
sysStats.addCall(call.toObject()); sysStats.addCall(call.toObject());
// we only want to notify clients if the clip is longer than 1 second. // we only want to notify clients if the clip is longer than 1 second.
@@ -222,8 +177,6 @@ exports.upload = function (req, res, next) {
if (err) { if (err) {
console.error("[" + call.shortName + "] " + call.name + " - content-length: " + req.headers['content-length'] + " Wasabi Error", err); console.error("[" + call.shortName + "] " + call.name + " - content-length: " + req.headers['content-length'] + " Wasabi Error", err);
} }
});
} catch (err) { } catch (err) {
console.warn("[" + call.shortName + "] Upload Error: " + err + " Filename: " + call.name + " content-length: " + req.headers['content-length']); console.warn("[" + call.shortName + "] Upload Error: " + err + " Filename: " + call.name + " content-length: " + req.headers['content-length']);
res.status(500); res.status(500);
@@ -239,6 +192,4 @@ exports.upload = function (req, res, next) {
console.log("error deleting: " + req.file.path); console.log("error deleting: " + req.file.path);
}); });
} }
});
});
} }