Apache Cordova File API via Windows Phone - apache

I have tried to use Apache Cordova File Plugin documentation
Here is my code. It just basically goes through all folders into file system.
function log(text) {
var element = document.createElement('div');
element.innerHTML = text;
document.getElementById("log").appendChild(element);
}
function onSuccess(fileSystem) {
function printEntries(entries) {
log("Enter printEntries function");
var i;
log("Number of entries" + entries.length);
for (i = 0; i < entries.length; i++) {
log("Interation number " + i);
if (entries[i].isFile) {
log(entries[i].name);
} else {
log("Moving into subdirectory name: " + entries[i].name);
entries[i].createReader().readEntries(printEntries, fail);
}
}
}
function fail(error) {
log("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(printEntries, fail);
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);
When I deploy my application to the my Lumia I have only this directories:
/
-Shared
---Media
---ShellContent
---Transfers
-debugOutput.txt
-DeviceID.txt
It seams that I have no access to files, that stored on my phone (images, videos).
So, my question is: Is it possible to get files from phone file system and sd card?

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?

How to Push Realm File to Internal Storage in React Native from Application

I am working on a application which ships whole database file shared within React Native Code to user internal storage. For pushing file to internal storage on Android I am using Realm the code we have done work correctly for iOS but for Android I am getting file not found (aka. The Realm is not pushing an file to Internal Storage Android)
Here what I done until now
export default new Realm({
path:Platform.OS === 'ios'
? RNFS.MainBundlePath +'/www/RippleEffect.realm'
: RNFS.DocumentDirectoryPath +'/RippleEffect.realm',
schema: [apply_it,
case_study,
got_it,
got_it_2,
got_it_2_question,
got_it_2_question_answer,
got_it_question,
got_it_question_answer,
howto,
howto_screens,
info,
info_screens,
model,
profile,
profile_result,
profile_statements,
related_topic,
special_assets_table_teens,
topic_audio,
topic_equivalence,
topics,
true_story,
your_mind,
],
readOnly: true
});
Use this two dependency
import Realm from 'realm';
import RNFS from 'react-native-fs'
And In App Class
const App = () => {
Realm.copyBundledRealmFiles();
return (
<App/>
);
};
For those who are working React Native with Realm DB
I solve this issue by pushing realm file from assets folder to internal folder(user mobile ) and thus I was able to read an write about database.
File dbDirectory = new File(MainApplication.getFileDirectory() + "/db");
/**
* Check for database
* directory
*/
if(!dbDirectory.exists()){
if(dbDirectory.mkdirs()){
moveDBFileToCard("database.realm");
}
}
private void moveDBFileToCard(String databaseFileName) {
try{
AssetManager assetsManagerFiles = getAssets();
/**
* Intialize Stream
*/
InputStream inputStream;
OutputStream outputStream;
inputStream = assetsManagerFiles.open(databaseFileName);
System.out.println("File Path = " + MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
File fileDB = new File(MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
if (fileDB.exists()) {
fileDB.delete();
}
outputStream = new FileOutputStream(MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}catch (IOException io){
io.printStackTrace();
}
}
And also removed
readOnly: true from file as it was giving issue to filter quesry on 0.60 version

Sending audio file created with RecordRTC to my server

I am new to working with Javascript, PHP, and with servers generally. I am working on a web page that will record audio from the user and save it to my server, using RecordRTC. I'm a bit confused about the XMLHttpRequest portion - how do I alter the following code to send to my server instead of the webrtc server?
function uploadToServer(recordRTC, callback) {
var blob = recordRTC instanceof Blob ? recordRTC : recordRTC.blob;
var fileType = blob.type.split('/')[0] || 'audio';
var fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + fileType + ' recording to server.');
makeXMLHttpRequest('https://webrtcweb.com/RecordRTC/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
callback('ended', initialURL + fileName);
listOfFilesUploaded.push(initialURL + fileName);
});
}
Via my web hosting provider, I'm using an Apache server, phpMyAdmin, and a mySQL database. Do I just replace
makeXMLHttpRequest(https://webrtcweb.com/RecordRTC/
with "https://mywebsite.com" and replace
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
with the path to the file I created to hold these audio files (https://mywebsite.com/uploads)? Then set permissions for that folder to allow public write capabilities (this seems unsafe, is there a good method)?
This is the makeXMLHttpRequest function:
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback('upload-ended');
}
};
request.upload.onloadstart = function() {
callback('Upload started...');
};
request.upload.onprogress = function(event) {
callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('progress-ended');
};
request.upload.onerror = function(error) {
callback('Failed to upload to server');
console.error('XMLHttpRequest failed', error);
};
request.upload.onabort = function(error) {
callback('Upload aborted.');
console.error('XMLHttpRequest aborted', error);
};
request.open('POST', url);
request.send(data);
}
Please make sure that your PHP server is running top over SSL (HTTPs)
Create a directory and name it uploadFiles
Create a sub-directory and name it uploads
Structure of the directories:
https://server.com/uploadFiles -> to upload files
https://server.com/uploadFiles/uploads -> to store files
index.php
Now create or upload following index.php file on this path: https://server.com/uploadFiles
<?php
// File Name: "index.php"
// via https://github.com/muaz-khan/RecordRTC/tree/master/RecordRTC-to-PHP
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
Why sub-directory?
Nested directory uploads will be used to store your uploaded files. You will get URLs similar to this:
https://server.com/uploadFiles/uploads/filename.webm
Longer file upload issues:
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
upload_max_filesize MUST be 500MB or greater.
max_execution_time MUST be at least 10800 (or greater).
It is recommended to modify php.ini otherwise create .htaccess.
How to link my own server?
Simply replace https://webrtcweb.com/RecordRTC/ with your own URL i.e. https://server.com/uploadFiles/.

PHP 7 SSH2.SFTP stat() bug work around

I have an app the uses an SFTP connection to download files. It was working correctly in PHP 5.6, not so much in PHP 7. The error I get is as follows:
PHP Warning: filesize(): stat failed for ssh2.sftp ...
My code is as follows:
public function retrieveFiles($downloadTargetFolder,$remoteFolder = '.') {
$fileCount = 0;
echo "\nSftpFetcher retrieveFiles\n";
$con = ssh2_connect($this->host,$this->port) or die("Couldn't connect\n");
if($this->pubKeyFile){
$isAuth = ssh2_auth_pubkey_file($con, $this->user, $this->pubKeyFile, $this->privKeyFile);
} else {
$isAuth = ssh2_auth_password($con, $this->user, $this->pass);
};
if ($isAuth) {
$sftp = ssh2_sftp($con);
$rd = "ssh2.sftp://{$sftp}{$remoteFolder}";
if (!$dir = opendir($rd)) {
echo "\nCould not open the remote directory\n";
} else {
$files = array();
while (false != ($file = readdir($dir))) {
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
if (is_array($files)) {
foreach ($files as $remoteFile) {
echo "\ncheck file: $remoteFile vs filter: " . $this->filter."\n";
if ($this->filter !== null && strpos($remoteFile,$this->filter) === false) {
continue;
}
echo "file matched\n";
$localFile = $downloadTargetFolder . DIRECTORY_SEPARATOR . basename($remoteFile);
//$result = ftp_get($con,$localFile,$remoteFile,FTP_BINARY);
$result = true;
// Remote stream
if (!$remoteStream = #fopen($rd."/".$remoteFile, 'r')) {
echo "Unable to open the remote file $remoteFolder/$remoteFile\n";
$return = false;
} else {
// Local stream
if (!$localStream = #fopen($localFile, 'w')) {
echo "Unable to open the local file $localFile\n";
$return = false;
} else {
// Write from our remote stream to our local stream
$read = 0;
$fileSize = filesize($rd."/".$remoteFile);
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
$read += strlen($buffer);
if (fwrite($localStream, $buffer) === FALSE) {
echo "Unable to write the local file $localFile\n";
$return = false;
break;
}
}
echo "File retrieved";
// Close
fclose($localStream);
fclose($remoteStream);
}
}
if ($result) {
$fileCount++;
}
}
}
ssh2_exec($con, 'exit');
unset($con);
}
} else {
echo "Error authenticating the user ".$this->user."\n";
}
return $fileCount;
}
}
After some research I found there was an issue with stat():
http://dougal.gunters.org/blog/2016/01/18/wordpress-php7-and-updates-via-php-ssh2/
https://bugs.php.net/bug.php?id=71376
My question
Is there a workaround to allow me to download via SFTP given my current code or is there another library someone can recommend to use instead?
My PHP version:
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Quoting PHP ssh2.sftp opendir/readdir fix,
Instead of using "ssh2.sftp://$sftp" as a stream path, convert $sftp to an integer like so: "ssh2.sftp://" . intval($sftp) . "/". Then it will work just fine.
The reason for the change is as follows:
PHP 5.6.28 (and apparently 7.0.13) introduced a security fix to URL parsing, that caused the string interpolation of the $sftp resource handle to no-longer be recognized as a valid URL. In turn, that causes opendir(), readdir(), etc. to fail when you use an $sftp resource in the path string, after an upgrade to one of those PHP versions.
As for other libraries... only other library I'm aware of is phpseclib, which has an emulator of sorts for libssh2:
https://github.com/phpseclib/libssh2-compatibility-layer
That "emulator" could certainly be improved upon tho. Like a composer.json file ought to be added, etc.
I had the same issue with php 8.0.
Try putting the filesize command before the fopens.

Access sd card in android for uploading a file to my php server using phonegap

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.
U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}