React Native : Unable to locate audio file after download - react-native

I'm using react-native-simple-download-manager to download audio files into the app's download folder :
headers = {
Authorization: "Téléchargement"
};
config = {
downloadTitle: `${audio.Title}`,
downloadDescription: "Téléchargement",
saveAsName: audio.Title +'.mp3',
allowedInRoaming: true,
allowedInMetered: true,
showInDownloads: true,
external: false, //when false basically means use the default Download path (version ^1.3)
};
downloadManager
.download((url = audio.FileUrl), (headers = headers), (config = config))
.then(response => {
saveData(audio);
})
.catch(err => {
if(index > -1) {
global.downloadingSongId.splice(index,1);
}
});
I can find the downloaded audio files on the phone, but the player can't read the audio given by the
following path : dirs.DocumentDir + '/Download/' + audio.Title + '.mp3'
And when I use RNFetchBlob to check if the path exists it always return false :
let path = dirs.DocumentDir + '/' + audio.Title + '.mp3';
RNFetchBlob.fs.exists(path);
I really appreciate if anyone could help!

Related

How to download files through development vscode extension on code-server?

I wrote a vscode extension. Now you want to download a file in the vscode working directory by developing extensions. But no files were obtained through vscode vscode.Uri.file.
const downloadPanel = vscode.window.createWebviewPanel(
"view",
"下载",
vscode.ViewColumn.Two,
{
enableScripts: true,
retainContextWhenHidden: true,
}
)
if (vscode.workspace.workspaceFolders === undefined) {
throw new Error("not found!");
}
const filePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
let downloadContent = vscode.commands.registerCommand('download.click', () => {
console.log("filePath = " + filePath);
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, "resources","blockchain.svg")
);
// And get the special URI to use with the webview
const catGifSrc = panel.webview.asWebviewUri(onDiskPath) + "";
getWebviewContent(catGifSrc);
function getWebviewContent(_src: string) {
return '<html><head><script></script></script></head><body><div>download</div></body></html>';
}
When clicking the link, the file is not found! Currently, only nginx proxy can be used for full path downloading. Is there any other plan or solution?

Electron auto updates through amazon s3 not working

I am trying to setup electron auto-updater with amazon s3 bucket. I don't get any errors but when I publish a new version, the auto updater doesn't show any updates on the app screen. But the latest version that has been published shows up in amazon s3 bucket. Below shows how its added:
require('dotenv').config({path: __dirname + '/.env'});
const aws4 = require('aws4');
const pkg = require('./package.json');
const {app, BrowserWindow, Menu, protocol, ipcMain} = require('electron');
const log = require('electron-log');
const {autoUpdater} = require("electron-updater");
autoUpdater.on('checking-for-update', () => {
alert('checking')
console.log('checking for updates')
const opts = {
service: 's3',
region: pkg.build.publish.region,
method: 'GET',
host: `s3-${pkg.build.publish.region}.amazonaws.com`,
path: path.join('/', pkg.build.publish.bucket, latest_yml_path)
};
aws4.sign(opts, {
accessKeyId: 'access key',
secretAccessKey: 'secret access key'
});
// signer.sign(opts); --remove this line --
autoUpdater.requestHeaders = opts.headers
document.getElementById('messages').innerText = "checking for updates"
sendStatusToWindow('Checking for update...');
})
autoUpdater.on('update-available', (info) => {
alert('update available')
sendStatusToWindow('Update available.');
})
autoUpdater.on('update-not-available', (info) => {
sendStatusToWindow('Update not available.');
})
autoUpdater.on('error', (err) => {
sendStatusToWindow('Error in auto-updater. ' + err);
})
autoUpdater.on('download-progress', (progressObj) => {
let log_message = "Download speed: " + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
sendStatusToWindow(log_message);
})
autoUpdater.on('update-downloaded', (info) => {
sendStatusToWindow('Update downloaded');
});
app.on('ready', function() {
// Create the Menu
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
console.log('ready')
createDefaultWindow();
autoUpdater.checkForUpdatesAndNotify();
});
No error shows up, but no messages show up too. Where is it possibly going wrong?
I suggest some tips to you.
check opts.headers' that header is correct. (If request url from aws4 doesn't correct, it is not work.)
setFeedURL after autoUpdater header setting.
when download update package, you change autoUpdater header(and setFeedUrl) for updater package path. Because when checking for updates, you set header about yaml file path to autoUpdater.

