Audio.src and paths in Firefox OS - javascript

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: ");
}

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);
});
}
}

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 to use vimeo-upload in node.js?

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
}))
}

Cordova - download image from URL to the pictures gallery

I created a simple cordova android app and I am trying to download an image from an URL to the pictures gallery, but I really can't figure out what is going wrong.
I have already searched a lot here in stackoverflow, including the following links:
Phonegap - Save image from url into device photo gallery
How to save an Image object into a file in Android with Phonegap?
I have installed cordova File Transfer plugin and tried to do the example from the official site, but it didn't work too: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/
I tried 2 different codes, which are:
1) First attempt:
document.getElementById("myBtn").addEventListener("click", function () {
download("http://cordova.apache.org/static/img/cordova_bot.png", "data", "new_file");
});
function download(URL, Folder_Name, File_Name) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var download_link = encodeURI(URL);
ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(Folder_Name, {
create: true,
exclusive: false
}, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.toURL();
fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
// Directory created successfuly
}
function onDirectoryFail(error) {
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
alert(evt.target.error.code);
}
}
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
fileTransfer.download(download_link, fp,
function (entry) {
alert("download complete: " + entry.fullPath);
//cordova.plugins.imagesaver.saveImageToGallery(entry.fullPath, successCallback, errorCallback);
},
function (error) {
alert("download error source " + error.source);
}
);
}
In this attempt, I get the alert message "download complete: /my_folder/new_file.png" but I can't find where the picture is downloaded.
It is definitely not in the pictures gallery or anywhere I can find it.
2) Second attempt:
function download() {
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
fs.root.getFile('downloaded-image.png', {
create: true,
exclusive: false
}, function (fileEntry) {
file_transfer(fileEntry, encodeURI(url), true);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function onErrorLoadFs(msg){
alert(msg);
}
function onErrorCreateFile(msg){
alert(msg);
}
function file_transfer(fileEntry, uri, readBinaryData) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
fileTransfer.download(
uri,
fileURL,
function (entry) {
alert("download complete: " + entry.toURL());
if (readBinaryData) {
// Read the file...
readBinaryFile(entry);
} else {
// Or just display it.
displayImageByFileURL(entry);
}
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
In this attempt, I get the alert message "download complete: file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png", but I also can't find the picture anywhere in the device.
I have already tried the application in two different android devices.
This is how I did it.
you will need the cordova file plugin
it wil take a url(png in my case)
and it will save it in your download folder (which makes it apear in the gallery of your phone)
//download file to device
function DownloadToDevice(fileurl) {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", fileurl);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function()
{
blob = xhr.response;//xhr.response is now a blob object
console.log(blob);
var storageLocation = "";
switch (device.platform) {
case "Android":
storageLocation = 'file:///storage/emulated/0/';
break;
case "iOS":
storageLocation = cordova.file.documentsDirectory;
break;
}
var folderpath = storageLocation + "Download";
var filename = "Myimg.png";
var DataBlob = blob;
window.resolveLocalFileSystemURL(folderpath, function(dir) {
dir.getFile(filename, {create:true}, function(file) {
file.createWriter(function(fileWriter) {
fileWriter.write(DataBlob);
//Download was succesfull
}, function(err){
// failed
console.log(err);
});
});
});
}
xhr.send();
}
You should change the line
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024,
->
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
and
if download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.
so i made a plugin ,
It is a plugin that updates the gallery after downloading.
https://github.com/pouu69/cordova-plugin-gallery-refresh
If you are still looking for solution try this working plugin for android
cordova plugin add cordova-plugin-downloadimage-to-gallery
I use this function with callbacks.
To check the different types of cordovaFileSystem see here or check the ones available to you by typing in the console console.log(cordova.file)
downloadFileToDevice('https://example.com/image.jpg', 'myimg.jpg', cordova.file.cacheDirectory,
(err, filePath) => {
if (err) {
console.log('An error was found: ', err)
} else {
console.log('file downloaded successfully to: ' + filePath)
}
})
Function declaration
function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
var blob = null
var xhr = new XMLHttpRequest()
xhr.open('GET', fileurl)
xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
xhr.onload = function () {
blob = xhr.response // xhr.response is now a blob object
var DataBlob = blob
window.resolveLocalFileSystemURL(cordovaFileSystem, function (dir) {
dir.getFile(filename, { create: true }, function (file) {
file.createWriter(function (fileWriter) {
fileWriter.write(DataBlob)
callback(null, cordovaFileSystem + filename)
}, function (err) {
callback(err)
})
})
})
}
xhr.send()
}

How to download multiple files in one shot in IE

I want to download multiple files on click of a button in jsp.
I am using the following code in the js to call one servlet twice.
var iframe = document.createElement("iframe");
iframe.width = iframe.height = iframe.frameBorder = 0;
iframe.scrolling = "no";
iframe.src = "/xyz.jsp?prodId=p10245";
document.getElementById("iframe_holder").appendChild(iframe);
var iframe2 = document.createElement("iframe");
iframe2.width = iframe2.height = iframe2.frameBorder = 0;
iframe2.scrolling = "no";
iframe2.src = "/xyz.jsp?prodId=p10243";
document.getElementById("iframe_holder").appendChild(iframe2);
In xyz.jsp i am calling the servlet which downloads the file from a path and send it on the browser.
Issue is that it is working safari,firefox but not in IE.
We cannot download multiple files with IE?
By design, non-user-initiated file downloads are blocked in IE. That inherently means that it should not be possible to download more than one file as the result of a single user-click.
I've used the following code to download multiple files in IE and Chrome
function downloadFile(url)
{
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function downloadFiles(urls)
{
downloadFile(urls[0]);
if (urls.length > 1)
window.setTimeout(function () { downloadFiles(urls.slice(1)) }, 1000);
}
You pass an array of URLs to the downloadFiles() function, which will call downloadFile() for each with a short delay between. The delay seems to be the key to getting it to work!
I had a similar need but also wanted the downloads to occur in a new window.
I created a js to download a list of files, and a php to do the actual file saving. I used the above as a starting point, and the PHP start from (okay, can't find the original source). I encode the passed URI so spaces in the file names don't cause troubles.
(function () {
"use strict";
var files = [], // Array of filename strings to download
newWindow, // New window to handle the download request
secondsBetweenDownloads; // Wait time beteen downloads in seconds
//
// Download a file using a new window given a URI
//
function downloadFile(uri) {
if (!newWindow) {
newWindow = window.open('',
'',
'width=1500 height=100');
}
if (newWindow) {
newWindow.location =
'saveAs.php?' +
'file_source=' + encodeURI(uri);
newWindow.document.title = "Download File: " + uri;
} else {
console.log("Unable to open new window. Popups blocked?");
}
}
//
// Download all files specified in the files[] array from siteName.
// Download the file at array position zero, then set a timeout for
// secondsBetweenDownloads seconds
//
function downloadFiles(siteName) {
var showTime = new Date();
console.log(
showTime.toTimeString().substring(0,8) +
" Starting download for: " + files[0]
);
// Skip any empty entries, download this file
if (files[0].length > 0) downloadFile(siteName + files.splice(0, 1));
if (files.length > 0) { // If more files in array
window.setTimeout(function () { // Then setup for another iteration
downloadFiles(siteName );
}, secondsBetweenDownloads * 1000); // Delay for n seconds between requests
} else {
newWindow.close(); // Finished, close the download window
}
}
//
// Set the web site name and fill the files[] array with the files to download
// then kick off the download of the files.
//
$(document).ready(function () {
var
siteName** = "http://www.mysteryshows.com/thank-you/";
secondsBetweenDownloads** = 35; // N seconds delay between requests
files = [
"show1.mp3",
"show2.mp3"
];
downloadFiles(siteName, files);
});
}());
The HTML for the page is simple. Basically any syntax-compliant page will do.
The saveAs.php page which the js file uses in the newWindow.location line is php only.
<?php
if (isset($_GET['file_source'])) {
$fullPath = $_GET['file_source'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
// force a download
header("Content-type: application/pdf"); // add here more headers for
// diff. extensions
break;
default;
header("Content-type: **application/octet-stream**");
header("Content-Disposition:
filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
$request = $path_parts["dirname"] . '/' .
rawurlencode($path_parts["basename"]);
readfile($request);
exit;
}
}
?>
I used rawurlencode on just the 'basename' portion of the URI to ensure it was a valid, encoded request.
It can be done by creating a blob using the file source URL. I have tested this with image and PDF files in IE 11.
if (navigator.msSaveBlob) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file_url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
navigator.msSaveBlob(blob, file_name);
}
}
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
xhr.send();
}
I got this idea when I came across this: Getting BLOB data from XHR request

Categories

Resources