MainApp.java 29 KB

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