MainApp.java 30 KB

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