Downloading remote image to local device is not listed in the Photo Library

I am developing a React Native application. Now, I am trying to download a remote image into the local device.
This is my code:
downloadFile = () => {
var date = new Date();
var url = 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968';
var ext = this.extention(url);
ext = "." + ext[0];
const { config, fs } = RNFetchBlob
let PictureDir = fs.dirs.PictureDir
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : true,
path: PictureDir + "/image_"+Math.floor(date.getTime() + date.getSeconds() / 2)+ext,
description : 'Image'
}
}
config(options).fetch('GET', url).then((res) => {
Alert.alert("Success Downloaded");
});
}
extention = (filename) => {
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
I am following this tutorial, https://medium.com/#derrybernicahyady/simple-download-file-react-native-2a4db7d51597?fbclid=IwAR1XR75fivHPtE8AfpXKUuFdaLIOehii4ahI4u0lMVgu7ee62yVmnqDnd04. When I run my code, it says the download was successful. But when I checked my photo library, the image is not there. What is wrong with my code?
Use CameraRoll.saveToCameraRoll method for this instead.

Javascript task processing but not updating with new code

I am making edits to my JS files but my gulp task is not updating them live or writing new code. It did used to work but all of a sudden it has stopped.
I tried upgrading the gulp to version 4 but that just created more issues and didn't fix the fact the JS wasn't working.
Added jshint to see if that threw any errors but seems fine too.
'use strict';
const
// source and build folders
dir = {
src : './src/',
build : './'
},
// Gulp and plugins
gulp = require('gulp'),
gutil = require('gulp-util'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
deporder = require('gulp-deporder'),
concat = require('gulp-concat'),
stripdebug = require('gulp-strip-debug'),
uglify = require('gulp-uglify'),
ftp = require( 'vinyl-ftp' ),
jshint = require('gulp-jshint');
// configure the jshint task
gulp.task('jshint', function() {
return gulp.src(dir.src + '/assets/js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Browser-sync
var browsersync = false;
//Dev FTP Connections
function getDevFtpConnection() {
return ftp.create({
host: '109.169.64.171',
// port: 20,
user: 'admin#powdersky.net',
password: '=Lx0$Zf=a}ZW',
parallel: 5,
log: gutil.log
});
}
//Deploy to dev
gulp.task('ftp-deploy-dev', function() {
var conn = getDevFtpConnection();
return gulp.src([dir.build + '/**/**/**/*',
"!./{src/,src/**/*}",
"!./{node_modules/,node_modules/**/**/**/*}",
"!./gulpfile.js",
"!./package-lock.json",
"!./package.json"], { base: '.', buffer: false })
.pipe( conn.newer( '/inthesnow.com/wp-content/themes/inthesnow/' ) ) // only upload newer files
.pipe( conn.dest( '/inthesnow.com/wp-content/themes/inthesnow/' ) )
;
});
// PHP settings
const php = {
src : dir.src + 'templates/**/*.php',
build : dir.build
};
// copy pugins files
gulp.task('php', () => {
return gulp.src([
dir.build + '/includes/**/**/**/*.php',
dir.build + '*.php'
])
.pipe(newer(dir.build))
.pipe(gulp.dest(dir.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
gulp.task('php-templates', () => {
return gulp.src([
dir.build + '*.php'
])
.pipe(newer(dir.build))
.pipe(gulp.dest(dir.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
// image settings
const images = {
src : dir.src + 'assets/images/**/*',
build : dir.build + 'assets/images/'
};
// image processing
gulp.task('images', () => {
return gulp.src(images.src)
.pipe(newer(images.build))
.pipe(imagemin())
.pipe(gulp.dest(images.build));
});
// CSS settings
var css = {
src : dir.src + 'assets/scss/style.scss',
watch : dir.src + 'assets/scss/**/**/*',
build : dir.build,
sassOpts: {
outputStyle : 'compressed',
imagePath : images.build,
precision : 3,
errLogToConsole : true
},
processors: [
require('postcss-assets')({
loadPaths: ['images/'],
basePath: dir.build,
baseUrl: '/wp-content/themes/inthesnow/'
}),
require('autoprefixer')({
browsers: ['last 2 versions', '> 2%']
}),
require('css-mqpacker'),
require('cssnano'),
]
};
// CSS processing
gulp.task('css', ['images'], () => {
return gulp.src([
css.src,
])
.pipe(sass(css.sassOpts))
.pipe(postcss(css.processors))
.pipe(concat('style.css'))
.pipe(gulp.dest(css.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
// Vendor JavaScript settings
const build_vendor_js = {
src : dir.src + 'assets/js/vendor/*',
build : dir.build + 'assets/js/',
filename : 'jquery.vendor.js'
};
// JavaScript processing
gulp.task('build_vendor_js', () => {
return gulp.src(build_vendor_js.src)
.pipe(deporder())
.pipe(concat(build_vendor_js.filename))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest(build_vendor_js.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
// General JavaScript processing
gulp.task('build_general_js', () => {
return gulp.src([
// dir.build + 'includes/plugins/**/assets/js/*.js',
dir.src + 'assets/js/*',
])
.pipe(deporder())
// .pipe(concat('jquery.functions.js'))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest(dir.build + 'assets/js/'))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
// run all tasks
gulp.task('build', ['css', 'build_vendor_js','build_general_js']);
// Browsersync options
const syncOpts = {
proxy : 'http://inthesnow',
reloadOnRestart: true,
ui: {
port: 8080
}
};
// browser-sync
gulp.task('browsersync', () => {
if (browsersync === false) {
browsersync = require('browser-sync').create();
browsersync.init(syncOpts);
}
});
// watch for file changes
gulp.task('watch', ['browsersync'], () => {
// page changes
// gulp.watch(php.src, ['php'], browsersync ? browsersync.reload : {});
// gulp.watch(php.src, ['php-templates'], browsersync ? browsersync.reload : {});
// image changes
gulp.watch(images.src, ['images']);
// CSS changes
gulp.watch(css.watch, ['css']);
// JavaScript main changes
gulp.watch([ dir.src + '/assets/js/*.js' ], ['jshint', 'build_general_js']);
//vendor
gulp.watch(build_vendor_js.src, ['build_vendor_js']);
});
gulp.task('default', ['build', 'watch']);
It seems to be correct to me but obviously not! I am assuming something may have updated that has triggered something but cant find which module it could be, the CSS task runs fine as well.
So this was me being silly, I didn't notice the stripdebug module which is was my alert/console.log wasn't working!
Rookie error

How to continue download multiple files (AWS server images) in background in react-native iOS

I created an app where user can download multiple images on one click using react-native-fs which is working perfectly in Android. But in iOS when app is inactive then download stopped and user have to start download again.
async.eachSeries(DownloadData, async function (tourData, finish) {
console.log("# resumable : 655612", tourData);
var fileExtension = '';
var fileURL = tourData.path;
var fileExtension = "/" + tourData.name + "Image" + p + ".png
p = p + 1;
const downloadDest = RNFS.DocumentDirectoryPath + fileExtension;
let dirs = RNFetchBlob.fs.dirs;
var v = dirs.DocumentDir;
var jobId = -1;
const ret = RNFS.downloadFile({
fromUrl: encodeURI(fileURL),
toFile: downloadDest,
connectionTimeout: 1000 * 10,
readTimeout: 1000 * 10,
background: true,
discretionary: true,
progressDivider: 1,
resumable: (res) => {
console.log("# resumable", res);
},
begin: (res) => {
console.log(res)
},
progress: (data) => {
console.log(data)
},
});
jobId = ret.jobId;
RNFS.isResumable(jobId).then(true);
if (await RNFS.isResumable(jobId)) {
console.log("# resumable : # resumable : # resumable :",jobId);
RNFS.resumeDownload(jobId)
}
ret.promise.then((res) => {
finish();
}).catch(err => {
finish();
})
},function (err) {
if (!err) {
callback(true)
} else {
callback(false)
}
}));
Running download in background in IOS require few extra settings check this section https://github.com/itinance/react-native-fs#background-downloads-tutorial-ios
they also mentioned that IOS will give you 30 sec after handleEventsForBackgroundURLSession
BE AWARE! iOS will give about 30 sec. to run your code after handleEventsForBackgroundURLSession is called and until completionHandler is triggered so don't do anything that might take a long time (like unzipping), you will be able to do it after the user re-launces the app, otherwide iOS will terminate your app.
I hope this helps