Skip to content

TagSpaces is an offline, open source, document manager with tagging support

TSN-355 Android download button from S3 (#1164)

Stanimir5091e7e320f1
diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsx
index 06436d157..7a5d49e24 100644
--- a/app/components/EntryContainer.tsx
+++ b/app/components/EntryContainer.tsx
@@ -72,8 +72,8 @@ import {
} from '-/reducers/app';
const defaultSplitSize = 103;
-const openedSplitSize = 360;
-const fullSplitSize = 600;
+const openedSplitSize = AppConfig.isElectron ? 560 : 360;
+const fullSplitSize = 750;
// const maxCharactersTitleLength = 50;
const bufferedSplitResize = buffer({
timeout: 300,
@@ -128,8 +128,8 @@ const styles: any = (theme: any) => ({
flexDirection: 'row',
flex: '1 1',
display: 'flex',
- overflowX: 'auto',
- marginRight: 100
+ overflowX: 'auto'
+ // marginRight: 100
},
fileBadge: {
color: 'white',
@@ -146,6 +146,7 @@ const styles: any = (theme: any) => ({
paddingBottom: 0,
minWidth: 20,
height: 44,
+ justifyContent: 'unset',
whiteSpace: 'nowrap'
},
entryCloseSection: {
@@ -191,6 +192,7 @@ interface Props {
toggleEntryFullWidth: () => void;
isReadOnlyMode: boolean;
setEntryPropertiesSplitSize: (size: number) => void;
+ entryPropertiesSplitSize?: number;
reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => void;
updateThumbnailUrl: (path: string, thumbUrl: string) => void;
setLastSelectedEntry: (path: string) => void;
@@ -206,12 +208,12 @@ interface State {
editingSupported?: boolean;
isSaveBeforeCloseConfirmDialogOpened?: boolean;
isSaveBeforeReloadConfirmDialogOpened?: boolean;
- openedSplitSize?: number;
+ // openedSplitSize?: number;
isEditTagsModalOpened?: boolean;
selectedItem?: any;
isDeleteEntryModalOpened?: boolean;
shouldCopyFile?: boolean;
- entryPropertiesSplitSize?: number;
+ // entryPropertiesSplitSize?: number;
EntryPropertiesKey: string;
}
@@ -222,13 +224,13 @@ class EntryContainer extends React.Component<Props, State> {
editingSupported: false,
isSaveBeforeCloseConfirmDialogOpened: false,
isSaveBeforeReloadConfirmDialogOpened: false,
- openedSplitSize,
+ // openedSplitSize,
isEditTagsModalOpened: false,
isDeleteEntryModalOpened: false,
currentEntry: null,
selectedItem: {},
shouldCopyFile: false,
- entryPropertiesSplitSize: 0,
+ // entryPropertiesSplitSize: 0,
EntryPropertiesKey: uuidv1()
};
@@ -281,7 +283,8 @@ class EntryContainer extends React.Component<Props, State> {
componentWillReceiveProps(nextProps: Props) {
if (nextProps.openedFiles.length > 0) {
const nextEntry = nextProps.openedFiles[0];
- if (this.state.currentEntry && this.state.currentEntry.changed) {
+ if (this.state.currentEntry && this.isChanged) {
+ // this.state.currentEntry.changed) {
// console.warn(i18n.t('core:currentlyFileChangedSaveOrClose'))
return true;
}
@@ -314,7 +317,7 @@ class EntryContainer extends React.Component<Props, State> {
});
this.setState({
- entryPropertiesSplitSize: settings.entryPropertiesSplitSize,
+ // entryPropertiesSplitSize: settings.entryPropertiesSplitSize,
isPropertiesPanelVisible:
settings.entryPropertiesSplitSize > defaultSplitSize
});
@@ -344,7 +347,11 @@ class EntryContainer extends React.Component<Props, State> {
fileViewerContainer;
- isPropertiesEditMode = false;
+ isPropertiesEditMode = false; // TODO rethink this! why exist?
+
+ isChanged = false;
+
+ shouldReload = false;
// logEventsFromExtensions = event => {
// console.log('Ext. Logging >>> ', event.message);
@@ -453,16 +460,20 @@ class EntryContainer extends React.Component<Props, State> {
console.warn('Error loading text content ' + err);
});
break;
- case 'contentChangedInEditor':
- if (this.state.currentEntry.editMode) {
+ case 'contentChangedInEditor': {
+ const { currentEntry } = this.state;
+ if (currentEntry.editMode && !this.isChanged) {
+ this.isChanged = true;
+ // dummy state change to rerender for DOT before file name (only first time)
this.setState({
currentEntry: {
- ...this.state.currentEntry,
- changed: true
+ ...currentEntry
+ // changed: true
}
});
}
break;
+ }
default:
console.log(
'Not recognized messaging command: ' + JSON.stringify(data)
@@ -472,30 +483,37 @@ class EntryContainer extends React.Component<Props, State> {
};
reloadDocument = () => {
- if (this.state.currentEntry && this.state.currentEntry.changed) {
- this.setState({ isSaveBeforeReloadConfirmDialogOpened: true });
- return true;
- }
- this.setState({
- currentEntry: {
- ...this.state.currentEntry,
- shouldReload: true,
- editMode: false
+ if (this.state.currentEntry) {
+ if (this.isChanged) {
+ this.setState({
+ isSaveBeforeReloadConfirmDialogOpened: true
+ });
+ } else {
+ this.shouldReload = true;
+ this.setState({
+ currentEntry: {
+ ...this.state.currentEntry,
+ // shouldReload: true,
+ editMode: false
+ }
+ });
}
- });
+ }
};
cancelEditing = () => {
- if (this.state.currentEntry && this.state.currentEntry.changed) {
+ if (this.state.currentEntry && this.isChanged) {
+ // this.state.currentEntry.changed) {
this.props.showNotification(
i18n.t('core:currentlyFileChangedSaveOrClose')
);
return true;
}
+ this.shouldReload = true;
this.setState({
currentEntry: {
...this.state.currentEntry,
- shouldReload: true,
+ // shouldReload: true,
editMode: false
}
});
@@ -506,7 +524,8 @@ class EntryContainer extends React.Component<Props, State> {
event.preventDefault(); // Let's stop this event.
event.stopPropagation();
}
- if (this.state.currentEntry && this.state.currentEntry.changed) {
+ if (this.state.currentEntry && this.isChanged) {
+ // this.state.currentEntry.changed) {
this.setState({ isSaveBeforeCloseConfirmDialogOpened: true });
} else {
this.closeFile();
@@ -514,6 +533,7 @@ class EntryContainer extends React.Component<Props, State> {
};
closeFile = () => {
+ this.isChanged = false;
this.setState(
{
currentEntry: null,
@@ -548,10 +568,12 @@ class EntryContainer extends React.Component<Props, State> {
true
)
.then(result => {
+ this.isChanged = false;
this.setState({
currentEntry: {
...this.state.currentEntry,
- changed: false
+ editMode: false
+ // shouldReload: false
}
});
this.props.showNotification(
@@ -651,21 +673,25 @@ class EntryContainer extends React.Component<Props, State> {
this.setState(
{
- openedSplitSize,
+ // openedSplitSize,
isPropertiesPanelVisible: true
},
- () => this.props.setEntryPropertiesSplitSize(openedSplitSize)
+ () => {
+ if (this.props.settings.entryPropertiesSplitSize === defaultSplitSize) {
+ this.props.setEntryPropertiesSplitSize(openedSplitSize);
+ }
+ }
);
};
closePanel = () => {
this.setState(
{
- openedSplitSize: defaultSplitSize,
- entryPropertiesSplitSize: defaultSplitSize,
+ // openedSplitSize: defaultSplitSize,
+ // entryPropertiesSplitSize: defaultSplitSize,
isPropertiesPanelVisible: false
- },
- () => this.props.setEntryPropertiesSplitSize(defaultSplitSize)
+ }
+ // ,() => this.props.setEntryPropertiesSplitSize(defaultSplitSize)
);
};
@@ -707,6 +733,39 @@ class EntryContainer extends React.Component<Props, State> {
}
};
+ downloadCordova = (uri, filename) => {
+ const { Downloader } = window.plugins;
+
+ const downloadSuccessCallback = result => {
+ // result is an object
+ /* {
+ path: "file:///storage/sdcard0/documents/My Pdf.pdf", // Returns full file path
+ file: "My Pdf.pdf", // Returns Filename
+ folder: "documents" // Returns folder name
+ } */
+ console.log(result.file); // My Pdf.pdf
+ };
+
+ const downloadErrorCallback = error => {
+ console.log(error);
+ };
+
+ const options = {
+ title: 'Downloading File:' + filename, // Download Notification Title
+ url: uri, // File Url
+ path: filename, // The File Name with extension
+ description: 'The file is downloading', // Download description Notification String
+ visible: true, // This download is visible and shows in the notifications while in progress and after completion.
+ folder: 'documents' // Folder to save the downloaded file, if not exist it will be created
+ };
+
+ Downloader.download(
+ options,
+ downloadSuccessCallback,
+ downloadErrorCallback
+ );
+ };
+
renderFileToolbar = classes => (
<div className={classes.toolbar2}>
<div className={classes.flexLeft}>
@@ -754,7 +813,6 @@ class EntryContainer extends React.Component<Props, State> {
aria-label={i18n.t('core:downloadFile')}
onClick={() => {
const { currentEntry } = this.state;
- const downloadLink = document.getElementById('downloadFile');
const entryName = `${baseName(
currentEntry.path,
PlatformIO.getDirSeparator()
@@ -764,27 +822,40 @@ class EntryContainer extends React.Component<Props, State> {
PlatformIO.getDirSeparator()
);
- if (downloadLink) {
- if (AppConfig.isWeb) {
- const link = `${location.protocol}//${location.hostname}${
- location.port !== '' ? `:${location.port}` : ''
- }/${currentEntry.path}`;
- downloadLink.setAttribute('href', link);
+ if (AppConfig.isCordova) {
+ if (currentEntry.url) {
+ this.downloadCordova(currentEntry.url, entryName);
} else {
- downloadLink.setAttribute(
- 'href',
- `file:///${currentEntry.path}`
+ console.log('Can only download HTTP/HTTPS URIs');
+ this.props.showNotification(
+ i18n.t('core:cantDownloadLocalFile'),
+ NotificationTypes.default
);
}
+ } else {
+ const downloadLink = document.getElementById('downloadFile');
+ if (downloadLink) {
+ if (AppConfig.isWeb) {
+ const link = `${location.protocol}//${location.hostname}${
+ location.port !== '' ? `:${location.port}` : ''
+ }/${currentEntry.path}`;
+ downloadLink.setAttribute('href', link);
+ } else {
+ downloadLink.setAttribute(
+ 'href',
+ `file:///${currentEntry.path}`
+ );
+ }
- if (currentEntry.url) {
- // mostly the s3 case
- downloadLink.setAttribute('target', '_blank');
- downloadLink.setAttribute('href', currentEntry.url);
- }
+ if (currentEntry.url) {
+ // mostly the s3 case
+ downloadLink.setAttribute('target', '_blank');
+ downloadLink.setAttribute('href', currentEntry.url);
+ }
- downloadLink.setAttribute('download', fileName); // works only for same origin
- downloadLink.click();
+ downloadLink.setAttribute('download', fileName); // works only for same origin
+ downloadLink.click();
+ }
}
}}
>
@@ -955,7 +1026,8 @@ class EntryContainer extends React.Component<Props, State> {
) +
'&locale=' +
i18n.language +
- '&edit=true';
+ '&edit=true' +
+ (this.shouldReload ? '&t=' + new Date().getTime() : '');
// } else if (!currentEntry.isFile) { // TODO needed for loading folder's default html
// fileOpenerURL = 'node_modules/@tagspaces/html-viewer/index.html?locale=' + i18n.language;
} else {
@@ -966,8 +1038,10 @@ class EntryContainer extends React.Component<Props, State> {
currentEntry.url ? currentEntry.url : currentEntry.path
) +
'&locale=' +
- i18n.language;
+ i18n.language +
+ (this.shouldReload ? '&t=' + new Date().getTime() : '');
}
+ this.shouldReload = false;
// if (!currentEntry.isFile) {
// fileOpenerURL = currentEntry.path + '/index.html';
@@ -1033,17 +1107,23 @@ class EntryContainer extends React.Component<Props, State> {
content="File was modified, do you want to save the changes?"
confirmCallback={result => {
if (result) {
+ this.setState({
+ isSaveBeforeReloadConfirmDialogOpened: false
+ });
this.startSavingFile();
+ } else {
+ this.isChanged = false;
+ this.shouldReload = true;
+ this.setState({
+ isSaveBeforeReloadConfirmDialogOpened: false,
+ currentEntry: {
+ ...this.state.currentEntry,
+ // shouldReload: true,
+ editMode: false
+ // changed: false
+ }
+ });
}
- this.setState({
- isSaveBeforeReloadConfirmDialogOpened: false,
- currentEntry: {
- ...this.state.currentEntry,
- shouldReload: true,
- editMode: false,
- changed: false
- }
- });
}}
cancelDialogTID="cancelSaveBeforeCloseDialog"
confirmDialogTID="confirmSaveBeforeCloseDialog"
@@ -1099,9 +1179,11 @@ class EntryContainer extends React.Component<Props, State> {
// maxSize={fullSplitSize}
// defaultSize={this.state.entryPropertiesSplitSize}
size={
- currentEntry && currentEntry.isFile
- ? this.state.entryPropertiesSplitSize
- : '100%'
+ this.state.isPropertiesPanelVisible
+ ? currentEntry && currentEntry.isFile
+ ? this.props.settings.entryPropertiesSplitSize
+ : '100%'
+ : defaultSplitSize
}
minSize={
currentEntry && currentEntry.isFile ? defaultSplitSize : '100%'
@@ -1109,15 +1191,20 @@ class EntryContainer extends React.Component<Props, State> {
maxSize={currentEntry && currentEntry.isFile ? fullSplitSize : '100%'}
defaultSize={
currentEntry && currentEntry.isFile
- ? this.state.entryPropertiesSplitSize
+ ? this.props.settings.entryPropertiesSplitSize
: '100%'
}
onChange={size => {
- this.setState({
- isPropertiesPanelVisible: size > defaultSplitSize,
- openedSplitSize: size,
- entryPropertiesSplitSize: size
- });
+ const isPropertiesPanelVisible = size > defaultSplitSize;
+ if (
+ this.state.isPropertiesPanelVisible !== isPropertiesPanelVisible
+ ) {
+ this.setState({
+ isPropertiesPanelVisible
+ // openedSplitSize: size,
+ // entryPropertiesSplitSize: size
+ });
+ }
bufferedSplitResize(() =>
this.props.setEntryPropertiesSplitSize(size)
);
@@ -1145,7 +1232,7 @@ class EntryContainer extends React.Component<Props, State> {
PlatformIO.getDirSeparator()
)}
</div>
- {currentEntry.changed
+ {this.isChanged // currentEntry.changed
? String.fromCharCode(0x25cf) + ' '
: ''}
{fileTitle}
@@ -1201,15 +1288,6 @@ class EntryContainer extends React.Component<Props, State> {
)}
{this.state.editingSupported && !currentEntry.editMode && (
<div className={classes.entryCloseSection}>
- {/* <IconButton
- disabled={false}
- onClick={this.editFile}
- title={i18n.t('core:editFile')}
- aria-label={i18n.t('core:editFile')}
- data-tid="fileContainerEditFile"
- >
- <EditIcon />
- </IconButton> */}
<Button
disabled={false}
size="small"
@@ -1245,6 +1323,7 @@ class EntryContainer extends React.Component<Props, State> {
</div>
)}
</div>
+
<div className={classes.entryProperties}>
{currentEntry.isFile
? this.renderFileToolbar(classes)
@@ -1255,7 +1334,7 @@ class EntryContainer extends React.Component<Props, State> {
setPropertiesEditMode={this.setPropertiesEditMode}
entryPath={currentEntry.path}
entryURL={currentEntry.url}
- shouldReload={currentEntry.shouldReload}
+ shouldReload={this.shouldReload}
renameFile={this.props.renameFile}
renameDirectory={this.props.renameDirectory}
editTagForEntry={this.props.editTagForEntry}
diff --git a/app/components/FolderContainer.tsx b/app/components/FolderContainer.tsx
index dac5af4d8..33f498bf5 100644
--- a/app/components/FolderContainer.tsx
+++ b/app/components/FolderContainer.tsx
@@ -205,7 +205,7 @@ interface State {
currentPerspective: string;
currentPath?: string;
pathParts?: Array<string>;
- isPropertiesPanelVisible?: boolean;
+ // isPropertiesPanelVisible?: boolean;
locationChooserMenuOpened?: boolean;
locationChooserMenuAnchorEl?: null | Object;
directoryMenuOpened?: boolean;
@@ -222,7 +222,7 @@ class FolderContainer extends React.Component<Props, State> {
currentPerspective: window.ExtDefaultPerspective || 'default',
currentPath: '',
pathParts: [],
- isPropertiesPanelVisible: false,
+ // isPropertiesPanelVisible: false,
isDirectoryMenuOpened: false,
directoryContextMenuOpened: false,
directoryContextMenuAnchorEl: null,
diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsx
index 71816a5da..00579f5cb 100644
--- a/app/containers/MainPage.tsx
+++ b/app/containers/MainPage.tsx
@@ -321,11 +321,15 @@ class MainPage extends Component<Props, State> {
};
UNSAFE_componentWillMount() {
- this.updateDimensions();
+ if (!AppConfig.isCordova) {
+ this.updateDimensions();
+ }
}
componentDidMount = () => {
- window.addEventListener('resize', this.updateDimensions);
+ if (!AppConfig.isCordova) {
+ window.addEventListener('resize', this.updateDimensions);
+ }
// this.setupDesktopMenu();
buildDesktopMenu(this.props);
buildTrayIconMenu(this.props);
@@ -396,7 +400,9 @@ class MainPage extends Component<Props, State> {
}
componentWillUnmount() {
- window.removeEventListener('resize', this.updateDimensions);
+ if (!AppConfig.isCordova) {
+ window.removeEventListener('resize', this.updateDimensions);
+ }
}
updateDimensions = () => {
diff --git a/app/locales/en/core.json b/app/locales/en/core.json
index 9c1f47b94..0830a78b0 100644
--- a/app/locales/en/core.json
+++ b/app/locales/en/core.json
@@ -468,5 +468,6 @@
"stopAll": "Stop all",
"fileExist": "File with the same name already exist",
"importMacTags": "Import macOS tags",
+ "cantDownloadLocalFile": "You can't download local files",
"-": "-"
}
diff --git a/cordova/package.json b/cordova/package.json
index 2c45fa4ae..28f9cbf32 100644
--- a/cordova/package.json
+++ b/cordova/package.json
@@ -10,6 +10,7 @@
"author": "Apache Cordova Team",
"license": "Apache-2.0",
"dependencies": {
+ "bamboo.cordova.plugin.downloader": "git+https://github.com/sytolk/cordova-plugin-downloader.git",
"cordova-android": "^7.1.4",
"cordova-plugin-background-mode": "^0.7.3",
"cordova-plugin-camera": "4.1.0",
@@ -31,7 +32,8 @@
"cordova-plugin-file": {},
"cordova-plugin-file-opener2": {
"ANDROID_SUPPORT_V4_VERSION": "27.+"
- }
+ },
+ "com.whebcraft.cordova.plugin.downloader": {}
},
"platforms": [
"android"
diff --git a/cordova/platforms/android/android.json b/cordova/platforms/android/android.json
index d069f91cb..a45011715 100644
--- a/cordova/platforms/android/android.json
+++ b/cordova/platforms/android/android.json
@@ -47,6 +47,20 @@
{
"xml": "<feature name=\"FileOpener2\"><param name=\"android-package\" value=\"io.github.pwlin.cordova.plugins.fileopener2.FileOpener2\" /></feature>",
"count": 1
+ },
+ {
+ "xml": "<feature name=\"Downloader\"><param name=\"android-package\" value=\"com.whebcraft.android.plugin.Downloader\" /></feature>",
+ "count": 1
+ },
+ {
+ "xml": "<feature name=\"FileTransfer\"><param name=\"android-package\" value=\"org.apache.cordova.filetransfer.FileTransfer\" /></feature>",
+ "count": 1
+ }
+ ],
+ "/widget": [
+ {
+ "xml": "<feature name=\"Zip\"><param name=\"android-package\" value=\"org.apache.cordova.Zip\" /></feature>",
+ "count": 1
}
]
}
@@ -67,6 +81,14 @@
{
"xml": "<uses-permission android:name=\"android.permission.WAKE_LOCK\" />",
"count": 1
+ },
+ {
+ "xml": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />",
+ "count": 1
+ },
+ {
+ "xml": "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />",
+ "count": 1
}
],
"/*": [
@@ -130,6 +152,18 @@
"cordova-plugin-file-opener2": {
"ANDROID_SUPPORT_V4_VERSION": "27.+",
"PACKAGE_NAME": "org.tagspaces.mobile"
+ },
+ "com.whebcraft.cordova.plugin.downloader": {
+ "PACKAGE_NAME": "org.tagspaces.mobile"
+ },
+ "cordova-plugin-file-transfer": {
+ "PACKAGE_NAME": "org.tagspaces.mobile"
+ },
+ "cordova-plugin-downloader": {
+ "PACKAGE_NAME": "org.tagspaces.mobile"
+ },
+ "cordova-plugin-zip": {
+ "PACKAGE_NAME": "org.tagspaces.mobile"
}
},
"dependent_plugins": {},
@@ -377,6 +411,46 @@
"clobbers": [
"cordova.plugins.fileOpener2"
]
+ },
+ {
+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",
+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",
+ "pluginId": "com.whebcraft.cordova.plugin.downloader",
+ "clobbers": [
+ "plugins.Downloader"
+ ]
+ },
+ {
+ "id": "cordova-plugin-file-transfer.FileTransferError",
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransferError"
+ ]
+ },
+ {
+ "id": "cordova-plugin-file-transfer.FileTransfer",
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransfer"
+ ]
+ },
+ {
+ "id": "cordova-plugin-downloader.download",
+ "file": "plugins/cordova-plugin-downloader/www/download.js",
+ "pluginId": "cordova-plugin-downloader",
+ "clobbers": [
+ "download"
+ ]
+ },
+ {
+ "id": "cordova-plugin-zip.Zip",
+ "file": "plugins/cordova-plugin-zip/zip.js",
+ "pluginId": "cordova-plugin-zip",
+ "clobbers": [
+ "zip"
+ ]
}
],
"plugin_metadata": {
@@ -387,6 +461,10 @@
"cordova-plugin-whitelist": "1.3.4",
"es6-promise-plugin": "4.2.2",
"cordova-plugin-x-socialsharing": "5.6.8",
- "cordova-plugin-file-opener2": "3.0.3"
+ "cordova-plugin-file-opener2": "3.0.3",
+ "com.whebcraft.cordova.plugin.downloader": "0.1.0",
+ "cordova-plugin-file-transfer": "1.7.1",
+ "cordova-plugin-downloader": "0.0.4",
+ "cordova-plugin-zip": "3.1.0"
}
}
diff --git a/cordova/platforms/android/app/src/main/java/com/whebcraft/android/plugin/Downloader.java b/cordova/platforms/android/app/src/main/java/com/whebcraft/android/plugin/Downloader.java
new file mode 100644
index 000000000..e3c8cfb40
--- /dev/null
+++ b/cordova/platforms/android/app/src/main/java/com/whebcraft/android/plugin/Downloader.java
@@ -0,0 +1,184 @@
+package com.whebcraft.android.plugin;
+
+import android.app.Activity;
+import android.app.DownloadManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.net.Uri;
+import java.io.File;
+import android.os.Environment;
+import android.preference.PreferenceManager;
+import android.util.Log;
+
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.json.JSONObject;
+import org.json.JSONArray;
+import org.json.JSONException;
+import java.util.HashMap;
+
+public class Downloader extends CordovaPlugin {
+
+ public static final String ACTION_DOWNLOAD = "download";
+
+ private static final String TAG = "DownloaderPlugin";
+
+ private Activity cordovaActivity;
+ private DownloadManager downloadManager;
+ private HashMap<Long, Download> downloadMap;
+
+ @Override
+ protected void pluginInitialize()
+ {
+ Log.d(TAG, "PluginInitialize");
+
+ cordovaActivity = this.cordova.getActivity();
+
+ downloadManager = (DownloadManager) cordovaActivity.getSystemService(Context.DOWNLOAD_SERVICE);
+ downloadMap = new HashMap();
+
+ // Register receiver for Notification actions
+ cordovaActivity.registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
+ }
+
+ @Override
+ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
+
+ Log.d(TAG, "CordovaPlugin: execute " + action);
+
+ if (ACTION_DOWNLOAD.equals(action)) {
+
+ Log.d(TAG, "CordovaPlugin: load " + action);
+ return download(args, callbackContext);
+
+ }
+
+ return false;
+
+
+ }
+
+ private boolean download(JSONArray args, CallbackContext callbackContext)
+ {
+ Log.d(TAG, "CordovaPlugin: " + ACTION_DOWNLOAD);
+
+ try {
+
+ JSONObject arg_object = args.getJSONObject(0);
+ String path = arg_object.getString("path");
+ String title = arg_object.getString("title");
+ String folder = arg_object.getString("folder");
+ String description = arg_object.getString("description");
+
+
+ File direct = new File(Environment.getExternalStorageDirectory()+ "/"+folder);
+
+ if (!direct.exists()) {
+ direct.mkdirs();
+ }
+
+ File delExisingFile = new File(Environment.getExternalStorageDirectory()+ "/"+folder+"/"+path);
+ delExisingFile.delete();
+
+ Boolean visible = Boolean.valueOf(arg_object.getString("visible"));
+
+ Uri uri = Uri.parse(arg_object.getString("url"));
+ Download mDownload = new Download(path, folder, callbackContext);
+
+ DownloadManager.Request request = new DownloadManager.Request(uri);
+ // Restrict the types of networks over which this download may proceed.
+ request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
+ // Set whether this download may proceed over a roaming connection.
+ request.setAllowedOverRoaming(true);
+ // Set the title of this download, to be displayed in notifications (if enabled).
+ request.setTitle(title);
+ // Set a description of this download, to be displayed in notifications (if enabled)
+ request.setDescription(description);
+ // This download doesn't show in the UI or in the notifications.
+ if(!visible){
+ request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
+ } else {
+ // This download is visible and shows in the notifications while in progress and after completion.
+ request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
+ }
+ // Set the destination for the downloaded as defined by the user within the device files directory
+ request.setDestinationInExternalPublicDir("/"+folder, path);
+
+ // save the download
+ downloadMap.put(downloadManager.enqueue(request), mDownload);
+
+ return true;
+
+ } catch (Exception e) {
+
+ System.err.println("Exception: " + e.getMessage());
+ callbackContext.error(e.getMessage());
+
+ return false;
+ }
+ }
+
+ private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+
+ DownloadManager.Query query = new DownloadManager.Query();
+ Long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
+ query.setFilterById(downloadId);
+ Cursor cursor = downloadManager.query(query);
+
+ if (cursor.moveToFirst()){
+
+ //Retrieve the saved download
+ Download currentDownload = downloadMap.get(downloadId);
+ downloadMap.remove(currentDownload);
+
+ int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
+ int status = cursor.getInt(columnIndex);
+ int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
+ int reason = cursor.getInt(columnReason);
+
+ switch (status) {
+ case DownloadManager.STATUS_SUCCESSFUL:
+ try {
+ JSONObject entry = new JSONObject();
+ entry.put("path", "file:///storage/sdcard0/"+currentDownload.folder+"/"+currentDownload.path);
+ entry.put("file", currentDownload.path);
+ entry.put("folder", currentDownload.folder);
+ currentDownload.callbackContext.success(entry);
+ } catch (Exception e) {
+ System.err.println("Exception: " + e.getMessage());
+ currentDownload.callbackContext.error(e.getMessage());
+ }
+ break;
+ case DownloadManager.STATUS_FAILED:
+ currentDownload.callbackContext.error(reason);
+ break;
+ case DownloadManager.STATUS_PAUSED:
+ case DownloadManager.STATUS_PENDING:
+ case DownloadManager.STATUS_RUNNING:
+ default:
+ break;
+ }
+ }
+ }
+
+ };
+
+ private class Download {
+ public String path;
+ public String folder;
+ public CallbackContext callbackContext;
+
+ public Download(String path, String folder, CallbackContext callbackContext) {
+ this.path = path;
+ this.folder = folder;
+ this.callbackContext = callbackContext;
+ }
+ }
+
+}
diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.java
new file mode 100644
index 000000000..4b5de862d
--- /dev/null
+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.java
@@ -0,0 +1,206 @@
+package org.apache.cordova;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.FileNotFoundException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+
+import android.net.Uri;
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
+import org.apache.cordova.PluginResult;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.util.Log;
+
+public class Zip extends CordovaPlugin {
+
+ private static final String LOG_TAG = "Zip";
+
+ @Override
+ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
+ if ("unzip".equals(action)) {
+ unzip(args, callbackContext);
+ return true;
+ }
+ return false;
+ }
+
+ private void unzip(final CordovaArgs args, final CallbackContext callbackContext) {
+ this.cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ unzipSync(args, callbackContext);
+ }
+ });
+ }
+
+ // Can't use DataInputStream because it has the wrong endian-ness.
+ private static int readInt(InputStream is) throws IOException {
+ int a = is.read();
+ int b = is.read();
+ int c = is.read();
+ int d = is.read();
+ return a | b << 8 | c << 16 | d << 24;
+ }
+
+ private void unzipSync(CordovaArgs args, CallbackContext callbackContext) {
+ InputStream inputStream = null;
+ try {
+ String zipFileName = args.getString(0);
+ String outputDirectory = args.getString(1);
+
+ // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
+ // Accept a path or a URI for the source zip.
+ Uri zipUri = getUriForArg(zipFileName);
+ Uri outputUri = getUriForArg(outputDirectory);
+
+ CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ File tempFile = resourceApi.mapUriToFile(zipUri);
+ if (tempFile == null || !tempFile.exists()) {
+ String errorMessage = "Zip file does not exist";
+ callbackContext.error(errorMessage);
+ Log.e(LOG_TAG, errorMessage);
+ return;
+ }
+
+ File outputDir = resourceApi.mapUriToFile(outputUri);
+ outputDirectory = outputDir.getAbsolutePath();
+ outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
+ if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())){
+ String errorMessage = "Could not create output directory";
+ callbackContext.error(errorMessage);
+ Log.e(LOG_TAG, errorMessage);
+ return;
+ }
+
+ OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
+ ProgressEvent progress = new ProgressEvent();
+ progress.setTotal(zipFile.length);
+
+ inputStream = new BufferedInputStream(zipFile.inputStream);
+ inputStream.mark(10);
+ int magic = readInt(inputStream);
+
+ if (magic != 875721283) { // CRX identifier
+ inputStream.reset();
+ } else {
+ // CRX files contain a header. This header consists of:
+ // * 4 bytes of magic number
+ // * 4 bytes of CRX format version,
+ // * 4 bytes of public key length
+ // * 4 bytes of signature length
+ // * the public key
+ // * the signature
+ // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.
+ readInt(inputStream); // version == 2.
+ int pubkeyLength = readInt(inputStream);
+ int signatureLength = readInt(inputStream);
+
+ inputStream.skip(pubkeyLength + signatureLength);
+ progress.setLoaded(16 + pubkeyLength + signatureLength);
+ }
+
+ // The inputstream is now pointing at the start of the actual zip file content.
+ ZipInputStream zis = new ZipInputStream(inputStream);
+ inputStream = zis;
+
+ ZipEntry ze;
+ byte[] buffer = new byte[32 * 1024];
+ boolean anyEntries = false;
+
+ while ((ze = zis.getNextEntry()) != null)
+ {
+ anyEntries = true;
+ String compressedName = ze.getName();
+
+ if (ze.isDirectory()) {
+ File dir = new File(outputDirectory + compressedName);
+ dir.mkdirs();
+ } else {
+ File file = new File(outputDirectory + compressedName);
+ file.getParentFile().mkdirs();
+ if(file.exists() || file.createNewFile()){
+ Log.w("Zip", "extracting: " + file.getPath());
+ FileOutputStream fout = new FileOutputStream(file);
+ int count;
+ while ((count = zis.read(buffer)) != -1)
+ {
+ fout.write(buffer, 0, count);
+ }
+ fout.close();
+ }
+
+ }
+ progress.addLoaded(ze.getCompressedSize());
+ updateProgress(callbackContext, progress);
+ zis.closeEntry();
+ }
+
+ // final progress = 100%
+ progress.setLoaded(progress.getTotal());
+ updateProgress(callbackContext, progress);
+
+ if (anyEntries)
+ callbackContext.success();
+ else
+ callbackContext.error("Bad zip file");
+ } catch (Exception e) {
+ String errorMessage = "An error occurred while unzipping.";
+ callbackContext.error(errorMessage);
+ Log.e(LOG_TAG, errorMessage, e);
+ } finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) throws JSONException {
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ pluginResult.setKeepCallback(true);
+ callbackContext.sendPluginResult(pluginResult);
+ }
+
+ private Uri getUriForArg(String arg) {
+ CordovaResourceApi resourceApi = webView.getResourceApi();
+ Uri tmpTarget = Uri.parse(arg);
+ return resourceApi.remapUri(
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
+ }
+
+ private static class ProgressEvent {
+ private long loaded;
+ private long total;
+ public long getLoaded() {
+ return loaded;
+ }
+ public void setLoaded(long loaded) {
+ this.loaded = loaded;
+ }
+ public void addLoaded(long add) {
+ this.loaded += add;
+ }
+ public long getTotal() {
+ return total;
+ }
+ public void setTotal(long total) {
+ this.total = total;
+ }
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{loaded:" + loaded +
+ ",total:" + total + "}");
+ }
+ }
+}
diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.java
new file mode 100644
index 000000000..76a7b13a7
--- /dev/null
+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.java
@@ -0,0 +1,63 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates in-progress status of uploading or downloading a file to a remote server.
+ */
+public class FileProgressResult {
+
+ private boolean lengthComputable = false; // declares whether total is known
+ private long loaded = 0; // bytes sent so far
+ private long total = 0; // bytes total, if known
+
+ public boolean getLengthComputable() {
+ return lengthComputable;
+ }
+
+ public void setLengthComputable(boolean computable) {
+ this.lengthComputable = computable;
+ }
+
+ public long getLoaded() {
+ return loaded;
+ }
+
+ public void setLoaded(long bytes) {
+ this.loaded = bytes;
+ }
+
+ public long getTotal() {
+ return total;
+ }
+
+ public void setTotal(long bytes) {
+ this.total = bytes;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{loaded:" + loaded +
+ ",total:" + total +
+ ",lengthComputable:" + (lengthComputable ? "true" : "false") + "}");
+ }
+}
diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.java
new file mode 100644
index 000000000..5a3c5d623
--- /dev/null
+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.java
@@ -0,0 +1,932 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.Inflater;
+
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaResourceApi;
+import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
+import org.apache.cordova.LOG;
+import org.apache.cordova.PluginManager;
+import org.apache.cordova.PluginResult;
+import org.apache.cordova.Whitelist;
+import org.apache.cordova.file.FileUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.net.Uri;
+import android.os.Build;
+import android.webkit.CookieManager;
+
+public class FileTransfer extends CordovaPlugin {
+
+ private static final String LOG_TAG = "FileTransfer";
+ private static final String LINE_START = "--";
+ private static final String LINE_END = "\r\n";
+ private static final String BOUNDARY = "+++++";
+
+ public static int FILE_NOT_FOUND_ERR = 1;
+ public static int INVALID_URL_ERR = 2;
+ public static int CONNECTION_ERR = 3;
+ public static int ABORTED_ERR = 4;
+ public static int NOT_MODIFIED_ERR = 5;
+
+ private static HashMap<String, RequestContext> activeRequests = new HashMap<String, RequestContext>();
+ private static final int MAX_BUFFER_SIZE = 16 * 1024;
+
+ private static final class RequestContext {
+ String source;
+ String target;
+ File targetFile;
+ CallbackContext callbackContext;
+ HttpURLConnection connection;
+ boolean aborted;
+ RequestContext(String source, String target, CallbackContext callbackContext) {
+ this.source = source;
+ this.target = target;
+ this.callbackContext = callbackContext;
+ }
+ void sendPluginResult(PluginResult pluginResult) {
+ synchronized (this) {
+ if (!aborted) {
+ callbackContext.sendPluginResult(pluginResult);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds an interface method to an InputStream to return the number of bytes
+ * read from the raw stream. This is used to track total progress against
+ * the HTTP Content-Length header value from the server.
+ */
+ private static abstract class TrackingInputStream extends FilterInputStream {
+ public TrackingInputStream(final InputStream in) {
+ super(in);
+ }
+ public abstract long getTotalRawBytesRead();
+ }
+
+ private static class ExposedGZIPInputStream extends GZIPInputStream {
+ public ExposedGZIPInputStream(final InputStream in) throws IOException {
+ super(in);
+ }
+ public Inflater getInflater() {
+ return inf;
+ }
+ }
+
+ /**
+ * Provides raw bytes-read tracking for a GZIP input stream. Reports the
+ * total number of compressed bytes read from the input, rather than the
+ * number of uncompressed bytes.
+ */
+ private static class TrackingGZIPInputStream extends TrackingInputStream {
+ private ExposedGZIPInputStream gzin;
+ public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {
+ super(gzin);
+ this.gzin = gzin;
+ }
+ public long getTotalRawBytesRead() {
+ return gzin.getInflater().getBytesRead();
+ }
+ }
+
+ /**
+ * Provides simple total-bytes-read tracking for an existing InputStream
+ */
+ private static class SimpleTrackingInputStream extends TrackingInputStream {
+ private long bytesRead = 0;
+ public SimpleTrackingInputStream(InputStream stream) {
+ super(stream);
+ }
+
+ private int updateBytesRead(int newBytesRead) {
+ if (newBytesRead != -1) {
+ bytesRead += newBytesRead;
+ }
+ return newBytesRead;
+ }
+
+ @Override
+ public int read() throws IOException {
+ return updateBytesRead(super.read());
+ }
+
+ // Note: FilterInputStream delegates read(byte[] bytes) to the below method,
+ // so we don't override it or else double count (CB-5631).
+ @Override
+ public int read(byte[] bytes, int offset, int count) throws IOException {
+ return updateBytesRead(super.read(bytes, offset, count));
+ }
+
+ public long getTotalRawBytesRead() {
+ return bytesRead;
+ }
+ }
+
+ @Override
+ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
+ if (action.equals("upload") || action.equals("download")) {
+ String source = args.getString(0);
+ String target = args.getString(1);
+
+ if (action.equals("upload")) {
+ upload(source, target, args, callbackContext);
+ } else {
+ download(source, target, args, callbackContext);
+ }
+ return true;
+ } else if (action.equals("abort")) {
+ String objectId = args.getString(0);
+ abort(objectId);
+ callbackContext.success();
+ return true;
+ }
+ return false;
+ }
+
+ private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
+ try {
+ for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) {
+ /* RFC 2616 says that non-ASCII characters and control
+ * characters are not allowed in header names or values.
+ * Additionally, spaces are not allowed in header names.
+ * RFC 2046 Quoted-printable encoding may be used to encode
+ * arbitrary characters, but we donon- not do that encoding here.
+ */
+ String headerKey = iter.next().toString();
+ String cleanHeaderKey = headerKey.replaceAll("\\n","")
+ .replaceAll("\\s+","")
+ .replaceAll(":", "")
+ .replaceAll("[^\\x20-\\x7E]+", "");
+
+ JSONArray headerValues = headers.optJSONArray(headerKey);
+ if (headerValues == null) {
+ headerValues = new JSONArray();
+
+ /* RFC 2616 also says that any amount of consecutive linear
+ * whitespace within a header value can be replaced with a
+ * single space character, without affecting the meaning of
+ * that value.
+ */
+
+ String headerValue = headers.getString(headerKey);
+ String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " ");
+ headerValues.put(finalValue);
+ }
+
+ //Use the clean header key, not the one that we passed in
+ connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0));
+ for (int i = 1; i < headerValues.length(); ++i) {
+ connection.addRequestProperty(headerKey, headerValues.getString(i));
+ }
+ }
+ } catch (JSONException e1) {
+ // No headers to be manipulated!
+ }
+ }
+
+ private String getCookies(final String target) {
+ boolean gotCookie = false;
+ String cookie = null;
+ Class webViewClass = webView.getClass();
+ try {
+ Method gcmMethod = webViewClass.getMethod("getCookieManager");
+ Class iccmClass = gcmMethod.getReturnType();
+ Method gcMethod = iccmClass.getMethod("getCookie", String.class);
+
+ cookie = (String)gcMethod.invoke(
+ iccmClass.cast(
+ gcmMethod.invoke(webView)
+ ), target);
+
+ gotCookie = true;
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ } catch (ClassCastException e) {
+ }
+
+ if (!gotCookie && CookieManager.getInstance() != null) {
+ cookie = CookieManager.getInstance().getCookie(target);
+ }
+
+ return cookie;
+ }
+
+ /**
+ * Uploads the specified file to the server URL provided using an HTTP multipart request.
+ * @param source Full path of the file on the file system
+ * @param target URL of the server to receive the file
+ * @param args JSON Array of args
+ * @param callbackContext callback id for optional progress reports
+ *
+ * args[2] fileKey Name of file request parameter
+ * args[3] fileName File name to be used on server
+ * args[4] mimeType Describes file content type
+ * args[5] params key:value pairs of user-defined parameters
+ * @return FileUploadResult containing result of upload request
+ */
+ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ LOG.d(LOG_TAG, "upload " + source + " to " + target);
+
+ // Setup the options
+ final String fileKey = getArgument(args, 2, "file");
+ final String fileName = getArgument(args, 3, "image.jpg");
+ final String mimeType = getArgument(args, 4, "image/jpeg");
+ final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
+ // Always use chunked mode unless set to false as per API
+ final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
+ // Look for headers on the params map for backwards compatibility with older Cordova versions.
+ final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
+ final String objectId = args.getString(9);
+ final String httpMethod = getArgument(args, 10, "POST");
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ LOG.d(LOG_TAG, "fileKey: " + fileKey);
+ LOG.d(LOG_TAG, "fileName: " + fileName);
+ LOG.d(LOG_TAG, "mimeType: " + mimeType);
+ LOG.d(LOG_TAG, "params: " + params);
+ LOG.d(LOG_TAG, "chunkedMode: " + chunkedMode);
+ LOG.d(LOG_TAG, "headers: " + headers);
+ LOG.d(LOG_TAG, "objectId: " + objectId);
+ LOG.d(LOG_TAG, "httpMethod: " + httpMethod);
+
+ final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
+
+ int uriType = CordovaResourceApi.getUriType(targetUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ LOG.e(LOG_TAG, "Unsupported URI: " + targetUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+
+ // We should call remapUri on background thread otherwise it throws
+ // IllegalStateException when trying to remap 'cdvfile://localhost/content/...' URIs
+ // via ContentFilesystem (see https://issues.apache.org/jira/browse/CB-9022)
+ Uri tmpSrc = Uri.parse(source);
+ final Uri sourceUri = resourceApi.remapUri(
+ tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));
+
+ HttpURLConnection conn = null;
+ int totalBytes = 0;
+ int fixedLength = -1;
+ try {
+ // Create return object
+ FileUploadResult result = new FileUploadResult();
+ FileProgressResult progress = new FileProgressResult();
+
+ //------------------ CLIENT REQUEST
+ // Open a HTTP connection to the URL based on protocol
+ conn = resourceApi.createHttpConnection(targetUri);
+
+ // Allow Inputs
+ conn.setDoInput(true);
+
+ // Allow Outputs
+ conn.setDoOutput(true);
+
+ // Don't use a cached copy.
+ conn.setUseCaches(false);
+
+ // Use a post method.
+ conn.setRequestMethod(httpMethod);
+
+ // if we specified a Content-Type header, don't do multipart form upload
+ boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
+ if (multipartFormUpload) {
+ conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
+ }
+
+ // Set the cookies on the response
+ String cookie = getCookies(target);
+
+ if (cookie != null) {
+ conn.setRequestProperty("Cookie", cookie);
+ }
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(conn, headers);
+ }
+
+ /*
+ * Store the non-file portions of the multipart data as a string, so that we can add it
+ * to the contentSize, since it is part of the body of the HTTP request.
+ */
+ StringBuilder beforeData = new StringBuilder();
+ try {
+ for (Iterator<?> iter = params.keys(); iter.hasNext();) {
+ Object key = iter.next();
+ if(!String.valueOf(key).equals("headers"))
+ {
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');
+ beforeData.append(LINE_END).append(LINE_END);
+ beforeData.append(params.getString(key.toString()));
+ beforeData.append(LINE_END);
+ }
+ }
+ } catch (JSONException e) {
+ LOG.e(LOG_TAG, e.getMessage(), e);
+ }
+
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
+ beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
+ beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
+ byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
+ byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");
+
+
+ // Get a input stream of the file on the phone
+ OpenForReadResult readResult = resourceApi.openForRead(sourceUri);
+
+ int stringLength = beforeDataBytes.length + tailParamsBytes.length;
+ if (readResult.length >= 0) {
+ fixedLength = (int)readResult.length;
+ if (multipartFormUpload)
+ fixedLength += stringLength;
+ progress.setLengthComputable(true);
+ progress.setTotal(fixedLength);
+ }
+ LOG.d(LOG_TAG, "Content Length: " + fixedLength);
+ // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
+ // http://code.google.com/p/android/issues/detail?id=3164
+ // It also causes OOM if HTTPS is used, even on newer devices.
+ boolean useChunkedMode = chunkedMode || (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO);
+ useChunkedMode = useChunkedMode || (fixedLength == -1);
+
+ if (useChunkedMode) {
+ conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
+ // Although setChunkedStreamingMode sets this header, setting it explicitly here works
+ // around an OutOfMemoryException when using https.
+ conn.setRequestProperty("Transfer-Encoding", "chunked");
+ } else {
+ conn.setFixedLengthStreamingMode(fixedLength);
+
+ if (useHttps) {
+ LOG.w(LOG_TAG, "setFixedLengthStreamingMode could cause OutOfMemoryException - switch to chunkedMode=true to avoid it if this is an issue.");
+ }
+ }
+
+ conn.connect();
+
+ OutputStream sendStream = null;
+ try {
+ sendStream = conn.getOutputStream();
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ if (multipartFormUpload) {
+ //We don't want to change encoding, we just want this to write for all Unicode.
+ sendStream.write(beforeDataBytes);
+ totalBytes += beforeDataBytes.length;
+ }
+
+ // create a buffer of maximum size
+ int bytesAvailable = readResult.inputStream.available();
+ int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ byte[] buffer = new byte[bufferSize];
+
+ // read file and write it into form...
+ int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ long prevBytesRead = 0;
+ while (bytesRead > 0) {
+ totalBytes += bytesRead;
+ result.setBytesSent(totalBytes);
+ sendStream.write(buffer, 0, bytesRead);
+ if (totalBytes > prevBytesRead + 102400) {
+ prevBytesRead = totalBytes;
+ LOG.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
+ }
+ bytesAvailable = readResult.inputStream.available();
+ bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ // Send a progress event.
+ progress.setLoaded(totalBytes);
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+
+ if (multipartFormUpload) {
+ // send multipart form data necessary after file data...
+ sendStream.write(tailParamsBytes);
+ totalBytes += tailParamsBytes.length;
+ }
+ sendStream.flush();
+ } finally {
+ safeClose(readResult.inputStream);
+ safeClose(sendStream);
+ }
+ synchronized (context) {
+ context.connection = null;
+ }
+ LOG.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);
+
+ //------------------ read the SERVER RESPONSE
+ String responseString;
+ int responseCode = conn.getResponseCode();
+ LOG.d(LOG_TAG, "response code: " + responseCode);
+ LOG.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
+ TrackingInputStream inStream = null;
+ try {
+ inStream = getInputStream(conn);
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
+ byte[] buffer = new byte[1024];
+ int bytesRead = 0;
+ // write bytes to file
+ while ((bytesRead = inStream.read(buffer)) > 0) {
+ out.write(buffer, 0, bytesRead);
+ }
+ responseString = out.toString("UTF-8");
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inStream);
+ }
+
+ LOG.d(LOG_TAG, "got response from server");
+ LOG.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));
+
+ // send request and retrieve response
+ result.setResponseCode(responseCode);
+ result.setResponse(responseString);
+
+ context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);
+ LOG.e(LOG_TAG, error.toString(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);
+ LOG.e(LOG_TAG, error.toString(), e);
+ LOG.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (JSONException e) {
+ LOG.e(LOG_TAG, e.getMessage(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } catch (Throwable t) {
+ // Shouldn't happen, but will
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);
+ LOG.e(LOG_TAG, error.toString(), t);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+ }
+ }
+ });
+ }
+
+ private static void safeClose(Closeable stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
+ String encoding = conn.getContentEncoding();
+ if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
+ return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
+ }
+ return new SimpleTrackingInputStream(conn.getInputStream());
+ }
+
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection, Throwable throwable) {
+
+ int httpStatus = 0;
+ StringBuilder bodyBuilder = new StringBuilder();
+ String body = null;
+ if (connection != null) {
+ try {
+ if (connection instanceof HttpURLConnection) {
+ httpStatus = ((HttpURLConnection)connection).getResponseCode();
+ InputStream err = ((HttpURLConnection) connection).getErrorStream();
+ if(err != null)
+ {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
+ try {
+ String line = reader.readLine();
+ while(line != null) {
+ bodyBuilder.append(line);
+ line = reader.readLine();
+ if(line != null) {
+ bodyBuilder.append('\n');
+ }
+ }
+ body = bodyBuilder.toString();
+ } finally {
+ reader.close();
+ }
+ }
+ }
+ // IOException can leave connection object in a bad state, so catch all exceptions.
+ } catch (Throwable e) {
+ LOG.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
+ }
+ }
+
+ return createFileTransferError(errorCode, source, target, body, httpStatus, throwable);
+ }
+
+ /**
+ * Create an error object based on the passed in errorCode
+ * @param errorCode the error
+ * @return JSONObject containing the error
+ */
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {
+ JSONObject error = null;
+ try {
+ error = new JSONObject();
+ error.put("code", errorCode);
+ error.put("source", source);
+ error.put("target", target);
+ if(body != null)
+ {
+ error.put("body", body);
+ }
+ if (httpStatus != null) {
+ error.put("http_status", httpStatus);
+ }
+ if (throwable != null) {
+ String msg = throwable.getMessage();
+ if (msg == null || "".equals(msg)) {
+ msg = throwable.toString();
+ }
+ error.put("exception", msg);
+ }
+ } catch (JSONException e) {
+ LOG.e(LOG_TAG, e.getMessage(), e);
+ }
+ return error;
+ }
+
+ /**
+ * Convenience method to read a parameter from the list of JSON args.
+ * @param args the args passed to the Plugin
+ * @param position the position to retrieve the arg from
+ * @param defaultString the default to be used if the arg does not exist
+ * @return String with the retrieved value
+ */
+ private static String getArgument(JSONArray args, int position, String defaultString) {
+ String arg = defaultString;
+ if (args.length() > position) {
+ arg = args.optString(position);
+ if (arg == null || "null".equals(arg)) {
+ arg = defaultString;
+ }
+ }
+ return arg;
+ }
+
+ /**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ *
+ * @param source URL of the server to receive the file
+ * @param target Full path of the file on the file system
+ */
+ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ LOG.d(LOG_TAG, "download " + source + " to " + target);
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ final String objectId = args.getString(3);
+ final JSONObject headers = args.optJSONObject(4);
+
+ final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
+ int uriType = CordovaResourceApi.getUriType(sourceUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
+ if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ LOG.e(LOG_TAG, "Unsupported URI: " + sourceUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
+ * Previously the CordovaWebView class had a method, getWhitelist, which would
+ * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x,
+ * the correct call now is to shouldAllowRequest from the plugin manager.
+ */
+ Boolean shouldAllowRequest = null;
+ if (isLocalTransfer) {
+ shouldAllowRequest = true;
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gwl = webView.getClass().getMethod("getWhitelist");
+ Whitelist whitelist = (Whitelist)gwl.invoke(webView);
+ shouldAllowRequest = whitelist.isUrlWhiteListed(source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gpm = webView.getClass().getMethod("getPluginManager");
+ PluginManager pm = (PluginManager)gpm.invoke(webView);
+ Method san = pm.getClass().getMethod("shouldAllowRequest", String.class);
+ shouldAllowRequest = (Boolean)san.invoke(pm, source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+
+ if (!Boolean.TRUE.equals(shouldAllowRequest)) {
+ LOG.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+
+ // Accept a path or a URI for the source.
+ Uri tmpTarget = Uri.parse(target);
+ Uri targetUri = resourceApi.remapUri(
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));
+ HttpURLConnection connection = null;
+ File file = null;
+ PluginResult result = null;
+ TrackingInputStream inputStream = null;
+ boolean cached = false;
+
+ OutputStream outputStream = null;
+ try {
+ OpenForReadResult readResult = null;
+
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+
+ LOG.d(LOG_TAG, "Download file:" + sourceUri);
+
+ FileProgressResult progress = new FileProgressResult();
+
+ if (isLocalTransfer) {
+ readResult = resourceApi.openForRead(sourceUri);
+ if (readResult.length != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(readResult.length);
+ }
+ inputStream = new SimpleTrackingInputStream(readResult.inputStream);
+ } else {
+ // connect to server
+ // Open a HTTP connection to the URL based on protocol
+ connection = resourceApi.createHttpConnection(sourceUri);
+ connection.setRequestMethod("GET");
+
+ // TODO: Make OkHttp use this CookieManager by default.
+ String cookie = getCookies(sourceUri.toString());
+
+ if(cookie != null)
+ {
+ connection.setRequestProperty("cookie", cookie);
+ }
+
+ // This must be explicitly set for gzip progress tracking to work.
+ connection.setRequestProperty("Accept-Encoding", "gzip");
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(connection, headers);
+ }
+
+ connection.connect();
+ if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ cached = true;
+ connection.disconnect();
+ LOG.d(LOG_TAG, "Resource not modified: " + source);
+ JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null);
+ result = new PluginResult(PluginResult.Status.ERROR, error);
+ } else {
+ if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
+ // Only trust content-length header if we understand
+ // the encoding -- identity or gzip
+ if (connection.getContentLength() != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(connection.getContentLength());
+ }
+ }
+ inputStream = getInputStream(connection);
+ }
+ }
+
+ if (!cached) {
+ try {
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = connection;
+ }
+
+ // write bytes to file
+ byte[] buffer = new byte[MAX_BUFFER_SIZE];
+ int bytesRead = 0;
+ outputStream = resourceApi.openOutputStream(targetUri);
+ while ((bytesRead = inputStream.read(buffer)) > 0) {
+ outputStream.write(buffer, 0, bytesRead);
+ // Send a progress event.
+ progress.setLoaded(inputStream.getTotalRawBytesRead());
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inputStream);
+ safeClose(outputStream);
+ }
+
+ LOG.d(LOG_TAG, "Saved file: " + target);
+
+
+ // create FileEntry object
+ Class webViewClass = webView.getClass();
+ PluginManager pm = null;
+ try {
+ Method gpm = webViewClass.getMethod("getPluginManager");
+ pm = (PluginManager) gpm.invoke(webView);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ if (pm == null) {
+ try {
+ Field pmf = webViewClass.getField("pluginManager");
+ pm = (PluginManager)pmf.get(webView);
+ } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException e) {
+ }
+ }
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+ FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
+ if (filePlugin != null) {
+ JSONObject fileEntry = filePlugin.getEntryForFile(file);
+ if (fileEntry != null) {
+ result = new PluginResult(PluginResult.Status.OK, fileEntry);
+ } else {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null);
+ LOG.e(LOG_TAG, "File plugin cannot represent download path");
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ }
+ } else {
+ LOG.e(LOG_TAG, "File plugin not found; cannot save downloaded file");
+ result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");
+ }
+ }
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
+ LOG.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ LOG.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (JSONException e) {
+ LOG.e(LOG_TAG, e.getMessage(), e);
+ result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
+ } catch (Throwable e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ LOG.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (result == null) {
+ result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null));
+ }
+ // Remove incomplete download.
+ if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
+ file.delete();
+ }
+ context.sendPluginResult(result);
+ }
+ }
+ });
+ }
+
+ /**
+ * Abort an ongoing upload or download.
+ */
+ private void abort(String objectId) {
+ final RequestContext context;
+ synchronized (activeRequests) {
+ context = activeRequests.remove(objectId);
+ }
+ if (context != null) {
+ // Closing the streams can block, so execute on a background thread.
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ synchronized (context) {
+ File file = context.targetFile;
+ if (file != null) {
+ file.delete();
+ }
+ // Trigger the abort callback immediately to minimize latency between it and abort() being called.
+ JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
+ context.aborted = true;
+ if (context.connection != null) {
+ try {
+ context.connection.disconnect();
+ } catch (Exception e) {
+ LOG.e(LOG_TAG, "CB-8431 Catch workaround for fatal exception", e);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.java
new file mode 100644
index 000000000..c24ea78ae
--- /dev/null
+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.java
@@ -0,0 +1,73 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates the result and/or status of uploading a file to a remote server.
+ */
+public class FileUploadResult {
+
+ private long bytesSent = 0; // bytes sent
+ private int responseCode = -1; // HTTP response code
+ private String response = null; // HTTP response
+ private String objectId = null; // FileTransfer object id
+
+ public long getBytesSent() {
+ return bytesSent;
+ }
+
+ public void setBytesSent(long bytes) {
+ this.bytesSent = bytes;
+ }
+
+ public int getResponseCode() {
+ return responseCode;
+ }
+
+ public void setResponseCode(int responseCode) {
+ this.responseCode = responseCode;
+ }
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public String getObjectId() {
+ return objectId;
+ }
+
+ public void setObjectId(String objectId) {
+ this.objectId = objectId;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{bytesSent:" + bytesSent +
+ ",responseCode:" + responseCode +
+ ",response:" + JSONObject.quote(response) +
+ ",objectId:" + JSONObject.quote(objectId) + "}");
+ }
+}
diff --git a/cordova/platforms/android/app/src/main/res/xml/config.xml b/cordova/platforms/android/app/src/main/res/xml/config.xml
index 81def37b1..d00f6f706 100644
--- a/cordova/platforms/android/app/src/main/res/xml/config.xml
+++ b/cordova/platforms/android/app/src/main/res/xml/config.xml
@@ -27,6 +27,15 @@
<feature name="FileOpener2">
<param name="android-package" value="io.github.pwlin.cordova.plugins.fileopener2.FileOpener2" />
</feature>
+ <feature name="Downloader">
+ <param name="android-package" value="com.whebcraft.android.plugin.Downloader" />
+ </feature>
+ <feature name="FileTransfer">
+ <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
+ </feature>
+ <feature name="Zip">
+ <param name="android-package" value="org.apache.cordova.Zip" />
+ </feature>
<name>TagSpaces Beta</name>
<description>
Offline file organizer and browser with tagging support.
diff --git a/cordova/platforms/android/platform_www/cordova_plugins.js b/cordova/platforms/android/platform_www/cordova_plugins.js
index 825eaebf2..78e3f9ed8 100644
--- a/cordova/platforms/android/platform_www/cordova_plugins.js
+++ b/cordova/platforms/android/platform_www/cordova_plugins.js
@@ -243,6 +243,14 @@ module.exports = [
"clobbers": [
"cordova.plugins.fileOpener2"
]
+ },
+ {
+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",
+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",
+ "pluginId": "com.whebcraft.cordova.plugin.downloader",
+ "clobbers": [
+ "plugins.Downloader"
+ ]
}
];
module.exports.metadata =
@@ -255,7 +263,8 @@ module.exports.metadata =
"cordova-plugin-whitelist": "1.3.4",
"es6-promise-plugin": "4.2.2",
"cordova-plugin-x-socialsharing": "5.6.8",
- "cordova-plugin-file-opener2": "3.0.3"
+ "cordova-plugin-file-opener2": "3.0.3",
+ "com.whebcraft.cordova.plugin.downloader": "0.1.0"
};
// BOTTOM OF METADATA
});
\ No newline at end of file
diff --git a/cordova/platforms/android/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js b/cordova/platforms/android/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js
new file mode 100644
index 000000000..b8dad0882
--- /dev/null
+++ b/cordova/platforms/android/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js
@@ -0,0 +1,25 @@
+cordova.define("com.whebcraft.cordova.plugin.downloader.Downloader", function(require, exports, module) {
+var Downloader = {
+ download: function (arguments, successCallback, errorCallback) {
+ cordova.exec(
+ successCallback,
+ errorCallback,
+ 'Downloader',
+ 'download',
+ [arguments]
+ );
+ }
+};
+
+function install() {
+ if (!window.plugins) {
+ window.plugins = {};
+ }
+
+ window.plugins.Downloader = Downloader;
+ return window.plugins.Downloader;
+};
+
+cordova.addConstructor(install);
+
+});
diff --git a/cordova/yarn.lock b/cordova/yarn.lock
index 92d5365d1..29c51aafd 100644
--- a/cordova/yarn.lock
+++ b/cordova/yarn.lock
@@ -2,7 +2,7 @@
# yarn lockfile v1
-abbrev@1:
+abbrev@*, abbrev@1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==
@@ -14,16 +14,20 @@ [email protected]:
dependencies:
semver "^5.4.1"
-ansi@^0.3.1:
+ansi@*, ansi@^0.3.1:
version "0.3.1"
resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21"
integrity sha1-DELU+xcWDVqa8eSEus4cZpIsGyE=
-balanced-match@^1.0.0:
+balanced-match@*, balanced-match@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=
+"bamboo.cordova.plugin.downloader@git+https://github.com/sytolk/cordova-plugin-downloader.git":
+ version "1.0.0"
+ resolved "git+https://github.com/sytolk/cordova-plugin-downloader.git#b33d614ac9d4dc4c50e38ebde5a9b11e987ca145"
+
version "1.2.0"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.0.tgz#a39992d723584811982be5e290bb6a53d86700f1"
@@ -34,10 +38,17 @@ [email protected]:
resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.32.tgz#5867458b25ecd5bcb36b627c30bb501a13c07e89"
integrity sha512-ljKJdR3wk9thHfLj4DtrNiOSTxvGFaMjWrG4pW75juXC4j7+XuKJVFdg4kgFMYp85PVkO05dFMj2dk2xVsH4xw==
-big-integer@^1.6.7:
- version "1.6.40"
- resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.40.tgz#02e4cd4d6e266c4d9ece2469c05cb6439149fc78"
- integrity sha512-CjhtJp0BViLzP1ZkEnoywjgtFQXS2pomKjAJtIISTCnuHILkLcAXLdFLG/nxsHc4s9kJfc+82Xpg8WNyhfACzQ==
+big-integer@^1.6.44, big-integer@^1.6.7:
+ version "1.6.48"
+ resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.48.tgz#8fd88bd1632cba4a1c8c3e3d7159f08bb95b4b9e"
+ integrity sha512-j51egjPa7/i+RdiRuJbPdJ2FIUYYPhvYLjzoYbcMMm62ooO6F94fETG4MTs46zPAF9Brs04OajboA/qTGuz78w==
+
+bplist-parser@*:
+ version "0.2.0"
+ resolved "https://registry.yarnpkg.com/bplist-parser/-/bplist-parser-0.2.0.tgz#43a9d183e5bf9d545200ceac3e712f79ebbe8d0e"
+ integrity sha512-z0M+byMThzQmD9NILRniCUXYsYpjwnlO8N5uCFaCqIOpqRsJCrQL9NK3JsD67CN5a08nF5oIL2bD6loTdHOuKw==
+ dependencies:
+ big-integer "^1.6.44"
bplist-parser@^0.1.0:
version "0.1.1"
@@ -46,7 +57,7 @@ bplist-parser@^0.1.0:
dependencies:
big-integer "^1.6.7"
-brace-expansion@^1.1.7:
+brace-expansion@*, brace-expansion@^1.1.7:
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==
@@ -54,7 +65,7 @@ brace-expansion@^1.1.7:
balanced-match "^1.0.0"
concat-map "0.0.1"
+concat-map@*, [email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=
@@ -113,9 +124,9 @@ cordova-plugin-device@^2.0.3:
integrity sha512-Jb3V72btxf3XHpkPQsGdyc8N6tVBYn1vsxSFj43fIz9vonJDUThYPCJJHqk6PX6N4dJw6I4FjxkpfCR4LDYMlw==
cordova-plugin-file-opener2@^3.0.3:
- version "3.0.3"
- resolved "https://registry.yarnpkg.com/cordova-plugin-file-opener2/-/cordova-plugin-file-opener2-3.0.3.tgz#921d49f319934abfd6156390f6d0e034e1ac97a6"
- integrity sha512-hIEwntib8fTGlLyVFhRUsrk2SueVJtLPSfqvMrbgaRUCKY2AFNYPtsGiu5oCBKXSe+9Xxh6nIdLKdqGzaOnGAQ==
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/cordova-plugin-file-opener2/-/cordova-plugin-file-opener2-3.0.4.tgz#e95cf2da11666cbf25346a4c9463ec4dd162c6fd"
+ integrity sha512-bd1aCx62X2RwpC+KUiuB7quoxL/8RnPMEJU7x38Tvs+cUGLWBvsmR9+/LqGBsSns2CIqgnJ34TW0Vazoqu7Ieg==
version "6.0.2"
@@ -132,7 +143,7 @@ cordova-plugin-x-socialsharing@^5.6.8:
resolved "https://registry.yarnpkg.com/cordova-plugin-x-socialsharing/-/cordova-plugin-x-socialsharing-5.6.8.tgz#81993336fa4260eb76a23ed1680cd63e1c72b040"
integrity sha512-R31ZQq00YNzLBwUM4VTE/uKhh/T0GEMuz/MZOw/Pu5AYIAAQkd7EMqFVhMtKs7wfHl1koiRz8+6nLDb19r2tBQ==
-cordova-registry-mapper@^1.1.8:
+cordova-registry-mapper@*, cordova-registry-mapper@^1.1.8:
version "1.1.15"
resolved "https://registry.yarnpkg.com/cordova-registry-mapper/-/cordova-registry-mapper-1.1.15.tgz#e244b9185b8175473bff6079324905115f83dc7c"
integrity sha1-4kS5GFuBdUc7/2B5MkkFEV+D3Hw=
@@ -160,7 +171,7 @@ [email protected], glob@^5.0.13:
once "^1.3.0"
path-is-absolute "^1.0.0"
-inflight@^1.0.4:
+inflight@*, inflight@^1.0.4:
version "1.0.6"
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=
@@ -168,12 +179,12 @@ inflight@^1.0.4:
once "^1.3.0"
wrappy "1"
-inherits@2:
- version "2.0.3"
- resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
- integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
+inherits@*, inherits@2:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
+ integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
-"minimatch@2 || 3", minimatch@^3.0.0:
+minimatch@*, "minimatch@2 || 3", minimatch@^3.0.0:
version "3.0.4"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==
@@ -187,7 +198,7 @@ [email protected]:
dependencies:
abbrev "1"
-once@^1.3.0:
+once@*, once@^1.3.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=
@@ -234,26 +245,26 @@ [email protected]:
integrity sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==
semver@^5.4.1:
- version "5.6.0"
- resolved "https://registry.yarnpkg.com/semver/-/semver-5.6.0.tgz#7e74256fbaa49c75aa7c7a205cc22799cac80004"
- integrity sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==
+ version "5.7.1"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
+ integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==
[email protected], shelljs@^0.5.3:
version "0.5.3"
resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.5.3.tgz#c54982b996c76ef0c1e6b59fbdc5825f5b713113"
integrity sha1-xUmCuZbHbvDB5rWfvcWCX1txMRM=
-underscore@^1.8.3:
- version "1.9.1"
- resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.9.1.tgz#06dce34a0e68a7babc29b365b8e74b8925203961"
- integrity sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg==
+underscore@*, underscore@^1.8.3:
+ version "1.10.2"
+ resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.10.2.tgz#73d6aa3668f3188e4adb0f1943bd12cfd7efaaaf"
+ integrity sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==
-unorm@^1.3.3:
+unorm@*, unorm@^1.3.3:
version "1.6.0"
resolved "https://registry.yarnpkg.com/unorm/-/unorm-1.6.0.tgz#029b289661fba714f1a9af439eb51d9b16c205af"
integrity sha512-b2/KCUlYZUeA7JFUuRJZPUtr4gZvBh7tavtv4fvk4+KV9pfGiR6CQAQAWl49ZpR3ts2dk4FYkP7EIgDJoiOLDA==
-wrappy@1:
+wrappy@*, wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
@@ -263,7 +274,12 @@ [email protected]:
resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-8.2.2.tgz#69248673410b4ba42e1a6136551d2922335aa773"
integrity sha1-aSSGc0ELS6QuGmE2VR0pIjNap3M=
+xmldom@*:
+ version "0.3.0"
+ resolved "https://registry.yarnpkg.com/xmldom/-/xmldom-0.3.0.tgz#e625457f4300b5df9c2e1ecb776147ece47f3e5a"
+ integrity sha512-z9s6k3wxE+aZHgXYxSTpGDo7BYOUfJsIRyoZiX6HTjwpwfS2wpQBQKa2fD+ShLyPkqDYo5ud7KitmLZ2Cd6r0g==
+
- version "0.1.27"
- resolved "https://registry.yarnpkg.com/xmldom/-/xmldom-0.1.27.tgz#d501f97b3bdb403af8ef9ecc20573187aadac0e9"
- integrity sha1-1QH5ezvbQDr4757MIFcxh6rawOk=
+ version "0.1.31"
+ resolved "https://registry.yarnpkg.com/xmldom/-/xmldom-0.1.31.tgz#b76c9a1bd9f0a9737e5a72dc37231cf38375e2ff"
+ integrity sha512-yS2uJflVQs6n+CyjHoaBmVSqIDevTAWrzMmjG1Gc7h1qQ7uVozNhEPJAwZXWyGQ/Gafo3fCwrcaokezLPupVyQ==
diff --git a/package.json b/package.json
index a0f0a6182..2048c6b50 100644
--- a/package.json
+++ b/package.json
@@ -281,7 +281,7 @@
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-router-redux": "^5.0.0-alpha.6",
- "react-split-pane": "^0.1.91",
+ "react-split-pane": "https://github.com/quarkw/react-split-pane",
"react-swipeable-views": "0.13.3",
"react-virtualized": "^9.21.1",
"redux": "^3.7.2",
diff --git a/yarn.lock b/yarn.lock
index 45dd96098..281421c04 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -14243,16 +14243,15 @@ react-router@^4.2.0, react-router@^4.3.1:
prop-types "^15.6.1"
warning "^4.0.1"
-react-split-pane@^0.1.91:
- version "0.1.91"
- resolved "https://registry.yarnpkg.com/react-split-pane/-/react-split-pane-0.1.91.tgz#18b9ef23b2ff225c957f77b6b096e458d85312ae"
- integrity sha512-8U56HOKQGFlvXXT1PaHbijjYy2W8g0iQaHC99Q2aV4yYfvUURcRGyfPKN3scGkbYN2pvy3qyoEwHyewUmR1VbQ==
+"react-split-pane@https://github.com/quarkw/react-split-pane":
+ version "0.1.87"
+ resolved "https://github.com/quarkw/react-split-pane#50ffccdfb012cd2159d04136a8e2a1ad42766617"
dependencies:
- prop-types "^15.7.2"
+ prop-types "^15.5.10"
react-lifecycles-compat "^3.0.4"
- react-style-proptype "^3.2.2"
+ react-style-proptype "^3.0.0"
-react-style-proptype@^3.2.2:
+react-style-proptype@^3.0.0:
version "3.2.2"
resolved "https://registry.yarnpkg.com/react-style-proptype/-/react-style-proptype-3.2.2.tgz#d8e998e62ce79ec35b087252b90f19f1c33968a0"
integrity sha512-ywYLSjNkxKHiZOqNlso9PZByNEY+FTyh3C+7uuziK0xFXu9xzdyfHwg4S9iyiRRoPCR4k2LqaBBsWVmSBwCWYQ==