MainApp.java 37 KB

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