How to use vimeo-upload in node.js? - javascript

I am going to upload the video to my app of vimeo in Node/Express.
I had googling and found the package to upload the video to the vimeo, it's the vimeo-upload.
But I am not sure how to use it.
Its the format is like following.
var uploader = new VimeoUpload({
file: file,
token: accessToken,
});
uploader.upload();
I got the accesstoken in my project and think file is the binary of video.
The problem is to get the binary from video.
Please help me!

I found the issues of vimeo-upload.js as the API version of vimeo was upgraded.
The function upload() in the vimeo-upload.js, the url was changed like following.
me.prototype.upload = function() {
var xhr = new XMLHttpRequest()
xhr.open(this.httpMethod, this.url, true)
xhr.setRequestHeader('Authorization', 'Bearer ' + this.token)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onload = function(e) {
// get vimeo upload url, user (for available quote), ticket id and complete url
if (e.target.status < 400) {
var response = JSON.parse(e.target.responseText)
this.url = response.upload.upload_link
this.user = response.user
this.ticket_id = response.ticket_id
this.complete_url = defaults.api_url + response.complete_uri
this.sendFile_()
} else {
this.onUploadError_(e)
}
}.bind(this)
xhr.onerror = this.onUploadError_.bind(this)
xhr.send(JSON.stringify({
type: 'streaming',
upgrade_to_1080: this.upgrade_to_1080
}))
}

Related

Is there any ways to send a canvas item by using telegram api?

Is there any possible ways to get my canvas by blob and send it using telegram api directly? I tried to convert the canvas into a url but telegram still cannot send it.
My system is about sending emergency message. When the alarm was triggered, the live graph will be send to a telegram group to notify the members. But what is troubling me is telegram only can send photo by using url or upload from local.
Below is my code example:
exportTelegramPNG(){
const bot = {
TOKEN:"telegram bot token",
chatID:"telegram bot chatID",
}
const filename = this.state.stationRecord["StationName"]+'_'+this.state.currentDate;
html2canvas(document.getElementById(this.chart2.current.chart.container.id)).then(function (canvas) {
if (canvas) {
canvas.toBlob(function (blob) {
const newImg = document.createElement('img');
const url = URL.createObjectURL(blob);
newImg.onload = () => {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
fetch(`https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}&photo=${newImg}`, {
method:"GET"
})
});
}
});
}
Here is the error log in console.
GET https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}&photo=[object%20HTMLImageElement] 400
Thank you for anyone who gives suggestion and helps.
Telegram api only accept either a url to an image or file/image upload. And you can use any blob data for sending without temporary file.
my code worked as below:
exportTelegramPNG(){
const bot = {
TOKEN: "Telegram bot token",
chatID:"telegram bot chatID",
}
html2canvas(document.getElementById(this.chart2.current.chart.container.id)).then(function (canvas) {
if (canvas) {
canvas.toBlob(function (blob) {
var caption = "Report"+'_'+this.state.currentDate;
var formData = new FormData();
formData.append('photo', blob);
formData.append('caption', caption);
var request = new XMLHttpRequest();
request.open('POST', `https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}`);
request.send(formData);
});
}
});
}
Now my code will be able to get the data from live chart and send it to telegram group after I click the button.
Thanks to Graficode and Tural who help me and giving suggestion.
Thank you.
I modified the code a bit to make it work for me.
function sendCanvas(obj) {
const bot = {
TOKEN: '5237151266:AAEqn8j4mRDnXxvcApmHJMzaXRsoIhvGKTY',
chatID:'-1001719430367',
}
var canvas = document.getElementById(obj);
if (canvas) {
canvas.toBlob(function (blob) {
var caption = 'Summary Chart';
var formData = new FormData();
formData.append('photo', blob);
formData.append('caption', caption);
var request = new XMLHttpRequest();
request.open('POST', 'https://api.telegram.org/bot' + bot.TOKEN + '/sendPhoto?chat_id=' + bot.chatID);
request.send(formData);
});
}
}

using SFTP in JSCH to upload files,I want to know how to display the progress about uploading files

