Implement stub Magisk Manager

This commit is contained in:
topjohnwu
2018-06-02 22:00:52 +08:00
parent 7b9ddc9b3b
commit 48085b5573
91 changed files with 891 additions and 678 deletions

View File

@@ -24,6 +24,7 @@ import com.topjohnwu.magisk.components.AlertDialogBuilder;
import com.topjohnwu.magisk.components.ExpandableView;
import com.topjohnwu.magisk.components.Fragment;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.ShowUI;
import com.topjohnwu.magisk.utils.Topic;
import com.topjohnwu.magisk.utils.Utils;
@@ -271,7 +272,7 @@ public class MagiskFragment extends Fragment
|| mm.remoteManagerVersionCode > BuildConfig.VERSION_CODE) {
install();
} else if (mm.remoteMagiskVersionCode >= Const.MAGISK_VER.FIX_ENV &&
!Utils.cmdResult("env_check")) {
!RootUtils.cmdResult("env_check")) {
ShowUI.envFixDialog(getActivity());
}
}

View File

@@ -89,7 +89,7 @@ public class MagiskLogFragment extends Fragment {
return true;
case R.id.menu_save:
Utils.runWithPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE,
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
() -> new LogManager().save());
return true;
case R.id.menu_clear:

View File

@@ -8,21 +8,28 @@ import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;
import android.util.Xml;
import com.topjohnwu.magisk.components.Application;
import com.topjohnwu.magisk.container.Module;
import com.topjohnwu.magisk.database.MagiskDatabaseHelper;
import com.topjohnwu.magisk.database.RepoDatabaseHelper;
import com.topjohnwu.magisk.services.UpdateCheckService;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.Topic;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.superuser.BusyBox;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.io.SuFile;
import com.topjohnwu.superuser.io.SuFileInputStream;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
@@ -32,10 +39,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
public class MagiskManager extends Shell.ContainerApp {
// Global weak reference to self
private static WeakReference<MagiskManager> weakSelf;
public class MagiskManager extends Application implements Shell.Container {
// Topics
public final Topic magiskHideDone = new Topic();
@@ -65,10 +69,6 @@ public class MagiskManager extends Shell.ContainerApp {
public Map<String, Module> moduleMap;
public List<Locale> locales;
// Configurations
public static Locale locale;
public static Locale defaultLocale;
public boolean magiskHide;
public boolean isDarkTheme;
public int suRequestTimeout;
@@ -87,12 +87,23 @@ public class MagiskManager extends Shell.ContainerApp {
public SharedPreferences prefs;
public MagiskDatabaseHelper mDB;
public RepoDatabaseHelper repoDB;
public Runnable permissionGrantCallback = null;
private static Handler mHandler = new Handler();
private volatile Shell mShell;
public MagiskManager() {
weakSelf = new WeakReference<>(this);
Shell.setContainer(this);
}
@Nullable
@Override
public Shell getShell() {
return mShell;
}
@Override
public void setShell(@Nullable Shell shell) {
mShell = shell;
}
@Override
@@ -137,17 +148,16 @@ public class MagiskManager extends Shell.ContainerApp {
String pkg = mDB.getStrings(Const.Key.SU_REQUESTER, Const.ORIG_PKG_NAME);
if (getPackageName().equals(Const.ORIG_PKG_NAME) && !pkg.equals(Const.ORIG_PKG_NAME)) {
mDB.setStrings(Const.Key.SU_REQUESTER, null);
Utils.uninstallPkg(pkg);
RootUtils.uninstallPkg(pkg);
mDB = MagiskDatabaseHelper.getInstance(this);
}
defaultLocale = Locale.getDefault();
setLocale();
loadConfig();
}
public static MagiskManager get() {
return weakSelf.get();
return (MagiskManager) weakSelf.get();
}
public void setLocale() {
@@ -183,7 +193,7 @@ public class MagiskManager extends Shell.ContainerApp {
prefs.edit()
.putBoolean(Const.Key.DARK_THEME, isDarkTheme)
.putBoolean(Const.Key.MAGISKHIDE, magiskHide)
.putBoolean(Const.Key.HOSTS, Const.MAGISK_HOST_FILE().exists())
.putBoolean(Const.Key.HOSTS, Const.MAGISK_HOST_FILE.exists())
.putBoolean(Const.Key.COREONLY, Const.MAGISK_DISABLE_FILE.exists())
.putString(Const.Key.SU_REQUEST_TIMEOUT, String.valueOf(suRequestTimeout))
.putString(Const.Key.SU_AUTO_RESPONSE, String.valueOf(suResponseType))
@@ -199,36 +209,24 @@ public class MagiskManager extends Shell.ContainerApp {
.apply();
}
public static void toast(CharSequence msg, int duration) {
mHandler.post(() -> Toast.makeText(weakSelf.get(), msg, duration).show());
}
public static void toast(int resId, int duration) {
mHandler.post(() -> Toast.makeText(weakSelf.get(), resId, duration).show());
}
public void loadMagiskInfo() {
try {
magiskVersionString = Utils.cmd("magisk -v").split(":")[0];
magiskVersionCode = Integer.parseInt(Utils.cmd("magisk -V"));
String s = Utils.cmd((magiskVersionCode >= Const.MAGISK_VER.RESETPROP_PERSIST ? "resetprop -p " : "getprop ")
magiskVersionString = RootUtils.cmd("magisk -v").split(":")[0];
magiskVersionCode = Integer.parseInt(RootUtils.cmd("magisk -V"));
String s = RootUtils.cmd((magiskVersionCode >= Const.MAGISK_VER.RESETPROP_PERSIST ? "resetprop -p " : "getprop ")
+ Const.MAGISKHIDE_PROP);
magiskHide = s == null || Integer.parseInt(s) != 0;
} catch (Exception ignored) {}
bootBlock = Utils.cmd("echo \"$BOOTIMAGE\"");
bootBlock = RootUtils.cmd("echo \"$BOOTIMAGE\"");
}
public void getDefaultInstallFlags() {
keepVerity = Boolean.parseBoolean(Utils.cmd("getvar KEEPVERITY; echo $KEEPVERITY")) ||
Utils.cmd("echo \"$DTBOIMAGE\"") != null;
keepVerity = Boolean.parseBoolean(RootUtils.cmd("getvar KEEPVERITY; echo $KEEPVERITY")) ||
RootUtils.cmd("echo \"$DTBOIMAGE\"") != null;
keepEnc = Boolean.parseBoolean(Utils.cmd("getvar KEEPFORCEENCRYPT; echo $KEEPFORCEENCRYPT")) ||
TextUtils.equals("encrypted", Utils.cmd("getprop ro.crypto.state"));
}
public void setPermissionGrantCallback(Runnable callback) {
permissionGrantCallback = callback;
keepEnc = Boolean.parseBoolean(RootUtils.cmd("getvar KEEPFORCEENCRYPT; echo $KEEPFORCEENCRYPT")) ||
TextUtils.equals("encrypted", RootUtils.cmd("getprop ro.crypto.state"));
}
public void setupUpdateCheck() {
@@ -249,4 +247,72 @@ public class MagiskManager extends Shell.ContainerApp {
scheduler.cancel(Const.UPDATE_SERVICE_VER);
}
}
public void dumpPrefs() {
// Flush prefs to disk
prefs.edit().commit();
File xml = new File(getFilesDir().getParent() + "/shared_prefs",
getPackageName() + "_preferences.xml");
Shell.Sync.su(Utils.fmt("for usr in /data/user/*; do cat %s > ${usr}/%s; done", xml, Const.MANAGER_CONFIGS));
}
public void loadPrefs() {
SuFile config = new SuFile(Utils.fmt("/data/user/%d/%s", Const.USER_ID, Const.MANAGER_CONFIGS), true);
if (config.exists()) {
SharedPreferences.Editor editor = prefs.edit();
try {
SuFileInputStream is = new SuFileInputStream(config);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, "UTF-8");
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "map");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String key = parser.getAttributeValue(null, "name");
String value = parser.getAttributeValue(null, "value");
switch (parser.getName()) {
case "string":
parser.require(XmlPullParser.START_TAG, null, "string");
editor.putString(key, parser.nextText());
parser.require(XmlPullParser.END_TAG, null, "string");
break;
case "boolean":
parser.require(XmlPullParser.START_TAG, null, "boolean");
editor.putBoolean(key, Boolean.parseBoolean(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "boolean");
break;
case "int":
parser.require(XmlPullParser.START_TAG, null, "int");
editor.putInt(key, Integer.parseInt(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "int");
break;
case "long":
parser.require(XmlPullParser.START_TAG, null, "long");
editor.putLong(key, Long.parseLong(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "long");
break;
case "float":
parser.require(XmlPullParser.START_TAG, null, "int");
editor.putFloat(key, Float.parseFloat(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "int");
break;
default:
parser.next();
}
}
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
editor.remove(Const.Key.ETAG_KEY);
editor.apply();
loadConfig();
config.delete();
}
}
}

View File

@@ -40,7 +40,8 @@ public class ModulesFragment extends Fragment implements Topic.Subscriber {
@BindView(R.id.empty_rv) TextView emptyRv;
@OnClick(R.id.fab)
public void selectFile() {
Utils.runWithPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, () -> {
Utils.runWithPermission(getActivity(),
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },() -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/zip");
startActivityForResult(intent, Const.ID.FETCH_ZIP);

View File

@@ -5,17 +5,18 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.support.v14.preference.SwitchPreference;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceCategory;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceScreen;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
@@ -63,7 +64,7 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
setFloating();
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new SettingsFragment()).commit();
getSupportFragmentManager().beginTransaction().add(R.id.container, new SettingsFragment()).commit();
}
}
@@ -78,7 +79,7 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
return new Topic[] { getMagiskManager().reloadActivity };
}
public static class SettingsFragment extends PreferenceFragment
public static class SettingsFragment extends PreferenceFragmentCompat
implements SharedPreferences.OnSharedPreferenceChangeListener, Topic.Subscriber {
private SharedPreferences prefs;
@@ -90,9 +91,8 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
private PreferenceCategory generalCatagory;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_settings);
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.app_settings, rootKey);
mm = Utils.getMagiskManager(getActivity());
prefs = mm.prefs;
prefScreen = getPreferenceScreen();
@@ -126,13 +126,13 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
EditText url = v.findViewById(R.id.custom_url);
url.setText(mm.prefs.getString(Const.Key.CUSTOM_CHANNEL, ""));
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_update_custom)
.setView(v)
.setPositiveButton(R.string.ok, (d, i) ->
prefs.edit().putString(Const.Key.CUSTOM_CHANNEL,
url.getText().toString()).apply())
.setNegativeButton(R.string.close, null)
.show();
.setTitle(R.string.settings_update_custom)
.setView(v)
.setPositiveButton(R.string.ok, (d, i) ->
prefs.edit().putString(Const.Key.CUSTOM_CHANNEL,
url.getText().toString()).apply())
.setNegativeButton(R.string.close, null)
.show();
}
return true;
});
@@ -166,14 +166,15 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
} else {
if (Utils.checkNetworkStatus()) {
restoreManager.setOnPreferenceClickListener((pref) -> {
Utils.runWithPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, () -> {
Intent intent = new Intent(mm, ManagerUpdate.class);
intent.putExtra(Const.Key.INTENT_SET_LINK, mm.managerLink);
intent.putExtra(Const.Key.INTENT_SET_FILENAME,
Utils.fmt("MagiskManager-v%s(%d).apk",
mm.remoteManagerVersionString, mm.remoteManagerVersionCode));
mm.sendBroadcast(intent);
});
Utils.runWithPermission(getActivity(),
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, () -> {
Intent intent = new Intent(mm, ManagerUpdate.class);
intent.putExtra(Const.Key.INTENT_SET_LINK, mm.managerLink);
intent.putExtra(Const.Key.INTENT_SET_FILENAME,
Utils.fmt("MagiskManager-v%s(%d).apk",
mm.remoteManagerVersionString, mm.remoteManagerVersionCode));
mm.sendBroadcast(intent);
});
return true;
});
} else {
@@ -224,17 +225,17 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
}
@Override
public void onResume() {
super.onResume();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs.registerOnSharedPreferenceChangeListener(this);
subscribeTopics();
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onPause() {
public void onDestroyView() {
prefs.unregisterOnSharedPreferenceChangeListener(this);
unsubscribeTopics();
super.onPause();
super.onDestroyView();
}
@Override
@@ -244,7 +245,7 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
case Const.Key.DARK_THEME:
mm.isDarkTheme = prefs.getBoolean(key, false);
mm.reloadActivity.publish(false);
break;
return;
case Const.Key.COREONLY:
if (prefs.getBoolean(key, false)) {
try {
@@ -265,12 +266,12 @@ public class SettingsActivity extends Activity implements Topic.Subscriber {
case Const.Key.HOSTS:
if (prefs.getBoolean(key, false)) {
Shell.Async.su(
"cp -af /system/etc/hosts " + Const.MAGISK_HOST_FILE(),
"mount -o bind " + Const.MAGISK_HOST_FILE() + " /system/etc/hosts");
"cp -af /system/etc/hosts " + Const.MAGISK_HOST_FILE,
"mount -o bind " + Const.MAGISK_HOST_FILE + " /system/etc/hosts");
} else {
Shell.Async.su(
"umount -l /system/etc/hosts",
"rm -f " + Const.MAGISK_HOST_FILE());
"rm -f " + Const.MAGISK_HOST_FILE);
}
break;
case Const.Key.ROOT_ACCESS:

View File

@@ -14,6 +14,7 @@ import com.topjohnwu.magisk.components.Activity;
import com.topjohnwu.magisk.database.RepoDatabaseHelper;
import com.topjohnwu.magisk.receivers.ShortcutReceiver;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.superuser.Shell;
@@ -23,12 +24,13 @@ public class SplashActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RootUtils.init();
MagiskManager mm = getMagiskManager();
mm.repoDB = new RepoDatabaseHelper(this);
mm.loadMagiskInfo();
mm.getDefaultInstallFlags();
Utils.loadPrefs();
mm.loadPrefs();
// Dynamic detect all locales
new LoadLocale().exec();
@@ -59,7 +61,7 @@ public class SplashActivity extends Activity {
// Fire asynctasks
loadModuleTask.exec();
// Check dtbo status
Utils.patchDTBO();
RootUtils.patchDTBO();
}
// Write back default values

View File

@@ -7,7 +7,9 @@ import android.view.View;
import com.topjohnwu.magisk.FlashActivity;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.components.SnackbarMaker;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.magisk.utils.ZipUtils;
import com.topjohnwu.superuser.Shell;
@@ -39,7 +41,7 @@ public class FlashZip extends ParallelTask<Void, Void, Integer> {
private boolean unzipAndCheck() throws Exception {
ZipUtils.unzip(mCachedFile, mCachedFile.getParentFile(), "META-INF/com/google/android", true);
String s = Utils.cmd("head -n 1 " + new File(mCachedFile.getParentFile(), "updater-script"));
String s = RootUtils.cmd("head -n 1 " + new File(mCachedFile.getParentFile(), "updater-script"));
return s != null && s.contains("#MAGISK");
}
@@ -93,7 +95,7 @@ public class FlashZip extends ParallelTask<Void, Void, Integer> {
switch (result) {
case -1:
console.add("! Installation failed");
Utils.showUriSnack(getActivity(), mUri);
SnackbarMaker.showUri(getActivity(), mUri);
break;
case 0:
console.add("! This zip is not a Magisk Module!");

View File

@@ -7,7 +7,7 @@ import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.ZipUtils;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.ShellUtils;
@@ -136,8 +136,8 @@ public class HideManager extends ParallelTask<Void, Void, Boolean> {
repack.delete();
mm.mDB.setStrings(Const.Key.SU_REQUESTER, pkg);
Utils.dumpPrefs();
Utils.uninstallPkg(Const.ORIG_PKG_NAME);
mm.dumpPrefs();
RootUtils.uninstallPkg(Const.ORIG_PKG_NAME);
return true;
}

View File

@@ -13,6 +13,7 @@ import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.container.TarEntry;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.magisk.utils.ZipUtils;
import com.topjohnwu.superuser.Shell;
@@ -147,7 +148,7 @@ public class InstallMagisk extends ParallelTask<Void, Void, Boolean> {
case DIRECT_MODE:
console.add("- Patch boot/ramdisk image: " + mBootLocation);
if (mm.remoteMagiskVersionCode >= 1463) {
highCompression = Integer.parseInt(Utils.cmd(Utils.fmt(
highCompression = Integer.parseInt(RootUtils.cmd(Utils.fmt(
"%s/magiskboot --parse %s; echo $?",
install, mBootLocation))) == 2;
if (highCompression)

View File

@@ -11,7 +11,7 @@ import java.util.List;
public class LoadModules extends ParallelTask<Void, Void, Void> {
private List<String> getModList() {
String command = "ls -d " + Const.MAGISK_PATH() + "/* | grep -v lost+found";
String command = "ls -d " + Const.MAGISK_PATH + "/* | grep -v lost+found";
return Shell.Sync.su(command);
}

View File

@@ -12,6 +12,7 @@ import android.widget.Toast;
import com.topjohnwu.magisk.FlashActivity;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.components.SnackbarMaker;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.magisk.utils.WebService;
@@ -147,7 +148,7 @@ public class ProcessRepoZip extends ParallelTask<Void, Object, Boolean> {
intent.setData(uri).putExtra(Const.Key.FLASH_ACTION, Const.Value.FLASH_ZIP);
activity.startActivity(intent);
} else {
Utils.showUriSnack(activity, uri);
SnackbarMaker.showUri(activity, uri);
}
} else {
MagiskManager.toast(R.string.process_error, Toast.LENGTH_LONG);
@@ -157,7 +158,7 @@ public class ProcessRepoZip extends ParallelTask<Void, Object, Boolean> {
@Override
public ParallelTask<Void, Object, Boolean> exec(Void... voids) {
Utils.runWithPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
Utils.runWithPermission(getActivity(), new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
() -> super.exec(voids));
return this;
}

View File

@@ -4,7 +4,7 @@ import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.ShellUtils;
@@ -13,9 +13,9 @@ public class RestoreImages extends ParallelTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... voids) {
String sha1;
sha1 = Utils.cmd("cat /.backup/.sha1");
sha1 = RootUtils.cmd("cat /.backup/.sha1");
if (sha1 == null) {
sha1 = Utils.cmd("cat /init.magisk.rc | grep STOCKSHA1");
sha1 = RootUtils.cmd("cat /init.magisk.rc | grep STOCKSHA1");
if (sha1 == null)
return false;
sha1 = sha1.substring(sha1.indexOf('=') + 1);

View File

@@ -1,13 +1,9 @@
package com.topjohnwu.magisk.components;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.app.AppCompatActivity;
@@ -16,33 +12,29 @@ import android.view.WindowManager;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Topic;
import com.topjohnwu.magisk.utils.Utils;
public abstract class Activity extends AppCompatActivity {
public abstract class FlavorActivity extends AppCompatActivity {
private AssetManager swappedAssetManager = null;
private Resources swappedResources = null;
private Resources.Theme swappedTheme = null;
private ActivityResultListener activityResultListener;
public Activity() {
super();
Configuration configuration = new Configuration();
configuration.setLocale(MagiskManager.locale);
applyOverrideConfiguration(configuration);
}
@StyleRes
public int getDarkTheme() {
return -1;
}
public MagiskManager getMagiskManager() {
return (MagiskManager) super.getApplicationContext();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (this instanceof Topic.Subscriber) {
((Topic.Subscriber) this).subscribeTopics();
}
if (getMagiskManager().isDarkTheme && getDarkTheme() != -1) {
setTheme(getDarkTheme());
}
@@ -56,34 +48,15 @@ public abstract class Activity extends AppCompatActivity {
super.onDestroy();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
MagiskManager mm = getMagiskManager();
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mm.permissionGrantCallback != null) {
mm.permissionGrantCallback.run();
}
private static AssetManager getAssets(String apk) {
try {
AssetManager asset = AssetManager.class.newInstance();
AssetManager.class.getMethod("addAssetPath", String.class).invoke(asset, apk);
return asset;
} catch (Exception e) {
e.printStackTrace();
return null;
}
mm.permissionGrantCallback = null;
}
@Override
public Resources.Theme getTheme() {
return swappedTheme == null ? super.getTheme() : swappedTheme;
}
@Override
public AssetManager getAssets() {
return swappedAssetManager == null ? super.getAssets() : swappedAssetManager;
}
@Override
public Resources getResources() {
return swappedResources == null ? super.getResources() : swappedResources;
}
public MagiskManager getMagiskManager() {
return (MagiskManager) super.getApplicationContext();
}
protected void setFloating() {
@@ -101,20 +74,23 @@ public abstract class Activity extends AppCompatActivity {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (activityResultListener != null)
activityResultListener.onActivityResult(requestCode, resultCode, data);
activityResultListener = null;
public Resources.Theme getTheme() {
return swappedTheme == null ? super.getTheme() : swappedTheme;
}
public void startActivityForResult(Intent intent, int requestCode, ActivityResultListener listener) {
activityResultListener = listener;
super.startActivityForResult(intent, requestCode);
@Override
public AssetManager getAssets() {
return swappedAssetManager == null ? super.getAssets() : swappedAssetManager;
}
@Override
public Resources getResources() {
return swappedResources == null ? super.getResources() : swappedResources;
}
@Keep
public void swapResources(String dexPath, int resId) {
swappedAssetManager = Utils.getAssets(dexPath);
swappedAssetManager = getAssets(dexPath);
if (swappedAssetManager == null)
return;
Resources res = super.getResources();
@@ -129,9 +105,4 @@ public abstract class Activity extends AppCompatActivity {
swappedResources = null;
swappedTheme = null;
}
public interface ActivityResultListener {
void onActivityResult(int requestCode, int resultCode, Intent data);
}
}

View File

@@ -1,11 +1,15 @@
package com.topjohnwu.magisk.components;
import android.app.Activity;
import android.net.Uri;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.TextView;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Utils;
public class SnackbarMaker {
public static Snackbar make(Activity activity, CharSequence text, int duration) {
@@ -34,4 +38,10 @@ public class SnackbarMaker {
text.setMaxLines(Integer.MAX_VALUE);
}
public static void showUri(Activity activity, Uri uri) {
make(activity, activity.getString(R.string.internal_storage,
"/MagiskManager/" + Utils.getNameFromUri(activity, uri)),
Snackbar.LENGTH_LONG)
.setAction(R.string.ok, (v)->{}).show();
}
}

View File

@@ -1,59 +0,0 @@
package com.topjohnwu.magisk.receivers;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Utils;
import java.io.File;
public abstract class DownloadReceiver extends BroadcastReceiver {
protected File mFile;
private long downloadID;
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(columnIndex);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
Uri uri = Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
onDownloadDone(uri);
break;
default:
MagiskManager.toast(R.string.download_file_error, Toast.LENGTH_LONG);
break;
}
context.unregisterReceiver(this);
}
c.close();
}
Utils.isDownloading = false;
}
public DownloadReceiver setDownloadID(long id) {
downloadID = id;
return this;
}
public DownloadReceiver setFile(File file) {
mFile = file;
return this;
}
public abstract void onDownloadDone(Uri uri);
}

View File

@@ -1,46 +0,0 @@
package com.topjohnwu.magisk.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.Utils;
import java.io.File;
public class ManagerUpdate extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Utils.dlAndReceive(
context,
new DownloadReceiver() {
@Override
public void onDownloadDone(Uri uri) {
if (!context.getPackageName().equals(Const.ORIG_PKG_NAME)) {
Utils.dumpPrefs();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Intent install = new Intent(Intent.ACTION_INSTALL_PACKAGE);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri content = FileProvider.getUriForFile(context,
context.getPackageName() + ".provider", new File(uri.getPath()));
install.setData(content);
context.startActivity(install);
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(uri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
}
},
intent.getStringExtra(Const.Key.INTENT_SET_LINK),
intent.getStringExtra(Const.Key.INTENT_SET_FILENAME)
);
}
}

View File

@@ -8,6 +8,7 @@ import android.support.v4.app.NotificationCompat;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.utils.Const;
import com.topjohnwu.magisk.utils.RootUtils;
import com.topjohnwu.magisk.utils.Utils;
import com.topjohnwu.superuser.Shell;
@@ -43,7 +44,7 @@ public class OnBootIntentService extends IntentService {
mm.loadMagiskInfo();
mm.getDefaultInstallFlags();
if (Shell.rootAccess()) {
Utils.patchDTBO();
RootUtils.patchDTBO();
}
}
}

View File

@@ -1,180 +0,0 @@
package com.topjohnwu.magisk.utils;
import android.os.Environment;
import android.os.Process;
import com.topjohnwu.magisk.BuildConfig;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.superuser.io.SuFile;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class Const {
public static final String DEBUG_TAG = "MagiskManager";
public static final String ORIG_PKG_NAME = BuildConfig.APPLICATION_ID;
public static final String SNET_PKG = "com.topjohnwu.snet";
public static final String MAGISKHIDE_PROP = "persist.magisk.hide";
// APK content
public static final String UNINSTALLER = "magisk_uninstaller.sh";
public static final String UTIL_FUNCTIONS= "util_functions.sh";
public static final String ANDROID_MANIFEST = "AndroidManifest.xml";
public static final String SU_KEYSTORE_KEY = "su_key";
// Paths
private static SuFile MAGISK_PATH = null;
public static final SuFile MAGISK_DISABLE_FILE = new SuFile("/cache/.disable_magisk", true);
public static final String BUSYBOX_PATH = "/sbin/.core/busybox";
public static final String TMP_FOLDER_PATH = "/dev/tmp";
public static final String MAGISK_LOG = "/cache/magisk.log";
public static final File EXTERNAL_PATH = new File(Environment.getExternalStorageDirectory(), "MagiskManager");
public static final String MANAGER_CONFIGS = ".tmp.magisk.config";
// Versions
public static final int UPDATE_SERVICE_VER = 1;
public static final int SNET_VER = 7;
public static int MIN_MODULE_VER() {
return MagiskManager.get().magiskVersionCode >= MAGISK_VER.REMOVE_LEGACY_LINK ? 1500 : 1400;
}
public synchronized static SuFile MAGISK_PATH() {
SuFile file;
if (MAGISK_PATH == null) {
file = new SuFile("/sbin/.core/img", true);
if (file.exists()) {
MAGISK_PATH = file;
} else if ((file = new SuFile("/dev/magisk/img", true)).exists()) {
MAGISK_PATH = file;
} else {
MAGISK_PATH = new SuFile("/magisk", true);
}
}
return MAGISK_PATH;
}
public static SuFile MAGISK_HOST_FILE() {
return new SuFile(MAGISK_PATH() + "/.core/hosts");
}
/* A list of apps that should not be shown as hide-able */
public static final List<String> HIDE_BLACKLIST = Arrays.asList(
"android",
MagiskManager.get().getPackageName(),
"com.google.android.gms"
);
public static final int USER_ID = Process.myUid() / 100000;
public static final class MAGISK_VER {
public static final int UNIFIED = 1300;
public static final int FBE_AWARE = 1410;
public static final int RESETPROP_PERSIST = 1436;
public static final int MANAGER_HIDE = 1440;
public static final int DTBO_SUPPORT = 1446;
public static final int LEGACY_GLOBAL_DB = 1450;
public static final int HIDDEN_PATH = 1460;
public static final int REMOVE_LEGACY_LINK = 1630;
public static final int SEPOL_REFACTOR = 1640;
public static final int FIX_ENV = 1650;
}
public static class ID {
public static final int UPDATE_SERVICE_ID = 1;
public static final int FETCH_ZIP = 2;
public static final int SELECT_BOOT = 3;
// notifications
public static final int MAGISK_UPDATE_NOTIFICATION_ID = 4;
public static final int APK_UPDATE_NOTIFICATION_ID = 5;
public static final int ONBOOT_NOTIFICATION_ID = 6;
public static final int DTBO_NOTIFICATION_ID = 7;
public static final String NOTIFICATION_CHANNEL = "magisk_notification";
}
public static class Url {
public static final String STABLE_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/stable.json";
public static final String BETA_URL = "https://raw.githubusercontent.com/topjohnwu/MagiskManager/update/beta.json";
public static final String SNET_URL = "https://github.com/topjohnwu/MagiskManager/raw/a82a5e5a49285df65da91d2e8b24f4783841b515/snet.apk";
public static final String REPO_URL = "https://api.github.com/users/Magisk-Modules-Repo/repos?per_page=100&page=%d";
public static final String FILE_URL = "https://raw.githubusercontent.com/Magisk-Modules-Repo/%s/master/%s";
public static final String ZIP_URL = "https://github.com/Magisk-Modules-Repo/%s/archive/master.zip";
public static final String DONATION_URL = "https://www.paypal.me/topjohnwu";
public static final String XDA_THREAD = "http://forum.xda-developers.com/showthread.php?t=3473445";
public static final String SOURCE_CODE_URL = "https://github.com/topjohnwu/MagiskManager";
}
public static class Key {
// su
public static final String ROOT_ACCESS = "root_access";
public static final String SU_MULTIUSER_MODE = "multiuser_mode";
public static final String SU_MNT_NS = "mnt_ns";
public static final String SU_REQUESTER = "requester";
public static final String SU_REQUEST_TIMEOUT = "su_request_timeout";
public static final String SU_AUTO_RESPONSE = "su_auto_response";
public static final String SU_NOTIFICATION = "su_notification";
public static final String SU_REAUTH = "su_reauth";
public static final String SU_FINGERPRINT = "su_fingerprint";
// intents
public static final String OPEN_SECTION = "section";
public static final String INTENT_SET_FILENAME = "filename";
public static final String INTENT_SET_LINK = "link";
public static final String INTENT_PERM = "perm_dialog";
public static final String FLASH_ACTION = "action";
public static final String FLASH_SET_BOOT = "boot";
// others
public static final String CHECK_UPDATES = "check_update";
public static final String UPDATE_CHANNEL = "update_channel";
public static final String CUSTOM_CHANNEL = "custom_channel";
public static final String BOOT_FORMAT = "boot_format";
public static final String UPDATE_SERVICE_VER = "update_service_version";
public static final String APP_VER = "app_version";
public static final String MAGISKHIDE = "magiskhide";
public static final String HOSTS = "hosts";
public static final String COREONLY = "disable";
public static final String LOCALE = "locale";
public static final String DARK_THEME = "dark_theme";
public static final String ETAG_KEY = "ETag";
public static final String LINK_KEY = "Link";
public static final String IF_NONE_MATCH = "If-None-Match";
public static final String REPO_ORDER = "repo_order";
}
public static class Value {
public static final int STABLE_CHANNEL = 0;
public static final int BETA_CHANNEL = 1;
public static final int CUSTOM_CHANNEL = 2;
public static final int ROOT_ACCESS_DISABLED = 0;
public static final int ROOT_ACCESS_APPS_ONLY = 1;
public static final int ROOT_ACCESS_ADB_ONLY = 2;
public static final int ROOT_ACCESS_APPS_AND_ADB = 3;
public static final int MULTIUSER_MODE_OWNER_ONLY = 0;
public static final int MULTIUSER_MODE_OWNER_MANAGED = 1;
public static final int MULTIUSER_MODE_USER = 2;
public static final int NAMESPACE_MODE_GLOBAL = 0;
public static final int NAMESPACE_MODE_REQUESTER = 1;
public static final int NAMESPACE_MODE_ISOLATE = 2;
public static final int NO_NOTIFICATION = 0;
public static final int NOTIFICATION_TOAST = 1;
public static final int NOTIFY_NORMAL_LOG = 0;
public static final int NOTIFY_USER_TOASTS = 1;
public static final int NOTIFY_USER_TO_OWNER = 2;
public static final int SU_PROMPT = 0;
public static final int SU_AUTO_DENY = 1;
public static final int SU_AUTO_ALLOW = 2;
public static final String FLASH_ZIP = "flash";
public static final String PATCH_BOOT = "patch";
public static final String FLASH_MAGISK = "magisk";
public static final int[] timeoutList = {0, -1, 10, 20, 30, 60};
public static final int ORDER_NAME = 0;
public static final int ORDER_DATE = 1;
}
}

View File

@@ -0,0 +1,43 @@
package com.topjohnwu.magisk.utils;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.ShellUtils;
import com.topjohnwu.superuser.io.SuFile;
public class RootUtils {
public static void init() {
Const.MAGISK_DISABLE_FILE = new SuFile("/cache/.disable_magisk", true);
SuFile file = new SuFile("/sbin/.core/img", true);
if (file.exists()) {
Const.MAGISK_PATH = file;
} else if ((file = new SuFile("/dev/magisk/img", true)).exists()) {
Const.MAGISK_PATH = file;
} else {
Const.MAGISK_PATH = new SuFile("/magisk", true);
}
Const.MAGISK_HOST_FILE = new SuFile(Const.MAGISK_PATH + "/.core/hosts");
}
public static String cmd(String cmd) {
return ShellUtils.fastCmd(Shell.getShell(), cmd);
}
public static boolean cmdResult(String cmd) {
return ShellUtils.fastCmdResult(Shell.getShell(), cmd);
}
public static void uninstallPkg(String pkg) {
Shell.Sync.su("db_clean " + Const.USER_ID, "pm uninstall " + pkg);
}
public static void patchDTBO() {
MagiskManager mm = MagiskManager.get();
if (mm.magiskVersionCode >= Const.MAGISK_VER.DTBO_SUPPORT && !mm.keepVerity) {
if (ShellUtils.fastCmdResult(Shell.getShell(), "patch_dtbo_image")) {
ShowUI.dtboPatchedNotification();
}
}
}
}

View File

@@ -20,6 +20,7 @@ import com.topjohnwu.magisk.SplashActivity;
import com.topjohnwu.magisk.asyncs.InstallMagisk;
import com.topjohnwu.magisk.asyncs.RestoreImages;
import com.topjohnwu.magisk.components.AlertDialogBuilder;
import com.topjohnwu.magisk.components.SnackbarMaker;
import com.topjohnwu.magisk.receivers.DownloadReceiver;
import com.topjohnwu.magisk.receivers.ManagerUpdate;
import com.topjohnwu.magisk.receivers.RebootReceiver;
@@ -136,7 +137,7 @@ public class ShowUI {
if (Shell.rootAccess()) {
options.add(mm.getString(R.string.direct_install));
}
String s = Utils.cmd("echo $SLOT");
String s = RootUtils.cmd("echo $SLOT");
if (s != null) {
options.add(mm.getString(R.string.install_second_slot));
}
@@ -185,7 +186,7 @@ public class ShowUI {
receiver = new DownloadReceiver() {
@Override
public void onDownloadDone(Uri uri) {
Utils.showUriSnack(activity, uri);
SnackbarMaker.showUri(activity, uri);
}
};
break;
@@ -210,7 +211,7 @@ public class ShowUI {
if (slot[1] == 'a') slot[1] = 'b';
else slot[1] = 'a';
// Then find the boot image again
boot = Utils.cmd(
boot = RootUtils.cmd(
"SLOT=" + String.valueOf(slot) +
"; find_boot_image;" +
"echo \"$BOOTIMAGE\""
@@ -254,7 +255,8 @@ public class ShowUI {
.setMessage(mm.getString(R.string.repo_install_msg, filename))
.setCancelable(true)
.setPositiveButton(R.string.install, (d, i) -> {
Utils.runWithPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, () -> {
Utils.runWithPermission(activity,
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, () -> {
Intent intent = new Intent(mm, ManagerUpdate.class);
intent.putExtra(Const.Key.INTENT_SET_LINK, mm.managerLink);
intent.putExtra(Const.Key.INTENT_SET_FILENAME, filename);
@@ -297,10 +299,10 @@ public class ShowUI {
} catch (IOException ignored) {}
MagiskManager.toast(R.string.uninstall_toast, Toast.LENGTH_LONG);
new Handler().postDelayed(() -> Utils.uninstallPkg(mm.getPackageName()), 5000);
new Handler().postDelayed(() -> RootUtils.uninstallPkg(mm.getPackageName()), 5000);
})
.setNeutralButton(R.string.restore_img, (d, i) -> new RestoreImages().exec())
.setNegativeButton(R.string.uninstall_app, (d, i) -> Utils.uninstallPkg(mm.getPackageName()))
.setNegativeButton(R.string.uninstall_app, (d, i) -> RootUtils.uninstallPkg(mm.getPackageName()))
.show();
}
}

View File

@@ -1,8 +1,7 @@
package com.topjohnwu.magisk.utils;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
public class Topic {
@@ -15,23 +14,24 @@ public class Topic {
private List<WeakReference<Subscriber>> subscribers;
private Object[] results;
public void subscribe(Subscriber sub) {
if (subscribers == null) {
subscribers = new LinkedList<>();
}
public Topic() {
subscribers = new SyncArrayList<>();
}
public synchronized void subscribe(Subscriber sub) {
subscribers.add(new WeakReference<>(sub));
}
public void unsubscribe() {
subscribers = null;
public synchronized void unsubscribe() {
subscribers = new SyncArrayList<>();
}
public void unsubscribe(Subscriber sub) {
for (Iterator<WeakReference<Subscriber>> i = subscribers.iterator(); i.hasNext();) {
WeakReference<Subscriber> subscriber = i.next();
if (subscriber.get() == null || subscriber.get() == sub) {
i.remove();
}
public synchronized void unsubscribe(Subscriber sub) {
List<WeakReference<Subscriber>> subs = subscribers;
subscribers = new ArrayList<>();
for (WeakReference<Subscriber> subscriber : subs) {
if (subscriber.get() != null && subscriber.get() != sub)
subscribers.add(subscriber);
}
}
@@ -52,11 +52,11 @@ public class Topic {
if (record)
state = PUBLISHED;
this.results = results;
if (subscribers != null) {
for (WeakReference<Subscriber> subscriber : subscribers) {
if (subscriber.get() != null)
subscriber.get().onTopicPublished(this);
}
// Snapshot
List<WeakReference<Subscriber>> subs = subscribers;
for (WeakReference<Subscriber> subscriber : subs) {
if (subscriber != null && subscriber.get() != null)
subscriber.get().onTopicPublished(this);
}
}
@@ -89,4 +89,11 @@ public class Topic {
void onTopicPublished(Topic topic);
Topic[] getSubscription();
}
private static class SyncArrayList<E> extends ArrayList<E> {
@Override
public synchronized boolean add(E e) {
return super.add(e);
}
}
}

View File

@@ -1,304 +0,0 @@
package com.topjohnwu.magisk.utils;
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Xml;
import android.widget.Toast;
import com.topjohnwu.magisk.MagiskManager;
import com.topjohnwu.magisk.R;
import com.topjohnwu.magisk.SplashActivity;
import com.topjohnwu.magisk.components.SnackbarMaker;
import com.topjohnwu.magisk.receivers.DownloadReceiver;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.ShellUtils;
import com.topjohnwu.superuser.io.SuFile;
import com.topjohnwu.superuser.io.SuFileInputStream;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
public class Utils {
public static boolean isDownloading = false;
public static String cmd(String cmd) {
return ShellUtils.fastCmd(Shell.getShell(), cmd);
}
public static boolean cmdResult(String cmd) {
return ShellUtils.fastCmdResult(Shell.getShell(), cmd);
}
public static void uninstallPkg(String pkg) {
Shell.Sync.su("db_clean " + Const.USER_ID, "pm uninstall " + pkg);
}
public static void dlAndReceive(Context context, DownloadReceiver receiver, String link, String filename) {
if (isDownloading)
return;
runWithPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, () -> {
File file = new File(Const.EXTERNAL_PATH, getLegalFilename(filename));
if ((!file.getParentFile().exists() && !file.getParentFile().mkdirs())
|| (file.exists() && !file.delete())) {
Toast.makeText(context, R.string.permissionNotGranted, Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(context, context.getString(R.string.downloading_toast, filename), Toast.LENGTH_LONG).show();
isDownloading = true;
DownloadManager.Request request = new DownloadManager
.Request(Uri.parse(link))
.setDestinationUri(Uri.fromFile(file));
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
receiver.setDownloadID(dm.enqueue(request)).setFile(file);
context.getApplicationContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
});
}
public static String getLegalFilename(CharSequence filename) {
return filename.toString().replace(" ", "_").replace("'", "").replace("\"", "")
.replace("$", "").replace("`", "").replace("*", "").replace("/", "_")
.replace("#", "").replace("@", "").replace("\\", "_");
}
public static int getPrefsInt(SharedPreferences prefs, String key, int def) {
return Integer.parseInt(prefs.getString(key, String.valueOf(def)));
}
public static int getPrefsInt(SharedPreferences prefs, String key) {
return getPrefsInt(prefs, key, 0);
}
public static MagiskManager getMagiskManager(Context context) {
return (MagiskManager) context.getApplicationContext();
}
public static String getNameFromUri(Context context, Uri uri) {
String name = null;
try (Cursor c = context.getContentResolver().query(uri, null, null, null, null)) {
if (c != null) {
int nameIndex = c.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (nameIndex != -1) {
c.moveToFirst();
name = c.getString(nameIndex);
}
}
}
if (name == null) {
int idx = uri.getPath().lastIndexOf('/');
name = uri.getPath().substring(idx + 1);
}
return name;
}
public static void showUriSnack(Activity activity, Uri uri) {
SnackbarMaker.make(activity, activity.getString(R.string.internal_storage,
"/MagiskManager/" + Utils.getNameFromUri(activity, uri)),
Snackbar.LENGTH_LONG)
.setAction(R.string.ok, (v)->{}).show();
}
public static boolean checkNetworkStatus() {
ConnectivityManager manager = (ConnectivityManager)
MagiskManager.get().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public static String getLocaleString(Locale locale, @StringRes int id) {
Context context = MagiskManager.get();
Configuration config = context.getResources().getConfiguration();
config.setLocale(locale);
Context localizedContext = context.createConfigurationContext(config);
return localizedContext.getString(id);
}
public static List<Locale> getAvailableLocale() {
List<Locale> locales = new ArrayList<>();
HashSet<String> set = new HashSet<>();
Locale locale;
@StringRes int compareId = R.string.download_file_error;
// Add default locale
locales.add(Locale.ENGLISH);
set.add(getLocaleString(Locale.ENGLISH, compareId));
// Add some special locales
locales.add(Locale.TAIWAN);
set.add(getLocaleString(Locale.TAIWAN, compareId));
locale = new Locale("pt", "BR");
locales.add(locale);
set.add(getLocaleString(locale, compareId));
// Other locales
for (String s : MagiskManager.get().getAssets().getLocales()) {
locale = Locale.forLanguageTag(s);
if (set.add(getLocaleString(locale, compareId))) {
locales.add(locale);
}
}
Collections.sort(locales, (l1, l2) -> l1.getDisplayName(l1).compareTo(l2.getDisplayName(l2)));
return locales;
}
public static void runWithPermission(Context context, String permission, Runnable callback) {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
// Passed in context should be an activity if not granted, need to show dialog!
Utils.getMagiskManager(context).setPermissionGrantCallback(callback);
if (!(context instanceof com.topjohnwu.magisk.components.Activity)) {
// Start activity to show dialog
Intent intent = new Intent(context, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Const.Key.INTENT_PERM, permission);
context.startActivity(intent);
} else {
ActivityCompat.requestPermissions((Activity) context, new String[] { permission }, 0);
}
} else {
callback.run();
}
}
public static AssetManager getAssets(String apk) {
try {
AssetManager asset = AssetManager.class.newInstance();
AssetManager.class.getMethod("addAssetPath", String.class).invoke(asset, apk);
return asset;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void patchDTBO() {
MagiskManager mm = MagiskManager.get();
if (mm.magiskVersionCode >= Const.MAGISK_VER.DTBO_SUPPORT && !mm.keepVerity) {
if (ShellUtils.fastCmdResult(Shell.getShell(), "patch_dtbo_image")) {
ShowUI.dtboPatchedNotification();
}
}
}
public static int dpInPx(int dp) {
Context context = MagiskManager.get();
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5);
}
public static void dumpPrefs() {
MagiskManager mm = MagiskManager.get();
// Flush prefs to disk
mm.prefs.edit().commit();
File xml = new File(mm.getFilesDir().getParent() + "/shared_prefs",
mm.getPackageName() + "_preferences.xml");
Shell.Sync.su(fmt("for usr in /data/user/*; do cat %s > ${usr}/%s; done", xml, Const.MANAGER_CONFIGS));
}
public static void loadPrefs() {
SuFile config = new SuFile(fmt("/data/user/%d/%s", Const.USER_ID, Const.MANAGER_CONFIGS), true);
if (config.exists()) {
MagiskManager mm = MagiskManager.get();
SharedPreferences.Editor editor = mm.prefs.edit();
try {
SuFileInputStream is = new SuFileInputStream(config);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, "UTF-8");
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "map");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String key = parser.getAttributeValue(null, "name");
String value = parser.getAttributeValue(null, "value");
switch (parser.getName()) {
case "string":
parser.require(XmlPullParser.START_TAG, null, "string");
editor.putString(key, parser.nextText());
parser.require(XmlPullParser.END_TAG, null, "string");
break;
case "boolean":
parser.require(XmlPullParser.START_TAG, null, "boolean");
editor.putBoolean(key, Boolean.parseBoolean(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "boolean");
break;
case "int":
parser.require(XmlPullParser.START_TAG, null, "int");
editor.putInt(key, Integer.parseInt(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "int");
break;
case "long":
parser.require(XmlPullParser.START_TAG, null, "long");
editor.putLong(key, Long.parseLong(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "long");
break;
case "float":
parser.require(XmlPullParser.START_TAG, null, "int");
editor.putFloat(key, Float.parseFloat(value));
parser.nextTag();
parser.require(XmlPullParser.END_TAG, null, "int");
break;
default:
parser.next();
}
}
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
editor.remove(Const.Key.ETAG_KEY);
editor.apply();
mm.loadConfig();
config.delete();
}
}
public static String fmt(String fmt, Object... args) {
return String.format(Locale.US, fmt, args);
}
public static String dos2unix(String s) {
String newString = s.replace("\r\n", "\n");
if(!newString.endsWith("\n")) {
return newString + "\n";
} else {
return newString;
}
}
}

View File

@@ -1,73 +0,0 @@
package com.topjohnwu.magisk.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class WebService {
public static String getString(String url) {
return getString(url, null);
}
public static String getString(String url, Map<String, String> header) {
HttpURLConnection conn = request(url, header);
if (conn == null) return "";
return getString(conn);
}
public static String getString(HttpURLConnection conn) {
try {
StringBuilder builder = new StringBuilder();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
int len;
char buf[] = new char[4096];
while ((len = br.read(buf)) != -1) {
builder.append(buf, 0, len);
}
}
}
conn.disconnect();
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static HttpURLConnection request(String address, Map<String, String> header) {
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.connect();
if (header != null) {
header.clear();
for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
List<String> l = entry.getValue();
header.put(entry.getKey(), l.get(l.size() - 1));
}
}
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}