MainApp.java 23 KB

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