MainApp.java 28 KB

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