Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java reflection to automatically import android plugins into MainActivity.java #3054

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,21 +1,5 @@
package com.getcapacitor.myapp;

import android.os.Bundle;

import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;

import java.util.ArrayList;

public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
}});
}
}
public class MainActivity extends BridgeActivity {}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -40,6 +46,11 @@ public class BridgeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.init(savedInstanceState, loadPluginList("plugin-imports.json"));
} catch (IOException | JSONException | ClassNotFoundException e) {
e.printStackTrace();
}
}

protected void init(Bundle savedInstanceState, List<Class<? extends Plugin>> plugins) {
Expand All @@ -57,6 +68,34 @@ protected void init(Bundle savedInstanceState, List<Class<? extends Plugin>> plu
this.load(savedInstanceState);
}

@SuppressWarnings("unchecked")
ArrayList<Class<? extends Plugin>> loadPluginList(String fileName) throws IOException, JSONException, ClassNotFoundException {
ArrayList<Class<? extends Plugin>> pluginList = new ArrayList<>();
JSONArray plugins = loadJsonArray(fileName);
for (int iPlugin = 0; iPlugin < plugins.length(); ++iPlugin) {
String plugin = (String) plugins.get(iPlugin);
pluginList.add((Class<? extends Plugin>) Class.forName(plugin));
}
return pluginList;
}

private JSONArray loadJsonArray(String fileName) throws IOException, JSONException {
JSONTokener tokener = new JSONTokener(loadJsonStringFromFile(fileName));
return new JSONArray(tokener);
}

private String loadJsonStringFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
// do reading, usually loop until end of file reading
StringBuilder b = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
//process line
b.append(line);
}
return b.toString();
}

