MainApp.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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.Manifest;
  24. import android.accounts.Account;
  25. import android.annotation.SuppressLint;
  26. import android.app.Activity;
  27. import android.app.NotificationChannel;
  28. import android.app.NotificationManager;
  29. import android.app.Service;
  30. import android.content.BroadcastReceiver;
  31. import android.content.ContentProvider;
  32. import android.content.ContentResolver;
  33. import android.content.Context;
  34. import android.content.Intent;
  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.evernote.android.job.JobManager;
  44. import com.evernote.android.job.JobRequest;
  45. import com.nextcloud.client.account.UserAccountManager;
  46. import com.nextcloud.client.appinfo.AppInfo;
  47. import com.nextcloud.client.device.PowerManagementService;
  48. import com.nextcloud.client.di.ActivityInjector;
  49. import com.nextcloud.client.di.DaggerAppComponent;
  50. import com.nextcloud.client.network.ConnectivityService;
  51. import com.nextcloud.client.onboarding.OnboardingService;
  52. import com.nextcloud.client.preferences.AppPreferences;
  53. import com.nextcloud.client.preferences.AppPreferencesImpl;
  54. import com.owncloud.android.authentication.PassCodeManager;
  55. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  56. import com.owncloud.android.datamodel.MediaFolder;
  57. import com.owncloud.android.datamodel.MediaFolderType;
  58. import com.owncloud.android.datamodel.MediaProvider;
  59. import com.owncloud.android.datamodel.SyncedFolder;
  60. import com.owncloud.android.datamodel.SyncedFolderProvider;
  61. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  62. import com.owncloud.android.datamodel.UploadsStorageManager;
  63. import com.owncloud.android.datastorage.DataStorageProvider;
  64. import com.owncloud.android.datastorage.StoragePoint;
  65. import com.owncloud.android.jobs.MediaFoldersDetectionJob;
  66. import com.owncloud.android.jobs.NCJobCreator;
  67. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  68. import com.owncloud.android.lib.common.utils.Log_OC;
  69. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  70. import com.owncloud.android.ui.activity.ContactsPreferenceActivity;
  71. import com.owncloud.android.ui.activity.SyncedFoldersActivity;
  72. import com.owncloud.android.ui.notifications.NotificationUtils;
  73. import com.owncloud.android.utils.DisplayUtils;
  74. import com.owncloud.android.utils.FilesSyncHelper;
  75. import com.owncloud.android.utils.PermissionUtil;
  76. import com.owncloud.android.utils.ReceiversHelper;
  77. import com.owncloud.android.utils.SecurityUtils;
  78. import java.lang.reflect.Method;
  79. import java.util.ArrayList;
  80. import java.util.HashMap;
  81. import java.util.List;
  82. import java.util.Map;
  83. import java.util.concurrent.TimeUnit;
  84. import javax.inject.Inject;
  85. import androidx.annotation.RequiresApi;
  86. import androidx.annotation.StringRes;
  87. import androidx.appcompat.app.AlertDialog;
  88. import androidx.core.util.Pair;
  89. import androidx.fragment.app.Fragment;
  90. import androidx.multidex.MultiDexApplication;
  91. import dagger.android.AndroidInjector;
  92. import dagger.android.DispatchingAndroidInjector;
  93. import dagger.android.HasActivityInjector;
  94. import dagger.android.HasBroadcastReceiverInjector;
  95. import dagger.android.HasContentProviderInjector;
  96. import dagger.android.HasServiceInjector;
  97. import dagger.android.support.HasSupportFragmentInjector;
  98. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  99. import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP;
  100. /**
  101. * Main Application of the project
  102. * <p>
  103. * Contains methods to build the "static" strings. These strings were before constants in different classes
  104. */
  105. public class MainApp extends MultiDexApplication implements
  106. HasActivityInjector,
  107. HasSupportFragmentInjector,
  108. HasServiceInjector,
  109. HasContentProviderInjector,
  110. HasBroadcastReceiverInjector {
  111. public static final OwnCloudVersion OUTDATED_SERVER_VERSION = OwnCloudVersion.nextcloud_13;
  112. public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_12;
  113. private static final String TAG = MainApp.class.getSimpleName();
  114. private static Context mContext;
  115. private static String storagePath;
  116. private static boolean mOnlyOnDevice;
  117. @Inject
  118. protected AppPreferences preferences;
  119. @Inject
  120. protected DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
  121. @Inject
  122. protected DispatchingAndroidInjector<Fragment> dispatchingFragmentInjector;
  123. @Inject
  124. protected DispatchingAndroidInjector<Service> dispatchingServiceInjector;
  125. @Inject
  126. protected DispatchingAndroidInjector<ContentProvider> dispatchingContentProviderInjector;
  127. @Inject
  128. protected DispatchingAndroidInjector<BroadcastReceiver> dispatchingBroadcastReceiverInjector;
  129. @Inject
  130. protected UserAccountManager accountManager;
  131. @Inject
  132. protected UploadsStorageManager uploadsStorageManager;
  133. @Inject
  134. protected AppInfo appInfo;
  135. @Inject
  136. protected OnboardingService onboarding;
  137. @Inject
  138. ConnectivityService connectivityService;
  139. @Inject PowerManagementService powerManagementService;
  140. private PassCodeManager passCodeManager;
  141. @SuppressWarnings("unused")
  142. private boolean mBound;
  143. /**
  144. * Temporary hack
  145. */
  146. private static void initGlobalContext(Context context) {
  147. mContext = context;
  148. }
  149. /**
  150. * Temporary getter replacing Dagger DI
  151. * TODO: remove when cleaning DI in NContentObserverJob
  152. */
  153. public AppPreferences getPreferences() {
  154. return preferences;
  155. }
  156. /**
  157. * Temporary getter replacing Dagger DI
  158. * TODO: remove when cleaning DI in NContentObserverJob
  159. */
  160. public PowerManagementService getPowerManagementService() {
  161. return powerManagementService;
  162. }
  163. @Override
  164. protected void attachBaseContext(Context base) {
  165. super.attachBaseContext(base);
  166. initGlobalContext(this);
  167. DaggerAppComponent.builder()
  168. .application(this)
  169. .build()
  170. .inject(this);
  171. }
  172. @SuppressFBWarnings("ST")
  173. @Override
  174. public void onCreate() {
  175. super.onCreate();
  176. registerActivityLifecycleCallbacks(new ActivityInjector());
  177. Thread t = new Thread(() -> {
  178. // best place, before any access to AccountManager or database
  179. accountManager.migrateUserId();
  180. });
  181. t.start();
  182. JobManager.create(this).addJobCreator(
  183. new NCJobCreator(
  184. getApplicationContext(),
  185. accountManager,
  186. preferences,
  187. uploadsStorageManager,
  188. connectivityService,
  189. powerManagementService
  190. )
  191. );
  192. new SecurityUtils();
  193. DisplayUtils.useCompatVectorIfNeeded();
  194. fixStoragePath();
  195. passCodeManager = new PassCodeManager(preferences);
  196. MainApp.storagePath = preferences.getStoragePath(getApplicationContext().getFilesDir().getAbsolutePath());
  197. OwnCloudClientManagerFactory.setUserAgent(getUserAgent());
  198. // initialise thumbnails cache on background thread
  199. new ThumbnailsCacheManager.InitDiskCacheTask().execute();
  200. if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
  201. // use app writable dir, no permissions needed
  202. Log_OC.startLogging(getAppContext());
  203. Log_OC.d("Debug", "start logging");
  204. }
  205. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  206. try {
  207. Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
  208. m.invoke(null);
  209. } catch (Exception e) {
  210. Log_OC.d("Debug", "Failed to disable uri exposure");
  211. }
  212. }
  213. initSyncOperations(uploadsStorageManager, accountManager, connectivityService, powerManagementService);
  214. initContactsBackup(accountManager);
  215. notificationChannels();
  216. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  217. .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
  218. .setUpdateCurrent(true)
  219. .build()
  220. .schedule();
  221. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  222. .startNow()
  223. .setUpdateCurrent(false)
  224. .build()
  225. .schedule();
  226. // register global protection with pass code
  227. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
  228. @Override
  229. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  230. Log_OC.d(activity.getClass().getSimpleName(), "onCreate(Bundle) starting");
  231. onboarding.launchActivityIfNeeded(activity);
  232. }
  233. @Override
  234. public void onActivityStarted(Activity activity) {
  235. Log_OC.d(activity.getClass().getSimpleName(), "onStart() starting");
  236. }
  237. @Override
  238. public void onActivityResumed(Activity activity) {
  239. Log_OC.d(activity.getClass().getSimpleName(), "onResume() starting");
  240. passCodeManager.onActivityStarted(activity);
  241. }
  242. @Override
  243. public void onActivityPaused(Activity activity) {
  244. Log_OC.d(activity.getClass().getSimpleName(), "onPause() ending");
  245. }
  246. @Override
  247. public void onActivityStopped(Activity activity) {
  248. Log_OC.d(activity.getClass().getSimpleName(), "onStop() ending");
  249. passCodeManager.onActivityStopped(activity);
  250. }
  251. @Override
  252. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  253. Log_OC.d(activity.getClass().getSimpleName(), "onSaveInstanceState(Bundle) starting");
  254. }
  255. @Override
  256. public void onActivityDestroyed(Activity activity) {
  257. Log_OC.d(activity.getClass().getSimpleName(), "onDestroy() ending");
  258. }
  259. });
  260. }
  261. public static void initContactsBackup(UserAccountManager accountManager) {
  262. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
  263. Account[] accounts = accountManager.getAccounts();
  264. for (Account account : accounts) {
  265. if (arbitraryDataProvider.getBooleanValue(account, PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
  266. ContactsPreferenceActivity.startContactBackupJob(account);
  267. }
  268. }
  269. }
  270. @SuppressLint("ApplySharedPref") // commit is done on purpose to write immediately
  271. private void fixStoragePath() {
  272. if (!preferences.isStoragePathFixEnabled()) {
  273. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  274. StoragePoint[] storagePoints = DataStorageProvider.getInstance().getAvailableStoragePoints();
  275. String storagePath = preferences.getStoragePath("");
  276. if (TextUtils.isEmpty(storagePath)) {
  277. if (preferences.getLastSeenVersionCode() != 0) {
  278. // We already used the app, but no storage is set - fix that!
  279. preferences.setStoragePath(Environment.getExternalStorageDirectory().getAbsolutePath());
  280. preferences.removeKeysMigrationPreference();
  281. } else {
  282. // find internal storage path that's indexable
  283. boolean set = false;
  284. for (StoragePoint storagePoint : storagePoints) {
  285. if (storagePoint.getStorageType() == StoragePoint.StorageType.INTERNAL &&
  286. storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  287. preferences.setStoragePath(storagePoint.getPath());
  288. preferences.removeKeysMigrationPreference();
  289. set = true;
  290. break;
  291. }
  292. }
  293. if (!set) {
  294. for (StoragePoint storagePoint : storagePoints) {
  295. if (storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  296. preferences.setStoragePath(storagePoint.getPath());
  297. preferences.removeKeysMigrationPreference();
  298. set = true;
  299. break;
  300. }
  301. }
  302. }
  303. }
  304. preferences.setStoragePathFixEnabled(true);
  305. } else {
  306. preferences.removeKeysMigrationPreference();
  307. preferences.setStoragePathFixEnabled(true);
  308. }
  309. } else {
  310. if (TextUtils.isEmpty(storagePath)) {
  311. preferences.setStoragePath(Environment.getExternalStorageDirectory().getAbsolutePath());
  312. }
  313. preferences.removeKeysMigrationPreference();
  314. preferences.setStoragePathFixEnabled(true);
  315. }
  316. }
  317. }
  318. public static void initSyncOperations(
  319. final UploadsStorageManager uploadsStorageManager,
  320. final UserAccountManager accountManager,
  321. final ConnectivityService connectivityService,
  322. final PowerManagementService powerManagementService
  323. ) {
  324. updateToAutoUpload();
  325. cleanOldEntries();
  326. updateAutoUploadEntries();
  327. if (getAppContext() != null) {
  328. if (PermissionUtil.checkSelfPermission(getAppContext(),
  329. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  330. splitOutAutoUploadEntries();
  331. } else {
  332. AppPreferences preferences = AppPreferencesImpl.fromContext(getAppContext());
  333. preferences.setAutoUploadSplitEntriesEnabled(true);
  334. }
  335. }
  336. initiateExistingAutoUploadEntries();
  337. FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
  338. FilesSyncHelper.restartJobsIfNeeded(
  339. uploadsStorageManager,
  340. accountManager,
  341. connectivityService,
  342. powerManagementService);
  343. FilesSyncHelper.scheduleOfflineSyncIfNeeded();
  344. ReceiversHelper.registerNetworkChangeReceiver(uploadsStorageManager,
  345. accountManager,
  346. connectivityService,
  347. powerManagementService);
  348. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  349. ReceiversHelper.registerPowerChangeReceiver(uploadsStorageManager,
  350. accountManager,
  351. connectivityService,
  352. powerManagementService);
  353. }
  354. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  355. ReceiversHelper.registerPowerSaveReceiver(uploadsStorageManager,
  356. accountManager,
  357. connectivityService,
  358. powerManagementService);
  359. }
  360. }
  361. public static void notificationChannels() {
  362. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && getAppContext() != null) {
  363. Context context = getAppContext();
  364. NotificationManager notificationManager = (NotificationManager)
  365. context.getSystemService(Context.NOTIFICATION_SERVICE);
  366. if (notificationManager != null) {
  367. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD,
  368. R.string.notification_channel_download_name,
  369. R.string.notification_channel_download_description, context);
  370. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD,
  371. R.string.notification_channel_upload_name,
  372. R.string.notification_channel_upload_description, context);
  373. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA,
  374. R.string.notification_channel_media_name,
  375. R.string.notification_channel_media_description, context);
  376. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC,
  377. R.string.notification_channel_file_sync_name,
  378. R.string.notification_channel_file_sync_description, context);
  379. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER,
  380. R.string.notification_channel_file_observer_name, R.string
  381. .notification_channel_file_observer_description, context);
  382. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_PUSH,
  383. R.string.notification_channel_push_name, R.string
  384. .notification_channel_push_description, context, NotificationManager.IMPORTANCE_DEFAULT);
  385. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL, R.string
  386. .notification_channel_general_name, R.string.notification_channel_general_description,
  387. context, NotificationManager.IMPORTANCE_DEFAULT);
  388. } else {
  389. Log_OC.e(TAG, "Notification manager is null");
  390. }
  391. }
  392. }
  393. @RequiresApi(api = Build.VERSION_CODES.N)
  394. private static void createChannel(NotificationManager notificationManager,
  395. String channelId, int channelName,
  396. int channelDescription, Context context) {
  397. createChannel(notificationManager, channelId, channelName, channelDescription, context,
  398. NotificationManager.IMPORTANCE_LOW);
  399. }
  400. private static void createChannel(NotificationManager notificationManager,
  401. String channelId, int channelName,
  402. int channelDescription, Context context, int importance) {
  403. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
  404. && getAppContext() != null
  405. && notificationManager.getNotificationChannel(channelId) == null) {
  406. CharSequence name = context.getString(channelName);
  407. String description = context.getString(channelDescription);
  408. NotificationChannel channel = new NotificationChannel(channelId, name, importance);
  409. channel.setDescription(description);
  410. channel.enableLights(false);
  411. channel.enableVibration(false);
  412. notificationManager.createNotificationChannel(channel);
  413. }
  414. }
  415. public static Context getAppContext() {
  416. return MainApp.mContext;
  417. }
  418. public static void setAppContext(Context context) {
  419. MainApp.mContext = context;
  420. }
  421. public static String getStoragePath() {
  422. return MainApp.storagePath;
  423. }
  424. public static void setStoragePath(String path) {
  425. MainApp.storagePath = path;
  426. }
  427. // Methods to obtain Strings referring app_name
  428. // From AccountAuthenticator
  429. // public static final String ACCOUNT_TYPE = "owncloud";
  430. public static String getAccountType(Context context) {
  431. return context.getResources().getString(R.string.account_type);
  432. }
  433. // From AccountAuthenticator
  434. // public static final String AUTHORITY = "org.owncloud";
  435. public static String getAuthority() {
  436. return getAppContext().getResources().getString(R.string.authority);
  437. }
  438. // From AccountAuthenticator
  439. // public static final String AUTH_TOKEN_TYPE = "org.owncloud";
  440. public static String getAuthTokenType() {
  441. return getAppContext().getResources().getString(R.string.authority);
  442. }
  443. // From ProviderMeta
  444. // public static final String DB_FILE = "owncloud.db";
  445. public static String getDBFile() {
  446. return getAppContext().getResources().getString(R.string.db_file);
  447. }
  448. // From ProviderMeta
  449. // private final String mDatabaseName = "ownCloud";
  450. public static String getDBName() {
  451. return getAppContext().getResources().getString(R.string.db_name);
  452. }
  453. /**
  454. * name of data_folder, e.g., "owncloud"
  455. */
  456. public static String getDataFolder() {
  457. return getAppContext().getResources().getString(R.string.data_folder);
  458. }
  459. public static void showOnlyFilesOnDevice(boolean state) {
  460. mOnlyOnDevice = state;
  461. }
  462. public static boolean isOnlyOnDevice() {
  463. return mOnlyOnDevice;
  464. }
  465. public static String getUserAgent() {
  466. // Mozilla/5.0 (Android) Nextcloud-android/2.1.0
  467. return getUserAgent(R.string.nextcloud_user_agent);
  468. }
  469. // user agent
  470. private static String getUserAgent(@StringRes int agent) {
  471. String appString = getAppContext().getResources().getString(agent);
  472. String packageName = getAppContext().getPackageName();
  473. String version = "";
  474. try {
  475. PackageInfo pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0);
  476. if (pInfo != null) {
  477. version = pInfo.versionName;
  478. }
  479. } catch (PackageManager.NameNotFoundException e) {
  480. Log_OC.e(TAG, "Trying to get packageName", e.getCause());
  481. }
  482. return String.format(appString, version);
  483. }
  484. private static void updateToAutoUpload() {
  485. Context context = getAppContext();
  486. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  487. if (preferences.instantPictureUploadEnabled() || preferences.instantVideoUploadEnabled()) {
  488. preferences.removeLegacyPreferences();
  489. // show info pop-up
  490. try {
  491. new AlertDialog.Builder(context, R.style.Theme_ownCloud_Dialog)
  492. .setTitle(R.string.drawer_synced_folders)
  493. .setMessage(R.string.synced_folders_new_info)
  494. .setPositiveButton(R.string.drawer_open, (dialog, which) -> {
  495. // show Auto Upload
  496. Intent folderSyncIntent = new Intent(context, SyncedFoldersActivity.class);
  497. dialog.dismiss();
  498. context.startActivity(folderSyncIntent);
  499. })
  500. .setNegativeButton(R.string.drawer_close, (dialog, which) -> dialog.dismiss())
  501. .setIcon(R.drawable.nav_synced_folders)
  502. .show();
  503. } catch (WindowManager.BadTokenException e) {
  504. Log_OC.i(TAG, "Error showing Auto Upload Update dialog, so skipping it: " + e.getMessage());
  505. }
  506. }
  507. }
  508. private static void updateAutoUploadEntries() {
  509. // updates entries to reflect their true paths
  510. Context context = getAppContext();
  511. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  512. if (!preferences.isAutoUploadPathsUpdateEnabled()) {
  513. SyncedFolderProvider syncedFolderProvider =
  514. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver(), preferences);
  515. syncedFolderProvider.updateAutoUploadPaths(mContext);
  516. }
  517. }
  518. private static void splitOutAutoUploadEntries() {
  519. Context context = getAppContext();
  520. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  521. if (!preferences.isAutoUploadSplitEntriesEnabled()) {
  522. // magic to split out existing synced folders in two when needed
  523. // otherwise, we migrate them to their proper type (image or video)
  524. Log_OC.i(TAG, "Migrate synced_folders records for image/video split");
  525. ContentResolver contentResolver = context.getContentResolver();
  526. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver, preferences);
  527. final List<MediaFolder> imageMediaFolders = MediaProvider.getImageFolders(contentResolver, 1, null, true);
  528. final List<MediaFolder> videoMediaFolders = MediaProvider.getVideoFolders(contentResolver, 1, null, true);
  529. ArrayList<Long> idsToDelete = new ArrayList<>();
  530. List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
  531. long primaryKey;
  532. SyncedFolder newSyncedFolder;
  533. for (SyncedFolder syncedFolder : syncedFolders) {
  534. idsToDelete.add(syncedFolder.getId());
  535. Log_OC.i(TAG, "Migration check for synced_folders record: "
  536. + syncedFolder.getId() + " - " + syncedFolder.getLocalPath());
  537. for (MediaFolder imageMediaFolder : imageMediaFolders) {
  538. if (imageMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  539. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  540. newSyncedFolder.setType(MediaFolderType.IMAGE);
  541. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  542. Log_OC.i(TAG, "Migrated image synced_folders record: "
  543. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  544. break;
  545. }
  546. }
  547. for (MediaFolder videoMediaFolder : videoMediaFolders) {
  548. if (videoMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  549. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  550. newSyncedFolder.setType(MediaFolderType.VIDEO);
  551. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  552. Log_OC.i(TAG, "Migrated video synced_folders record: "
  553. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  554. break;
  555. }
  556. }
  557. }
  558. for (long id : idsToDelete) {
  559. Log_OC.i(TAG, "Removing legacy synced_folders record: " + id);
  560. syncedFolderProvider.deleteSyncedFolder(id);
  561. }
  562. preferences.setAutoUploadSplitEntriesEnabled(true);
  563. }
  564. }
  565. private static void initiateExistingAutoUploadEntries() {
  566. new Thread(() -> {
  567. AppPreferences preferences = AppPreferencesImpl.fromContext(getAppContext());
  568. if (!preferences.isAutoUploadInitialized()) {
  569. SyncedFolderProvider syncedFolderProvider =
  570. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver(), preferences);
  571. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  572. if (syncedFolder.isEnabled()) {
  573. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder);
  574. }
  575. }
  576. preferences.setAutoUploadInit(true);
  577. }
  578. }).start();
  579. }
  580. private static void cleanOldEntries() {
  581. // previous versions of application created broken entries in the SyncedFolderProvider
  582. // database, and this cleans all that and leaves 1 (newest) entry per synced folder
  583. Context context = getAppContext();
  584. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  585. if (!preferences.isLegacyClean()) {
  586. SyncedFolderProvider syncedFolderProvider =
  587. new SyncedFolderProvider(context.getContentResolver(), preferences);
  588. List<SyncedFolder> syncedFolderList = syncedFolderProvider.getSyncedFolders();
  589. Map<Pair<String, String>, Long> syncedFolders = new HashMap<>();
  590. ArrayList<Long> ids = new ArrayList<>();
  591. for (SyncedFolder syncedFolder : syncedFolderList) {
  592. Pair<String, String> checkPair = new Pair<>(syncedFolder.getAccount(), syncedFolder.getLocalPath());
  593. if (syncedFolders.containsKey(checkPair)) {
  594. if (syncedFolder.getId() > syncedFolders.get(checkPair)) {
  595. syncedFolders.put(checkPair, syncedFolder.getId());
  596. }
  597. } else {
  598. syncedFolders.put(checkPair, syncedFolder.getId());
  599. }
  600. }
  601. ids.addAll(syncedFolders.values());
  602. if (ids.size() > 0) {
  603. int deletedCount = syncedFolderProvider.deleteSyncedFoldersNotInList(ids);
  604. if (deletedCount > 0) {
  605. preferences.setLegacyClean(true);
  606. }
  607. } else {
  608. preferences.setLegacyClean(true);
  609. }
  610. }
  611. }
  612. @Override
  613. public AndroidInjector<Activity> activityInjector() {
  614. return dispatchingActivityInjector;
  615. }
  616. @Override
  617. public AndroidInjector<Fragment> supportFragmentInjector() {
  618. return dispatchingFragmentInjector;
  619. }
  620. @Override
  621. public AndroidInjector<Service> serviceInjector() {
  622. return dispatchingServiceInjector;
  623. }
  624. @Override
  625. public AndroidInjector<ContentProvider> contentProviderInjector() {
  626. return dispatchingContentProviderInjector;
  627. }
  628. @Override
  629. public AndroidInjector<BroadcastReceiver> broadcastReceiverInjector() {
  630. return dispatchingBroadcastReceiverInjector;
  631. }
  632. }