MainApp.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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.owncloud.android.authentication.AccountUtils;
  42. import com.owncloud.android.authentication.PassCodeManager;
  43. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  44. import com.owncloud.android.datamodel.MediaFolder;
  45. import com.owncloud.android.datamodel.MediaFolderType;
  46. import com.owncloud.android.datamodel.MediaProvider;
  47. import com.owncloud.android.datamodel.SyncedFolder;
  48. import com.owncloud.android.datamodel.SyncedFolderProvider;
  49. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  50. import com.owncloud.android.datastorage.DataStorageProvider;
  51. import com.owncloud.android.datastorage.StoragePoint;
  52. import com.owncloud.android.db.PreferenceManager;
  53. import com.owncloud.android.jobs.MediaFoldersDetectionJob;
  54. import com.owncloud.android.jobs.NCJobCreator;
  55. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  56. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory.Policy;
  57. import com.owncloud.android.lib.common.utils.Log_OC;
  58. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  59. import com.owncloud.android.ui.activity.ContactsPreferenceActivity;
  60. import com.owncloud.android.ui.activity.Preferences;
  61. import com.owncloud.android.ui.activity.SyncedFoldersActivity;
  62. import com.owncloud.android.ui.activity.WhatsNewActivity;
  63. import com.owncloud.android.ui.notifications.NotificationUtils;
  64. import com.owncloud.android.utils.DisplayUtils;
  65. import com.owncloud.android.utils.FilesSyncHelper;
  66. import com.owncloud.android.utils.PermissionUtil;
  67. import com.owncloud.android.utils.ReceiversHelper;
  68. import com.owncloud.android.utils.SecurityUtils;
  69. import java.lang.reflect.Method;
  70. import java.util.ArrayList;
  71. import java.util.HashMap;
  72. import java.util.List;
  73. import java.util.Map;
  74. import java.util.concurrent.TimeUnit;
  75. import androidx.annotation.RequiresApi;
  76. import androidx.annotation.StringRes;
  77. import androidx.appcompat.app.AlertDialog;
  78. import androidx.core.util.Pair;
  79. import androidx.multidex.MultiDexApplication;
  80. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  81. import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP;
  82. /**
  83. * Main Application of the project
  84. *
  85. * Contains methods to build the "static" strings. These strings were before constants in different
  86. * classes
  87. */
  88. public class MainApp extends MultiDexApplication {
  89. public static final OwnCloudVersion OUTDATED_SERVER_VERSION = OwnCloudVersion.nextcloud_12;
  90. public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_10;
  91. private static final String TAG = MainApp.class.getSimpleName();
  92. private static final String AUTH_ON = "on";
  93. @SuppressWarnings("unused")
  94. private static final String POLICY_SINGLE_SESSION_PER_ACCOUNT = "single session per account";
  95. @SuppressWarnings("unused")
  96. private static final String POLICY_ALWAYS_NEW_CLIENT = "always new client";
  97. private static Context mContext;
  98. private static String storagePath;
  99. private static boolean mOnlyOnDevice;
  100. private SharedPreferences appPrefs;
  101. @SuppressWarnings("unused")
  102. private boolean mBound;
  103. @SuppressFBWarnings("ST")
  104. @Override
  105. public void onCreate() {
  106. super.onCreate();
  107. JobManager.create(this).addJobCreator(new NCJobCreator());
  108. MainApp.mContext = getApplicationContext();
  109. new SecurityUtils();
  110. DisplayUtils.useCompatVectorIfNeeded();
  111. appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  112. fixStoragePath();
  113. MainApp.storagePath = appPrefs.getString(Preferences.PreferenceKeys.STORAGE_PATH,
  114. getApplicationContext().getFilesDir().getAbsolutePath());
  115. boolean isSamlAuth = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
  116. OwnCloudClientManagerFactory.setUserAgent(getUserAgent());
  117. OwnCloudClientManagerFactory.setNextcloudUserAgent(getNextcloudUserAgent());
  118. if (isSamlAuth) {
  119. OwnCloudClientManagerFactory.setDefaultPolicy(Policy.SINGLE_SESSION_PER_ACCOUNT);
  120. } else {
  121. OwnCloudClientManagerFactory
  122. .setDefaultPolicy(Policy.SINGLE_SESSION_PER_ACCOUNT_IF_SERVER_SUPPORTS_SERVER_MONITORING);
  123. }
  124. // initialise thumbnails cache on background thread
  125. new ThumbnailsCacheManager.InitDiskCacheTask().execute();
  126. if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled) ||
  127. appPrefs.getBoolean(Preferences.PREFERENCE_EXPERT_MODE, false)) {
  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(Preferences.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(Preferences.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(Preferences.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(Preferences.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(Preferences.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. PreferenceManager.setAutoUploadSplitEntries(getAppContext(), true);
  260. }
  261. }
  262. initiateExistingAutoUploadEntries();
  263. FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
  264. FilesSyncHelper.restartJobsIfNeeded();
  265. FilesSyncHelper.scheduleOfflineSyncIfNeeded();
  266. ReceiversHelper.registerNetworkChangeReceiver();
  267. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  268. ReceiversHelper.registerPowerChangeReceiver();
  269. }
  270. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  271. ReceiversHelper.registerPowerSaveReceiver();
  272. }
  273. }
  274. public static void notificationChannels() {
  275. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && getAppContext() != null) {
  276. Context context = getAppContext();
  277. NotificationManager notificationManager = (NotificationManager)
  278. context.getSystemService(Context.NOTIFICATION_SERVICE);
  279. if (notificationManager != null) {
  280. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD,
  281. R.string.notification_channel_download_name,
  282. R.string.notification_channel_download_description, context);
  283. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD,
  284. R.string.notification_channel_upload_name,
  285. R.string.notification_channel_upload_description, context);
  286. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA,
  287. R.string.notification_channel_media_name,
  288. R.string.notification_channel_media_description, context);
  289. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC,
  290. R.string.notification_channel_file_sync_name,
  291. R.string.notification_channel_file_sync_description, context);
  292. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER,
  293. R.string.notification_channel_file_observer_name, R.string
  294. .notification_channel_file_observer_description, context);
  295. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_PUSH,
  296. R.string.notification_channel_push_name, R.string
  297. .notification_channel_push_description, context, NotificationManager.IMPORTANCE_DEFAULT);
  298. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL, R.string
  299. .notification_channel_general_name, R.string.notification_channel_general_description,
  300. context, NotificationManager.IMPORTANCE_DEFAULT);
  301. } else {
  302. Log_OC.e(TAG, "Notification manager is null");
  303. }
  304. }
  305. }
  306. @RequiresApi(api = Build.VERSION_CODES.N)
  307. private static void createChannel(NotificationManager notificationManager,
  308. String channelId, int channelName,
  309. int channelDescription, Context context) {
  310. createChannel(notificationManager, channelId, channelName, channelDescription, context,
  311. NotificationManager.IMPORTANCE_LOW);
  312. }
  313. private static void createChannel(NotificationManager notificationManager,
  314. String channelId, int channelName,
  315. int channelDescription, Context context, int importance) {
  316. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
  317. && getAppContext() != null
  318. && notificationManager.getNotificationChannel(channelId) == null) {
  319. CharSequence name = context.getString(channelName);
  320. String description = context.getString(channelDescription);
  321. NotificationChannel channel = new NotificationChannel(channelId, name, importance);
  322. channel.setDescription(description);
  323. channel.enableLights(false);
  324. channel.enableVibration(false);
  325. notificationManager.createNotificationChannel(channel);
  326. }
  327. }
  328. public static Context getAppContext() {
  329. return MainApp.mContext;
  330. }
  331. public static void setAppContext(Context context) {
  332. MainApp.mContext = context;
  333. }
  334. public static String getStoragePath() {
  335. return MainApp.storagePath;
  336. }
  337. public static void setStoragePath(String path) {
  338. MainApp.storagePath = path;
  339. }
  340. // Methods to obtain Strings referring app_name
  341. // From AccountAuthenticator
  342. // public static final String ACCOUNT_TYPE = "owncloud";
  343. public static String getAccountType(Context context) {
  344. return context.getResources().getString(R.string.account_type);
  345. }
  346. // Non gradle build systems do not provide BuildConfig.VERSION_CODE
  347. // so we must fallback to this method :(
  348. public static int getVersionCode() {
  349. try {
  350. String thisPackageName = getAppContext().getPackageName();
  351. return getAppContext().getPackageManager().getPackageInfo(thisPackageName, 0).versionCode;
  352. } catch (PackageManager.NameNotFoundException e) {
  353. return 0;
  354. }
  355. }
  356. // Non gradle build systems do not provide BuildConfig.VERSION_CODE
  357. // so we must fallback to this method :(
  358. public static String getVersionName() {
  359. try {
  360. String thisPackageName = getAppContext().getPackageName();
  361. return getAppContext().getPackageManager().getPackageInfo(thisPackageName, 0).versionName;
  362. } catch (PackageManager.NameNotFoundException e) {
  363. return "";
  364. }
  365. }
  366. // From AccountAuthenticator
  367. // public static final String AUTHORITY = "org.owncloud";
  368. public static String getAuthority() {
  369. return getAppContext().getResources().getString(R.string.authority);
  370. }
  371. // From AccountAuthenticator
  372. // public static final String AUTH_TOKEN_TYPE = "org.owncloud";
  373. public static String getAuthTokenType() {
  374. return getAppContext().getResources().getString(R.string.authority);
  375. }
  376. // From ProviderMeta
  377. // public static final String DB_FILE = "owncloud.db";
  378. public static String getDBFile() {
  379. return getAppContext().getResources().getString(R.string.db_file);
  380. }
  381. // From ProviderMeta
  382. // private final String mDatabaseName = "ownCloud";
  383. public static String getDBName() {
  384. return getAppContext().getResources().getString(R.string.db_name);
  385. }
  386. /**
  387. * name of data_folder, e.g., "owncloud"
  388. */
  389. public static String getDataFolder() {
  390. return getAppContext().getResources().getString(R.string.data_folder);
  391. }
  392. // log_name
  393. public static String getLogName() {
  394. return getAppContext().getResources().getString(R.string.log_name);
  395. }
  396. public static void showOnlyFilesOnDevice(boolean state) {
  397. mOnlyOnDevice = state;
  398. }
  399. public static boolean isOnlyOnDevice() {
  400. return mOnlyOnDevice;
  401. }
  402. public static String getUserAgent() {
  403. // Mozilla/5.0 (Android) ownCloud-android/1.7.0
  404. return getUserAgent(R.string.user_agent);
  405. }
  406. public static String getNextcloudUserAgent() {
  407. // Mozilla/5.0 (Android) Nextcloud-android/2.1.0
  408. return getUserAgent(R.string.nextcloud_user_agent);
  409. }
  410. // user agent
  411. private static String getUserAgent(@StringRes int agent) {
  412. String appString = getAppContext().getResources().getString(agent);
  413. String packageName = getAppContext().getPackageName();
  414. String version = "";
  415. try {
  416. PackageInfo pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0);
  417. if (pInfo != null) {
  418. version = pInfo.versionName;
  419. }
  420. } catch (PackageManager.NameNotFoundException e) {
  421. Log_OC.e(TAG, "Trying to get packageName", e.getCause());
  422. }
  423. return String.format(appString, version);
  424. }
  425. private static void updateToAutoUpload() {
  426. Context context = getAppContext();
  427. if (PreferenceManager.instantPictureUploadEnabled(context) ||
  428. PreferenceManager.instantVideoUploadEnabled(context)){
  429. // remove legacy shared preferences
  430. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
  431. editor.remove("instant_uploading")
  432. .remove("instant_video_uploading")
  433. .remove("instant_upload_path")
  434. .remove("instant_upload_path_use_subfolders")
  435. .remove("instant_upload_on_wifi")
  436. .remove("instant_upload_on_charging")
  437. .remove("instant_video_upload_path")
  438. .remove("instant_video_upload_path_use_subfolders")
  439. .remove("instant_video_upload_on_wifi")
  440. .remove("instant_video_uploading")
  441. .remove("instant_video_upload_on_charging")
  442. .remove("prefs_instant_behaviour").apply();
  443. // show info pop-up
  444. try {
  445. new AlertDialog.Builder(context, R.style.Theme_ownCloud_Dialog)
  446. .setTitle(R.string.drawer_synced_folders)
  447. .setMessage(R.string.synced_folders_new_info)
  448. .setPositiveButton(R.string.drawer_open, (dialog, which) -> {
  449. // show Auto Upload
  450. Intent folderSyncIntent = new Intent(context, SyncedFoldersActivity.class);
  451. dialog.dismiss();
  452. context.startActivity(folderSyncIntent);
  453. })
  454. .setNegativeButton(R.string.drawer_close, (dialog, which) -> dialog.dismiss())
  455. .setIcon(R.drawable.nav_synced_folders)
  456. .show();
  457. } catch (WindowManager.BadTokenException e) {
  458. Log_OC.i(TAG, "Error showing Auto Upload Update dialog, so skipping it: " + e.getMessage());
  459. }
  460. }
  461. }
  462. private static void updateAutoUploadEntries() {
  463. // updates entries to reflect their true paths
  464. Context context = getAppContext();
  465. if (!PreferenceManager.getAutoUploadPathsUpdate(context)) {
  466. SyncedFolderProvider syncedFolderProvider =
  467. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver());
  468. syncedFolderProvider.updateAutoUploadPaths(mContext);
  469. }
  470. }
  471. private static void splitOutAutoUploadEntries() {
  472. Context context = getAppContext();
  473. if (!PreferenceManager.getAutoUploadSplitEntries(context)) {
  474. // magic to split out existing synced folders in two when needed
  475. // otherwise, we migrate them to their proper type (image or video)
  476. Log_OC.i(TAG, "Migrate synced_folders records for image/video split");
  477. ContentResolver contentResolver = context.getContentResolver();
  478. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
  479. final List<MediaFolder> imageMediaFolders = MediaProvider.getImageFolders(contentResolver, 1, null, true);
  480. final List<MediaFolder> videoMediaFolders = MediaProvider.getVideoFolders(contentResolver, 1, null, true);
  481. ArrayList<Long> idsToDelete = new ArrayList<>();
  482. List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
  483. long primaryKey;
  484. SyncedFolder newSyncedFolder;
  485. for (SyncedFolder syncedFolder : syncedFolders) {
  486. idsToDelete.add(syncedFolder.getId());
  487. Log_OC.i(TAG, "Migration check for synced_folders record: "
  488. + syncedFolder.getId() + " - " + syncedFolder.getLocalPath());
  489. for (MediaFolder imageMediaFolder : imageMediaFolders) {
  490. if (imageMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  491. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  492. newSyncedFolder.setType(MediaFolderType.IMAGE);
  493. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  494. Log_OC.i(TAG, "Migrated image synced_folders record: "
  495. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  496. break;
  497. }
  498. }
  499. for (MediaFolder videoMediaFolder : videoMediaFolders) {
  500. if (videoMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  501. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  502. newSyncedFolder.setType(MediaFolderType.VIDEO);
  503. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  504. Log_OC.i(TAG, "Migrated video synced_folders record: "
  505. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  506. break;
  507. }
  508. }
  509. }
  510. for (long id : idsToDelete) {
  511. Log_OC.i(TAG, "Removing legacy synced_folders record: " + id);
  512. syncedFolderProvider.deleteSyncedFolder(id);
  513. }
  514. PreferenceManager.setAutoUploadSplitEntries(context, true);
  515. }
  516. }
  517. private static void initiateExistingAutoUploadEntries() {
  518. new Thread(() -> {
  519. if (!PreferenceManager.getAutoUploadInit(getAppContext())) {
  520. SyncedFolderProvider syncedFolderProvider =
  521. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver());
  522. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  523. if (syncedFolder.isEnabled()) {
  524. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder);
  525. }
  526. }
  527. PreferenceManager.setAutoUploadInit(getAppContext(), true);
  528. }
  529. }).start();
  530. }
  531. private static void cleanOldEntries() {
  532. // previous versions of application created broken entries in the SyncedFolderProvider
  533. // database, and this cleans all that and leaves 1 (newest) entry per synced folder
  534. Context context = getAppContext();
  535. if (!PreferenceManager.getLegacyClean(context)) {
  536. SyncedFolderProvider syncedFolderProvider =
  537. new SyncedFolderProvider(context.getContentResolver());
  538. List<SyncedFolder> syncedFolderList = syncedFolderProvider.getSyncedFolders();
  539. Map<Pair<String, String>, Long> syncedFolders = new HashMap<>();
  540. ArrayList<Long> ids = new ArrayList<>();
  541. for (SyncedFolder syncedFolder : syncedFolderList) {
  542. Pair<String, String> checkPair = new Pair<>(syncedFolder.getAccount(), syncedFolder.getLocalPath());
  543. if (syncedFolders.containsKey(checkPair)) {
  544. if (syncedFolder.getId() > syncedFolders.get(checkPair)) {
  545. syncedFolders.put(checkPair, syncedFolder.getId());
  546. }
  547. } else {
  548. syncedFolders.put(checkPair, syncedFolder.getId());
  549. }
  550. }
  551. ids.addAll(syncedFolders.values());
  552. if (ids.size() > 0) {
  553. syncedFolderProvider.deleteSyncedFoldersNotInList(mContext, ids);
  554. } else {
  555. PreferenceManager.setLegacyClean(context, true);
  556. }
  557. }
  558. }
  559. }