my web page have a button to select the files,when the button clicked,it will send files data to webserver,then webserver will build a SFTP service which is built from JSCH,then the files will be sent to remote server.now I want to know how to develop the progress bar.I have already developed the progress bar when files send to web server.I try to develop the progress bar when files send to remote server but i failed. enter image description here
picture one is the process which sends files to webserver.
picture two is the process which sends files to remote server.
enter image description here
// here is code which sends files to webserver.
$(function() {
$('#inputButton').on('click', function() {
var fd = new FormData();
var files_upload_num = document.getElementById('fileToUpload').files.length;
if(files_upload_num == 0)
{
alert('请选择文件,完成上传!');
return;
}
for(let i=0;i<files_upload_num;i++)
fd.append("fileToUpload", document.getElementById('fileToUpload').files[i]);
$.ajax({
url: '<%=path%>/FileCl?method=submitFile',
type: 'post',
data: fd,
processData: false,
contentType: false,
xhr: function() {
var newxhr;
if (window.XMLHttpRequest) {
newxhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
newxhr = new ActiveXObject("Microsoft.XMLHTTP");
}
newxhr.upload.onprogress = function(e) {
console.log(e)
var percent = ( (e.loaded / e.total).toFixed(2) ) * 100 + '%'
$('#progressBar').css('width', percent)
document.getElementById('progressBar').innerHTML = percent;
}
newxhr.addEventListener("load", uploadComplete, false);
newxhr.addEventListener("error", uploadFailed, false);
newxhr.addEventListener("abort", uploadCanceled, false);
return newxhr
},
success: function(res) {
console.log(res)
},
dataType: 'json'
})
})
})
//here is code which sends files to remote server.
JSch jSch = new JSch();
Session jSchSession = null;
ChannelSftp chSftp = null;
jSchSession = jSch.getSession(username, host, port);
jSchSession.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jSchSession.setConfig(config);
jSchSession.setTimeout(1000*10);
jSchSession.connect();
chSftp = (ChannelSftp)jSchSession.openChannel("sftp");
chSftp.connect();
chSftp.setFilenameEncoding("UTF-8");
sftpUtil sftpUtil = new sftpUtil(chSftp);
for (FileItem item : fileItemList) {
String filename = item.getName();
if (filename == null || filename.trim().equals("")) {
continue;
}
String id = UUID.randomUUID().toString().replace("-","");
id = id.substring(0,8);
File saveFile = new File(path,id+filename);
fileNameList.add(id+filename);
sftpUtil.upload("/home/liuyb/uploads",filename,item.getInputStream(),new uploadFileProgressMonitor(item.getSize()));
}

problem while trying to implement a drag and drop direct upload with shrine direct_upload for aws rails 5.2

