Download or view file using google firebase cloud function - firebase

What I'm trying to do:
Generate invoice using a third party lib.
Download/View invoice
My code
let createPdf = functions.https.onRequest(async (request, response) => {
// more code here
if (download == 'true') {
return response.status(200).download(__dirname + "/docs/" + newFileName, newFileName, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("Downloaded:", filename)
}
})
} else {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
return response.status(200).sendFile("/docs/" + newFileName, options, (err) => {
if (err) {
console.log(err);
} else {
console.log('Sent:', filename);
}
});
}
});
The error
{
"error": {
"code": 500,
"status": "INTERNAL",
"message": "function crashed",
"errors": [
"socket hang up"
]
}
}
Note:
When I return a simple string instead of the file it works.

Use express request and response objects to send a file.
Read this documentation: using_express_request_and_response_objects
And don't forget to use absolute path when using sendFile

Related

hapi server : when i request with POST method, hapi server responding with null, but working fine in localhost

using hapi server -v = 16.7
joi -v = 10.6
deployed in aws ec2, nginx reverse proxy
Server Code in server.js:
'use strict';
//let newrelic = require('newrelic');
let Hapi = require('hapi');
let Routes = require('./Routes');
let Plugins = require('./Plugins');
let Bootstrap = require('./Utils/BootStrap');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const Config = require('./Config');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = new Hapi.Server();
server.connection({
port: Config.dbConfig.config.PORT,
routes: {cors: true}
});
let mongoOpts = {
reconnectTries: 60,
reconnectInterval: 2000,
useMongoClient:true
};
mongoose.connect(Config.dbConfig.config.dbURI,mongoOpts, (err, res) => {
if (err) {
console.log("DB Error: ", err);
process.exit(1);
} else {
console.log('MongoDB Connected');
}
});
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': {
info: {
'title': Config.dbConfig.config.SWAGGERNAME,
'version': Pack.version,
description: '',
},
//documentationPath: '/',
tags:[
{
name: 'v2.1.0',
description: 'API'
}
],
grouping: 'tags',
},
}], (err) => {
server.start((err) => {
if (err) {
console.log("Server err----------->", err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
server.on('response', (request) => {console.log('response===>>>:');
if(request.url.path.startsWith('/panel')){
}
else {//console.log('HEADERS===========>:',request.headers);
/* console for checking the params in the request*/
console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() +
' ' + request.url.path + ' --> ' + request.response.statusCode);
console.log('Request payload:', request.payload);
}
});
process.on('uncaughtException', function (err) {
console.log(err);
});
server.register(Plugins, function (err) {
if (err) {
server.error('Error while loading plugins : ' + err)
} else {
server.log('info', 'Plugins Loaded')
}
});
server.register(Inert, function (err) {
if (err) {
throw err;
}
server.route(Routes);
});
server.route([
{
method: 'GET',
path: '/{param*}', /* show error page */
handler: function (req, res) {
res.file('./error.html')
}
},
{
path: "/panel/{path*}",
method: "GET",
handler: { /* open admin panel index from panel path*/
directory: {
path: ['./_admin'],
listing: false,
index: ['index.html']
}
}
}
]);
This is deployed in AWS-EC2, with Nginx reverse proxy.When we hit POST request with payload, working fine in localhost and saves data to MongoDB. But when we hit same POST method from another domain against ec2 deployed server, the below error is showing in pm2 logs. It seems its responding with null before running the controller.
Error in pm2 logs, when we hit POST method:
TypeError: Cannot read property 'statusCode' of null
at /var/www/html/vhosts/custom_BE_ecommerce/api/server.js:123:65
at Object.internals.handler (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:283:33)
at invoke (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:255:23)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:259:13)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:276:18)
at module.exports.internals.Server.internals.Podium._emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:156:15)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:197:47)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at relay (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:198:15)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:202:16)
at internals.emitEmitter (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:303:15)
at processTicksAndRejections (node:internal/process/task_queues:79:21)
Need help on this issue.

push notification FCM - 401 INVALID_KEY or MismatchSenderId postman

Code to generate keys : Ps validPublicKey is a firebase code p256dh.
I donĀ“t know where is the problem. If is in the generate code, or the send notification.
I need to put it in php code yet.
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg;
console.log(swreg.pushManager.getSubscription());
console.log(JSON.stringify(swreg.pushManager.getSubscription()));
return swreg.pushManager.getSubscription();
})
.then(function(sub) {
if (sub === null) {
console.log('criando a chave');
var validPublicKey = 'BIG2EEduGTIoAYMFC3zpq2lksUw-OLRUrq_abhLs1Y2Zbo_xDUGwlozyezbSKqNkYylNN2yWKV5adB0819nQ1y0';
var convertValidPublicKey = urlBase64ToUint8Array(validPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:convertValidPublicKey
});
} else {
//we have
}
}).then(function(newSub) {
return fetch('https://???????.firebaseio.com/subscriptions.json', {
method:'POST',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body:JSON.stringify(newSub)
})
}).then(function(res) {
if (res.ok) {
displayConfirmNotification();
}
}).catch(function(err) {
console.log(err);
});
}

upload image using file transfer ionic 3 not work on iOS