/**
* Load the WebView and create the Bridge
*/
Expand Down
2 changes: 2 additions & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"open": "^6.1.0",
"ora": "^1.3.0",
"plist": "^3.0.1",
"read-installed": "^4.0.3",
"semver": "^5.4.1",
"which": "^1.3.0",
"xml2js": "^0.4.19"
Expand All @@ -61,6 +62,7 @@
"@types/inquirer": "0.0.35",
"@types/jest": "^23.3.9",
"@types/mock-fs": "^3.6.30",
"@types/node": "12.12.21",
"@types/open": "^6.1.0",
"@types/ora": "^1.3.1",
"@types/semver": "^5.4.0",
Expand Down
31 changes: 24 additions & 7 deletions cli/src/android/update.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Config } from '../config';
import { checkPlatformVersions, logFatal, resolveNode, runTask } from '../common';
import { checkPlatformVersions, log, logFatal, readXML, resolveNode, runTask } from '../common';
import { getAndroidPlugins } from './common';
import { checkAndInstallDependencies, handleCordovaPluginsJS, writeCordovaAndroidManifest } from '../cordova';
import { convertToUnixPath, copySync, existsSync, readFileAsync, removeSync, writeFileAsync} from '../util/fs';
Expand All @@ -8,16 +8,33 @@ import { Plugin, PluginType, getAllElements, getFilePath, getPlatformElement, ge

const platform = 'android';

export async function updateAndroid(config: Config) {
let plugins = await getPluginsTask(config);
async function listAndroidClasses(plugins: Plugin[], config: Config): Promise<string[]> {
return Promise.all(
plugins.map(async (p: Plugin) => {
const manifestPath = resolve(p.rootPath, p.android!.path, 'src', 'main', 'AndroidManifest.xml');
const pluginManifest = await readXML(manifestPath);
return `${pluginManifest.manifest.$.package}.${p.name}`;
})
);
}

async function writePluginImports(plugins: Plugin[], config: Config) {
const compatiblePlugins = plugins.filter((p: Plugin) => getPluginType(p, platform) !== PluginType.Incompatible);
const imports = await listAndroidClasses(compatiblePlugins, config);
const writePath = resolve(config.android.platformDir, 'plugin-imports.json')
await writeFileAsync(writePath, JSON.stringify(imports))
}

export async function updateAndroid(config: Config, allPlugins: Plugin[]) {
let plugins = await getPluginsTask(config, allPlugins);

const capacitorPlugins = plugins.filter(p => getPluginType(p, platform) === PluginType.Core);

let needsPluginUpdate = true;
while (needsPluginUpdate) {
needsPluginUpdate = await checkAndInstallDependencies(config, plugins, platform);
if (needsPluginUpdate) {
plugins = await getPluginsTask(config);
plugins = await getPluginsTask(config, allPlugins);
}
}

Expand All @@ -29,10 +46,11 @@ export async function updateAndroid(config: Config) {
if (cordovaPlugins.length > 0) {
copyPluginsNativeFiles(config, cordovaPlugins);
}
await handleCordovaPluginsJS(cordovaPlugins, config, platform);
await handleCordovaPluginsJS(allPlugins, cordovaPlugins, config, platform);
await installGradlePlugins(config, capacitorPlugins, cordovaPlugins);
await handleCordovaPluginsGradle(config, cordovaPlugins);
await writeCordovaAndroidManifest(cordovaPlugins, config, platform);
await writePluginImports(plugins, config);

const incompatibleCordovaPlugins = plugins
.filter(p => getPluginType(p, platform) === PluginType.Incompatible);
Expand Down Expand Up @@ -190,9 +208,8 @@ function removePluginsNativeFiles(config: Config) {
copySync(config.android.assets.pluginsDir, pluginsRoot);
}

async function getPluginsTask(config: Config) {
async function getPluginsTask(config: Config, allPlugins: Plugin[]) {
return await runTask('Updating Android plugins', async () => {
const allPlugins = await getPlugins(config);
const androidPlugins = getAndroidPlugins(allPlugins);
return androidPlugins;
});
Expand Down
7 changes: 3 additions & 4 deletions cli/src/cordova.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,9 @@ function getWebDir(config: Config, platform: string): string {
return '';
}

export async function handleCordovaPluginsJS(cordovaPlugins: Plugin[], config: Config, platform: string) {
export async function handleCordovaPluginsJS(allPlugins: Plugin[], cordovaPlugins: Plugin[], config: Config, platform: string) {
if (!existsSync(getWebDir(config, platform))) {
await copy(config, platform);
await copy(config, allPlugins, platform);
}
if (cordovaPlugins.length > 0) {
printPlugins(cordovaPlugins, platform, 'cordova');
Expand All @@ -219,8 +219,7 @@ export async function handleCordovaPluginsJS(cordovaPlugins: Plugin[], config: C
await autoGenerateConfig(config, cordovaPlugins, platform);
}

export async function getCordovaPlugins(config: Config, platform: string): Promise<Plugin[]> {
const allPlugins = await getPlugins(config);
export async function getCordovaPlugins(config: Config, allPlugins: Plugin[], platform: string): Promise<Plugin[]> {
let plugins: Plugin[] = [];
if (platform === config.ios.name) {
plugins = getIOSPlugins(allPlugins);
Expand Down
11 changes: 5 additions & 6 deletions cli/src/ios/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { checkAndInstallDependencies, handleCordovaPluginsJS, logCordovaManualSt
export const updateIOSChecks: CheckFunction[] = [checkCocoaPods, checkIOSProject];
const platform = 'ios';

export async function updateIOS(config: Config, deployment: boolean) {
export async function updateIOS(config: Config, allPlugins: Plugin[], deployment: boolean) {

let plugins = await getPluginsTask(config);
let plugins = await getPluginsTask(config, allPlugins);

const capacitorPlugins = plugins.filter(p => getPluginType(p, platform) === PluginType.Core);

Expand All @@ -23,7 +23,7 @@ export async function updateIOS(config: Config, deployment: boolean) {
while (needsPluginUpdate) {
needsPluginUpdate = await checkAndInstallDependencies(config, plugins, platform);
if (needsPluginUpdate) {
plugins = await getPluginsTask(config);
plugins = await getPluginsTask(config, allPlugins);
}
}

Expand All @@ -33,7 +33,7 @@ export async function updateIOS(config: Config, deployment: boolean) {
if (cordovaPlugins.length > 0) {
copyPluginsNativeFiles(config, cordovaPlugins);
}
await handleCordovaPluginsJS(cordovaPlugins, config, platform);
await handleCordovaPluginsJS(allPlugins, cordovaPlugins, config, platform);
await generateCordovaPodspecs(cordovaPlugins, config);
await installCocoaPodsPlugins(config, plugins, deployment);
await logCordovaManualSteps(cordovaPlugins, config, platform);
Expand Down Expand Up @@ -348,9 +348,8 @@ function removeNoSystem(library: string, sourceFrameworks: Array<string>) {
return libraries.length === 0;
}

async function getPluginsTask(config: Config) {
async function getPluginsTask(config: Config, allPlugins: Plugin[]) {
return await runTask('Updating iOS plugins', async () => {
const allPlugins = await getPlugins(config);
const iosPlugins = getIOSPlugins(allPlugins);
return iosPlugins;
});
Expand Down
114 changes: 74 additions & 40 deletions cli/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import readInstalled = require('read-installed');
import semver = require('semver');
import { Config } from './config';
import { join } from 'path';
import { log, logFatal, readJSON, readXML, resolveNode } from './common';

import { log, logFatal, logWarn, readJSON, readXML, resolveNode, runTask } from './common';
import { existsAsync } from './util/fs';

export const enum PluginType {
Core,
Expand Down Expand Up @@ -37,55 +39,87 @@ export interface Plugin {
};
}

export async function getPlugins(config: Config): Promise<Plugin[]> {
const deps = getDependencies(config);
const plugins = await Promise.all(deps.map(async p => resolvePlugin(config, p)));
return plugins.filter(p => !!p) as Plugin[];
function flatten(pkg: any) {
let seen: any[] = [];
const _flatten = (pkg: any): any[] => {
if (pkg.constructor !== Object || seen.indexOf(pkg) >= 0) return [];
seen.push(pkg);
if (!Object.keys(pkg.dependencies)) return [pkg];
return [ pkg, ...([] as any[]).concat(...Object.values(pkg.dependencies).map(_flatten)) ];
};
return _flatten(pkg);
}

export async function resolvePlugin(config: Config, name: string): Promise<Plugin | null> {
try {
const rootPath = resolveNode(config, name);
if (!rootPath) {
logFatal(`Unable to find node_modules/${name}. Are you sure ${name} is installed?`);
return null;

function getInstalled(config: Config): Promise<any> {
return new Promise((resolve, reject) => {
readInstalled(config.app.rootDir, { dev: true },
(err: Error, tree) => err ? reject(err) : resolve(tree));
});
}

export async function getPlugins(config: Config): Promise<Plugin[]> {
return await runTask('Finding plugins', async () => {
const rootPkg = await getInstalled(config);
const nullablePlugins = await Promise.all(flatten(rootPkg).map(resolvePlugin));
const plugins: Plugin[] = nullablePlugins.filter(p => p !== null) as Plugin[];

const pluginMap = plugins.reduce((o, p) => {
(o[p.id] = o[p.id] || []).push(p);
return o;
}, {} as { [key: string]: Plugin[] });

const returnedPlugins = [];
for (let id in pluginMap) {
const variations = pluginMap[id];
if (variations.length > 1) {
variations.sort((a, b) => semver.rcompare(a.version, b.version));
const usedVersion = variations[0].version;
log();
logWarn(`Found multiple versions of plugin ${id} using ${usedVersion}.`);
variations.slice(1).forEach((plugin) => {
const otherVersion = plugin.version;
const diff = semver.diff(usedVersion, otherVersion);
if ( diff !== null ) { // if not equal
logWarn(` ${usedVersion} is a ${diff} change ahead of ${otherVersion}, which was found but unused.`);
}
});
}
returnedPlugins.push(variations[0]);
}
return returnedPlugins;
});
}

const packagePath = join(rootPath, 'package.json');
const meta = await readJSON(packagePath);
if (!meta) {
return null;
export async function resolvePlugin(pkg: any): Promise<Plugin | null> {
try {
if (pkg.capacitor) {
return {
id: pkg.name,
name: fixName(pkg.name),
version: pkg.version,
rootPath: pkg.path,
repository: pkg.repository,
manifest: pkg.capacitor
};
}
if (meta.capacitor) {
const xmlPath = join(pkg.path, 'plugin.xml');
if (await existsAsync(xmlPath)) return null;
const xml = await readXML(xmlPath);
if (xml) {
return {
id: name,
name: fixName(name),
version: meta.version,
rootPath: rootPath,
repository: meta.repository,
manifest: meta.capacitor
id: pkg.name,
name: fixName(pkg.name),
version: pkg.version,
rootPath: pkg.path,
repository: pkg.repository,
xml: xml.plugin
};
}
const pluginXMLPath = join(rootPath, 'plugin.xml');
const xmlMeta = await readXML(pluginXMLPath);
return {
id: name,
name: fixName(name),
version: meta.version,
rootPath: rootPath,
repository: meta.repository,
xml: xmlMeta.plugin
};
} catch (e) { }
} catch (_) {}
return null;
}

export function getDependencies(config: Config): string[] {
const dependencies = config.app.package.dependencies ? config.app.package.dependencies : [];
const devDependencies = config.app.package.devDependencies ? config.app.package.devDependencies : [];
return Object.keys(dependencies).concat(Object.keys(devDependencies));
}

export function fixName(name: string): string {
name = name
.replace(/\//g, '_')
Expand Down
18 changes: 18 additions & 0 deletions cli/src/read-installed.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
interface Opt {
dev?: boolean,
log?: () => void,
depth?: number,
}

interface PkgNode {
path: string,
parent: PkgNode,
dependencies: PkgNode[],
}

type Func = (err: Error, tree: PkgNode) => void;

declare module 'read-installed' {
function readInstalled(folder: string, options: Opt, func: Func): void;
export = readInstalled;
}
Loading