MainApp.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author masensio
  5. * @author David A. Velasco
  6. * @author Chris Narkiewicz
  7. * @author TSI-mc
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  10. * Copyright (C) 2023 TSI-mc
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License version 2,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android;
  25. import android.annotation.SuppressLint;
  26. import android.app.Activity;
  27. import android.app.ActivityManager;
  28. import android.app.Application;
  29. import android.app.NotificationChannel;
  30. import android.app.NotificationManager;
  31. import android.content.ContentResolver;
  32. import android.content.Context;
  33. import android.content.Intent;
  34. import android.content.pm.ActivityInfo;
  35. import android.content.pm.PackageInfo;
  36. import android.content.pm.PackageManager;
  37. import android.content.res.Resources;
  38. import android.os.Build;
  39. import android.os.Bundle;
  40. import android.os.Environment;
  41. import android.os.StrictMode;
  42. import android.text.TextUtils;
  43. import android.view.WindowManager;
  44. import com.nextcloud.appReview.InAppReviewHelper;
  45. import com.nextcloud.client.account.User;
  46. import com.nextcloud.client.account.UserAccountManager;
  47. import com.nextcloud.client.appinfo.AppInfo;
  48. import com.nextcloud.client.core.Clock;
  49. import com.nextcloud.client.device.PowerManagementService;
  50. import com.nextcloud.client.di.ActivityInjector;
  51. import com.nextcloud.client.di.AppComponent;
  52. import com.nextcloud.client.di.DaggerAppComponent;
  53. import com.nextcloud.client.errorhandling.ExceptionHandler;
  54. import com.nextcloud.client.jobs.BackgroundJobManager;
  55. import com.nextcloud.client.logger.LegacyLoggerAdapter;
  56. import com.nextcloud.client.logger.Logger;
  57. import com.nextcloud.client.migrations.MigrationsManager;
  58. import com.nextcloud.client.network.ConnectivityService;
  59. import com.nextcloud.client.network.WalledCheckCache;
  60. import com.nextcloud.client.onboarding.OnboardingService;
  61. import com.nextcloud.client.preferences.AppPreferences;
  62. import com.nextcloud.client.preferences.AppPreferencesImpl;
  63. import com.nextcloud.client.preferences.DarkMode;
  64. import com.nmc.android.ui.LauncherActivity;
  65. import com.owncloud.android.authentication.AuthenticatorActivity;
  66. import com.owncloud.android.authentication.PassCodeManager;
  67. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  68. import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
  69. import com.owncloud.android.datamodel.MediaFolder;
  70. import com.owncloud.android.datamodel.MediaFolderType;
  71. import com.owncloud.android.datamodel.MediaProvider;
  72. import com.owncloud.android.datamodel.SyncedFolder;
  73. import com.owncloud.android.datamodel.SyncedFolderProvider;
  74. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  75. import com.owncloud.android.datamodel.UploadsStorageManager;
  76. import com.owncloud.android.datastorage.DataStorageProvider;
  77. import com.owncloud.android.datastorage.StoragePoint;
  78. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  79. import com.owncloud.android.lib.common.utils.Log_OC;
  80. import com.owncloud.android.lib.resources.status.NextcloudVersion;
  81. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  82. import com.owncloud.android.ui.activity.SyncedFoldersActivity;
  83. import com.owncloud.android.ui.notifications.NotificationUtils;
  84. import com.owncloud.android.utils.DisplayUtils;
  85. import com.owncloud.android.utils.FilesSyncHelper;
  86. import com.owncloud.android.utils.PermissionUtil;
  87. import com.owncloud.android.utils.ReceiversHelper;
  88. import com.owncloud.android.utils.SecurityUtils;
  89. import com.owncloud.android.utils.theme.ViewThemeUtils;
  90. import org.conscrypt.Conscrypt;
  91. import org.greenrobot.eventbus.EventBus;
  92. import java.lang.reflect.Method;
  93. import java.security.NoSuchAlgorithmException;
  94. import java.security.Security;
  95. import java.util.ArrayList;
  96. import java.util.Arrays;
  97. import java.util.HashMap;
  98. import java.util.List;
  99. import java.util.Locale;
  100. import java.util.Map;
  101. import javax.inject.Inject;
  102. import javax.inject.Provider;
  103. import javax.net.ssl.SSLContext;
  104. import javax.net.ssl.SSLEngine;
  105. import androidx.annotation.NonNull;
  106. import androidx.annotation.StringRes;
  107. import androidx.appcompat.app.AlertDialog;
  108. import androidx.appcompat.app.AppCompatDelegate;
  109. import androidx.core.util.Pair;
  110. import androidx.multidex.MultiDexApplication;
  111. import dagger.android.AndroidInjector;
  112. import dagger.android.DispatchingAndroidInjector;
  113. import dagger.android.HasAndroidInjector;
  114. import de.cotech.hw.SecurityKeyManager;
  115. import de.cotech.hw.SecurityKeyManagerConfig;
  116. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  117. import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP;
  118. /**
  119. * Main Application of the project
  120. * <p>
  121. * Contains methods to build the "static" strings. These strings were before constants in different classes
  122. */
  123. public class MainApp extends MultiDexApplication implements HasAndroidInjector {
  124. public static final OwnCloudVersion OUTDATED_SERVER_VERSION = NextcloudVersion.nextcloud_23;
  125. public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_16;
  126. private static final String TAG = MainApp.class.getSimpleName();
  127. public static final String DOT = ".";
  128. private static Context mContext;
  129. private static String storagePath;
  130. private static boolean mOnlyOnDevice;
  131. private static boolean mOnlyPersonalFiles;
  132. @Inject
  133. protected AppPreferences preferences;
  134. @Inject
  135. protected DispatchingAndroidInjector<Object> dispatchingAndroidInjector;
  136. @Inject
  137. protected UserAccountManager accountManager;
  138. @Inject
  139. protected UploadsStorageManager uploadsStorageManager;
  140. @Inject
  141. protected OnboardingService onboarding;
  142. @Inject
  143. ConnectivityService connectivityService;
  144. @Inject PowerManagementService powerManagementService;
  145. @Inject
  146. Logger logger;
  147. @Inject
  148. AppInfo appInfo;
  149. @Inject
  150. BackgroundJobManager backgroundJobManager;
  151. @Inject
  152. Clock clock;
  153. @Inject
  154. EventBus eventBus;
  155. @Inject
  156. MigrationsManager migrationsManager;
  157. @Inject
  158. InAppReviewHelper inAppReviewHelper;
  159. @Inject
  160. PassCodeManager passCodeManager;
  161. @Inject WalledCheckCache walledCheckCache;
  162. // workaround because injection is initialized on onAttachBaseContext
  163. // and getApplicationContext is null at that point, which crashes when getting current user
  164. @Inject Provider<ViewThemeUtils> viewThemeUtilsProvider;
  165. private ViewThemeUtils viewThemeUtils;
  166. @SuppressWarnings("unused")
  167. private boolean mBound;
  168. private static AppComponent appComponent;
  169. /**
  170. * Temporary hack
  171. */
  172. private static void initGlobalContext(Context context) {
  173. mContext = context;
  174. }
  175. /**
  176. * Temporary getter replacing Dagger DI
  177. * TODO: remove when cleaning DI in NContentObserverJob
  178. */
  179. public AppPreferences getPreferences() {
  180. return preferences;
  181. }
  182. /**
  183. * Temporary getter replacing Dagger DI
  184. * TODO: remove when cleaning DI in NContentObserverJob
  185. */
  186. public PowerManagementService getPowerManagementService() {
  187. return powerManagementService;
  188. }
  189. private String getAppProcessName() {
  190. String processName = "";
  191. if(Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
  192. ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
  193. final int ownPid = android.os.Process.myPid();
  194. final List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
  195. if (processes != null) {
  196. for (ActivityManager.RunningAppProcessInfo info : processes) {
  197. if (info.pid == ownPid) {
  198. processName = info.processName;
  199. break;
  200. }
  201. }
  202. }
  203. } else {
  204. processName = Application.getProcessName();
  205. }
  206. return processName;
  207. }
  208. @Override
  209. protected void attachBaseContext(Context base) {
  210. super.attachBaseContext(base);
  211. initGlobalContext(this);
  212. initDagger();
  213. // we don't want to handle crashes occurring inside crash reporter activity/process;
  214. // let the platform deal with those
  215. final boolean isCrashReportingProcess = getAppProcessName().endsWith(":crash");
  216. if (!isCrashReportingProcess && !appInfo.isDebugBuild()) {
  217. Thread.UncaughtExceptionHandler defaultPlatformHandler = Thread.getDefaultUncaughtExceptionHandler();
  218. if (defaultPlatformHandler != null) {
  219. final ExceptionHandler crashReporter = new ExceptionHandler(this,
  220. defaultPlatformHandler);
  221. Thread.setDefaultUncaughtExceptionHandler(crashReporter);
  222. }
  223. }
  224. }
  225. private void initDagger() {
  226. appComponent = DaggerAppComponent.builder()
  227. .application(this)
  228. .build();
  229. appComponent.inject(this);
  230. }
  231. /**
  232. * <b>USE SPARINGLY!</b> This should only be used for injection of Theme classes in custom Views, and they need to
  233. * be added as methods in the {@link AppComponent} itself.
  234. * <p>
  235. * Once we adopt Hilt this won't be necessary either, as View is a supported target in Hilt.
  236. *
  237. * @return the {@link AppComponent} for this app
  238. */
  239. public static AppComponent getAppComponent() {
  240. if (appComponent == null) {
  241. throw new IllegalStateException("Dagger not initialized!");
  242. }
  243. return appComponent;
  244. }
  245. @SuppressFBWarnings("ST")
  246. @Override
  247. public void onCreate() {
  248. enableStrictMode();
  249. viewThemeUtils = viewThemeUtilsProvider.get();
  250. setAppTheme(preferences.getDarkThemeMode());
  251. super.onCreate();
  252. insertConscrypt();
  253. initSecurityKeyManager();
  254. registerActivityLifecycleCallbacks(new ActivityInjector());
  255. //update the app restart count when app is launched by the user
  256. inAppReviewHelper.resetAndIncrementAppRestartCounter();
  257. int startedMigrationsCount = migrationsManager.startMigration();
  258. logger.i(TAG, String.format(Locale.US, "Started %d migrations", startedMigrationsCount));
  259. new SecurityUtils();
  260. DisplayUtils.useCompatVectorIfNeeded();
  261. fixStoragePath();
  262. MainApp.storagePath = preferences.getStoragePath(getApplicationContext().getFilesDir().getAbsolutePath());
  263. OwnCloudClientManagerFactory.setUserAgent(getUserAgent());
  264. try {
  265. OwnCloudClientManagerFactory.setProxyHost(getResources().getString(R.string.proxy_host));
  266. OwnCloudClientManagerFactory.setProxyPort(getResources().getInteger(R.integer.proxy_port));
  267. } catch (Resources.NotFoundException e) {
  268. // no proxy set
  269. }
  270. // initialise thumbnails cache on background thread
  271. new ThumbnailsCacheManager.InitDiskCacheTask().execute();
  272. if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
  273. // use app writable dir, no permissions needed
  274. Log_OC.setLoggerImplementation(new LegacyLoggerAdapter(logger));
  275. Log_OC.d("Debug", "start logging");
  276. }
  277. try {
  278. Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
  279. m.invoke(null);
  280. } catch (Exception e) {
  281. Log_OC.d("Debug", "Failed to disable uri exposure");
  282. }
  283. initSyncOperations(preferences,
  284. uploadsStorageManager,
  285. accountManager,
  286. connectivityService,
  287. powerManagementService,
  288. backgroundJobManager,
  289. clock,
  290. viewThemeUtils,
  291. walledCheckCache);
  292. initContactsBackup(accountManager, backgroundJobManager);
  293. notificationChannels();
  294. backgroundJobManager.scheduleMediaFoldersDetectionJob();
  295. backgroundJobManager.startMediaFoldersDetectionJob();
  296. backgroundJobManager.schedulePeriodicHealthStatus();
  297. registerGlobalPassCodeProtection();
  298. }
  299. private void registerGlobalPassCodeProtection() {
  300. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
  301. @Override
  302. public void onActivityCreated(@NonNull Activity activity, Bundle savedInstanceState) {
  303. Log_OC.d(activity.getClass().getSimpleName(), "onCreate(Bundle) starting");
  304. onboarding.launchActivityIfNeeded(activity);
  305. }
  306. @Override
  307. public void onActivityStarted(@NonNull Activity activity) {
  308. Log_OC.d(activity.getClass().getSimpleName(), "onStart() starting");
  309. }
  310. @Override
  311. public void onActivityResumed(@NonNull Activity activity) {
  312. Log_OC.d(activity.getClass().getSimpleName(), "onResume() starting");
  313. // we are checking activity is not launcher activity because there is timer in launcher
  314. // which will reopen the passcode screen
  315. if (!(activity instanceof LauncherActivity)) {
  316. passCodeManager.onActivityResumed(activity);
  317. }
  318. }
  319. @Override
  320. public void onActivityPaused(@NonNull Activity activity) {
  321. Log_OC.d(activity.getClass().getSimpleName(), "onPause() ending");
  322. }
  323. @Override
  324. public void onActivityStopped(@NonNull Activity activity) {
  325. Log_OC.d(activity.getClass().getSimpleName(), "onStop() ending");
  326. // since we are not showing passcode on launch activity
  327. // so we don't need to call the stopped method as well
  328. if (!(activity instanceof LauncherActivity)) {
  329. passCodeManager.onActivityStopped(activity);
  330. }
  331. }
  332. @Override
  333. public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
  334. Log_OC.d(activity.getClass().getSimpleName(), "onSaveInstanceState(Bundle) starting");
  335. }
  336. @Override
  337. public void onActivityDestroyed(@NonNull Activity activity) {
  338. Log_OC.d(activity.getClass().getSimpleName(), "onDestroy() ending");
  339. }
  340. });
  341. }
  342. @SuppressWarnings("unchecked")
  343. private void initSecurityKeyManager() {
  344. SecurityKeyManager securityKeyManager = SecurityKeyManager.getInstance();
  345. final SecurityKeyManagerConfig.Builder configBuilder = new SecurityKeyManagerConfig.Builder()
  346. .setEnableDebugLogging(BuildConfig.DEBUG);
  347. try {
  348. // exclude all activities except AuthenticatorActivity
  349. final PackageManager pm = this.getPackageManager();
  350. final PackageInfo info = pm.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
  351. final ActivityInfo[] activities = info.activities;
  352. for (ActivityInfo activityInfo : activities) {
  353. try {
  354. final Class<? extends Activity> aClass = (Class<? extends Activity>) Class.forName(activityInfo.name);
  355. if (aClass != AuthenticatorActivity.class) {
  356. configBuilder.addExcludedActivityClass(aClass);
  357. }
  358. } catch (ClassNotFoundException | ClassCastException e) {
  359. Log_OC.e(TAG, "Couldn't disable activity for security key listener", e);
  360. }
  361. }
  362. } catch (PackageManager.NameNotFoundException e) {
  363. Log_OC.e(TAG, "Couldn't disable activities for security key listener", e);
  364. }
  365. securityKeyManager.init(this, configBuilder.build());
  366. }
  367. public static void initContactsBackup(UserAccountManager accountManager, BackgroundJobManager backgroundJobManager) {
  368. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProviderImpl(mContext);
  369. List<User> users = accountManager.getAllUsers();
  370. for (User user : users) {
  371. if (arbitraryDataProvider.getBooleanValue(user, PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
  372. backgroundJobManager.schedulePeriodicContactsBackup(user);
  373. }
  374. }
  375. }
  376. private void insertConscrypt() {
  377. Security.insertProviderAt(Conscrypt.newProvider(), 1);
  378. try {
  379. Conscrypt.Version version = Conscrypt.version();
  380. Log_OC.i(TAG, "Using Conscrypt/"
  381. + version.major()
  382. + DOT
  383. + version.minor()
  384. + DOT + version.patch()
  385. + " for TLS");
  386. SSLEngine engine = SSLContext.getDefault().createSSLEngine();
  387. Log_OC.i(TAG, "Enabled protocols: " + Arrays.toString(engine.getEnabledProtocols()) + " }");
  388. Log_OC.i(TAG, "Enabled ciphers: " + Arrays.toString(engine.getEnabledCipherSuites()) + " }");
  389. } catch (NoSuchAlgorithmException e) {
  390. Log_OC.e(TAG, e.getMessage());
  391. }
  392. }
  393. @SuppressLint("ApplySharedPref") // commit is done on purpose to write immediately
  394. private void fixStoragePath() {
  395. if (!preferences.isStoragePathFixEnabled()) {
  396. StoragePoint[] storagePoints = DataStorageProvider.getInstance().getAvailableStoragePoints();
  397. String storagePath = preferences.getStoragePath("");
  398. if (TextUtils.isEmpty(storagePath)) {
  399. if (preferences.getLastSeenVersionCode() != 0) {
  400. // We already used the app, but no storage is set - fix that!
  401. preferences.setStoragePath(Environment.getExternalStorageDirectory().getAbsolutePath());
  402. preferences.removeKeysMigrationPreference();
  403. } else {
  404. // find internal storage path that's indexable
  405. boolean set = false;
  406. for (StoragePoint storagePoint : storagePoints) {
  407. if (storagePoint.getStorageType() == StoragePoint.StorageType.INTERNAL &&
  408. storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  409. preferences.setStoragePath(storagePoint.getPath());
  410. preferences.removeKeysMigrationPreference();
  411. set = true;
  412. break;
  413. }
  414. }
  415. if (!set) {
  416. for (StoragePoint storagePoint : storagePoints) {
  417. if (storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  418. preferences.setStoragePath(storagePoint.getPath());
  419. preferences.removeKeysMigrationPreference();
  420. set = true;
  421. break;
  422. }
  423. }
  424. }
  425. }
  426. preferences.setStoragePathFixEnabled(true);
  427. } else {
  428. preferences.removeKeysMigrationPreference();
  429. preferences.setStoragePathFixEnabled(true);
  430. }
  431. }
  432. }
  433. private void enableStrictMode() {
  434. if (BuildConfig.DEBUG && BuildConfig.RUNTIME_PERF_ANALYSIS) {
  435. Log_OC.d(TAG, "Enabling StrictMode");
  436. StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
  437. .detectDiskReads()
  438. .detectDiskWrites()
  439. .detectAll()
  440. .penaltyLog()
  441. .build());
  442. StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
  443. .detectLeakedSqlLiteObjects()
  444. .detectLeakedClosableObjects()
  445. .penaltyLog()
  446. .build());
  447. }
  448. }
  449. public static void initSyncOperations(
  450. final AppPreferences preferences,
  451. final UploadsStorageManager uploadsStorageManager,
  452. final UserAccountManager accountManager,
  453. final ConnectivityService connectivityService,
  454. final PowerManagementService powerManagementService,
  455. final BackgroundJobManager backgroundJobManager,
  456. final Clock clock,
  457. final ViewThemeUtils viewThemeUtils,
  458. final WalledCheckCache walledCheckCache) {
  459. updateToAutoUpload();
  460. cleanOldEntries(clock);
  461. updateAutoUploadEntries(clock);
  462. if (getAppContext() != null) {
  463. if (PermissionUtil.checkExternalStoragePermission(getAppContext())) {
  464. splitOutAutoUploadEntries(clock, viewThemeUtils);
  465. } else {
  466. preferences.setAutoUploadSplitEntriesEnabled(true);
  467. }
  468. }
  469. if (!preferences.isAutoUploadInitialized()) {
  470. backgroundJobManager.startImmediateFilesSyncJob(false, false);
  471. preferences.setAutoUploadInit(true);
  472. }
  473. FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext, backgroundJobManager);
  474. FilesSyncHelper.restartJobsIfNeeded(
  475. uploadsStorageManager,
  476. accountManager,
  477. connectivityService,
  478. powerManagementService);
  479. backgroundJobManager.scheduleOfflineSync();
  480. ReceiversHelper.registerNetworkChangeReceiver(uploadsStorageManager,
  481. accountManager,
  482. connectivityService,
  483. powerManagementService,
  484. walledCheckCache);
  485. ReceiversHelper.registerPowerChangeReceiver(uploadsStorageManager,
  486. accountManager,
  487. connectivityService,
  488. powerManagementService);
  489. ReceiversHelper.registerPowerSaveReceiver(uploadsStorageManager,
  490. accountManager,
  491. connectivityService,
  492. powerManagementService);
  493. }
  494. public static void notificationChannels() {
  495. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && getAppContext() != null) {
  496. Context context = getAppContext();
  497. NotificationManager notificationManager = (NotificationManager)
  498. context.getSystemService(Context.NOTIFICATION_SERVICE);
  499. if (notificationManager != null) {
  500. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD,
  501. R.string.notification_channel_download_name_short,
  502. R.string.notification_channel_download_description, context);
  503. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD,
  504. R.string.notification_channel_upload_name_short,
  505. R.string.notification_channel_upload_description, context);
  506. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA,
  507. R.string.notification_channel_media_name,
  508. R.string.notification_channel_media_description, context);
  509. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC,
  510. R.string.notification_channel_file_sync_name,
  511. R.string.notification_channel_file_sync_description, context);
  512. notificationManager.deleteNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER);
  513. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_PUSH,
  514. R.string.notification_channel_push_name, R.string
  515. .notification_channel_push_description, context, NotificationManager.IMPORTANCE_DEFAULT);
  516. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL, R.string
  517. .notification_channel_general_name, R.string.notification_channel_general_description,
  518. context, NotificationManager.IMPORTANCE_DEFAULT);
  519. } else {
  520. Log_OC.e(TAG, "Notification manager is null");
  521. }
  522. }
  523. }
  524. private static void createChannel(NotificationManager notificationManager,
  525. String channelId, int channelName,
  526. int channelDescription, Context context) {
  527. createChannel(notificationManager, channelId, channelName, channelDescription, context,
  528. NotificationManager.IMPORTANCE_LOW);
  529. }
  530. private static void createChannel(NotificationManager notificationManager,
  531. String channelId, int channelName,
  532. int channelDescription, Context context, int importance) {
  533. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
  534. && getAppContext() != null) {
  535. CharSequence name = context.getString(channelName);
  536. String description = context.getString(channelDescription);
  537. NotificationChannel channel = new NotificationChannel(channelId, name, importance);
  538. channel.setDescription(description);
  539. channel.enableLights(false);
  540. channel.enableVibration(false);
  541. notificationManager.createNotificationChannel(channel);
  542. }
  543. }
  544. public static Context getAppContext() {
  545. return MainApp.mContext;
  546. }
  547. public static void setAppContext(Context context) {
  548. MainApp.mContext = context;
  549. }
  550. public static String getStoragePath() {
  551. return MainApp.storagePath;
  552. }
  553. public static void setStoragePath(String path) {
  554. MainApp.storagePath = path;
  555. }
  556. // Methods to obtain Strings referring app_name
  557. // From AccountAuthenticator
  558. // public static final String ACCOUNT_TYPE = "owncloud";
  559. public static String getAccountType(Context context) {
  560. return context.getResources().getString(R.string.account_type);
  561. }
  562. // From AccountAuthenticator
  563. // public static final String AUTHORITY = "org.owncloud";
  564. public static String getAuthority() {
  565. return getAppContext().getResources().getString(R.string.authority);
  566. }
  567. // From AccountAuthenticator
  568. // public static final String AUTH_TOKEN_TYPE = "org.owncloud";
  569. public static String getAuthTokenType() {
  570. return getAppContext().getResources().getString(R.string.authority);
  571. }
  572. // From ProviderMeta
  573. // public static final String DB_FILE = "owncloud.db";
  574. public static String getDBFile() {
  575. return getAppContext().getResources().getString(R.string.db_file);
  576. }
  577. // From ProviderMeta
  578. // private final String mDatabaseName = "ownCloud";
  579. public static String getDBName() {
  580. return getAppContext().getResources().getString(R.string.db_name);
  581. }
  582. /**
  583. * name of data_folder, e.g., "owncloud"
  584. */
  585. public static String getDataFolder() {
  586. return getAppContext().getResources().getString(R.string.data_folder);
  587. }
  588. public static void showOnlyFilesOnDevice(boolean state) {
  589. mOnlyOnDevice = state;
  590. }
  591. public static void showOnlyPersonalFiles(boolean state) {
  592. mOnlyPersonalFiles = state;
  593. }
  594. public static boolean isOnlyOnDevice() {
  595. return mOnlyOnDevice;
  596. }
  597. public static boolean isOnlyPersonFiles() {
  598. return mOnlyPersonalFiles;
  599. }
  600. public static String getUserAgent() {
  601. // Mozilla/5.0 (Android) Nextcloud-android/2.1.0
  602. return getUserAgent(R.string.nextcloud_user_agent);
  603. }
  604. // user agent
  605. private static String getUserAgent(@StringRes int agent) {
  606. String appString = getAppContext().getResources().getString(agent);
  607. String brandedName = getAppContext().getString(R.string.name_for_branded_user_agent);
  608. String packageName = getAppContext().getPackageName();
  609. String version = "";
  610. try {
  611. PackageInfo pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0);
  612. if (pInfo != null) {
  613. version = pInfo.versionName;
  614. }
  615. } catch (PackageManager.NameNotFoundException e) {
  616. Log_OC.e(TAG, "Trying to get packageName", e.getCause());
  617. }
  618. return String.format(appString, version, brandedName);
  619. }
  620. private static void updateToAutoUpload() {
  621. Context context = getAppContext();
  622. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  623. if (preferences.instantPictureUploadEnabled() || preferences.instantVideoUploadEnabled()) {
  624. preferences.removeLegacyPreferences();
  625. // show info pop-up
  626. try {
  627. new AlertDialog.Builder(context, R.style.Theme_ownCloud_Dialog)
  628. .setTitle(R.string.drawer_synced_folders)
  629. .setMessage(R.string.synced_folders_new_info)
  630. .setPositiveButton(R.string.drawer_open, (dialog, which) -> {
  631. // show Auto Upload
  632. Intent folderSyncIntent = new Intent(context, SyncedFoldersActivity.class);
  633. dialog.dismiss();
  634. context.startActivity(folderSyncIntent);
  635. })
  636. .setNegativeButton(R.string.drawer_close, (dialog, which) -> dialog.dismiss())
  637. .setIcon(R.drawable.nav_synced_folders)
  638. .show();
  639. } catch (WindowManager.BadTokenException e) {
  640. Log_OC.i(TAG, "Error showing Auto Upload Update dialog, so skipping it: " + e.getMessage());
  641. }
  642. }
  643. }
  644. private static void updateAutoUploadEntries(Clock clock) {
  645. // updates entries to reflect their true paths
  646. Context context = getAppContext();
  647. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  648. if (!preferences.isAutoUploadPathsUpdateEnabled()) {
  649. SyncedFolderProvider syncedFolderProvider =
  650. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver(), preferences, clock);
  651. syncedFolderProvider.updateAutoUploadPaths(mContext);
  652. }
  653. }
  654. private static void splitOutAutoUploadEntries(Clock clock,
  655. final ViewThemeUtils viewThemeUtils) {
  656. Context context = getAppContext();
  657. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  658. if (!preferences.isAutoUploadSplitEntriesEnabled()) {
  659. // magic to split out existing synced folders in two when needed
  660. // otherwise, we migrate them to their proper type (image or video)
  661. Log_OC.i(TAG, "Migrate synced_folders records for image/video split");
  662. ContentResolver contentResolver = context.getContentResolver();
  663. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver, preferences, clock);
  664. final List<MediaFolder> imageMediaFolders = MediaProvider.getImageFolders(contentResolver,
  665. 1,
  666. null,
  667. true,
  668. viewThemeUtils);
  669. final List<MediaFolder> videoMediaFolders = MediaProvider.getVideoFolders(contentResolver,
  670. 1,
  671. null,
  672. true,
  673. viewThemeUtils);
  674. ArrayList<Long> idsToDelete = new ArrayList<>();
  675. List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
  676. long primaryKey;
  677. SyncedFolder newSyncedFolder;
  678. for (SyncedFolder syncedFolder : syncedFolders) {
  679. idsToDelete.add(syncedFolder.getId());
  680. Log_OC.i(TAG, "Migration check for synced_folders record: "
  681. + syncedFolder.getId() + " - " + syncedFolder.getLocalPath());
  682. for (MediaFolder imageMediaFolder : imageMediaFolders) {
  683. String absolutePathOfImageFolder = imageMediaFolder.absolutePath;
  684. if (absolutePathOfImageFolder != null) {
  685. if (absolutePathOfImageFolder.equals(syncedFolder.getLocalPath())) {
  686. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  687. newSyncedFolder.setType(MediaFolderType.IMAGE);
  688. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  689. Log_OC.i(TAG, "Migrated image synced_folders record: "
  690. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  691. break;
  692. }
  693. }
  694. }
  695. for (MediaFolder videoMediaFolder : videoMediaFolders) {
  696. String absolutePathOfVideoFolder = videoMediaFolder.absolutePath;
  697. if (absolutePathOfVideoFolder != null) {
  698. if (absolutePathOfVideoFolder.equals(syncedFolder.getLocalPath())) {
  699. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  700. newSyncedFolder.setType(MediaFolderType.VIDEO);
  701. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  702. Log_OC.i(TAG, "Migrated video synced_folders record: "
  703. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  704. break;
  705. }
  706. }
  707. }
  708. }
  709. for (long id : idsToDelete) {
  710. Log_OC.i(TAG, "Removing legacy synced_folders record: " + id);
  711. syncedFolderProvider.deleteSyncedFolder(id);
  712. }
  713. preferences.setAutoUploadSplitEntriesEnabled(true);
  714. }
  715. }
  716. private static void cleanOldEntries(Clock clock) {
  717. // previous versions of application created broken entries in the SyncedFolderProvider
  718. // database, and this cleans all that and leaves 1 (newest) entry per synced folder
  719. Context context = getAppContext();
  720. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  721. if (!preferences.isLegacyClean()) {
  722. SyncedFolderProvider syncedFolderProvider =
  723. new SyncedFolderProvider(context.getContentResolver(), preferences, clock);
  724. List<SyncedFolder> syncedFolderList = syncedFolderProvider.getSyncedFolders();
  725. Map<Pair<String, String>, Long> syncedFolders = new HashMap<>();
  726. for (SyncedFolder syncedFolder : syncedFolderList) {
  727. Pair<String, String> checkPair = new Pair<>(syncedFolder.getAccount(), syncedFolder.getLocalPath());
  728. if (syncedFolders.containsKey(checkPair)) {
  729. Long folderId = syncedFolders.get(checkPair);
  730. if (folderId != null) {
  731. if (syncedFolder.getId() > folderId) {
  732. syncedFolders.put(checkPair, syncedFolder.getId());
  733. }
  734. }
  735. } else {
  736. syncedFolders.put(checkPair, syncedFolder.getId());
  737. }
  738. }
  739. ArrayList<Long> ids = new ArrayList<>(syncedFolders.values());
  740. if (ids.size() > 0) {
  741. int deletedCount = syncedFolderProvider.deleteSyncedFoldersNotInList(ids);
  742. if (deletedCount > 0) {
  743. preferences.setLegacyClean(true);
  744. }
  745. } else {
  746. preferences.setLegacyClean(true);
  747. }
  748. }
  749. }
  750. @Override
  751. public AndroidInjector<Object> androidInjector() {
  752. return dispatchingAndroidInjector;
  753. }
  754. public static void setAppTheme(DarkMode mode) {
  755. switch (mode) {
  756. case LIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
  757. case DARK -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
  758. case SYSTEM -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
  759. }
  760. }
  761. }