upload image using file transfer in ionic 3 works fine on android,
but give me error on iOS when try it in simulator ..
* this is the error:
My Ionic Code:
chooseImageFromGallery()
{
this.type="0"
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum:true,
sourceType:0
}
this.camera.getPicture(options)
.then((imageData) => {
if (this.platform.is('ios'))
{
this.base64Image = imageData;
}
else
{
this.base64Image = imageData;
}
this.uploadimage(); // this function to upload img to server
},
(err) => {
}).then((path)=>{
})
}
uploadimage(){
this.photoSrc="";
this.translate.get("uploading Image...").subscribe(
value => {
this.sucesss=false
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "file",
fileName:'test',
chunkedMode:false,
mimeType:"image/jpeg",
headers:{
Connection:"close"
},
httpMethod: "POST",
}
//------------ android ------------//
this.base64Image =this.base64Image
//------------ ios ------------//
//this.base64Image =this.base64Image.substring(28)
fileTransfer.upload(this.base64Image,encodeURI('mydomain/api/Product/upload'), options)
.then((data:any) => {
alert("upload success ")
}, (err) => {
this.translate.get( "error in upload Data").subscribe(
value => {
this.service.presentToast(value,2000)
}
)
})
})
}
using asp.net api2 .. My server Code :
[HttpPost]
[Route("upload")]
[AllowAnonymous]
public HttpResponseMessage uploadImage()
{
var request = HttpContext.Current.Request;
if (Request.Content.IsMimeMultipartContent())
{
foreach (string file in request.Files)
{
var postedFile = request.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
string root = HttpContext.Current.Server.MapPath("~/ServerImg");
root = root + "/" + postedFile.FileName;
postedFile.SaveAs(root);
//Save post to DB
return Request.CreateResponse(HttpStatusCode.Found, new
{
error = false,
status = "created",
path = root
});
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound, new
{
error = true
});
}
// var title = request.Params["title"];
}
// }
return null;
}
else
{
return Request.CreateResponse(HttpStatusCode.Forbidden, new
{
error = true
});
}
}
I spend more than 4 days.. but nothing is work for me ..
And this code works fine on Android but not iOS I don't know what's the wrong, I tried real iPhone and Xcode simulator and not worked
always upload error {"code":3... "http_status":500,..
Can anyone Help me please...

The generic template and list template didn't work

I'm following the facebook messenger develop QuickStart to create a Node.js project, and I improved it to work in quick reply. Then when I tried the Generic Template and List Template, but it didn't work.
As the following source code, when I input the work "generic" or "list", the messenger should reply me with the template messege. But there was nothing happened.
} else if (received_message.text === 'generic') {
console.log('generic in');
response = {
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome!",
"image_url":"http://webapplication120181023051009.azurewebsites.net/colorcar1.jpg",
"subtitle":"We have the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://www.taobao.com/",
"messenger_extensions": false,
"webview_height_ratio": "tall",
"fallback_url": "https://www.taobao.com/"
},
"buttons":[
{
"type":"web_url",
"url":"https://www.taobao.com/",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}
}
// Sends the response message
callSendAPI(sender_psid, response);
// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
console.log('PAGE_ACCESS_TOKEN:');
console.log(PAGE_ACCESS_TOKEN);
console.log('request body:');
console.log(request_body);
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages?access_token=" + PAGE_ACCESS_TOKEN,
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
Sorry, I forgot to add the url into whiltelist.

botkit middleware - How to use sendToWatson to update context?

I use https://github.com/watson-developer-cloud/botkit-middleware#implementing-app-actions as my reference.
The context in my conversation does not update.
Here is my bot-facebook.js.
function checkBalance(context, callback) {
var contextDelta = {
user_name: 'Henrietta',
fname: 'Pewdiepie'
};
callback(null, context);
}
var checkBalanceAsync = Promise.promisify(checkBalance);
var processWatsonResponse = function (bot, message) {
if (message.watsonError) {
console.log(message.watsonError);
return bot.reply(message, "I'm sorry, but for technical reasons I can't respond to your message");
}
if (typeof message.watsonData.output !== 'undefined') {
//send "Please wait" to users
bot.reply(message, message.watsonData.output.text.join('\n'));
if (message.watsonData.output.action === 'check_balance') {
var newMessage = clone(message);
newMessage.text = 'check new name';
checkBalanceAsync(message.watsonData.context).then(function (contextDelta) {
console.log("contextDelta: " + JSON.stringify(contextDelta));
return watsonMiddleware.sendToWatsonAsync(bot, newMessage, contextDelta);
}).catch(function (error) {
newMessage.watsonError = error;
}).then(function () {
return processWatsonResponse(bot, newMessage);
});
}
}
};
controller.on('message_received', processWatsonResponse);
The JSON editor of welcome node in my watson conversation.
{
"context": {
"fname": "",
"user_name": ""
},
"output": {
"text": {
"values": [
"Good day :) My name is Doug and I am a chatbot."
],
"selection_policy": "random"
},
"action": "check_balance"
}
}
I have tried multiple ways I could imagine.
Do I need to do something like fname: <?contextDelta.fname?> in the json editor?
You aren't checking context in your dialog.
Context object in JSON editor is used to store captured data in context,
so your node actually empties context variable.
Probably you need to remove that context initialization from your dialog,
To see value of context variable, you have to use it in the output
"Good day, $fname :) My name is Doug and I am a chatbot."

Resources