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