MainApp.java 28 KB

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