MainApp.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author masensio
  5. * @author David A. Velasco
  6. * @author Chris Narkiewicz
  7. * Copyright (C) 2015 ownCloud Inc.
  8. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License version 2,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. package com.owncloud.android;
  23. import android.Manifest;
  24. import android.accounts.Account;
  25. import android.annotation.SuppressLint;
  26. import android.app.Activity;
  27. import android.app.ActivityManager;
  28. import android.app.Application;
  29. import android.app.NotificationChannel;
  30. import android.app.NotificationManager;
  31. import android.content.ContentResolver;
  32. import android.content.Context;
  33. import android.content.Intent;
  34. import android.content.pm.PackageInfo;
  35. import android.content.pm.PackageManager;
  36. import android.os.Build;
  37. import android.os.Bundle;
  38. import android.os.Environment;
  39. import android.os.StrictMode;
  40. import android.text.TextUtils;
  41. import android.view.WindowManager;
  42. import com.evernote.android.job.JobManager;
  43. import com.evernote.android.job.JobRequest;
  44. import com.nextcloud.client.account.UserAccountManager;
  45. import com.nextcloud.client.appinfo.AppInfo;
  46. import com.nextcloud.client.device.PowerManagementService;
  47. import com.nextcloud.client.di.ActivityInjector;
  48. import com.nextcloud.client.di.DaggerAppComponent;
  49. import com.nextcloud.client.errorhandling.ExceptionHandler;
  50. import com.nextcloud.client.logger.LegacyLoggerAdapter;
  51. import com.nextcloud.client.logger.Logger;
  52. import com.nextcloud.client.network.ConnectivityService;
  53. import com.nextcloud.client.onboarding.OnboardingService;
  54. import com.nextcloud.client.preferences.AppPreferences;
  55. import com.nextcloud.client.preferences.AppPreferencesImpl;
  56. import com.owncloud.android.authentication.PassCodeManager;
  57. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  58. import com.owncloud.android.datamodel.MediaFolder;
  59. import com.owncloud.android.datamodel.MediaFolderType;
  60. import com.owncloud.android.datamodel.MediaProvider;
  61. import com.owncloud.android.datamodel.SyncedFolder;
  62. import com.owncloud.android.datamodel.SyncedFolderProvider;
  63. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  64. import com.owncloud.android.datamodel.UploadsStorageManager;
  65. import com.owncloud.android.datastorage.DataStorageProvider;
  66. import com.owncloud.android.datastorage.StoragePoint;
  67. import com.owncloud.android.jobs.MediaFoldersDetectionJob;
  68. import com.owncloud.android.jobs.NCJobCreator;
  69. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  70. import com.owncloud.android.lib.common.utils.Log_OC;
  71. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  72. import com.owncloud.android.ui.activity.ContactsPreferenceActivity;
  73. import com.owncloud.android.ui.activity.SyncedFoldersActivity;
  74. import com.owncloud.android.ui.notifications.NotificationUtils;
  75. import com.owncloud.android.utils.DisplayUtils;
  76. import com.owncloud.android.utils.FilesSyncHelper;
  77. import com.owncloud.android.utils.PermissionUtil;
  78. import com.owncloud.android.utils.ReceiversHelper;
  79. import com.owncloud.android.utils.SecurityUtils;
  80. import java.lang.reflect.Method;
  81. import java.util.ArrayList;
  82. import java.util.HashMap;
  83. import java.util.List;
  84. import java.util.Map;
  85. import java.util.concurrent.TimeUnit;
  86. import javax.inject.Inject;
  87. import androidx.annotation.RequiresApi;
  88. import androidx.annotation.StringRes;
  89. import androidx.appcompat.app.AlertDialog;
  90. import androidx.core.util.Pair;
  91. import androidx.multidex.MultiDexApplication;
  92. import dagger.android.AndroidInjector;
  93. import dagger.android.DispatchingAndroidInjector;
  94. import dagger.android.HasAndroidInjector;
  95. import de.cotech.hw.SecurityKeyManager;
  96. import de.cotech.hw.SecurityKeyManagerConfig;
  97. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  98. import static com.owncloud.android.ui.activity.ContactsPreferenceActivity.PREFERENCE_CONTACTS_AUTOMATIC_BACKUP;
  99. /**
  100. * Main Application of the project
  101. * <p>
  102. * Contains methods to build the "static" strings. These strings were before constants in different classes
  103. */
  104. public class MainApp extends MultiDexApplication implements HasAndroidInjector {
  105. public static final OwnCloudVersion OUTDATED_SERVER_VERSION = OwnCloudVersion.nextcloud_13;
  106. public static final OwnCloudVersion MINIMUM_SUPPORTED_SERVER_VERSION = OwnCloudVersion.nextcloud_12;
  107. private static final String TAG = MainApp.class.getSimpleName();
  108. private static Context mContext;
  109. private static String storagePath;
  110. private static boolean mOnlyOnDevice;
  111. @Inject
  112. protected AppPreferences preferences;
  113. @Inject
  114. protected DispatchingAndroidInjector<Object> dispatchingAndroidInjector;
  115. @Inject
  116. protected UserAccountManager accountManager;
  117. @Inject
  118. protected UploadsStorageManager uploadsStorageManager;
  119. @Inject
  120. protected OnboardingService onboarding;
  121. @Inject
  122. ConnectivityService connectivityService;
  123. @Inject PowerManagementService powerManagementService;
  124. @Inject
  125. Logger logger;
  126. @Inject
  127. AppInfo appInfo;
  128. private PassCodeManager passCodeManager;
  129. @SuppressWarnings("unused")
  130. private boolean mBound;
  131. /**
  132. * Temporary hack
  133. */
  134. private static void initGlobalContext(Context context) {
  135. mContext = context;
  136. }
  137. /**
  138. * Temporary getter replacing Dagger DI
  139. * TODO: remove when cleaning DI in NContentObserverJob
  140. */
  141. public AppPreferences getPreferences() {
  142. return preferences;
  143. }
  144. /**
  145. * Temporary getter replacing Dagger DI
  146. * TODO: remove when cleaning DI in NContentObserverJob
  147. */
  148. public PowerManagementService getPowerManagementService() {
  149. return powerManagementService;
  150. }
  151. private String getAppProcessName() {
  152. String processName = "";
  153. if(Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
  154. ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
  155. final int ownPid = android.os.Process.myPid();
  156. final List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
  157. if (processes != null) {
  158. for (ActivityManager.RunningAppProcessInfo info : processes) {
  159. if (info.pid == ownPid) {
  160. processName = info.processName;
  161. break;
  162. }
  163. }
  164. }
  165. } else {
  166. processName = Application.getProcessName();
  167. }
  168. return processName;
  169. }
  170. @Override
  171. protected void attachBaseContext(Context base) {
  172. super.attachBaseContext(base);
  173. initGlobalContext(this);
  174. DaggerAppComponent.builder()
  175. .application(this)
  176. .build()
  177. .inject(this);
  178. // we don't want to handle crashes occurring inside crash reporter activity/process;
  179. // let the platform deal with those
  180. final boolean isCrashReportingProcess = getAppProcessName().endsWith(":crash");
  181. final boolean useExceptionHandler = !appInfo.isDebugBuild();
  182. if (!isCrashReportingProcess && useExceptionHandler) {
  183. Thread.UncaughtExceptionHandler defaultPlatformHandler = Thread.getDefaultUncaughtExceptionHandler();
  184. final ExceptionHandler crashReporter = new ExceptionHandler(this,
  185. defaultPlatformHandler);
  186. Thread.setDefaultUncaughtExceptionHandler(crashReporter);
  187. }
  188. }
  189. @SuppressFBWarnings("ST")
  190. @Override
  191. public void onCreate() {
  192. super.onCreate();
  193. SecurityKeyManager securityKeyManager = SecurityKeyManager.getInstance();
  194. SecurityKeyManagerConfig config = new SecurityKeyManagerConfig.Builder()
  195. .setEnableDebugLogging(BuildConfig.DEBUG)
  196. .build();
  197. securityKeyManager.init(this, config);
  198. registerActivityLifecycleCallbacks(new ActivityInjector());
  199. Thread t = new Thread(() -> {
  200. // best place, before any access to AccountManager or database
  201. if (!preferences.isUserIdMigrated()) {
  202. final boolean migrated = accountManager.migrateUserId();
  203. preferences.setMigratedUserId(migrated);
  204. }
  205. });
  206. t.start();
  207. JobManager.create(this).addJobCreator(
  208. new NCJobCreator(
  209. getApplicationContext(),
  210. accountManager,
  211. preferences,
  212. uploadsStorageManager,
  213. connectivityService,
  214. powerManagementService
  215. )
  216. );
  217. new SecurityUtils();
  218. DisplayUtils.useCompatVectorIfNeeded();
  219. fixStoragePath();
  220. passCodeManager = new PassCodeManager(preferences);
  221. MainApp.storagePath = preferences.getStoragePath(getApplicationContext().getFilesDir().getAbsolutePath());
  222. OwnCloudClientManagerFactory.setUserAgent(getUserAgent());
  223. // initialise thumbnails cache on background thread
  224. new ThumbnailsCacheManager.InitDiskCacheTask().execute();
  225. if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
  226. // use app writable dir, no permissions needed
  227. Log_OC.setLoggerImplementation(new LegacyLoggerAdapter(logger));
  228. Log_OC.d("Debug", "start logging");
  229. }
  230. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  231. try {
  232. Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
  233. m.invoke(null);
  234. } catch (Exception e) {
  235. Log_OC.d("Debug", "Failed to disable uri exposure");
  236. }
  237. }
  238. initSyncOperations(uploadsStorageManager, accountManager, connectivityService, powerManagementService);
  239. initContactsBackup(accountManager);
  240. notificationChannels();
  241. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  242. .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
  243. .setUpdateCurrent(true)
  244. .build()
  245. .schedule();
  246. new JobRequest.Builder(MediaFoldersDetectionJob.TAG)
  247. .startNow()
  248. .setUpdateCurrent(false)
  249. .build()
  250. .schedule();
  251. // register global protection with pass code
  252. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
  253. @Override
  254. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  255. Log_OC.d(activity.getClass().getSimpleName(), "onCreate(Bundle) starting");
  256. onboarding.launchActivityIfNeeded(activity);
  257. }
  258. @Override
  259. public void onActivityStarted(Activity activity) {
  260. Log_OC.d(activity.getClass().getSimpleName(), "onStart() starting");
  261. }
  262. @Override
  263. public void onActivityResumed(Activity activity) {
  264. Log_OC.d(activity.getClass().getSimpleName(), "onResume() starting");
  265. passCodeManager.onActivityStarted(activity);
  266. }
  267. @Override
  268. public void onActivityPaused(Activity activity) {
  269. Log_OC.d(activity.getClass().getSimpleName(), "onPause() ending");
  270. }
  271. @Override
  272. public void onActivityStopped(Activity activity) {
  273. Log_OC.d(activity.getClass().getSimpleName(), "onStop() ending");
  274. passCodeManager.onActivityStopped(activity);
  275. }
  276. @Override
  277. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  278. Log_OC.d(activity.getClass().getSimpleName(), "onSaveInstanceState(Bundle) starting");
  279. }
  280. @Override
  281. public void onActivityDestroyed(Activity activity) {
  282. Log_OC.d(activity.getClass().getSimpleName(), "onDestroy() ending");
  283. }
  284. });
  285. }
  286. public static void initContactsBackup(UserAccountManager accountManager) {
  287. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
  288. Account[] accounts = accountManager.getAccounts();
  289. for (Account account : accounts) {
  290. if (arbitraryDataProvider.getBooleanValue(account, PREFERENCE_CONTACTS_AUTOMATIC_BACKUP)) {
  291. ContactsPreferenceActivity.startContactBackupJob(account);
  292. }
  293. }
  294. }
  295. @SuppressLint("ApplySharedPref") // commit is done on purpose to write immediately
  296. private void fixStoragePath() {
  297. if (!preferences.isStoragePathFixEnabled()) {
  298. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  299. StoragePoint[] storagePoints = DataStorageProvider.getInstance().getAvailableStoragePoints();
  300. String storagePath = preferences.getStoragePath("");
  301. if (TextUtils.isEmpty(storagePath)) {
  302. if (preferences.getLastSeenVersionCode() != 0) {
  303. // We already used the app, but no storage is set - fix that!
  304. preferences.setStoragePath(Environment.getExternalStorageDirectory().getAbsolutePath());
  305. preferences.removeKeysMigrationPreference();
  306. } else {
  307. // find internal storage path that's indexable
  308. boolean set = false;
  309. for (StoragePoint storagePoint : storagePoints) {
  310. if (storagePoint.getStorageType() == StoragePoint.StorageType.INTERNAL &&
  311. storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  312. preferences.setStoragePath(storagePoint.getPath());
  313. preferences.removeKeysMigrationPreference();
  314. set = true;
  315. break;
  316. }
  317. }
  318. if (!set) {
  319. for (StoragePoint storagePoint : storagePoints) {
  320. if (storagePoint.getPrivacyType() == StoragePoint.PrivacyType.PUBLIC) {
  321. preferences.setStoragePath(storagePoint.getPath());
  322. preferences.removeKeysMigrationPreference();
  323. set = true;
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. preferences.setStoragePathFixEnabled(true);
  330. } else {
  331. preferences.removeKeysMigrationPreference();
  332. preferences.setStoragePathFixEnabled(true);
  333. }
  334. } else {
  335. if (TextUtils.isEmpty(storagePath)) {
  336. preferences.setStoragePath(Environment.getExternalStorageDirectory().getAbsolutePath());
  337. }
  338. preferences.removeKeysMigrationPreference();
  339. preferences.setStoragePathFixEnabled(true);
  340. }
  341. }
  342. }
  343. public static void initSyncOperations(
  344. final UploadsStorageManager uploadsStorageManager,
  345. final UserAccountManager accountManager,
  346. final ConnectivityService connectivityService,
  347. final PowerManagementService powerManagementService
  348. ) {
  349. updateToAutoUpload();
  350. cleanOldEntries();
  351. updateAutoUploadEntries();
  352. if (getAppContext() != null) {
  353. if (PermissionUtil.checkSelfPermission(getAppContext(),
  354. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  355. splitOutAutoUploadEntries();
  356. } else {
  357. AppPreferences preferences = AppPreferencesImpl.fromContext(getAppContext());
  358. preferences.setAutoUploadSplitEntriesEnabled(true);
  359. }
  360. }
  361. initiateExistingAutoUploadEntries();
  362. FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
  363. FilesSyncHelper.restartJobsIfNeeded(
  364. uploadsStorageManager,
  365. accountManager,
  366. connectivityService,
  367. powerManagementService);
  368. FilesSyncHelper.scheduleOfflineSyncIfNeeded();
  369. ReceiversHelper.registerNetworkChangeReceiver(uploadsStorageManager,
  370. accountManager,
  371. connectivityService,
  372. powerManagementService);
  373. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  374. ReceiversHelper.registerPowerChangeReceiver(uploadsStorageManager,
  375. accountManager,
  376. connectivityService,
  377. powerManagementService);
  378. }
  379. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  380. ReceiversHelper.registerPowerSaveReceiver(uploadsStorageManager,
  381. accountManager,
  382. connectivityService,
  383. powerManagementService);
  384. }
  385. }
  386. public static void notificationChannels() {
  387. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && getAppContext() != null) {
  388. Context context = getAppContext();
  389. NotificationManager notificationManager = (NotificationManager)
  390. context.getSystemService(Context.NOTIFICATION_SERVICE);
  391. if (notificationManager != null) {
  392. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD,
  393. R.string.notification_channel_download_name,
  394. R.string.notification_channel_download_description, context);
  395. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD,
  396. R.string.notification_channel_upload_name,
  397. R.string.notification_channel_upload_description, context);
  398. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA,
  399. R.string.notification_channel_media_name,
  400. R.string.notification_channel_media_description, context);
  401. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC,
  402. R.string.notification_channel_file_sync_name,
  403. R.string.notification_channel_file_sync_description, context);
  404. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER,
  405. R.string.notification_channel_file_observer_name, R.string
  406. .notification_channel_file_observer_description, context);
  407. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_PUSH,
  408. R.string.notification_channel_push_name, R.string
  409. .notification_channel_push_description, context, NotificationManager.IMPORTANCE_DEFAULT);
  410. createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL, R.string
  411. .notification_channel_general_name, R.string.notification_channel_general_description,
  412. context, NotificationManager.IMPORTANCE_DEFAULT);
  413. } else {
  414. Log_OC.e(TAG, "Notification manager is null");
  415. }
  416. }
  417. }
  418. @RequiresApi(api = Build.VERSION_CODES.N)
  419. private static void createChannel(NotificationManager notificationManager,
  420. String channelId, int channelName,
  421. int channelDescription, Context context) {
  422. createChannel(notificationManager, channelId, channelName, channelDescription, context,
  423. NotificationManager.IMPORTANCE_LOW);
  424. }
  425. private static void createChannel(NotificationManager notificationManager,
  426. String channelId, int channelName,
  427. int channelDescription, Context context, int importance) {
  428. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
  429. && getAppContext() != null
  430. && notificationManager.getNotificationChannel(channelId) == null) {
  431. CharSequence name = context.getString(channelName);
  432. String description = context.getString(channelDescription);
  433. NotificationChannel channel = new NotificationChannel(channelId, name, importance);
  434. channel.setDescription(description);
  435. channel.enableLights(false);
  436. channel.enableVibration(false);
  437. notificationManager.createNotificationChannel(channel);
  438. }
  439. }
  440. public static Context getAppContext() {
  441. return MainApp.mContext;
  442. }
  443. public static void setAppContext(Context context) {
  444. MainApp.mContext = context;
  445. }
  446. public static String getStoragePath() {
  447. return MainApp.storagePath;
  448. }
  449. public static void setStoragePath(String path) {
  450. MainApp.storagePath = path;
  451. }
  452. // Methods to obtain Strings referring app_name
  453. // From AccountAuthenticator
  454. // public static final String ACCOUNT_TYPE = "owncloud";
  455. public static String getAccountType(Context context) {
  456. return context.getResources().getString(R.string.account_type);
  457. }
  458. // From AccountAuthenticator
  459. // public static final String AUTHORITY = "org.owncloud";
  460. public static String getAuthority() {
  461. return getAppContext().getResources().getString(R.string.authority);
  462. }
  463. // From AccountAuthenticator
  464. // public static final String AUTH_TOKEN_TYPE = "org.owncloud";
  465. public static String getAuthTokenType() {
  466. return getAppContext().getResources().getString(R.string.authority);
  467. }
  468. // From ProviderMeta
  469. // public static final String DB_FILE = "owncloud.db";
  470. public static String getDBFile() {
  471. return getAppContext().getResources().getString(R.string.db_file);
  472. }
  473. // From ProviderMeta
  474. // private final String mDatabaseName = "ownCloud";
  475. public static String getDBName() {
  476. return getAppContext().getResources().getString(R.string.db_name);
  477. }
  478. /**
  479. * name of data_folder, e.g., "owncloud"
  480. */
  481. public static String getDataFolder() {
  482. return getAppContext().getResources().getString(R.string.data_folder);
  483. }
  484. public static void showOnlyFilesOnDevice(boolean state) {
  485. mOnlyOnDevice = state;
  486. }
  487. public static boolean isOnlyOnDevice() {
  488. return mOnlyOnDevice;
  489. }
  490. public static String getUserAgent() {
  491. // Mozilla/5.0 (Android) Nextcloud-android/2.1.0
  492. return getUserAgent(R.string.nextcloud_user_agent);
  493. }
  494. // user agent
  495. private static String getUserAgent(@StringRes int agent) {
  496. String appString = getAppContext().getResources().getString(agent);
  497. String packageName = getAppContext().getPackageName();
  498. String version = "";
  499. try {
  500. PackageInfo pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0);
  501. if (pInfo != null) {
  502. version = pInfo.versionName;
  503. }
  504. } catch (PackageManager.NameNotFoundException e) {
  505. Log_OC.e(TAG, "Trying to get packageName", e.getCause());
  506. }
  507. return String.format(appString, version);
  508. }
  509. private static void updateToAutoUpload() {
  510. Context context = getAppContext();
  511. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  512. if (preferences.instantPictureUploadEnabled() || preferences.instantVideoUploadEnabled()) {
  513. preferences.removeLegacyPreferences();
  514. // show info pop-up
  515. try {
  516. new AlertDialog.Builder(context, R.style.Theme_ownCloud_Dialog)
  517. .setTitle(R.string.drawer_synced_folders)
  518. .setMessage(R.string.synced_folders_new_info)
  519. .setPositiveButton(R.string.drawer_open, (dialog, which) -> {
  520. // show Auto Upload
  521. Intent folderSyncIntent = new Intent(context, SyncedFoldersActivity.class);
  522. dialog.dismiss();
  523. context.startActivity(folderSyncIntent);
  524. })
  525. .setNegativeButton(R.string.drawer_close, (dialog, which) -> dialog.dismiss())
  526. .setIcon(R.drawable.nav_synced_folders)
  527. .show();
  528. } catch (WindowManager.BadTokenException e) {
  529. Log_OC.i(TAG, "Error showing Auto Upload Update dialog, so skipping it: " + e.getMessage());
  530. }
  531. }
  532. }
  533. private static void updateAutoUploadEntries() {
  534. // updates entries to reflect their true paths
  535. Context context = getAppContext();
  536. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  537. if (!preferences.isAutoUploadPathsUpdateEnabled()) {
  538. SyncedFolderProvider syncedFolderProvider =
  539. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver(), preferences);
  540. syncedFolderProvider.updateAutoUploadPaths(mContext);
  541. }
  542. }
  543. private static void splitOutAutoUploadEntries() {
  544. Context context = getAppContext();
  545. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  546. if (!preferences.isAutoUploadSplitEntriesEnabled()) {
  547. // magic to split out existing synced folders in two when needed
  548. // otherwise, we migrate them to their proper type (image or video)
  549. Log_OC.i(TAG, "Migrate synced_folders records for image/video split");
  550. ContentResolver contentResolver = context.getContentResolver();
  551. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver, preferences);
  552. final List<MediaFolder> imageMediaFolders = MediaProvider.getImageFolders(contentResolver, 1, null, true);
  553. final List<MediaFolder> videoMediaFolders = MediaProvider.getVideoFolders(contentResolver, 1, null, true);
  554. ArrayList<Long> idsToDelete = new ArrayList<>();
  555. List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
  556. long primaryKey;
  557. SyncedFolder newSyncedFolder;
  558. for (SyncedFolder syncedFolder : syncedFolders) {
  559. idsToDelete.add(syncedFolder.getId());
  560. Log_OC.i(TAG, "Migration check for synced_folders record: "
  561. + syncedFolder.getId() + " - " + syncedFolder.getLocalPath());
  562. for (MediaFolder imageMediaFolder : imageMediaFolders) {
  563. if (imageMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  564. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  565. newSyncedFolder.setType(MediaFolderType.IMAGE);
  566. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  567. Log_OC.i(TAG, "Migrated image synced_folders record: "
  568. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  569. break;
  570. }
  571. }
  572. for (MediaFolder videoMediaFolder : videoMediaFolders) {
  573. if (videoMediaFolder.absolutePath.equals(syncedFolder.getLocalPath())) {
  574. newSyncedFolder = (SyncedFolder) syncedFolder.clone();
  575. newSyncedFolder.setType(MediaFolderType.VIDEO);
  576. primaryKey = syncedFolderProvider.storeSyncedFolder(newSyncedFolder);
  577. Log_OC.i(TAG, "Migrated video synced_folders record: "
  578. + primaryKey + " - " + newSyncedFolder.getLocalPath());
  579. break;
  580. }
  581. }
  582. }
  583. for (long id : idsToDelete) {
  584. Log_OC.i(TAG, "Removing legacy synced_folders record: " + id);
  585. syncedFolderProvider.deleteSyncedFolder(id);
  586. }
  587. preferences.setAutoUploadSplitEntriesEnabled(true);
  588. }
  589. }
  590. private static void initiateExistingAutoUploadEntries() {
  591. new Thread(() -> {
  592. AppPreferences preferences = AppPreferencesImpl.fromContext(getAppContext());
  593. if (!preferences.isAutoUploadInitialized()) {
  594. SyncedFolderProvider syncedFolderProvider =
  595. new SyncedFolderProvider(MainApp.getAppContext().getContentResolver(), preferences);
  596. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  597. if (syncedFolder.isEnabled()) {
  598. FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder);
  599. }
  600. }
  601. preferences.setAutoUploadInit(true);
  602. }
  603. }).start();
  604. }
  605. private static void cleanOldEntries() {
  606. // previous versions of application created broken entries in the SyncedFolderProvider
  607. // database, and this cleans all that and leaves 1 (newest) entry per synced folder
  608. Context context = getAppContext();
  609. AppPreferences preferences = AppPreferencesImpl.fromContext(context);
  610. if (!preferences.isLegacyClean()) {
  611. SyncedFolderProvider syncedFolderProvider =
  612. new SyncedFolderProvider(context.getContentResolver(), preferences);
  613. List<SyncedFolder> syncedFolderList = syncedFolderProvider.getSyncedFolders();
  614. Map<Pair<String, String>, Long> syncedFolders = new HashMap<>();
  615. ArrayList<Long> ids = new ArrayList<>();
  616. for (SyncedFolder syncedFolder : syncedFolderList) {
  617. Pair<String, String> checkPair = new Pair<>(syncedFolder.getAccount(), syncedFolder.getLocalPath());
  618. if (syncedFolders.containsKey(checkPair)) {
  619. if (syncedFolder.getId() > syncedFolders.get(checkPair)) {
  620. syncedFolders.put(checkPair, syncedFolder.getId());
  621. }
  622. } else {
  623. syncedFolders.put(checkPair, syncedFolder.getId());
  624. }
  625. }
  626. ids.addAll(syncedFolders.values());
  627. if (ids.size() > 0) {
  628. int deletedCount = syncedFolderProvider.deleteSyncedFoldersNotInList(ids);
  629. if (deletedCount > 0) {
  630. preferences.setLegacyClean(true);
  631. }
  632. } else {
  633. preferences.setLegacyClean(true);
  634. }
  635. }
  636. }
  637. @Override
  638. public AndroidInjector<Object> androidInjector() {
  639. return dispatchingAndroidInjector;
  640. }
  641. }