MainApp.java 23 KB

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