Code:
image_upload.js
function uploadAttachment(attachment) {
var file = attachment.file;
var form = new FormData;
form.append("Content-Type", file.type);
form.append("forum_post_photo[image]", file);
var xhr = new XMLHttpRequest;
xhr.open("POST", "/forum_post_photos.json", true);
xhr.setRequestHeader("X-CSRF-Token", Rails.csrfToken());
xhr.upload.onprogress = function(event){
var progress = event.loaded / event.total * 100;
attachment.setUploadProgress(progress);
}
xhr.onload = function(){
if (xhr.status == 201){
var data = JSON.parse(xhr.responseText);
return attachment.setAttributes({
url: data.image_url,
href: data.image_url
})
}
}
return xhr.send(form);
}
document.addEventListener("trix-attachment-add", function(event){
var attachment = event.attachment;
if (attachment.file){
console.log('new',attachment);
return uploadAttachment(attachment);
}
});
shrine.rb
require "shrine/storage/s3"
s3_options = {
bucket: Rails.application.credentials.aws[:bucket_name], # required
access_key_id: Rails.application.credentials.aws[:access_key_id],
secret_access_key: Rails.application.credentials.aws[:secret_access_key],
region: Rails.application.credentials.aws[:bucket_region],
}
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: "cache",upload_options: { acl: "public-read" } , **s3_options),
store: Shrine::Storage::S3.new(prefix: "store",upload_options: { acl: "public-read" } ,**s3_options),
}
Shrine.plugin :activerecord
Shrine.plugin :presign_endpoint, presign_options: -> (request) {
filename = request.params["filename"]
type = request.params["type"]
{
content_disposition: "inline; filename=\"#{filename}\"", # set download filename
content_type: type, # set content type (required if using DigitalOcean Spaces)
content_length_range: 0..(10*1024*1024), # limit upload size to 10 MB
}
}
Shrine.plugin :restore_cached_data
trix-upload
require "shrine/storage/s3"
s3_options = {
bucket: Rails.application.credentials.aws[:bucket_name], # required
access_key_id: Rails.application.credentials.aws[:access_key_id],
secret_access_key: Rails.application.credentials.aws[:secret_access_key],
region: Rails.application.credentials.aws[:bucket_region],
}
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: "cache",upload_options: { acl: "public-read" } , **s3_options),
store: Shrine::Storage::S3.new(prefix: "store",upload_options: { acl: "public-read" } ,**s3_options),
}
Shrine.plugin :activerecord
Shrine.plugin :presign_endpoint, presign_options: -> (request) {
filename = request.params["filename"]
type = request.params["type"]
{
content_disposition: "inline; filename=\"#{filename}\"", # set download filename
content_type: type, # set content type (required if using DigitalOcean Spaces)
content_length_range: 0..(10*1024*1024), # limit upload size to 10 MB
}
}
Shrine.plugin :restore_cached_data
trix-upload
function uploadAttachment(attachment) {
var file = attachment.file;
var form = new FormData;
form.append("Content-Type", file.type);
form.append("forum_post_photo[image]", file);
var xhr = new XMLHttpRequest;
xhr.open("POST", "/forum_post_photos.json", true);
xhr.setRequestHeader("X-CSRF-Token", Rails.csrfToken());
xhr.upload.onprogress = function(event){
var progress = event.loaded / event.total * 100;
attachment.setUploadProgress(progress);
}
xhr.onload = function(){
if (xhr.status == 201){
var data = JSON.parse(xhr.responseText);
return attachment.setAttributes({
url: data.image_url,
href: data.image_url
})
}
}
return xhr.send(form);
}
document.addEventListener("trix-attachment-add", function(event){
var attachment = event.attachment;
if (attachment.file){
console.log('new',attachment);
return uploadAttachment(attachment);
}
});
Long story short I am using trix for rich text on a forum, all models and controllers are working, I am attempting to direct_upload on with a drag and drop into the editor as shown here
but can't get the js right.
all other config is set direct from the documentation
Photos are being uploaded to my aws but all are expiring in a few mins
example: https://sprout-free-forum-photos.s3.amazonaws.com/store/de6271df193b0ae16e14c3297c58c363.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAINSUNFHRJEDP6TQA%2F20181027%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181027T192116Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=a4c9da3b5933ca29954dfaf11e592543c69a5a7ad1d4dcd3b70747ef0a695c38
even with my bucket set to public read
any help would be great I am lost!
This is current site live and here is my full git
Experienced this problem today also.
Also using Shrine with AWS S3, and Trix in an old rails app.
What I noticed is that the images are present in the S3 server, its just the URLs that Trix is using that does not work.
After searching some other similar questions, ran into this: https://stackoverflow.com/a/51197576/2561325
The answer there is from one of the maintainer of the shrine gem. All you have to do is apply the public settings in your shrine initializer in config/initializers/shrine.rb.
My problem is fixed now, images used by Trix editor not expiring.

How do i force download Video in AngularJs from Amazon S3?

