spee.ch/controllers/publishController.js

70 lines
2.1 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
2017-06-20 01:15:28 +02:00
const logger = require('winston');
const lbryApi = require('../helpers/libraries/lbryApi.js');
const db = require('../models');
2017-06-03 05:56:33 +02:00
function deleteTemporaryFile (filePath) {
fs.unlink(filePath, err => {
if (err) throw err;
2017-06-20 04:34:34 +02:00
logger.debug(`successfully deleted ${filePath}`);
});
2017-06-03 05:56:33 +02:00
}
function upsert (Model, values, condition) {
return Model
.findOne({ where: condition })
.then(function (obj) {
if (obj) { // update
return obj.update(values);
} else { // insert
return Model.create(values);
}
}).catch(function (error) {
logger.error('Sequelize findOne error', error);
});
}
2017-06-03 05:56:33 +02:00
module.exports = {
publish: (publishParams, fileName, fileType) => {
2017-06-26 19:49:03 +02:00
const deferred = new Promise((resolve, reject) => {
// 1. publish the file
lbryApi
.publishClaim(publishParams)
.then(result => {
logger.info(`Successfully published ${fileName}`, result);
// 2. update old record of create new one (update is in case the claim has been published before by this daemon)
upsert(
db.File,
{
name : publishParams.name,
claimId : result.claim_id,
outpoint: `${result.txid}:${result.nout}`,
height : 0,
fileName,
filePath: publishParams.file_path,
fileType,
nsfw : publishParams.metadata.nsfw,
},
{ name: publishParams.name, claimId: result.claim_id }
2017-06-27 00:01:41 +02:00
).then(() => {
// resolve the promise with the result from lbryApi.publishClaim;
resolve(result);
})
.catch(error => {
2017-06-26 19:49:03 +02:00
logger.error('Sequelize findOne error', error);
2017-06-27 00:01:41 +02:00
// reject the promise
reject(error);
2017-06-26 19:49:03 +02:00
});
})
.catch(error => {
logger.error(`Error publishing ${fileName}`, error);
// delete the local file
deleteTemporaryFile(publishParams.file_path);
2017-06-27 00:01:41 +02:00
// reject the promise
reject(error);
});
2017-06-26 19:49:03 +02:00
});
return deferred;
},
};