Use Messenger SDK to send file data - javascript

I have a webview that opens from a messenger bot.
From the webview I want to send image data to the conversation (no URL - data coming from the canvas).
I tried to use Messenger SDK beginShareFlow with file data attachment:
function uploadImage(data) {
let message = {
"attachment": {
"type": "image",
"payload": {
"is_reusable": true
},
"filedata": data
}
};
MessengerExtensions.beginShareFlow(function (share_response) {
// User dismissed without error
if (share_response.is_sent) {
// The user actually did share.
//close the webview
MessengerExtensions.requestCloseBrowser(function success() {
// webview closed
}, function error(err) {
console.log(err);
});
}
},
function (errorCode, errorMessage) {
// An error occurred in the process
console.log(errorMessage);
},
message, "current_thread");
}
But I get an error:
Messenger Extensions unexpected error.
Would appreciate help =]
EDIT:
I found out that filedata is used to transfer a file location (which I do not have).
So I tried other solutions:
I created from my cavas blob, and tried to pass it in filedata - did not work
I created a blob file (by adding name and date) and tried to move the location - did not work
I created a url from blob and tried to move it as a url (not as filedata) - and got an error:
Invalid image URL provided in message content
When I go to the blob url from the browser I see the image =[

Per the SDK's section on sending attachments:
There are three ways to attach an asset to a message:
URL
File
attachment_id
The attachment_id refers to previously uploaded URL/File attachments. Sending raw file data is not an option. You must either upload the image to a URL or save it to a file. Blob URLs do not work because they refer only to data stored in the local system's memory. You need to move that data to an image or file on a server.
Upload the image to a URL
Your first option is to upload the image to a URL. Depending on how private the contents of the image are, you could use a public image hosting service like imgur, or you could upload the image to a public location on your server. If you want to keep the image hidden, you could save the image at a URL containing a randomly generated hash and delete that file as soon as the attachment has been uploaded to Messenger. However, you could keep the image totally private with the second option:
Upload the image from a (temp) file
Your second option is to upload the image according to a file location. By uploading the image to a file on your server, you could avoid the image ever becoming visible to the public. To avoid filling up server space, you could manually delete the file once the attachment has uploaded, or you could use a temp file. In fact, the SDK's example for sending a file demonstrates sending a temporary file saved in the /tmp folder.

Related

Generate HTTP response from raw file data in JavaScript

I need to be able to take the raw data from any file and generate a response object within a service worker.
Short explanation:
I have a website that takes file names, paths, mime types and raw text and stores it in cache. If I make a request to a file with that path and name, a service worker responds with that raw data.
Here is the very basic service worker response code:
self.addEventListener("fetch", async event =>
event.respondWith(caches.match(event.request))
);
This system works fine for HTML, CSS, JS and probably other files, but not for PNGs. I keep getting the image not found image:
I have checked that the correct mime type is being sent and the correct data is stored in cache. I have tried putting the data in cache with the text I find in notepad after opening the PNG, and the text result of a fetch request to an actual PNG file, using the .text() method.
Here are partial images of both:
Notepad++:
Fetch:
This data in the images is put into cache with this code:
cache.put(
rawFileText,
new Response(
"filePath/example.html",
{
status: 200,
headers: new Headers({
"content-type": "image/png" + "; charset=utf-8",
}),
},
),
);
More background info:
This is for a web code editor I am working on. When I want to run code in the editor:
website1 will create an iframe with website2 as source
website1 post messages all the file names, paths, mime types and raw text containing code, images, etc. (by raw data I mean whatever you would see if you opened the file with notepad)
then the iframe (website2) stores the file names and data as cache
when a request is made to any file stored in website2's cache, the service worker responds with whatever data is under the file name
The reason I use 2 different websites is to avoid conflicts with the editor website's files, local storage, and everything else. There could still be conflict with the second website's cache and service worker but that isn't a problem in my case.

Why local file is showing corrupted after downloading using javascript?

Good Afternoon,
Scenario: I am having pdf's file on local system and when user click the button, I want it to get downloaded. But after getting download the file on opening shows corrupted. While posting this query I notice the file which is getting download is of 1KB and original file size is 28KB. I didn't understand why ?
I am creating the excel file at backend and saving at user location as due to huge data it is taking a lot of time so once file is created, the user can download the file.
Below are the codes of JS .
function download() {
var filename="output.pdf";
var element = document.createElement('a');
var fileloc="C:\\ebooks\\PDF\\abc.pdf";
element.setAttribute('href','data:text/plain;charset=utf-8, ' +
encodeURIComponent(fileloc));
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
}
Original file is good. Please correct me what I am doing it wrong .
The data: scheme URL you are creating resolves to a plain text document (not a PDF) containing the text C:\ebooks\PDF\abc.pdf.
You are saving this file with a .pdf extension so when you try to open it, your PDF reader tries to read it as a PDF (which it isn't).
If you want to save the contents of the file at the path you specified then you need to:
Have the user select the file using a <input type="file"> (because JS is not allowed access to files on the user's disk unless they select them explicitly and generating the URL using the FileReader.readAsDataURL() method.
If you are creating the file on the server, as you said, then there is no need to construct a data: scheme URL, you can just use the https: scheme URL that points to the file on the server.

firebase functions upload file from web via stream only partially working

I am trying to create a firebase function that downloads a photo off the web via URL and uploads it to firebase storage.
Using Axios to stream the file to the bucket. it appears the file gets uploaded but i cant download or view it.
This is my code:
let fileURL = 'https://www.example.file.path.png'
let myFile = await axios.get(fileURL, { responseType: 'stream' })
let destFile = bucket.file(photoId).createWriteStream({ contentType: myFile.headers['content-type']})
myFile.data.pipe(destFile)
And here is the storage console from firebase:
I have messed around with the storage api and attempted using the upload and save functions. using axios get and write streams is the closest that I'v got to getting this to work.
Reading the example in the docs only aids in my confusion because the file is never reference in the upload function.. just the file name??
Feel like i'm almost there considering the file or rather the name of the file is there and the size and the type.. just not the content?
This problem is related with Firebase console only. There is no problem with downloading with command: gsutil cp gs://<your bucket>/yourfile . (doc) and as well it is working in Google Cloud Console in Storage browser (direct link).
However indeed file uploaded like this is not possible to be downloaded or previewed with Firebase console.
After many tries I have realized that this is related with custom metadata Access token, which underneath is calledfirebaseStorageDownloadTokens. It appears automatically if ex. you download the file directly in Firebase console.
Anyway I noticed that value of the metadata is irrelevant. According to my test if you change your createWriteStream method parameters to:
let destFile = bucket.file(photoId)
.createWriteStream({
metadata: {
contentType: myFile.headers['content-type'],
metadata: {
firebaseStorageDownloadTokens: 'canBeAnyThing'
}
}
});
The problem disappears...
A file already downloaded to Firebase Storage and affected by the issue can be fixed by adding the same metadata. In the screenshot you have provided you can see "File Location" if you open you will see link "Create new access token" or as well you can add it in GCP Storage Browser adding it manually in "Edit metadata" for such object (remember to refresh FB console in browser).
At this point we can think of why it's looks like this. I have found interesting information in github here.

How to encode image to base64 in TinyMCE?

This is a part of my TinyMCE config:
{
...
plugins: 'code paste',
paste_data_images: true,
...
}
When I add pics via simple drag and drop in TinyMCE, the local images will appear as Blob encoded image.
I want to encode to base64. Can find nothing about it. Only this:
images_upload_handler: function (blobInfo, success, failure) {
success("data:" + blobInfo.blob().type + ";base64," + blobInfo.base64());
}
What can I do?
When those images are sent to the server they are indeed Base64 encoded images. The browser just shows you a blob URL when the content is pasted/dragged into the editor.
If you look at this documentation page it outlines what you can configure TinyMCE to do when images are pasted/dragged into the editor:
https://www.tiny.cloud/docs-4x/advanced/handle-async-image-uploads/
Effectively you need server side code to process the image when TinyMCE sends it to the server. Most people don't need to write their own image handling code for the client side - you can just configure the images_upload_url parameter to tell the editor where to send the file:
https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url
The real work is what do you do with that file once its uploaded - that is server side code you need to write to process the Base64 image and store it on your server. You then return JSON that tells TinyMCE what to put in for the src attribute of the image.
The process for what to do once the image is uploaded is covered here:
https://www.tiny.cloud/docs/advanced/handle-async-image-uploads/#imageuploaderrequirements

Error in uploading file (from public url) to onedrive using REST API

I am getting an when trying to upload a file to Microsoft OneDrive using its REST API. The file is located on another site(MSDN for this example). Is there a way to upload a file(using its full url path) to onedrive without downloading it first?
REST query -
https://apis.live.net/v5.0/me/skydrive/files/fileurl?access_token=mytoken
Error
{ "error": {
"code": "request_url_invalid",
"message": "The URL contains the path 'blogs.msdn.com', which isn't supported." } }
Your client will need to download the URL and then POST/PUT the content to a specific file name. You cannot specify a URL to another resource instead of the name.

Categories

Resources