MainApp.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author masensio
  5. * @author David A. Velasco
  6. * Copyright (C) 2015 ownCloud Inc.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License version 2,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.owncloud.android;
  21. import android.Manifest;
  22. import android.accounts.Account;
  23. import android.annotation.SuppressLint;
  24. import android.app.Activity;
  25. import android.app.NotificationChannel;
  26. import android.app.NotificationManager;
  27. import android.content.ContentResolver;
  28. import android.content.Context;
  29. import android.content.Intent;
  30. import android.content.SharedPreferences;
  31. import android.content.pm.PackageInfo;
  32. import android.content.pm.PackageManager;
  33. import android.os.Build;
  34. import android.os.Bundle;
  35. import android.os.Environment;
  36. import android.os.StrictMode;
  37. import android.text.TextUtils;
  38. import android.view.WindowManager;
  39. import com.evernote.android.job.JobManager;
  40. import com.evernote.android.job.JobRequest;
  41. import com.nextcloud.client.preferences.AppPreferences;
  42. import com.nextcloud.client.preferences.PreferenceManager;
  43. import com.owncloud.android.authentication.AccountUtils;
  44. import com.owncloud.android.authentication.PassCodeManager;
  45. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  46. import com.owncloud.android.datamodel.MediaFolder;
  47. import com.owncloud.android.datamodel.MediaFolderType;
  48. import com.owncloud.android.datamodel.MediaProvider;
  49. import com.owncloud.android.datamodel.SyncedFolder;
  50. import com.owncloud.android.datamodel.SyncedFolderProvider;
  51. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  52. import com.owncloud.android.datastorage.DataStorageProvider;
  53. import com.owncloud.android.datastorage.StoragePoint;
  54. import com.owncloud.android.jobs.MediaFoldersDetectionJob;
  55. import com.owncloud.android.jobs.NCJobCreator;
  56. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  57. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory.Policy;
  58. import com.owncloud.android.lib.common.utils.Log_OC;
  59. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  60. import com.owncloud.android.ui.activity.ContactsPreferenceActivity;
  61. import com.owncloud.android.ui.activity.SettingsActivity;
  62. import com.owncloud.android.ui.activity.SyncedFoldersActivity;
  63. import com.owncloud.android.ui.activity.WhatsNewActivity;
  64. import com.owncloud.android.ui.notifications.NotificationUtils;
  65. import com.owncloud.android.utils.DisplayUtils;
  66. import com.owncloud.android.utils.FilesSyncHelper;
  67. import com.owncloud.android.utils.PermissionUtil;
  68. import com.owncloud.android.utils.ReceiversHelper;
  69. import com.owncloud.android.utils.SecurityUtils;
  70. import java.lang.reflect.Method;
  71. import java.util.ArrayList;
  72. import java.util.HashMap;
  73. import java.util.List;
  74. import java.util.Map;
  75. import java.util.concurrent.TimeUnit;
  76. import androidx.annotation.RequiresApi;
  77. import androidx.annotation.StringRes;
  78. import androidx.appcompat.app.AlertDialog;
  79. import androidx.core.util.Pair;
  80. import androidx.multidex.MultiDexApplication;
  81. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  82. import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP;
  83. /**
  84. * Main Application of the project
  85. *
  86. * Contains methods to build the "static" strings. These strings were before constants in different
  87. * classes
  88. */
  89. public class MainApp extends MultiDexApplication {
  90. public static final OwnCloudVersion OUTDATED_SERVER_VERSION = OwnCloudVersion.nextcloud_12;
  91. public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_10;
  92. private static final String TAG = MainApp.class.getSimpleName();
  93. private static final String AUTH_ON = "on";
  94. @SuppressWarnings("unused")
  95. private static final String POLICY_SINGLE_SESSION_PER_ACCOUNT = "single session per account";
  96. @SuppressWarnings("unused")
  97. private static final String POLICY_ALWAYS_NEW_CLIENT = "always new client";
  98. private static Context mContext;
  99. private static String storagePath;
  100. private static boolean mOnlyOnDevice;
  101. private SharedPreferences appPrefs;
  102. @SuppressWarnings("unused")
  103. private boolean mBound;
  104. @SuppressFBWarnings("ST")
  105. @Override
  106. public void onCreate() {
  107. super.onCreate();
  108. JobManager.create(this).addJobCreator(new NCJobCreator());
  109. MainApp.mContext = getApplicationContext();
  110. new SecurityUtils();
  111. DisplayUtils.useCompatVectorIfNeeded();
  112. appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  113. fixStoragePath();
  114. MainApp.storagePath = appPrefs.getString(SettingsActivity.PreferenceKeys.STORAGE_PATH,
  115. getApplicationContext().getFilesDir().getAbsolutePath());
  116. boolean isSamlAuth = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
  117. OwnCloudClientManagerFactory.setUserAgent(getUserAgent());
  118. OwnCloudClientManagerFactory.setNextcloudUserAgent(getNextcloudUserAgent());
  119. if (isSamlAuth) {
  120. OwnCloudClientManagerFactory.setDefaultPolicy(Policy.SINGLE_SESSION_PER_ACCOUNT);
  121. } else {
  122. OwnCloudClientManagerFactory
  123. .setDefaultPolicy(Policy.SINGLE_SESSION_PER_ACCOUNT_IF_SERVER_SUPPORTS_SERVER_MONITORING);
  124. }
  125. // initialise thumbnails cache on background thread
  126. new ThumbnailsCacheManager.InitDiskCacheTask().execute();
  127. if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
  128. // use app writable dir, no permissions needed
  129. Log_OC.startLogging(getAppContext());
  130. Log_OC.d("Debug", "start logging");
  131. }
  132. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  133. try {
  134. Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
  135. m.invoke(null);
  136. } catch (Exception e) {
  137. Log_OC.d("Debug", "Failed to disable uri exposure");
  138. }
  139. }
  140. initSyncOperations();
  141. initContactsBackup();
  142. notificationChannels();
  143. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  144. .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
  145. .setUpdateCurrent(true)
  146. .build()
  147. .schedule();
  148. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  149. .startNow()
  150. .setUpdateCurrent(false)
  151. .build()
  152. .schedule();
  153. // register global protection with pass code
  154. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
  155. @Override
  156. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  157. Log_OC.d(activity.getClass().getSimpleName(), "onCreate(Bundle) starting");
  158. WhatsNewActivity.runIfNeeded(activity);
  159. PassCodeManager.getPassCodeManager().onActivityCreated(activity);
  160. }
  161. @Override
  162. public void onActivityStarted(Activity activity) {
  163. Log_OC.d(activity.getClass().getSimpleName(), "onStart() starting");
  164. PassCodeManager.getPassCodeManager().onActivityStarted(activity);
  165. }
  166. @Override
  167. public void onActivityResumed(Activity activity) {
  168. Log_OC.d(activity.getClass().getSimpleName(), "onResume() starting");
  169. }
  170. @Override
  171. public void onActivityPaused(Activity activity) {
  172. Log_OC.d(activity.getClass().getSimpleName(), "onPause() ending");
  173. }
  174. @Override
  175. public void onActivityStopped(Activity activity) {
  176. Log_OC.d(activity.getClass().getSimpleName(), "onStop() ending");
  177. PassCodeManager.getPassCodeManager().onActivityStopped(activity);
  178. }
  179. @Override
  180. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  181. Log_OC.d(activity.getClass().getSimpleName(), "onSaveInstanceState(Bundle) starting");
  182. }
  183. @Override
  184. public void onActivityDestroyed(Activity activity) {
  185. Log_OC.d(activity.getClass().getSimpleName(), "onDestroy() ending");
  186. }
  187. });
  188. }
  189. public static void initContactsBackup() {
  190. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
  191. Account[] accounts = AccountUtils.getAccounts(mContext);
  192. for (Account account : accounts) {
  193. if (arbitraryDataProvider.getBooleanValue(account, PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
  194. ContactsPreferenceActivity.startContactBackupJob(account);
  195. }
  196. }
  197. }
  198. @SuppressLint("ApplySharedPref") // commit is done on purpose to write immediately
  199. private void fixStoragePath() {
  200. if (!PreferenceManager.getStoragePathFix(this)) {
  201. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  202. StoragePoint[] storagePoints = DataStorageProvider.getInstance().getAvailableStoragePoints();
  203. String storagePath = appPrefs.getString(SettingsActivity.PreferenceKeys.STORAGE_PATH, "");
  204. if (TextUtils.isEmpty(storagePath)) {
  205. if (PreferenceManager.getLastSeenVersionCode(this) != 0) {
  206. // We already used the app, but no storage is set - fix that!
  207. appPrefs.edit().putString(SettingsActivity.PreferenceKeys.STORAGE_PATH,
  208. Environment.getExternalStorageDirectory().getAbsolutePath()).commit();
  209. appPrefs.edit().remove(PreferenceManager.PREF__KEYS_MIGRATION).commit();
  210. } else {
  211. // find internal storage path that's indexable
  212. boolean set = false;
  213. for (StoragePoint storagePoint : storagePoints) {
  214. if (storagePoint.getStorageType().equals(StoragePoint.StorageType.INTERNAL) &&
  215. storagePoint.getPrivacyType().equals(StoragePoint.PrivacyType.PUBLIC)) {
  216. appPrefs.edit().putString(SettingsActivity.PreferenceKeys.STORAGE_PATH,
  217. storagePoint.getPath()).commit();
  218. appPrefs.edit().remove(PreferenceManager.PREF__KEYS_MIGRATION).commit();
  219. set = true;
  220. break;
  221. }
  222. }
  223. if (!set) {
  224. for (StoragePoint storagePoint : storagePoints) {
  225. if (storagePoint.getPrivacyType().equals(StoragePoint.PrivacyType.PUBLIC)) {
  226. appPrefs.edit().putString(SettingsActivity.PreferenceKeys.STORAGE_PATH,
  227. storagePoint.getPath()).commit();
  228. appPrefs.edit().remove(PreferenceManager.PREF__KEYS_MIGRATION).commit();
  229. set = true;
  230. break;
  231. }
  232. }
  233. }
  234. }
  235. PreferenceManager.setStoragePathFix(this, true);
  236. } else {
  237. appPrefs.edit().remove(PreferenceManager.PREF__KEYS_MIGRATION).commit();
  238. PreferenceManager.setStoragePathFix(this, true);
  239. }
  240. } else {
  241. if (TextUtils.isEmpty(storagePath)) {
  242. appPrefs.edit().putString(SettingsActivity.PreferenceKeys.STORAGE_PATH,
  243. Environment.getExternalStorageDirectory().getAbsolutePath()).commit();
  244. }
  245. appPrefs.edit().remove(PreferenceManager.PREF__KEYS_MIGRATION).commit();
  246. PreferenceManager.setStoragePathFix(this, true);
  247. }
  248. }
  249. }
  250. public static void initSyncOperations() {
  251. updateToAutoUpload();
  252. cleanOldEntries();
  253. updateAutoUploadEntries();
  254. if (getAppContext() != null) {
  255. if (PermissionUtil.checkSelfPermission(getAppContext(),
  256. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  257. splitOutAutoUploadEntries();
  258. } else {
  259. AppPreferences preferences = PreferenceManager.fromContext(getAppContext());
  260. preferences.setAutoUploadSplitEntriesEnabled(true);
  261. }
  262. }
  263. initiateExistingAutoUploadEntries();
  264. FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
  265. FilesSyncHelper.restartJobsIfNeeded();
  266. FilesSyncHelper.scheduleOfflineSyncIfNeeded();
  267. ReceiversHelper.registerNetworkChangeReceiver();
  268. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  269. ReceiversHelper.registerPowerChangeReceiver();
  270. }
  271. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  272. ReceiversHelper.registerPowerSaveReceiver();
  273. }
  274. }
  275. public static void notificationChannels() {
  276. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && getAppContext() != null) {
  277. Context context = getAppContext();
  278. NotificationManager notificationManager = (NotificationManager)
  279. context.getSystemService(Context.NOTIFICATION_SERVICE);
  280. if (notificationManager != null) {
  281. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD,
  282. R.string.notification_channel_download_name,
  283. R.string.notification_channel_download_description, context);
  284. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD,
  285. R.string.notification_channel_upload_name,
  286. R.string.notification_channel_upload_description, context);
  287. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA,
  288. R.string.notification_channel_media_name,
  289. R.string.notification_channel_media_description, context);
  290. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC,
  291. R.string.notification_channel_file_sync_name,
  292. R.string.notification_channel_file_sync_description, context);
  293. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER,
  294. R.string.notification_channel_file_observer_name, R.string
  295. .notification_channel_file_observer_description, context);
  296. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_PUSH,
  297. R.string.notification_channel_push_name, R.string
  298. .notification_channel_push_description, context, NotificationManager.IMPORTANCE_DEFAULT);
  299. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL, R.string
  300. .notification_channel_general_name, R.string.notification_channel_general_description,
  301. context, NotificationManager.IMPORTANCE_DEFAULT);
  302. } else {
  303. Log_OC.e(TAG, "Notification manager is null");
  304. }
  305. }
  306. }
  307. @RequiresApi(api = Build.VERSION_CODES.N)
  308. private static void createChannel(NotificationManager notificationManager,
  309. String channelId, int channelName,
  310. int channelDescription, Context context) {
  311. createChannel(notificationManager, channelId, channelName, channelDescription, context,
  312. NotificationManager.IMPORTANCE_LOW);
  313. }
  314. private static void createChannel(NotificationManager notificationManager,
  315. String channelId, int channelName,
  316. int channelDescription, Context context, int importance) {
  317. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
  318. && getAppContext() != null
  319. && notificationManager.getNotificationChannel(channelId) == null) {
  320. CharSequence name = context.getString(channelName);
  321. String description = context.getString(channelDescription);
  322. NotificationChannel channel = new NotificationChannel(channelId, name, importance);
  323. channel.setDescription(description);
  324. channel.enableLights(false);
  325. channel.enableVibration(false);
  326. notificationManager.createNotificationChannel(channel);
  327. }
  328. }
  329. public static Context getAppContext() {
  330. return MainApp.mContext;
  331. }
  332. public static void setAppContext(Context context) {
  333. MainApp.mContext = context;
  334. }
  335. public static String getStoragePath() {
  336. return MainApp.storagePath;
  337. }
  338. public static void setStoragePath(String path) {
  339. MainApp.storagePath = path;
  340. }
  341. // Methods to obtain Strings referring app_name
  342. // From AccountAuthenticator
  343. // public static final String ACCOUNT_TYPE = "owncloud";
  344. public static String getAccountType(Context context) {
  345. return context.getResources().getString(R.string.account_type);
  346. }
  347. // Non gradle build systems do not provide BuildConfig.VERSION_CODE
  348. // so we must fallback to this method :(
  349. public static int getVersionCode() {
  350. try {
  351. String thisPackageName = getAppContext().getPackageName();
  352. return getAppContext().getPackageManager().getPackageInfo(thisPackageName, 0).versionCode;
  353. } catch (PackageManager.NameNotFoundException e) {
  354. return 0;
  355. }
  356. }
  357. // Non gradle build systems do not provide BuildConfig.VERSION_CODE
  358. // so we must fallback to this method :(
  359. public static String getVersionName() {
  360. try {
  361. String thisPackageName = getAppContext().getPackageName();
  362. return getAppContext().getPackageManager().getPackageInfo(thisPackageName, 0).versionName;
  363. } catch (PackageManager.NameNotFoundException e) {
  364. return "";
  365. }
  366. }
  367. // From AccountAuthenticator
  368. // public static final String AUTHORITY = "org.owncloud";
  369. public static String getAuthority() {
  370. return getAppContext().getResources().getString(R.string.authority);
  371. }
  372. // From AccountAuthenticator
  373. // public static final String AUTH_TOKEN_TYPE = "org.owncloud";
  374. public static String getAuthTokenType() {
  375. return getAppContext().getResources().getString(R.string.authority);
  376. }
  377. // From ProviderMeta
  378. // public static final String DB_FILE = "owncloud.db";
  379. public static String getDBFile() {
  380. return getAppContext().getResources().getString(R.string.db_file);
  381. }
  382. // From ProviderMeta
  383. // private final String mDatabaseName = "ownCloud";
  384. public static String getDBName() {
  385. return getAppContext().getResources().getString(R.string.db_name);
  386. }
  387. /**
  388. * name of data_folder, e.g., "owncloud"
  389. */
  390. public static String getDataFolder() {
  391. return getAppContext().getResources().getString(R.string.data_folder);
  392. }
  393. // log_name
  394. public static String getLogName() {
  395. return getAppContext().getResources().getString(R.string.log_name);
  396. }
  397. public static void showOnlyFilesOnDevice(boolean state) {
  398. mOnlyOnDevice = state;
  399. }
  400. public static boolean isOnlyOnDevice() {
  401. return mOnlyOnDevice;
  402. }
  403. public static String getUserAgent() {
  404. // Mozilla/5.0 (Android) ownCloud-android/1.7.0
  405. return getUserAgent(R.string.user_agent);
  406. }
  407. public static String getNextcloudUserAgent() {
  408. // Mozilla/5.0 (Android) Nextcloud-android/2.1.0
  409. return getUserAgent(R.string.nextcloud_user_agent);
  410. }
  411. // user agent
  412. private static String getUserAgent(@StringRes int agent) {
  413. String appString = getAppContext().getResources().getString(agent);
  414. String packageName = getAppContext().getPackageName();
  415. String version = "";
  416. try {
  417. PackageInfo pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0);
  418. if (pInfo != null) {
  419. version = pInfo.versionName;
  420. }
  421. } catch (PackageManager.NameNotFoundException e) {
  422. Log_OC.e(TAG, "Trying to get packageName", e.getCause());
  423. }
  424. return String.format(appString, version);
  425. }
  426. private static void updateToAutoUpload() {
  427. Context context = getAppContext();
  428. AppPreferences preferences = PreferenceManager.fromContext(context);
  429. if (preferences.instantPictureUploadEnabled() || preferences.instantVideoUploadEnabled()){
  430. preferences.removeLegacyPreferences();
  431. // show info pop-up
  432. try {
  433. new AlertDialog.Builder(context, R.style.Theme_ownCloud_Dialog)
  434. .setTitle(R.string.drawer_synced_folders)
  435. .setMessage(R.string.synced_folders_new_info)
  436. .setPositiveButton(R.string.drawer_open, (dialog, which) -> {
  437. // show Auto Upload
  438. Intent folderSyncIntent = new Intent(context, SyncedFoldersActivity.class);
  439. dialog.dismiss();
  440. context.startActivity(folderSyncIntent);
  441. })
  442. .setNegativeButton(R.string.drawer_close, (dialog, which) -> dialog.dismiss())
  443. .setIcon(R.drawable.nav_synced_folders)
  444. .show();
  445. } catch (WindowManager.BadTokenException e) {
  446. Log_OC.i(TAG, "Error showing Auto Upload Update dialog, so skipping it: " + e.getMessage());
  447. }
  448. }
  449. }
  450. private static void updateAutoUploadEntries() {
  451. // updates entries to reflect their true paths
  452. Context context = getAppContext();
  453. AppPreferences preferences = PreferenceManager.fromContext(context);
  454. if (!preferences.isAutoUploadPathsUpdateEnabled()) {
  455. SyncedFolderProvider syncedFolderProvider =
  456. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver());
  457. syncedFolderProvider.updateAutoUploadPaths(mContext);
  458. }
  459. }
  460. private static void splitOutAutoUploadEntries() {
  461. Context context = getAppContext();
  462. AppPreferences preferences = PreferenceManager.fromContext(context);
  463. if (!preferences.isAutoUploadSplitEntriesEnabled()) {
  464. // magic to split out existing synced folders in two when needed
  465. // otherwise, we migrate them to their proper type (image or video)
  466. Log_OC.i(TAG, "Migrate synced_folders records for image/video split");
  467. ContentResolver contentResolver = context.getContentResolver();
  468. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
  469. final List<MediaFolder> imageMediaFolders = MediaProvider.getImageFolders(contentResolver, 1, null, true);
  470. final List<MediaFolder> videoMediaFolders = MediaProvider.getVideoFolders(contentResolver, 1, null, true);
  471. ArrayList<Long> idsToDelete = new ArrayList<>();
  472. List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
  473. long primaryKey;
  474. SyncedFolder newSyncedFolder;
  475. for (SyncedFolder syncedFolder : syncedFolders) {
  476. idsToDelete.add(syncedFolder.getId());
  477. Log_OC.i(TAG, "Migration check for synced_folders record: "
  478. + syncedFolder.getId() + " - " + syncedFolder.getLocalPath());
  479. for (MediaFolder imageMediaFolder : imageMediaFolders) {
  480. if (imageMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  481. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  482. newSyncedFolder.setType(MediaFolderType.IMAGE);
  483. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  484. Log_OC.i(TAG, "Migrated image synced_folders record: "
  485. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  486. break;
  487. }
  488. }
  489. for (MediaFolder videoMediaFolder : videoMediaFolders) {
  490. if (videoMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  491. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  492. newSyncedFolder.setType(MediaFolderType.VIDEO);
  493. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  494. Log_OC.i(TAG, "Migrated video synced_folders record: "
  495. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  496. break;
  497. }
  498. }
  499. }
  500. for (long id : idsToDelete) {
  501. Log_OC.i(TAG, "Removing legacy synced_folders record: " + id);
  502. syncedFolderProvider.deleteSyncedFolder(id);
  503. }
  504. preferences.setAutoUploadSplitEntriesEnabled(true);
  505. }
  506. }
  507. private static void initiateExistingAutoUploadEntries() {
  508. new Thread(() -> {
  509. AppPreferences preferences = PreferenceManager.fromContext(getAppContext());
  510. if (!preferences.isAutoUploadInitialized()) {
  511. SyncedFolderProvider syncedFolderProvider =
  512. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver());
  513. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  514. if (syncedFolder.isEnabled()) {
  515. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder);
  516. }
  517. }
  518. preferences.setAutoUploadInit(true);
  519. }
  520. }).start();
  521. }
  522. private static void cleanOldEntries() {
  523. // previous versions of application created broken entries in the SyncedFolderProvider
  524. // database, and this cleans all that and leaves 1 (newest) entry per synced folder
  525. Context context = getAppContext();
  526. if (!PreferenceManager.getLegacyClean(context)) {
  527. SyncedFolderProvider syncedFolderProvider =
  528. new SyncedFolderProvider(context.getContentResolver());
  529. List<SyncedFolder> syncedFolderList = syncedFolderProvider.getSyncedFolders();
  530. Map<Pair<String, String>, Long> syncedFolders = new HashMap<>();
  531. ArrayList<Long> ids = new ArrayList<>();
  532. for (SyncedFolder syncedFolder : syncedFolderList) {
  533. Pair<String, String> checkPair = new Pair<>(syncedFolder.getAccount(), syncedFolder.getLocalPath());
  534. if (syncedFolders.containsKey(checkPair)) {
  535. if (syncedFolder.getId() > syncedFolders.get(checkPair)) {
  536. syncedFolders.put(checkPair, syncedFolder.getId());
  537. }
  538. } else {
  539. syncedFolders.put(checkPair, syncedFolder.getId());
  540. }
  541. }
  542. ids.addAll(syncedFolders.values());
  543. if (ids.size() > 0) {
  544. syncedFolderProvider.deleteSyncedFoldersNotInList(mContext, ids);
  545. } else {
  546. PreferenceManager.setLegacyClean(context, true);
  547. }
  548. }
  549. }
  550. }