I have written code to download a video uploaded to amazon s3 using aws javascript sdk. Everything works fine but for some videos open up in the browser and start playing. Here is the code below:
View:
Download Video
Controller:
$scope.downloadVideo = function (video) {
videoLocation = video.video_location;
var bucketPath = videoLocation.substring(0, videoLocation.lastIndexOf("/") + 1);
bucketPath = bucketPath.substring(0, bucketPath.length - 1);
var fileName = videoLocation.substring(videoLocation.lastIndexOf("/") + 1, videoLocation.length);
var videoSignedUrl = VideoFactory.downloadVideo(bucketPath,fileName);
$window.open(videoSignedUrl);
}
VideoFactory :
downloadVideo: function (bucketPath,fileName) {
bucketName = aws.bucket_name;
options = {
accessKeyId : 'XXXXXXXXXXXXXXXXXXXXX',
secretAccessKey : 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
region : 'XXXXXX'
}
var params = {
Bucket: bucketName + '/'+ bucketPath, Key: fileName, Expires: 60
};
var s3 = new AWS.S3(options);
var url = s3.getSignedUrl('getObject', params);
return url;
}
So when videos open up in a new window they start getting downloaded at the bottom of the browsers. But for some unknown videos they open up in a window and start playing. How can i stop this in angularjs. What is the suggested workaround and how do others handle this kind of issues??
I did google but most of the stackoverflow answers here say to open files in window and browsers automatically downloads it.
Try this solution it may help you.enter link description here
View:
Download Video
<a id="ExportToExcel" style="display: none;"></a>
Controller:
$scope.downloadVideo = function (video) {
videoLocation = video.video_location;
var bucketPath = videoLocation.substring(0, videoLocation.lastIndexOf("/") + 1);
bucketPath = bucketPath.substring(0, bucketPath.length - 1);
var fileName = videoLocation.substring(videoLocation.lastIndexOf("/") + 1, videoLocation.length);
var videoSignedUrl = VideoFactory.downloadVideo(bucketPath,fileName);
document.getElementById("ExportToExcel").href = videoSignedUrl;
document.getElementById("ExportToExcel").click();
}
The trick that worked was making the video as an attachment during the video upload to S3 :
options = {
accessKeyId : 'xxxxxxxxxxxxxxxxxxxxxxx',
secretAccessKey : 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
region : 'xxxxxx'
}
var s3 = new AWS.S3(options);
var params = {
Bucket : bucketName + '/' + bucketStructure,
Key: fileName,
ContentType: file.type,
Body: file,
ServerSideEncryption: 'AES256',
ACL : 'private',
ContentDisposition: 'attachment; filename=' + fileName,
ContentType: 'application/octet-stream'
};
s3.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
console.log('AWS Error : '+err.message);
return false;
}
else {
console.log('AWS Video upload done!');
}
})
This would make the video to force download automatically when a signed url was used. Has worked for most of the video mime types for me.

Audio.src and paths in Firefox OS

I'm working on an app for Firefox OS < 1.3 to set your songs as ringtones.
The repo https://github.com/Mte90/RingTone-Picker-for-FirefoxOS and the file with the problem is script.js
In the line https://github.com/Mte90/RingTone-Picker-for-FirefoxOS/blob/master/script.js#L73 the path it's correct like "/emmc/audio.ogg" but the audio player return core error 4.
This problem is for a wrong path but the path is correct!
If i add on the line 74 console.log(player.src) return a path like "app://strangenumberhash/emmc/audio.ogg".
I have no absolutely idea how to fix this problem.
The app protocol is not allowed to be used to reference audio/video files within a packaged app. I believe this is a security restriction is to prevent cross app content reading. You need to either use an audio tag in your HTML or use an XMLHttpRequest. Something like the following (video example):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myvid.ogg');
xhr.responseType = 'blob';
xhr.send();
xhr.onload = function() {
videoblob = new Blob([xhr.response], { type: 'video/ogg' });
var openingVideo = new MozActivity({
name: "open",
data: {
type: [
"video/webm",
"video/mp4",
"video/3gpp",
"video/mkv",
"video/ogg"
],
blob: videoblob
}
});
};
xhr.onerror = function() {
console.log('Error loading test video', xhr.error.name);
};
If the file is on the SDCard you have a couple of options:
One you could just use a pick activity and let the user locate it:
var act = new MozActivity({
name: 'pick',
data: {
type: 'audio/ogg'
}
});
or you can set the readwrite permission on the sdcard in the manifest and read it manually and play it with the audio tag or with a open activity (very little error checking).
var sdcard = navigator.getDeviceStorage('sdcard');
//assumes sample.ogg is located at the top of the sdcard
var request = sdcard.get("sample.ogg");
request.onsuccess = function () {
var file = this.result;
console.log("Get the file: " + file.name);
var mysrc = URL.createObjectURL(file);
var audio1 = new Audio();
audio1.onerror = function(e) {
console.log(" error playing file ");
}
audio1.src = mysrc;
audio1.type = "video/ogg";
console.log( "audio src " + audio1.src);
audio1.play();
URL.revokeObjectURL(url);
}
request.onerror = function () {
console.warn("Unable to get the file: ");
}

Categories

Resources