MainApp.java 30 KB

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