mirror of
https://gitee.com/shuto/cordova-plugin-file-opener2.git
synced 2025-03-15 22:21:01 +08:00
Merge branch 'master' into master
This commit is contained in:
commit
ebf97733be
1
.gitignore
vendored
1
.gitignore
vendored
@ -4,3 +4,4 @@
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.bak
|
||||
|
173
README.md
173
README.md
@ -1,14 +1,8 @@
|
||||
Contributors
|
||||
------------
|
||||
[@Gillardo](https://github.com/Gillardo/), [@TankOs](https://github.com/TankOs), [@Rovi23](https://github.com/Rovi23), [@josemanuelbd](https://github.com/josemanuelbd), [@ielcoro](https://github.com/ielcoro), [@keturn](https://github.com/keturn), [@conform](https://github.com/conform), [@guyc](https://github.com/guyc)
|
||||
|
||||
|
||||
A File Opener Plugin for Cordova (The Original Version)
|
||||
==========================
|
||||
This plugin will open a file on your device file system with its default application.
|
||||
|
||||
Current Version: 2.0.2
|
||||
----------------
|
||||
[](https://badge.fury.io/js/cordova-plugin-file-opener2)
|
||||
|
||||
Requirements
|
||||
-------------
|
||||
@ -17,85 +11,142 @@ Requirements
|
||||
|
||||
Installation
|
||||
-------------
|
||||
cordova plugin add cordova-plugin-file-opener2
|
||||
|
||||
```shell
|
||||
$ cordova plugin add cordova-plugin-file-opener2
|
||||
$ cordova plugin add cordova-plugin-file-opener2 --variable ANDROID_SUPPORT_VERSION={required version}
|
||||
```
|
||||
|
||||
Usage
|
||||
------
|
||||
cordova.plugins.fileOpener2.open(
|
||||
filePath,
|
||||
fileMIMEType,
|
||||
{
|
||||
error : function(){ },
|
||||
success : function(){ }
|
||||
position : [x, y]
|
||||
}
|
||||
);
|
||||
|
||||
`position` array of coordinates from top-left device screen, use for iOS dialog positioning
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.open(
|
||||
filePath,
|
||||
fileMIMEType,
|
||||
{
|
||||
error : function(){ },
|
||||
success : function(){ },
|
||||
position : [x, y]
|
||||
}
|
||||
);
|
||||
```
|
||||
`position` array of coordinates from top-left device screen, use for iOS dialog positioning.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Open an APK install dialog:
|
||||
|
||||
cordova.plugins.fileOpener2.open(
|
||||
'/sdcard/Download/gmail.apk',
|
||||
'application/vnd.android.package-archive'
|
||||
);
|
||||
|
||||
Open a PDF document with the default PDF reader and optional callback object:
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.open(
|
||||
'/sdcard/Download/gmail.apk',
|
||||
'application/vnd.android.package-archive'
|
||||
);
|
||||
```
|
||||
|
||||
cordova.plugins.fileOpener2.open(
|
||||
'/sdcard/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
|
||||
'application/pdf',
|
||||
{
|
||||
error : function(e) {
|
||||
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
|
||||
},
|
||||
success : function () {
|
||||
console.log('file opened successfully');
|
||||
}
|
||||
Install From Market: to install an APK from a market place, such as Google Play or the App Store, you can use an `<a>` tag in combination with the `market://` protocol:
|
||||
|
||||
```html
|
||||
<a href="market://details?id=xxxx" target="_system">Install from Google Play</a>
|
||||
<a href="itms-apps://itunes.apple.com/app/my-app/idxxxxxxxx?mt=8" target="_system">Install from App Store</a>
|
||||
```
|
||||
|
||||
or in code:
|
||||
```javascript
|
||||
window.open("[market:// or itms-apps:// link]","_system");
|
||||
```
|
||||
|
||||
Open a PDF document with the default PDF reader and optional callback object:
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.open(
|
||||
'/sdcard/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
|
||||
'application/pdf',
|
||||
{
|
||||
error : function(e) {
|
||||
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
|
||||
},
|
||||
success : function () {
|
||||
console.log('file opened successfully');
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
```
|
||||
Open a system modal to open PDF document with one of the already installed app and optional callback object:
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.showOpenWithDialog(
|
||||
'/sdcard/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
|
||||
'application/pdf',
|
||||
{
|
||||
error : function(e) {
|
||||
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
|
||||
},
|
||||
success : function () {
|
||||
console.log('file opened successfully');
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Notes
|
||||
------
|
||||
|
||||
- For properly opening _any_ file, you must already have a suitable reader for that particular file type installed on your device. Otherwise this will not work.
|
||||
|
||||
|
||||
- [It is reported](https://github.com/pwlin/cordova-plugin-file-opener2/issues/2#issuecomment-41295793) that in iOS, you might need to remove `<preference name="iosPersistentFileLocation" value="Library" />` from your `config.xml`
|
||||
|
||||
- If you are wondering what MIME-type should you pass as the second argument to `open` function, [here is a list of all known MIME-types](http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=co)
|
||||
|
||||
|
||||
Android APK installation limitation
|
||||
---
|
||||
The following limitations apply when opening an APK file for installation:
|
||||
- On Android 8+, your application must have the `ACTION_INSTALL_PACKAGE` permission. You can add it by adding this to your app's `config.xml` file:
|
||||
```xml
|
||||
<platform name="android">
|
||||
<config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
</config-file>
|
||||
</platform>
|
||||
```
|
||||
|
||||
- Before Android 7, you can only install APKs from the "external" partition. For example, you can install from `cordova.file.externalDataDirectory`, but **not** from `cordova.file.dataDirectory`. Android 7+ does not have this limitation.
|
||||
|
||||
Additional Android Functions
|
||||
-----------------------------
|
||||
####The following functions are available in Android platform
|
||||
---
|
||||
The following functions are available in Android platform:
|
||||
|
||||
###.uninstall(_packageId, callbackContext_)
|
||||
`.uninstall(packageId, callbackContext)`
|
||||
---
|
||||
Uninstall a package with its id.
|
||||
|
||||
cordova.plugins.fileOpener2.uninstall('com.zynga.FarmVille2CountryEscape', {
|
||||
error : function(e) {
|
||||
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
|
||||
},
|
||||
success : function() {
|
||||
console.log('Uninstall intent activity started.');
|
||||
}
|
||||
});
|
||||
|
||||
###.appIsInstalled(_packageId, callbackContext_)
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.uninstall('com.zynga.FarmVille2CountryEscape', {
|
||||
error : function(e) {
|
||||
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
|
||||
},
|
||||
success : function() {
|
||||
console.log('Uninstall intent activity started.');
|
||||
}
|
||||
});
|
||||
```
|
||||
`.appIsInstalled(packageId, callbackContext)`
|
||||
---
|
||||
Check if an app is already installed.
|
||||
|
||||
cordova.plugins.fileOpener2.appIsInstalled('com.adobe.reader', {
|
||||
success : function(res) {
|
||||
if (res.status === 0) {
|
||||
console.log('Adobe Reader is not installed.');
|
||||
} else {
|
||||
console.log('Adobe Reader is installed.')
|
||||
}
|
||||
```javascript
|
||||
cordova.plugins.fileOpener2.appIsInstalled('com.adobe.reader', {
|
||||
success : function(res) {
|
||||
if (res.status === 0) {
|
||||
console.log('Adobe Reader is not installed.');
|
||||
} else {
|
||||
console.log('Adobe Reader is installed.')
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
---
|
||||
|
||||
Contributors
|
||||
------------
|
||||
[@Gillardo](https://github.com/Gillardo/), [@TankOs](https://github.com/TankOs), [@Rovi23](https://github.com/Rovi23), [@josemanuelbd](https://github.com/josemanuelbd), [@ielcoro](https://github.com/ielcoro), [@keturn](https://github.com/keturn), [@conform](https://github.com/conform), [@guyc](https://github.com/guyc), [@J3r0M3D3V](https://github.com/J3r0M3D3V), [@WuglyakBolgoink](https://github.com/WuglyakBolgoink), [@lincolnthree](https://github.com/lincolnthree), [@rocco](https://github.com/rocco/), [@FrankFenton](https://github.com/FrankFenton), [@MHolmes91](https://github.com/MHolmes91), [@souly1](https://github.com/souly1), [@diogodias86](https://github.com/diogodias86), [@Arxi](https://github.com/Arxi), [@vzharkov](https://github.com/vzharkov), [@lp1bp](https://github.com/lp1bp), [@stalniy](https://github.com/stalniy), [@liugogal](https://github.com/liugogal), [@lcaprini](https://github.com/lcaprini), [@jcdickman](https://github.com/jcdickman) [@shnist](https://github.com/shnist) [@Eeems](https://github.com/Eeems)
|
||||
|
||||
---
|
||||
|
||||
LICENSE
|
||||
--------
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cordova-plugin-file-opener2",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.0",
|
||||
"description": "A File Opener Plugin for Cordova. (The Original Version)",
|
||||
"cordova": {
|
||||
"id": "cordova-plugin-file-opener2",
|
||||
|
14
plugin.xml
14
plugin.xml
@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-file-opener2" version="2.0.2">
|
||||
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-file-opener2" version="2.1.0">
|
||||
|
||||
<name>File Opener2</name>
|
||||
<description>A File Opener Plugin for Cordova. (The Original Version)</description>
|
||||
@ -16,6 +16,7 @@
|
||||
<!-- Android -->
|
||||
<platform name="android">
|
||||
<source-file src="src/android/io/github/pwlin/cordova/plugins/fileopener2/FileOpener2.java" target-dir="src/io/github/pwlin/cordova/plugins/fileopener2" />
|
||||
<source-file src="src/android/io/github/pwlin/cordova/plugins/fileopener2/FileProvider.java" target-dir="src/io/github/pwlin/cordova/plugins/fileopener2" />
|
||||
<config-file target="res/xml/config.xml" parent="/*">
|
||||
<feature name="FileOpener2">
|
||||
<param name="android-package" value="io.github.pwlin.cordova.plugins.fileopener2.FileOpener2" />
|
||||
@ -24,6 +25,14 @@
|
||||
<config-file target="AndroidManifest.xml" parent="/*">
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
</config-file>
|
||||
<config-file target="AndroidManifest.xml" parent="/manifest/application">
|
||||
<provider android:name="io.github.pwlin.cordova.plugins.fileopener2.FileProvider" android:authorities="${applicationId}.opener.provider" android:exported="false" android:grantUriPermissions="true">
|
||||
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/opener_paths" />
|
||||
</provider>
|
||||
</config-file>
|
||||
<source-file src="src/android/res/xml/opener_paths.xml" target-dir="res/xml" />
|
||||
<preference name="ANDROID_SUPPORT_V4_VERSION" default="27.+"/>
|
||||
<framework src="com.android.support:support-v4:$ANDROID_SUPPORT_V4_VERSION"/>
|
||||
</platform>
|
||||
|
||||
<!-- iOS -->
|
||||
@ -46,9 +55,8 @@
|
||||
</config-file>
|
||||
<source-file src="src/wp8/FileOpener2.cs" />
|
||||
</platform>
|
||||
|
||||
|
||||
<!-- windows -->
|
||||
<!-- windows -->
|
||||
<platform name="windows">
|
||||
<js-module src="src/windows/fileOpener2Proxy.js" name="fileOpener2Proxy">
|
||||
<merges target="" />
|
||||
|
@ -23,15 +23,20 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
package io.github.pwlin.cordova.plugins.fileopener2;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.net.Uri;
|
||||
//import android.util.Log;
|
||||
import android.os.Build;
|
||||
|
||||
import io.github.pwlin.cordova.plugins.fileopener2.FileProvider;
|
||||
|
||||
import org.apache.cordova.CordovaPlugin;
|
||||
import org.apache.cordova.CallbackContext;
|
||||
@ -42,7 +47,7 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
|
||||
/**
|
||||
* Executes the request and returns a boolean.
|
||||
*
|
||||
*
|
||||
* @param action
|
||||
* The action to execute.
|
||||
* @param args
|
||||
@ -53,8 +58,14 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
*/
|
||||
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
|
||||
if (action.equals("open")) {
|
||||
this._open(args.getString(0), args.getString(1), callbackContext);
|
||||
}
|
||||
String fileUrl = args.getString(0);
|
||||
String contentType = args.getString(1);
|
||||
Boolean openWithDefault = true;
|
||||
if(args.length() > 2){
|
||||
openWithDefault = args.getBoolean(2);
|
||||
}
|
||||
this._open(fileUrl, contentType, openWithDefault, callbackContext);
|
||||
}
|
||||
else if (action.equals("uninstall")) {
|
||||
this._uninstall(args.getString(0), callbackContext);
|
||||
}
|
||||
@ -79,7 +90,7 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
return true;
|
||||
}
|
||||
|
||||
private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
|
||||
private void _open(String fileArg, String contentType, Boolean openWithDefault, CallbackContext callbackContext) throws JSONException {
|
||||
String fileName = "";
|
||||
try {
|
||||
CordovaResourceApi resourceApi = webView.getResourceApi();
|
||||
@ -91,16 +102,40 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
File file = new File(fileName);
|
||||
if (file.exists()) {
|
||||
try {
|
||||
Uri path = Uri.fromFile(file);
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setDataAndType(path, contentType);
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
Intent intent;
|
||||
if (contentType.equals("application/vnd.android.package-archive")) {
|
||||
// https://stackoverflow.com/questions/9637629/can-we-install-an-apk-from-a-contentprovider/9672282#9672282
|
||||
intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
|
||||
Uri path;
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||
path = Uri.fromFile(file);
|
||||
} else {
|
||||
Context context = cordova.getActivity().getApplicationContext();
|
||||
path = FileProvider.getUriForFile(context, cordova.getActivity().getPackageName() + ".opener.provider", file);
|
||||
}
|
||||
intent.setDataAndType(path, contentType);
|
||||
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
|
||||
} else {
|
||||
intent = new Intent(Intent.ACTION_VIEW);
|
||||
Context context = cordova.getActivity().getApplicationContext();
|
||||
Uri path = FileProvider.getUriForFile(context, cordova.getActivity().getPackageName() + ".opener.provider", file);
|
||||
intent.setDataAndType(path, contentType);
|
||||
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NO_HISTORY);
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* @see
|
||||
* http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
|
||||
*/
|
||||
cordova.getActivity().startActivity(intent);
|
||||
//cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
|
||||
if(openWithDefault){
|
||||
cordova.getActivity().startActivity(intent);
|
||||
}
|
||||
else{
|
||||
cordova.getActivity().startActivity(Intent.createChooser(intent, "Open File in..."));
|
||||
}
|
||||
|
||||
callbackContext.success();
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
JSONObject errorObj = new JSONObject();
|
||||
@ -115,7 +150,7 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
callbackContext.error(errorObj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void _uninstall(String packageId, CallbackContext callbackContext) throws JSONException {
|
||||
if (this._appIsInstalled(packageId)) {
|
||||
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
|
||||
@ -130,7 +165,7 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
callbackContext.error(errorObj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private boolean _appIsInstalled(String packageId) {
|
||||
PackageManager pm = cordova.getActivity().getPackageManager();
|
||||
boolean appInstalled = false;
|
||||
@ -146,6 +181,8 @@ public class FileOpener2 extends CordovaPlugin {
|
||||
private String stripFileProtocol(String uriString) {
|
||||
if (uriString.startsWith("file://")) {
|
||||
uriString = uriString.substring(7);
|
||||
} else if (uriString.startsWith("content://")) {
|
||||
uriString = uriString.substring(10);
|
||||
}
|
||||
return uriString;
|
||||
}
|
||||
|
@ -0,0 +1,29 @@
|
||||
/*
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 pwlin - pwlin05@gmail.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.pwlin.cordova.plugins.fileopener2;
|
||||
|
||||
/*
|
||||
* http://stackoverflow.com/questions/40746144/error-with-duplicated-fileprovider-in-manifest-xml-with-cordova/41550634#41550634
|
||||
*/
|
||||
public class FileProvider extends android.support.v4.content.FileProvider {
|
||||
}
|
14
src/android/res/xml/opener_paths.xml
Normal file
14
src/android/res/xml/opener_paths.xml
Normal file
@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- https://developer.android.com/reference/android/support/v4/content/FileProvider.html#SpecifyFiles -->
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- cordova.file.dataDirectory -->
|
||||
<files-path name="files" path="." />
|
||||
<!-- cordova.file.cacheDirectory -->
|
||||
<cache-path name="cache" path="." />
|
||||
<!-- cordova.file.externalDataDirectory -->
|
||||
<external-files-path name="external-files" path="." />
|
||||
<!-- cordova.file.externalCacheDirectory -->
|
||||
<external-cache-path name="external-cache" path="." />
|
||||
<!-- cordova.file.externalRootDirectory -->
|
||||
<external-path name="external" path="." />
|
||||
</paths>
|
@ -28,6 +28,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
}
|
||||
|
||||
@property(nonatomic, strong) UIDocumentInteractionController *controller;
|
||||
@property(nonatomic, strong) CDVViewController *cdvViewController;
|
||||
|
||||
- (void) open: (CDVInvokedUrlCommand*)command;
|
||||
|
||||
|
@ -27,62 +27,90 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
#import <MobileCoreServices/MobileCoreServices.h>
|
||||
|
||||
@implementation FileOpener2
|
||||
@synthesize controller = docController;
|
||||
|
||||
- (void) open: (CDVInvokedUrlCommand*)command {
|
||||
|
||||
NSString *path = command.arguments[0];
|
||||
NSString *uti = command.arguments[1];
|
||||
if (!uti || (NSNull*)uti == [NSNull null]) {
|
||||
NSArray *dotParts = [path componentsSeparatedByString:@"."];
|
||||
NSString *fileExt = [dotParts lastObject];
|
||||
|
||||
uti = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExt, NULL);
|
||||
}
|
||||
|
||||
CGRect rect;
|
||||
if (3 >= [command.arguments count]) {
|
||||
NSArray *positionValues = command.arguments[2];
|
||||
rect = CGRectMake(0,0,[[positionValues objectAtIndex:0] floatValue],[[positionValues objectAtIndex:1] floatValue]);
|
||||
} else {
|
||||
rect = CGRectMake(0, 0, 1000.0f, 150.0f);
|
||||
}
|
||||
NSString *path = [[command.arguments objectAtIndex:0] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
|
||||
NSString *contentType = [command.arguments objectAtIndex:1];
|
||||
BOOL showPreview = YES;
|
||||
|
||||
CDVViewController* cont = (CDVViewController*)[ super viewController ];
|
||||
if ([command.arguments count] >= 3) {
|
||||
showPreview = [[command.arguments objectAtIndex:2] boolValue];
|
||||
}
|
||||
|
||||
CGRect rect;
|
||||
if ([command.arguments count] >= 4) {
|
||||
NSArray *positionValues = command.arguments[3];
|
||||
rect = CGRectMake(0,0,[[positionValues objectAtIndex:0] floatValue],[[positionValues objectAtIndex:1] floatValue]);
|
||||
} else {
|
||||
rect = CGRectMake(0, 0, cont.view.bounds.size.width, cont.view.bounds.size.height);
|
||||
}
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// TODO: test if this is a URI or a path
|
||||
NSURL *fileURL = [NSURL URLWithString:path];
|
||||
|
||||
localFile = fileURL.path;
|
||||
|
||||
NSLog(@"looking for file at %@", fileURL);
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
if(![fm fileExistsAtPath:localFile]) {
|
||||
NSDictionary *jsonObj = @{@"status" : @"9",
|
||||
@"message" : @"File does not exist"};
|
||||
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
|
||||
messageAsDictionary:jsonObj];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
return;
|
||||
}
|
||||
CDVViewController* cont = (CDVViewController*)[super viewController];
|
||||
self.cdvViewController = cont;
|
||||
NSString *uti = nil;
|
||||
|
||||
self.controller = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
|
||||
self.controller.delegate = self;
|
||||
self.controller.UTI = uti;
|
||||
if([contentType length] == 0){
|
||||
NSArray *dotParts = [path componentsSeparatedByString:@"."];
|
||||
NSString *fileExt = [dotParts lastObject];
|
||||
|
||||
CDVPluginResult* pluginResult = nil;
|
||||
BOOL wasOpened = [self.controller presentOptionsMenuFromRect:rect inView:cont.view animated:NO];
|
||||
uti = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExt, NULL);
|
||||
} else {
|
||||
uti = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)contentType, NULL);
|
||||
}
|
||||
|
||||
if(wasOpened) {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @""];
|
||||
} else {
|
||||
NSDictionary *jsonObj = @{@"status" : @"9",
|
||||
@"message" : @"Could not handle UTI"};
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
|
||||
messageAsDictionary:jsonObj];
|
||||
}
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
});
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
NSURL *fileURL = [NSURL URLWithString:path];
|
||||
|
||||
localFile = fileURL.path;
|
||||
|
||||
NSLog(@"looking for file at %@", fileURL);
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
if(![fm fileExistsAtPath:localFile]) {
|
||||
NSDictionary *jsonObj = @{@"status" : @"9",
|
||||
@"message" : @"File does not exist"};
|
||||
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:jsonObj];
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
return;
|
||||
}
|
||||
|
||||
docController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
|
||||
docController.delegate = self;
|
||||
docController.UTI = uti;
|
||||
|
||||
CDVPluginResult* pluginResult = nil;
|
||||
|
||||
//Opens the file preview
|
||||
BOOL wasOpened = NO;
|
||||
|
||||
if (showPreview) {
|
||||
wasOpened = [docController presentPreviewAnimated: NO];
|
||||
} else {
|
||||
CDVViewController* cont = self.cdvViewController;
|
||||
wasOpened = [docController presentOpenInMenuFromRect:rect inView:cont.view animated:YES];
|
||||
}
|
||||
|
||||
if(wasOpened) {
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @""];
|
||||
//NSLog(@"Success");
|
||||
} else {
|
||||
NSDictionary *jsonObj = [ [NSDictionary alloc]
|
||||
initWithObjectsAndKeys :
|
||||
@"9", @"status",
|
||||
@"Could not handle UTI", @"message",
|
||||
nil
|
||||
];
|
||||
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:jsonObj];
|
||||
}
|
||||
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
|
||||
});
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation FileOpener2 (UIDocumentInteractionControllerDelegate)
|
||||
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
|
||||
return self.cdvViewController;
|
||||
}
|
||||
@end
|
||||
|
@ -4,18 +4,46 @@
|
||||
|
||||
var schemes = [
|
||||
{ protocol: 'ms-app', getFile: getFileFromApplicationUri },
|
||||
{ protocol: 'file:///', getFile: getFileFromFileUri }
|
||||
{ protocol: 'cdvfile', getFile: getFileFromFileUri } //protocol cdvfile
|
||||
]
|
||||
|
||||
function nthIndex(str, pat, n) {
|
||||
var L = str.length, i = -1;
|
||||
while (n-- && i++ < L) {
|
||||
i = str.indexOf(pat, i);
|
||||
if (i < 0) break;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
function getFileFromApplicationUri(uri) {
|
||||
var applicationUri = new Windows.Foundation.Uri(uri);
|
||||
/* bad path from a file entry due to the last '//'
|
||||
example: ms-appdata:///local//path/to/file
|
||||
*/
|
||||
var index = nthIndex(uri, "//", 3);
|
||||
var newUri = uri.substr(0, index) + uri.substr(index + 1);
|
||||
|
||||
var applicationUri = new Windows.Foundation.Uri(newUri);
|
||||
|
||||
return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(applicationUri);
|
||||
}
|
||||
|
||||
function getFileFromFileUri(uri) {
|
||||
var path = Windows.Storage.ApplicationData.current.localFolder.path +
|
||||
uri.substr(8);
|
||||
/* uri example:
|
||||
cdvfile://localhost/persistent|temporary|another-fs-root/path/to/file
|
||||
*/
|
||||
var indexFrom = nthIndex(uri, "/", 3) + 1;
|
||||
var indexTo = nthIndex(uri, "/", 4);
|
||||
var whichFolder = uri.substring(indexFrom, indexTo);
|
||||
var filePath = uri.substr(indexTo + 1);
|
||||
var path = "\\" + filePath;
|
||||
|
||||
if (whichFolder == "persistent") {
|
||||
path = Windows.Storage.ApplicationData.current.localFolder.path + path;
|
||||
}
|
||||
else { //temporary, note: no roaming management
|
||||
path = Windows.Storage.ApplicationData.current.temporaryFolder.path + path;
|
||||
}
|
||||
|
||||
return getFileFromNativePath(path);
|
||||
}
|
||||
@ -39,23 +67,27 @@
|
||||
module.exports = {
|
||||
|
||||
open: function (successCallback, errorCallback, args) {
|
||||
|
||||
var path = args[0];
|
||||
|
||||
var getFile = getFileLoaderForScheme(path);
|
||||
|
||||
|
||||
getFile(path).then(function (file) {
|
||||
var options = new Windows.System.LauncherOptions();
|
||||
|
||||
Windows.System.Launcher.launchFileAsync(file, options).then(function (success) {
|
||||
if (success) {
|
||||
|
||||
try{
|
||||
Windows.System.Launcher.launchFileAsync(file, options).then(function (success) {
|
||||
successCallback();
|
||||
} else {
|
||||
errorCallback();
|
||||
}
|
||||
});
|
||||
}, function (error) {
|
||||
errorCallback(error);
|
||||
});
|
||||
}catch(error){
|
||||
errorCallback(error);
|
||||
}
|
||||
|
||||
}, function (errror) {
|
||||
console.log("Error abriendo el archivo");
|
||||
}, function (error) {
|
||||
console.log("Error while opening the file: "+error);
|
||||
errorCallback(error);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -27,13 +27,20 @@ var exec = require('cordova/exec');
|
||||
function FileOpener2() {}
|
||||
|
||||
FileOpener2.prototype.open = function (fileName, contentType, options) {
|
||||
contentType = contentType || '';
|
||||
options = options || {};
|
||||
exec(options.success || null, options.error || null, 'FileOpener2', 'open', [fileName, contentType, options.position]);
|
||||
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType, false, options.position]);
|
||||
};
|
||||
|
||||
FileOpener2.prototype.uninstall = function (packageId, options) {
|
||||
options = options || {};
|
||||
exec(options.success || null, options.error || null, 'FileOpener2', 'uninstall', [packageId]);
|
||||
FileOpener2.prototype.showOpenWithDialog = function (fileName, contentType, callbackContext) {
|
||||
contentType = contentType || '';
|
||||
callbackContext = callbackContext || {};
|
||||
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType, false]);
|
||||
};
|
||||
|
||||
FileOpener2.prototype.uninstall = function (packageId, callbackContext) {
|
||||
callbackContext = callbackContext || {};
|
||||
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'uninstall', [packageId]);
|
||||
};
|
||||
|
||||
FileOpener2.prototype.appIsInstalled = function (packageId, options) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user