MainApp.java 35 KB

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