New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

cordova-plugin-pvt-file-transfer

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cordova-plugin-pvt-file-transfer - npm Package Compare versions

Comparing version 1.6.3 to 2.0.0

12

package.json
{
"name": "cordova-plugin-pvt-file-transfer",
"version": "1.6.3",
"version": "2.0.0",
"description": "Cordova File Transfer Plugin",

@@ -23,5 +23,4 @@ "types": "./types/index.d.ts",

"scripts": {
"test": "npm run lint && npm run style",
"lint": "jshint www && jshint src && jshint tests",
"style": "jscs tests/tests.js"
"test": "npm run lint",
"lint": "eslint ."
},

@@ -53,3 +52,3 @@ "repository": {

"cordovaDependencies": {
"2.0.0": {
"3.0.0": {
"cordova": ">100"

@@ -60,5 +59,4 @@ }

"devDependencies": {
"jscs": "^2.6.0",
"jshint": "^2.8.0"
"@cordova/eslint-config": "^4.0.0"
}
}

@@ -23,2 +23,13 @@ <!--

### 1.7.1 (Jan 24, 2018)
* [CB-13749](https://issues.apache.org/jira/browse/CB-13749) Add build-tools-26.0.2 to travis
### 1.7.0 (Nov 06, 2017)
* Updated `README` with Deprecated Status
* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again
* [CB-12809](https://issues.apache.org/jira/browse/CB-12809) Google Play Blocker: Unsafe SSL TrustManager Defined
* [CB-7995](https://issues.apache.org/jira/browse/CB-7995) document that `FileTransferError.exception` on **iOS** is never defined.
* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds
* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
### 1.6.3 (Apr 27, 2017)

@@ -309,2 +320,2 @@ * [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder

* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file-transfer to org.apache.cordova.file-transfer and updating dependency
* Rename CHANGELOG.md -> RELEASENOTES.md
* Rename CHANGELOG.md -> RELEASENOTES.md

@@ -20,25 +20,22 @@ /*

*
*/
*/
/*jshint -W030 */
/*global Windows, WinJS*/
/*global module, require*/
/* global Windows, WinJS */
var FTErr = require('./FileTransferError'),
ProgressEvent = require('cordova-plugin-file.ProgressEvent'),
FileUploadResult = require('cordova-plugin-file.FileUploadResult'),
FileProxy = require('cordova-plugin-file.FileProxy');
const FTErr = require('./FileTransferError');
const ProgressEvent = require('cordova-plugin-file.ProgressEvent');
const FileUploadResult = require('cordova-plugin-file.FileUploadResult');
const FileProxy = require('cordova-plugin-file.FileProxy');
var appData = Windows.Storage.ApplicationData.current;
const appData = Windows.Storage.ApplicationData.current;
var LINE_START = "--";
var LINE_END = "\r\n";
var BOUNDARY = '+++++';
const LINE_START = '--';
const LINE_END = '\r\n';
const BOUNDARY = '+++++';
var fileTransferOps = [];
const fileTransferOps = [];
// Some private helper functions, hidden by the module
function cordovaPathToNative(path) {
var cleanPath = String(path);
function cordovaPathToNative (path) {
let cleanPath = String(path);
// turn / into \\

@@ -53,8 +50,8 @@ cleanPath = cleanPath.replace(/\//g, '\\');

function nativePathToCordova(path) {
function nativePathToCordova (path) {
return String(path).replace(/\\/g, '/');
}
function alreadyCancelled(opId) {
var op = fileTransferOps[opId];
function alreadyCancelled (opId) {
const op = fileTransferOps[opId];
return op && op.state === FileTransferOperation.CANCELLED;

@@ -70,3 +67,3 @@ }

// update internal TransferOperation object with newly created promise
var uploadOperation = upload.startAsync();
const uploadOperation = upload.startAsync();
fileTransferOps[uploadId].promise = uploadOperation;

@@ -78,3 +75,3 @@

// since it is not actual anymore
var currentUploadOp = fileTransferOps[uploadId];
const currentUploadOp = fileTransferOps[uploadId];
if (currentUploadOp) {

@@ -85,4 +82,4 @@ currentUploadOp.state = FileTransferOperation.DONE;

var response = result.getResponseInformation();
var ftResult = new FileUploadResult(result.progress.bytesSent, response.statusCode, '');
const response = result.getResponseInformation();
const ftResult = new FileUploadResult(result.progress.bytesSent, response.statusCode, '');

@@ -96,3 +93,3 @@ // if server's response doesn't contain any data, then resolve operation now

// otherwise create a data reader, attached to response stream to get server's response
var reader = new Windows.Storage.Streams.DataReader(result.getResultStreamAt(0));
const reader = new Windows.Storage.Streams.DataReader(result.getResultStreamAt(0));
reader.loadAsync(result.progress.bytesReceived).then(function (size) {

@@ -105,7 +102,7 @@ ftResult.response = reader.readString(size);

function (error) {
var source = nativePathToCordova(filePath);
const source = nativePathToCordova(filePath);
// Handle download error here.
// Wrap this routines into promise due to some async methods
var getTransferError = new WinJS.Promise(function (resolve) {
const getTransferError = new WinJS.Promise(function (resolve) {
if (error.message === 'Canceled') {

@@ -116,9 +113,9 @@ // If download was cancelled, message property will be specified

// in the other way, try to get response property
var response = upload.getResponseInformation();
const response = upload.getResponseInformation();
if (!response) {
resolve(new FTErr(FTErr.CONNECTION_ERR, source, server));
} else {
var reader = new Windows.Storage.Streams.DataReader(upload.getResultStreamAt(0));
const reader = new Windows.Storage.Streams.DataReader(upload.getResultStreamAt(0));
reader.loadAsync(upload.progress.bytesReceived).then(function (size) {
var responseText = reader.readString(size);
const responseText = reader.readString(size);
resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, server, response.statusCode, responseText, error));

@@ -133,3 +130,3 @@ reader.close();

// since it is not actual anymore
var currentUploadOp = fileTransferOps[uploadId];
const currentUploadOp = fileTransferOps[uploadId];
if (currentUploadOp) {

@@ -146,3 +143,3 @@ currentUploadOp.state = FileTransferOperation.CANCELLED;

function (evt) {
var progressEvent = new ProgressEvent('progress', {
const progressEvent = new ProgressEvent('progress', {
loaded: evt.progress.bytesSent,

@@ -158,3 +155,3 @@ total: evt.progress.totalBytesToSend,

function FileTransferOperation(state, promise) {
function FileTransferOperation (state, promise) {
this.state = state;

@@ -168,29 +165,28 @@ this.promise = promise;

var HTTP_E_STATUS_NOT_MODIFIED = -2145844944;
const HTTP_E_STATUS_NOT_MODIFIED = -2145844944;
module.exports = {
/*
exec(win, fail, 'FileTransfer', 'upload',
/*
exec(win, fail, 'FileTransfer', 'upload',
[filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
*/
upload: function (successCallback, errorCallback, options) {
var filePath = options[0];
var server = options[1];
var fileKey = options[2] || 'source';
var fileName = options[3];
var mimeType = options[4];
var params = options[5];
let filePath = options[0];
const server = options[1];
const fileKey = options[2] || 'source';
let fileName = options[3];
let mimeType = options[4];
const params = options[5];
// var trustAllHosts = options[6]; // todo
// var chunkedMode = options[7]; // todo
var headers = options[8] || {};
var uploadId = options[9];
var httpMethod = options[10];
// var chunkedMode = options[7]; // todo
const headers = options[8] || {};
const uploadId = options[9];
const httpMethod = options[10];
var isMultipart = typeof headers["Content-Type"] === 'undefined';
const isMultipart = typeof headers['Content-Type'] === 'undefined';
function stringToByteArray(str) {
var byteCharacters = atob(str);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
function stringToByteArray (str) {
const byteCharacters = atob(str);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);

@@ -201,3 +197,3 @@ }

if (!filePath || (typeof filePath !== 'string')) {
if (!filePath || typeof filePath !== 'string') {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, null, server));

@@ -207,12 +203,12 @@ return;

if (filePath.indexOf("data:") === 0 && filePath.indexOf("base64") !== -1) {
// First a DataWriter object is created, backed by an in-memory stream where
if (filePath.indexOf('data:') === 0 && filePath.indexOf('base64') !== -1) {
// First a DataWriter object is created, backed by an in-memory stream where
// the data will be stored.
var writer = Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream());
const writer = Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream());
writer.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
writer.byteOrder = Windows.Storage.Streams.ByteOrder.littleEndian;
var commaIndex = filePath.indexOf(",");
const commaIndex = filePath.indexOf(',');
if (commaIndex === -1) {
errorCallback(new FTErr(FTErr.INVALID_URL_ERR, fileName, server, null, null, "No comma in data: URI"));
errorCallback(new FTErr(FTErr.INVALID_URL_ERR, fileName, server, null, null, 'No comma in data: URI'));
return;

@@ -224,9 +220,9 @@ }

var fileDataString = filePath.substr(commaIndex + 1);
const fileDataString = filePath.substr(commaIndex + 1);
// setting request headers for uploader
var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
const uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
uploader.method = httpMethod;
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
uploader.setRequestHeader(header, headers[header]);

@@ -238,7 +234,7 @@ }

// adding params supplied to request payload
var multipartParams = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
let multipartParams = '';
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
multipartParams += LINE_START + BOUNDARY + LINE_END;
multipartParams += "Content-Disposition: form-data; name=\"" + key + "\"";
multipartParams += 'Content-Disposition: form-data; name="' + key + '"';
multipartParams += LINE_END + LINE_END;

@@ -250,10 +246,10 @@ multipartParams += params[key];

var multipartFile = LINE_START + BOUNDARY + LINE_END;
multipartFile += "Content-Disposition: form-data; name=\"file\";";
multipartFile += " filename=\"" + fileName + "\"" + LINE_END;
multipartFile += "Content-Type: " + mimeType + LINE_END + LINE_END;
let multipartFile = LINE_START + BOUNDARY + LINE_END;
multipartFile += 'Content-Disposition: form-data; name="file";';
multipartFile += ' filename="' + fileName + '"' + LINE_END;
multipartFile += 'Content-Type: ' + mimeType + LINE_END + LINE_END;
var bound = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
const bound = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
uploader.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
uploader.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + BOUNDARY);
writer.writeString(multipartParams);

@@ -267,55 +263,59 @@ writer.writeString(multipartFile);

var stream;
let stream;
// The call to store async sends the actual contents of the writer
// The call to store async sends the actual contents of the writer
// to the backing stream.
writer.storeAsync().then(function () {
// For the in-memory stream implementation we are using, the flushAsync call
// is superfluous, but other types of streams may require it.
return writer.flushAsync();
}).then(function () {
// We detach the stream to prolong its useful lifetime. Were we to fail
// to detach the stream, the call to writer.close() would close the underlying
// stream, preventing its subsequent use by the DataReader below. Most clients
// of DataWriter will have no reason to use the underlying stream after
// writer.close() is called, and will therefore have no reason to call
// writer.detachStream(). Note that once we detach the stream, we assume
// responsibility for closing the stream subsequently; after the stream
// has been detached, a call to writer.close() will have no effect on the stream.
stream = writer.detachStream();
// Make sure the stream is read from the beginning in the reader
// we are creating below.
stream.seek(0);
// Most DataWriter clients will not call writer.detachStream(),
// and furthermore will be working with a file-backed or network-backed stream,
// rather than an in-memory-stream. In such cases, it would be particularly
// important to call writer.close(). Doing so is always a best practice.
writer.close();
writer
.storeAsync()
.then(function () {
// For the in-memory stream implementation we are using, the flushAsync call
// is superfluous, but other types of streams may require it.
return writer.flushAsync();
})
.then(function () {
// We detach the stream to prolong its useful lifetime. Were we to fail
// to detach the stream, the call to writer.close() would close the underlying
// stream, preventing its subsequent use by the DataReader below. Most clients
// of DataWriter will have no reason to use the underlying stream after
// writer.close() is called, and will therefore have no reason to call
// writer.detachStream(). Note that once we detach the stream, we assume
// responsibility for closing the stream subsequently; after the stream
// has been detached, a call to writer.close() will have no effect on the stream.
stream = writer.detachStream();
// Make sure the stream is read from the beginning in the reader
// we are creating below.
stream.seek(0);
// Most DataWriter clients will not call writer.detachStream(),
// and furthermore will be working with a file-backed or network-backed stream,
// rather than an in-memory-stream. In such cases, it would be particularly
// important to call writer.close(). Doing so is always a best practice.
writer.close();
if (alreadyCancelled(uploadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
return;
}
if (alreadyCancelled(uploadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
return;
}
// create download object. This will throw an exception if URL is malformed
var uri = new Windows.Foundation.Uri(server);
// create download object. This will throw an exception if URL is malformed
const uri = new Windows.Foundation.Uri(server);
var createUploadOperation;
try {
createUploadOperation = uploader.createUploadFromStreamAsync(uri, stream);
} catch (e) {
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
}
let createUploadOperation;
try {
createUploadOperation = uploader.createUploadFromStreamAsync(uri, stream);
} catch (e) {
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
}
createUploadOperation.then(
function (upload) {
doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
},
function (err) {
var errorObj = new FTErr(FTErr.INVALID_URL_ERR);
errorObj.exception = err;
errorCallback(errorObj);
});
});
createUploadOperation.then(
function (upload) {
doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
},
function (err) {
const errorObj = new FTErr(FTErr.INVALID_URL_ERR);
errorObj.exception = err;
errorCallback(errorObj);
}
);
});

@@ -325,11 +325,13 @@ return;

if (filePath.substr(0, 8) === "file:///") {
filePath = appData.localFolder.path + filePath.substr(8).split("/").join("\\");
if (filePath.substr(0, 8) === 'file:///') {
filePath = appData.localFolder.path + filePath.substr(8).split('/').join('\\');
} else if (filePath.indexOf('ms-appdata:///') === 0) {
// Handle 'ms-appdata' scheme
filePath = filePath.replace('ms-appdata:///local', appData.localFolder.path)
.replace('ms-appdata:///temp', appData.temporaryFolder.path);
filePath = filePath
.replace('ms-appdata:///local', appData.localFolder.path)
.replace('ms-appdata:///temp', appData.temporaryFolder.path);
} else if (filePath.indexOf('cdvfile://') === 0) {
filePath = filePath.replace('cdvfile://localhost/persistent', appData.localFolder.path)
.replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
filePath = filePath
.replace('cdvfile://localhost/persistent', appData.localFolder.path)
.replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
}

@@ -343,82 +345,88 @@

Windows.Storage.StorageFile.getFileFromPathAsync(filePath)
.then(function (storageFile) {
Windows.Storage.StorageFile.getFileFromPathAsync(filePath).then(
function (storageFile) {
if (!fileName) {
fileName = storageFile.name;
}
if (!mimeType) {
// use the actual content type of the file, probably this should be the default way.
// other platforms probably can't look this up.
mimeType = storageFile.contentType;
}
if (!fileName) {
fileName = storageFile.name;
}
if (!mimeType) {
// use the actual content type of the file, probably this should be the default way.
// other platforms probably can't look this up.
mimeType = storageFile.contentType;
}
if (alreadyCancelled(uploadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
return;
}
if (alreadyCancelled(uploadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
return;
}
// setting request headers for uploader
var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
uploader.method = httpMethod;
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
uploader.setRequestHeader(header, headers[header]);
// setting request headers for uploader
const uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
uploader.method = httpMethod;
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
uploader.setRequestHeader(header, headers[header]);
}
}
}
// create download object. This will throw an exception if URL is malformed
var uri = new Windows.Foundation.Uri(server);
// create download object. This will throw an exception if URL is malformed
const uri = new Windows.Foundation.Uri(server);
var createUploadOperation;
try {
if (isMultipart) {
// adding params supplied to request payload
var transferParts = [];
for (var key in params) {
// Create content part for params only if value is specified because CreateUploadAsync fails otherwise
if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== undefined && params[key].toString() !== "") {
var contentPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart();
contentPart.setHeader("Content-Disposition", "form-data; name=\"" + key + "\"");
contentPart.setText(params[key]);
transferParts.push(contentPart);
let createUploadOperation;
try {
if (isMultipart) {
// adding params supplied to request payload
const transferParts = [];
for (const key in params) {
// Create content part for params only if value is specified because CreateUploadAsync fails otherwise
if (
Object.prototype.hasOwnProperty.call(params, key) &&
params[key] !== null &&
params[key] !== undefined &&
params[key].toString() !== ''
) {
const contentPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart();
contentPart.setHeader('Content-Disposition', 'form-data; name="' + key + '"');
contentPart.setText(params[key]);
transferParts.push(contentPart);
}
}
}
// Adding file to upload to request payload
var fileToUploadPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(fileKey, fileName);
fileToUploadPart.setHeader("Content-Type", mimeType);
fileToUploadPart.setFile(storageFile);
transferParts.push(fileToUploadPart);
// Adding file to upload to request payload
const fileToUploadPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(fileKey, fileName);
fileToUploadPart.setHeader('Content-Type', mimeType);
fileToUploadPart.setFile(storageFile);
transferParts.push(fileToUploadPart);
createUploadOperation = uploader.createUploadAsync(uri, transferParts);
} else {
createUploadOperation = WinJS.Promise.wrap(uploader.createUpload(uri, storageFile));
createUploadOperation = uploader.createUploadAsync(uri, transferParts);
} else {
createUploadOperation = WinJS.Promise.wrap(uploader.createUpload(uri, storageFile));
}
} catch (e) {
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
}
} catch (e) {
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
createUploadOperation.then(
function (upload) {
doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
},
function (err) {
const errorObj = new FTErr(FTErr.INVALID_URL_ERR);
errorObj.exception = err;
errorCallback(errorObj);
}
);
},
function (err) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, fileName, server, null, null, err));
}
createUploadOperation.then(
function (upload) {
doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
},
function (err) {
var errorObj = new FTErr(FTErr.INVALID_URL_ERR);
errorObj.exception = err;
errorCallback(errorObj);
}
);
}, function (err) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, fileName, server, null, null, err));
});
);
},
// [source, target, trustAllHosts, id, headers]
download:function(successCallback, errorCallback, options) {
var source = options[0];
var target = options[1];
var downloadId = options[3];
var headers = options[4] || {};
download: function (successCallback, errorCallback, options) {
const source = options[0];
let target = options[1];
const downloadId = options[3];
const headers = options[4] || {};

@@ -429,16 +437,18 @@ if (!target) {

}
if (target.substr(0, 8) === "file:///") {
target = appData.localFolder.path + target.substr(8).split("/").join("\\");
if (target.substr(0, 8) === 'file:///') {
target = appData.localFolder.path + target.substr(8).split('/').join('\\');
} else if (target.indexOf('ms-appdata:///') === 0) {
// Handle 'ms-appdata' scheme
target = target.replace('ms-appdata:///local', appData.localFolder.path)
.replace('ms-appdata:///temp', appData.temporaryFolder.path);
target = target
.replace('ms-appdata:///local', appData.localFolder.path)
.replace('ms-appdata:///temp', appData.temporaryFolder.path);
} else if (target.indexOf('cdvfile://') === 0) {
target = target.replace('cdvfile://localhost/persistent', appData.localFolder.path)
.replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
target = target
.replace('cdvfile://localhost/persistent', appData.localFolder.path)
.replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
}
target = cordovaPathToNative(target);
var path = target.substr(0, target.lastIndexOf("\\"));
var fileName = target.substr(target.lastIndexOf("\\") + 1);
const path = target.substr(0, target.lastIndexOf('\\'));
const fileName = target.substr(target.lastIndexOf('\\') + 1);
if (path === null || fileName === null) {

@@ -448,7 +458,7 @@ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR));

}
// Download to a temp file to avoid the file deletion on 304
// Download to a temp file to avoid the file deletion on 304
// CB-7006 Empty file is created on file transfer if server response is 304
var tempFileName = '~' + fileName;
const tempFileName = '~' + fileName;
var download = null;
let download = null;

@@ -458,111 +468,122 @@ // Create internal download operation object

var downloadCallback = function(storageFolder) {
storageFolder.createFileAsync(tempFileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (storageFile) {
const downloadCallback = function (storageFolder) {
storageFolder.createFileAsync(tempFileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(
function (storageFile) {
if (alreadyCancelled(downloadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, source, target));
return;
}
if (alreadyCancelled(downloadId)) {
errorCallback(new FTErr(FTErr.ABORT_ERR, source, target));
return;
}
// if download isn't cancelled, contunue with creating and preparing download operation
const downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
downloader.setRequestHeader(header, headers[header]);
}
}
// if download isn't cancelled, contunue with creating and preparing download operation
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
downloader.setRequestHeader(header, headers[header]);
// create download object. This will throw an exception if URL is malformed
try {
const uri = Windows.Foundation.Uri(source);
download = downloader.createDownload(uri, storageFile);
} catch (e) {
// so we handle this and call errorCallback
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
}
}
// create download object. This will throw an exception if URL is malformed
try {
var uri = Windows.Foundation.Uri(source);
download = downloader.createDownload(uri, storageFile);
} catch (e) {
// so we handle this and call errorCallback
errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
return;
}
const downloadOperation = download.startAsync();
// update internal TransferOperation object with newly created promise
fileTransferOps[downloadId].promise = downloadOperation;
var downloadOperation = download.startAsync();
// update internal TransferOperation object with newly created promise
fileTransferOps[downloadId].promise = downloadOperation;
downloadOperation.then(
function () {
// Update TransferOperation object with new state, delete promise property
// since it is not actual anymore
const currentDownloadOp = fileTransferOps[downloadId];
if (currentDownloadOp) {
currentDownloadOp.state = FileTransferOperation.DONE;
currentDownloadOp.promise = null;
}
downloadOperation.then(function () {
storageFile.renameAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(
function () {
const nativeURI = storageFile.path
.replace(appData.localFolder.path, 'ms-appdata:///local')
.replace(appData.temporaryFolder.path, 'ms-appdata:///temp')
.replace(/\\/g, '/');
// Update TransferOperation object with new state, delete promise property
// since it is not actual anymore
var currentDownloadOp = fileTransferOps[downloadId];
if (currentDownloadOp) {
currentDownloadOp.state = FileTransferOperation.DONE;
currentDownloadOp.promise = null;
}
// Passing null as error callback here because downloaded file should exist in any case
// otherwise the error callback will be hit during file creation in another place
FileProxy.resolveLocalFileSystemURI(successCallback, null, [nativeURI]);
},
function (error) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
}
);
},
function (error) {
const getTransferError = new WinJS.Promise(function (resolve) {
// Handle download error here. If download was cancelled,
// message property will be specified
if (error.message === 'Canceled') {
resolve(new FTErr(FTErr.ABORT_ERR, source, target, null, null, error));
} else if (error && error.number === HTTP_E_STATUS_NOT_MODIFIED) {
resolve(new FTErr(FTErr.NOT_MODIFIED_ERR, source, target, 304, null, error));
} else {
// in the other way, try to get response property
const response = download.getResponseInformation();
if (!response) {
resolve(new FTErr(FTErr.CONNECTION_ERR, source, target));
} else {
if (download.progress.bytesReceived === 0) {
resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, null, error));
return;
}
const reader = new Windows.Storage.Streams.DataReader(download.getResultStreamAt(0));
reader.loadAsync(download.progress.bytesReceived).then(function (bytesLoaded) {
const payload = reader.readString(bytesLoaded);
resolve(
new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, payload, error)
);
});
}
}
});
getTransferError.then(function (fileTransferError) {
// Update TransferOperation object with new state, delete promise property
// since it is not actual anymore
const currentDownloadOp = fileTransferOps[downloadId];
if (currentDownloadOp) {
currentDownloadOp.state = FileTransferOperation.CANCELLED;
currentDownloadOp.promise = null;
}
storageFile.renameAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function () {
var nativeURI = storageFile.path.replace(appData.localFolder.path, 'ms-appdata:///local')
.replace(appData.temporaryFolder.path, 'ms-appdata:///temp')
.replace(/\\/g, '/');
// Passing null as error callback here because downloaded file should exist in any case
// otherwise the error callback will be hit during file creation in another place
FileProxy.resolveLocalFileSystemURI(successCallback, null, [nativeURI]);
}, function(error) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
});
}, function(error) {
var getTransferError = new WinJS.Promise(function (resolve) {
// Handle download error here. If download was cancelled,
// message property will be specified
if (error.message === 'Canceled') {
resolve(new FTErr(FTErr.ABORT_ERR, source, target, null, null, error));
} else if (error && error.number === HTTP_E_STATUS_NOT_MODIFIED) {
resolve(new FTErr(FTErr.NOT_MODIFIED_ERR, source, target, 304, null, error));
} else {
// in the other way, try to get response property
var response = download.getResponseInformation();
if (!response) {
resolve(new FTErr(FTErr.CONNECTION_ERR, source, target));
} else {
var reader = new Windows.Storage.Streams.DataReader(download.getResultStreamAt(0));
reader.loadAsync(download.progress.bytesReceived).then(function (bytesLoaded) {
var payload = reader.readString(bytesLoaded);
resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, payload, error));
// Cleanup, remove incompleted file
storageFile.deleteAsync().then(function () {
errorCallback(fileTransferError);
});
}
}
});
getTransferError.then(function (fileTransferError) {
});
},
function (evt) {
const progressEvent = new ProgressEvent('progress', {
loaded: evt.progress.bytesReceived,
total: evt.progress.totalBytesToReceive,
target: evt.resultFile
});
// when bytesReceived == 0, BackgroundDownloader has not yet differentiated whether it could get file length or not,
// when totalBytesToReceive == 0, BackgroundDownloader is unable to get file length
progressEvent.lengthComputable = evt.progress.bytesReceived > 0 && evt.progress.totalBytesToReceive > 0;
// Update TransferOperation object with new state, delete promise property
// since it is not actual anymore
var currentDownloadOp = fileTransferOps[downloadId];
if (currentDownloadOp) {
currentDownloadOp.state = FileTransferOperation.CANCELLED;
currentDownloadOp.promise = null;
successCallback(progressEvent, { keepCallback: true });
}
// Cleanup, remove incompleted file
storageFile.deleteAsync().then(function() {
errorCallback(fileTransferError);
});
});
}, function(evt) {
var progressEvent = new ProgressEvent('progress', {
loaded: evt.progress.bytesReceived,
total: evt.progress.totalBytesToReceive,
target: evt.resultFile
});
// when bytesReceived == 0, BackgroundDownloader has not yet differentiated whether it could get file length or not,
// when totalBytesToReceive == 0, BackgroundDownloader is unable to get file length
progressEvent.lengthComputable = (evt.progress.bytesReceived > 0) && (evt.progress.totalBytesToReceive > 0);
successCallback(progressEvent, { keepCallback: true });
});
}, function(error) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
});
);
},
function (error) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
}
);
};
var fileNotFoundErrorCallback = function(error) {
const fileNotFoundErrorCallback = function (error) {
errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));

@@ -574,6 +595,6 @@ };

if (error.number === -2147024894) {
var parent = path.substr(0, path.lastIndexOf('\\')),
folderNameToCreate = path.substr(path.lastIndexOf('\\') + 1);
const parent = path.substr(0, path.lastIndexOf('\\'));
const folderNameToCreate = path.substr(path.lastIndexOf('\\') + 1);
Windows.Storage.StorageFolder.getFolderFromPathAsync(parent).then(function(parentFolder) {
Windows.Storage.StorageFolder.getFolderFromPathAsync(parent).then(function (parentFolder) {
parentFolder.createFolderAsync(folderNameToCreate).then(downloadCallback, fileNotFoundErrorCallback);

@@ -588,6 +609,6 @@ }, fileNotFoundErrorCallback);

abort: function (successCallback, error, options) {
var fileTransferOpId = options[0];
const fileTransferOpId = options[0];
// Try to find transferOperation with id specified, and cancel its' promise
var currentOp = fileTransferOps[fileTransferOpId];
const currentOp = fileTransferOps[fileTransferOpId];
if (currentOp) {

@@ -601,5 +622,4 @@ currentOp.state = FileTransferOperation.CANCELLED;

}
};
require("cordova/exec/proxy").add("FileTransfer",module.exports);
require('cordova/exec/proxy').add('FileTransfer', module.exports);
#!/usr/bin/env node
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var path = require('path');
var fs = require('fs');
const path = require('path');
const fs = require('fs');
module.exports = function(context) {
function main() {
module.exports = function (context) {
function main () {
// get the file transfer server address from the specified variables
var fileTransferServerAddress = getFileTransferServerAddress(context) || getDefaultFileTransferServerAddress(context);
const fileTransferServerAddress = getFileTransferServerAddress(context) || getDefaultFileTransferServerAddress(context);
console.log('Tests will use the following file transfer server address: ' + fileTransferServerAddress);
console.log('If you\'re using cordova@6.3.1 and the above address is wrong at "platform add", don\'t worry, it\'ll fix itself on "cordova run" or "cordova prepare".');
console.log(
'If you\'re using cordova@6.3.1 and the above address is wrong at "platform add", don\'t worry, it\'ll fix itself on "cordova run" or "cordova prepare".'
);

@@ -38,8 +40,8 @@ // pass it to the tests

function getDefaultFileTransferServerAddress(context) {
var address = null;
var configNodes = context.opts.plugin.pluginInfo._et._root._children;
function getDefaultFileTransferServerAddress (context) {
let address = null;
const configNodes = context.opts.plugin.pluginInfo._et._root._children;
for (var node in configNodes) {
if (configNodes[node].attrib.name == 'FILETRANSFER_SERVER_ADDRESS') {
for (const node in configNodes) {
if (configNodes[node].attrib.name === 'FILETRANSFER_SERVER_ADDRESS') {
address = configNodes[node].attrib.default;

@@ -52,7 +54,17 @@ }

function getFileTransferServerAddress(context) {
var platformJsonFile = path.join(context.opts.projectRoot, 'platforms', context.opts.platforms[0], context.opts.platforms[0] + '.json');
var platformJson = JSON.parse(fs.readFileSync(platformJsonFile, 'utf8'));
function getFileTransferServerAddress (context) {
const platformJsonFile = path.join(
context.opts.projectRoot,
'platforms',
context.opts.platforms[0],
context.opts.platforms[0] + '.json'
);
const platformJson = JSON.parse(fs.readFileSync(platformJsonFile, 'utf8'));
if (platformJson && platformJson.installed_plugins && platformJson.installed_plugins['cordova-plugin-file-transfer-tests'] && platformJson.installed_plugins['cordova-plugin-file-transfer-tests'].FILETRANSFER_SERVER_ADDRESS) {
if (
platformJson &&
platformJson.installed_plugins &&
platformJson.installed_plugins['cordova-plugin-file-transfer-tests'] &&
platformJson.installed_plugins['cordova-plugin-file-transfer-tests'].FILETRANSFER_SERVER_ADDRESS
) {
return platformJson.installed_plugins['cordova-plugin-file-transfer-tests'].FILETRANSFER_SERVER_ADDRESS;

@@ -64,9 +76,9 @@ } else {

function writeFileTransferOptions(address, context) {
for (var p in context.opts.paths) {
var ftOpts = {
function writeFileTransferOptions (address, context) {
for (const p in context.opts.paths) {
const ftOpts = {
serverAddress: address
};
var ftOptsString = JSON.stringify(ftOpts);
var ftOptsFile = path.join(context.opts.paths[p], 'fileTransferOpts.json');
const ftOptsString = JSON.stringify(ftOpts);
const ftOptsFile = path.join(context.opts.paths[p], 'fileTransferOpts.json');
fs.writeFileSync(ftOptsFile, ftOptsString, 'utf8');

@@ -77,3 +89,2 @@ }

main();
};
};

@@ -20,22 +20,22 @@ /*

*
*/
*/
/*global module, require*/
/* global FileUploadResult */
var argscheck = require('cordova/argscheck'),
FileTransferError = require('./FileTransferError');
const argscheck = require('cordova/argscheck');
const FileTransferError = require('./FileTransferError');
function getParentPath(filePath) {
var pos = filePath.lastIndexOf('/');
function getParentPath (filePath) {
const pos = filePath.lastIndexOf('/');
return filePath.substring(0, pos + 1);
}
function getFileName(filePath) {
var pos = filePath.lastIndexOf('/');
function getFileName (filePath) {
const pos = filePath.lastIndexOf('/');
return filePath.substring(pos + 1);
}
function getUrlCredentials(urlString) {
var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
credentials = credentialsPattern.exec(urlString);
function getUrlCredentials (urlString) {
const credentialsPattern = /^https?:\/\/(?:(?:(([^:@/]*)(?::([^@/]*))?)?@)?([^:/?#]*)(?::(\d*))?).*$/;
const credentials = credentialsPattern.exec(urlString);

@@ -45,6 +45,5 @@ return credentials && credentials[1];

function getBasicAuthHeader(urlString) {
var header = null;
function getBasicAuthHeader (urlString) {
let header = null;
// This is changed due to MS Windows doesn't support credentials in http uris

@@ -55,10 +54,10 @@ // so we detect them by regexp and strip off from result url

if (window.btoa) {
var credentials = getUrlCredentials(urlString);
const credentials = getUrlCredentials(urlString);
if (credentials) {
var authHeader = "Authorization";
var authHeaderValue = "Basic " + window.btoa(credentials);
const authHeader = 'Authorization';
const authHeaderValue = 'Basic ' + window.btoa(credentials);
header = {
name : authHeader,
value : authHeaderValue
name: authHeader,
value: authHeaderValue
};

@@ -71,9 +70,9 @@ }

function checkURL(url) {
return url.indexOf(' ') === -1 ? true : false;
function checkURL (url) {
return url.indexOf(' ') === -1;
}
var idCounter = 0;
let idCounter = 0;
var transfers = {};
const transfers = {};

@@ -84,3 +83,3 @@ /**

*/
var FileTransfer = function() {
const FileTransfer = function () {
this._id = ++idCounter;

@@ -100,3 +99,3 @@ this.onprogress = null; // optional callback

*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options) {
FileTransfer.prototype.upload = function (filePath, server, successCallback, errorCallback, options) {
// check for arguments

@@ -116,12 +115,12 @@ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);

var fileKey = options.fileKey || "file";
var fileName = options.fileName || "image.jpg";
var mimeType = options.mimeType || "image/jpeg";
var params = options.params || {};
var withCredentials = options.withCredentials || false;
const fileKey = options.fileKey || 'file';
const fileName = options.fileName || 'image.jpg';
const mimeType = options.mimeType || 'image/jpeg';
const params = options.params || {};
const withCredentials = options.withCredentials || false;
// var chunkedMode = !!options.chunkedMode; // Not supported
var headers = options.headers || {};
var httpMethod = options.httpMethod && options.httpMethod.toUpperCase() === "PUT" ? "PUT" : "POST";
const headers = options.headers || {};
const httpMethod = options.httpMethod && options.httpMethod.toUpperCase() === 'PUT' ? 'PUT' : 'POST';
var basicAuthHeader = getBasicAuthHeader(server);
const basicAuthHeader = getBasicAuthHeader(server);
if (basicAuthHeader) {

@@ -132,88 +131,98 @@ server = server.replace(getUrlCredentials(server) + '@', '');

var that = this;
var xhr = transfers[this._id] = new XMLHttpRequest();
const that = this;
const xhr = (transfers[this._id] = new XMLHttpRequest());
xhr.withCredentials = withCredentials;
var fail = errorCallback && function(code, status, response) {
if (transfers[this._id]) {
delete transfers[this._id];
}
var error = new FileTransferError(code, filePath, server, status, response);
if (errorCallback) {
errorCallback(error);
}
};
const fail =
errorCallback &&
function (code, status, response) {
if (transfers[this._id]) {
delete transfers[this._id];
}
const error = new FileTransferError(code, filePath, server, status, response);
if (errorCallback) {
errorCallback(error);
}
};
window.resolveLocalFileSystemURL(filePath, function(entry) {
entry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function() {
var blob = new Blob([this.result], {type: mimeType});
window.resolveLocalFileSystemURL(
filePath,
function (entry) {
entry.file(
function (file) {
const reader = new FileReader();
reader.onloadend = function () {
const blob = new Blob([this.result], { type: mimeType });
// Prepare form data to send to server
var fd = new FormData();
fd.append(fileKey, blob, fileName);
for (var prop in params) {
if (params.hasOwnProperty(prop)) {
fd.append(prop, params[prop]);
}
}
// Prepare form data to send to server
const fd = new FormData();
fd.append(fileKey, blob, fileName);
for (const prop in params) {
if (Object.prototype.hasOwnProperty.call(params, prop)) {
fd.append(prop, params[prop]);
}
}
xhr.open(httpMethod, server);
xhr.open(httpMethod, server);
// Fill XHR headers
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
// Fill XHR headers
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
xhr.onload = function() {
if (this.status === 200) {
var result = new FileUploadResult(); // jshint ignore:line
result.bytesSent = blob.size;
result.responseCode = this.status;
result.response = this.response;
delete transfers[that._id];
successCallback(result);
} else if (this.status === 404) {
fail(FileTransferError.INVALID_URL_ERR, this.status, this.response);
} else {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
}
};
xhr.onload = function () {
// 2xx codes are valid
if (this.status >= 200 && this.status < 300) {
const result = new FileUploadResult();
result.bytesSent = blob.size;
result.responseCode = this.status;
result.response = this.response;
delete transfers[that._id];
successCallback(result);
} else if (this.status === 404) {
fail(FileTransferError.INVALID_URL_ERR, this.status, this.response);
} else {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
}
};
xhr.ontimeout = function() {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
};
xhr.ontimeout = function () {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
};
xhr.onerror = function() {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
};
xhr.onerror = function () {
fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
};
xhr.onabort = function () {
fail(FileTransferError.ABORT_ERR, this.status, this.response);
};
xhr.onabort = function () {
fail(FileTransferError.ABORT_ERR, this.status, this.response);
};
xhr.upload.onprogress = function (e) {
if (that.onprogress) {
that.onprogress(e);
}
};
xhr.upload.onprogress = function (e) {
if (that.onprogress) {
that.onprogress(e);
}
};
xhr.send(fd);
// Special case when transfer already aborted, but XHR isn't sent.
// In this case XHR won't fire an abort event, so we need to check if transfers record
// isn't deleted by filetransfer.abort and if so, call XHR's abort method again
if (!transfers[that._id]) {
xhr.abort();
xhr.send(fd);
// Special case when transfer already aborted, but XHR isn't sent.
// In this case XHR won't fire an abort event, so we need to check if transfers record
// isn't deleted by filetransfer.abort and if so, call XHR's abort method again
if (!transfers[that._id]) {
xhr.abort();
}
};
reader.readAsArrayBuffer(file);
},
function () {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
}
};
reader.readAsArrayBuffer(file);
}, function() {
);
},
function () {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
});
}, function() {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
});
}
);
};

@@ -230,3 +239,3 @@

*/
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
FileTransfer.prototype.download = function (source, target, successCallback, errorCallback, trustAllHosts, options) {
argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);

@@ -244,7 +253,7 @@

options = options || {};
var headers = options.headers || {};
var withCredentials = options.withCredentials || false;
var basicAuthHeader = getBasicAuthHeader(source);
const headers = options.headers || {};
const withCredentials = options.withCredentials || false;
const basicAuthHeader = getBasicAuthHeader(source);
if (basicAuthHeader) {

@@ -255,54 +264,64 @@ source = source.replace(getUrlCredentials(source) + '@', '');

var that = this;
var xhr = transfers[this._id] = new XMLHttpRequest();
const that = this;
const xhr = (transfers[this._id] = new XMLHttpRequest());
xhr.withCredentials = withCredentials;
var fail = errorCallback && function(code, status, response) {
if (transfers[that._id]) {
delete transfers[that._id];
}
// In XHR GET reqests we're setting response type to Blob
// but in case of error we need to raise event with plain text response
if (response instanceof Blob) {
var reader = new FileReader();
reader.readAsText(response);
reader.onloadend = function(e) {
var error = new FileTransferError(code, source, target, status, e.target.result);
const fail =
errorCallback &&
function (code, status, response) {
if (transfers[that._id]) {
delete transfers[that._id];
}
// In XHR GET reqests we're setting response type to Blob
// but in case of error we need to raise event with plain text response
if (response instanceof Blob) {
const reader = new FileReader();
reader.readAsText(response);
reader.onloadend = function (e) {
const error = new FileTransferError(code, source, target, status, e.target.result);
errorCallback(error);
};
} else {
const error = new FileTransferError(code, source, target, status, response);
errorCallback(error);
};
} else {
var error = new FileTransferError(code, source, target, status, response);
errorCallback(error);
}
};
}
};
xhr.onload = function (e) {
var fileNotFound = function () {
const fileNotFound = function () {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
};
var req = e.target;
const req = e.target;
// req.status === 0 is special case for local files with file:// URI scheme
if ((req.status === 200 || req.status === 0) && req.response) {
window.resolveLocalFileSystemURL(getParentPath(target), function (dir) {
dir.getFile(getFileName(target), {create: true}, function writeFile(entry) {
entry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (evt) {
if (!evt.target.error) {
entry.filesystemName = entry.filesystem.name;
delete transfers[that._id];
if (successCallback) {
successCallback(entry);
}
} else {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
}
};
fileWriter.onerror = function () {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
};
fileWriter.write(req.response);
}, fileNotFound);
}, fileNotFound);
}, fileNotFound);
window.resolveLocalFileSystemURL(
getParentPath(target),
function (dir) {
dir.getFile(
getFileName(target),
{ create: true },
function writeFile (entry) {
entry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (evt) {
if (!evt.target.error) {
entry.filesystemName = entry.filesystem.name;
delete transfers[that._id];
if (successCallback) {
successCallback(entry);
}
} else {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
}
};
fileWriter.onerror = function () {
fail(FileTransferError.FILE_NOT_FOUND_ERR);
};
fileWriter.write(req.response);
}, fileNotFound);
},
fileNotFound
);
},
fileNotFound
);
} else if (req.status === 404) {

@@ -329,6 +348,6 @@ fail(FileTransferError.INVALID_URL_ERR, req.status, req.response);

xhr.open("GET", source, true);
xhr.open('GET', source, true);
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
xhr.setRequestHeader(header, headers[header]);

@@ -338,3 +357,3 @@ }

xhr.responseType = "blob";
xhr.responseType = 'blob';

@@ -348,3 +367,3 @@ xhr.send();

*/
FileTransfer.prototype.abort = function() {
FileTransfer.prototype.abort = function () {
if (this instanceof FileTransfer) {

@@ -358,2 +377,2 @@ if (transfers[this._id]) {

module.exports = FileTransfer;
module.exports = FileTransfer;

@@ -20,13 +20,13 @@ /*

*
*/
*/
/* global cordova, FileSystem */
var argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
FileTransferError = require('./FileTransferError'),
ProgressEvent = require('cordova-plugin-file.ProgressEvent');
const argscheck = require('cordova/argscheck');
const exec = require('cordova/exec');
const FileTransferError = require('./FileTransferError');
const ProgressEvent = require('cordova-plugin-file.ProgressEvent');
function newProgressEvent(result) {
var pe = new ProgressEvent();
function newProgressEvent (result) {
const pe = new ProgressEvent();
pe.lengthComputable = result.lengthComputable;

@@ -38,5 +38,5 @@ pe.loaded = result.loaded;

function getUrlCredentials(urlString) {
var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
credentials = credentialsPattern.exec(urlString);
function getUrlCredentials (urlString) {
const credentialsPattern = /^https?:\/\/(?:(?:(([^:@/]*)(?::([^@/]*))?)?@)?([^:/?#]*)(?::(\d*))?).*$/;
const credentials = credentialsPattern.exec(urlString);

@@ -46,6 +46,5 @@ return credentials && credentials[1];

function getBasicAuthHeader(urlString) {
var header = null;
function getBasicAuthHeader (urlString) {
let header = null;
// This is changed due to MS Windows doesn't support credentials in http uris

@@ -56,10 +55,10 @@ // so we detect them by regexp and strip off from result url

if (window.btoa) {
var credentials = getUrlCredentials(urlString);
const credentials = getUrlCredentials(urlString);
if (credentials) {
var authHeader = "Authorization";
var authHeaderValue = "Basic " + window.btoa(credentials);
const authHeader = 'Authorization';
const authHeaderValue = 'Basic ' + window.btoa(credentials);
header = {
name : authHeader,
value : authHeaderValue
name: authHeader,
value: authHeaderValue
};

@@ -72,7 +71,7 @@ }

function convertHeadersToArray(headers) {
var result = [];
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
var headerValue = headers[header];
function convertHeadersToArray (headers) {
const result = [];
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
const headerValue = headers[header];
result.push({

@@ -87,3 +86,3 @@ name: header,

var idCounter = 0;
let idCounter = 0;

@@ -94,3 +93,3 @@ /**

*/
var FileTransfer = function() {
const FileTransfer = function () {
this._id = ++idCounter;

@@ -101,22 +100,22 @@ this.onprogress = null; // optional callback

/**
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String} Full path of the file on the device
* @param server {String} URL of the server to receive the file
* @param successCallback (Function} Callback to be invoked when upload has completed
* @param errorCallback {Function} Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String} Full path of the file on the device
* @param server {String} URL of the server to receive the file
* @param successCallback (Function} Callback to be invoked when upload has completed
* @param errorCallback {Function} Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
*/
FileTransfer.prototype.upload = function (filePath, server, successCallback, errorCallback, options, trustAllHosts) {
argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
// check for options
var fileKey = null;
var fileName = null;
var mimeType = null;
var params = null;
var chunkedMode = true;
var headers = null;
var httpMethod = null;
var basicAuthHeader = getBasicAuthHeader(server);
let fileKey = null;
let fileName = null;
let mimeType = null;
let params = null;
let chunkedMode = true;
let headers = null;
let httpMethod = null;
const basicAuthHeader = getBasicAuthHeader(server);
if (basicAuthHeader) {

@@ -135,9 +134,9 @@ server = server.replace(getUrlCredentials(server) + '@', '');

headers = options.headers;
httpMethod = options.httpMethod || "POST";
if (httpMethod.toUpperCase() == "PUT"){
httpMethod = "PUT";
httpMethod = options.httpMethod || 'POST';
if (httpMethod.toUpperCase() === 'PUT') {
httpMethod = 'PUT';
} else {
httpMethod = "POST";
httpMethod = 'POST';
}
if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
if (options.chunkedMode !== null || typeof options.chunkedMode !== 'undefined') {
chunkedMode = options.chunkedMode;

@@ -147,4 +146,3 @@ }

params = options.params;
}
else {
} else {
params = {};

@@ -154,3 +152,3 @@ }

if (cordova.platformId === "windowsphone") {
if (cordova.platformId === 'windowsphone') {
headers = headers && convertHeadersToArray(headers);

@@ -160,10 +158,12 @@ params = params && convertHeadersToArray(params);

var fail = errorCallback && function(e) {
var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
errorCallback(error);
};
const fail =
errorCallback &&
function (e) {
const error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
errorCallback(error);
};
var self = this;
var win = function(result) {
if (typeof result.lengthComputable != "undefined") {
const self = this;
const win = function (result) {
if (typeof result.lengthComputable !== 'undefined') {
if (self.onprogress) {

@@ -178,3 +178,15 @@ self.onprogress(newProgressEvent(result));

};
exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
exec(win, fail, 'FileTransfer', 'upload', [
filePath,
server,
fileKey,
fileName,
mimeType,
params,
trustAllHosts,
chunkedMode,
headers,
this._id,
httpMethod
]);
};

@@ -191,7 +203,7 @@

*/
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
FileTransfer.prototype.download = function (source, target, successCallback, errorCallback, trustAllHosts, options) {
argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
var self = this;
const self = this;
var basicAuthHeader = getBasicAuthHeader(source);
const basicAuthHeader = getBasicAuthHeader(source);
if (basicAuthHeader) {

@@ -205,3 +217,3 @@ source = source.replace(getUrlCredentials(source) + '@', '');

var headers = null;
let headers = null;
if (options) {

@@ -211,8 +223,8 @@ headers = options.headers || null;

if (cordova.platformId === "windowsphone" && headers) {
if (cordova.platformId === 'windowsphone' && headers) {
headers = convertHeadersToArray(headers);
}
var win = function(result) {
if (typeof result.lengthComputable != "undefined") {
const win = function (result) {
if (typeof result.lengthComputable !== 'undefined') {
if (self.onprogress) {

@@ -222,7 +234,6 @@ return self.onprogress(newProgressEvent(result));

} else if (successCallback) {
var entry = null;
let entry = null;
if (result.isDirectory) {
entry = new (require('cordova-plugin-file.DirectoryEntry'))();
}
else if (result.isFile) {
} else if (result.isFile) {
entry = new (require('cordova-plugin-file.FileEntry'))();

@@ -234,3 +245,5 @@ }

entry.fullPath = result.fullPath;
entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
entry.filesystem = new FileSystem(
result.filesystemName || (result.filesystem === window.PERSISTENT ? 'persistent' : 'temporary')
);
entry.nativeURL = result.nativeURL;

@@ -241,6 +254,8 @@ successCallback(entry);

var fail = errorCallback && function(e) {
var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
errorCallback(error);
};
const fail =
errorCallback &&
function (e) {
const error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
errorCallback(error);
};

@@ -254,6 +269,6 @@ exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);

*/
FileTransfer.prototype.abort = function() {
FileTransfer.prototype.abort = function () {
exec(null, null, 'FileTransfer', 'abort', [this._id]);
};
module.exports = FileTransfer;
module.exports = FileTransfer;

@@ -20,3 +20,3 @@ /*

*
*/
*/

@@ -27,3 +27,3 @@ /**

*/
var FileTransferError = function(code, source, target, status, body, exception) {
const FileTransferError = function (code, source, target, status, body, exception) {
this.code = code || null;

@@ -43,2 +43,2 @@ this.source = source || null;

module.exports = FileTransferError;
module.exports = FileTransferError;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc