FileDisplayActivity.java 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * @author Andy Scherzinger
  7. * @author Chris Narkiewicz
  8. * Copyright (C) 2011 Bartek Przybylski
  9. * Copyright (C) 2016 ownCloud Inc.
  10. * Copyright (C) 2018 Andy Scherzinger
  11. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License version 2,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. */
  25. package com.owncloud.android.ui.activity;
  26. import android.Manifest;
  27. import android.accounts.Account;
  28. import android.accounts.AccountManager;
  29. import android.accounts.AuthenticatorException;
  30. import android.annotation.TargetApi;
  31. import android.app.Activity;
  32. import android.app.SearchManager;
  33. import android.content.BroadcastReceiver;
  34. import android.content.ComponentName;
  35. import android.content.ContentResolver;
  36. import android.content.Context;
  37. import android.content.DialogInterface;
  38. import android.content.Intent;
  39. import android.content.IntentFilter;
  40. import android.content.ServiceConnection;
  41. import android.content.SyncRequest;
  42. import android.content.pm.PackageManager;
  43. import android.content.res.Resources.NotFoundException;
  44. import android.net.Uri;
  45. import android.os.Build;
  46. import android.os.Bundle;
  47. import android.os.IBinder;
  48. import android.os.Parcelable;
  49. import android.text.TextUtils;
  50. import android.view.Menu;
  51. import android.view.MenuInflater;
  52. import android.view.MenuItem;
  53. import android.view.View;
  54. import android.view.ViewTreeObserver;
  55. import android.widget.EditText;
  56. import android.widget.ImageView;
  57. import com.google.android.material.bottomnavigation.BottomNavigationView;
  58. import com.google.android.material.snackbar.Snackbar;
  59. import com.nextcloud.client.appinfo.AppInfo;
  60. import com.nextcloud.client.di.Injectable;
  61. import com.nextcloud.client.network.ConnectivityService;
  62. import com.nextcloud.client.preferences.AppPreferences;
  63. import com.nextcloud.client.preferences.AppPreferencesImpl;
  64. import com.owncloud.android.BuildConfig;
  65. import com.owncloud.android.MainApp;
  66. import com.owncloud.android.R;
  67. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  68. import com.owncloud.android.datamodel.FileDataStorageManager;
  69. import com.owncloud.android.datamodel.OCFile;
  70. import com.owncloud.android.datamodel.VirtualFolderType;
  71. import com.owncloud.android.files.services.FileDownloader;
  72. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  73. import com.owncloud.android.files.services.FileUploader;
  74. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  75. import com.owncloud.android.lib.common.accounts.AccountUtils;
  76. import com.owncloud.android.lib.common.operations.RemoteOperation;
  77. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  78. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  79. import com.owncloud.android.lib.common.utils.Log_OC;
  80. import com.owncloud.android.lib.resources.files.RestoreFileVersionRemoteOperation;
  81. import com.owncloud.android.lib.resources.shares.OCShare;
  82. import com.owncloud.android.lib.resources.shares.ShareType;
  83. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  84. import com.owncloud.android.media.MediaService;
  85. import com.owncloud.android.media.MediaServiceBinder;
  86. import com.owncloud.android.operations.CopyFileOperation;
  87. import com.owncloud.android.operations.CreateFolderOperation;
  88. import com.owncloud.android.operations.CreateShareViaLinkOperation;
  89. import com.owncloud.android.operations.CreateShareWithShareeOperation;
  90. import com.owncloud.android.operations.MoveFileOperation;
  91. import com.owncloud.android.operations.RefreshFolderOperation;
  92. import com.owncloud.android.operations.RemoveFileOperation;
  93. import com.owncloud.android.operations.RenameFileOperation;
  94. import com.owncloud.android.operations.SynchronizeFileOperation;
  95. import com.owncloud.android.operations.UnshareOperation;
  96. import com.owncloud.android.operations.UpdateNoteForShareOperation;
  97. import com.owncloud.android.operations.UpdateSharePermissionsOperation;
  98. import com.owncloud.android.operations.UpdateShareViaLinkOperation;
  99. import com.owncloud.android.operations.UploadFileOperation;
  100. import com.owncloud.android.providers.UsersAndGroupsSearchProvider;
  101. import com.owncloud.android.syncadapter.FileSyncAdapter;
  102. import com.owncloud.android.ui.asynctasks.CheckAvailableSpaceTask;
  103. import com.owncloud.android.ui.asynctasks.FetchRemoteFileTask;
  104. import com.owncloud.android.ui.dialog.SendShareDialog;
  105. import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
  106. import com.owncloud.android.ui.events.SyncEventFinished;
  107. import com.owncloud.android.ui.events.TokenPushEvent;
  108. import com.owncloud.android.ui.fragment.ExtendedListFragment;
  109. import com.owncloud.android.ui.fragment.FileDetailFragment;
  110. import com.owncloud.android.ui.fragment.FileFragment;
  111. import com.owncloud.android.ui.fragment.OCFileListFragment;
  112. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  113. import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment;
  114. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  115. import com.owncloud.android.ui.helpers.UriUploader;
  116. import com.owncloud.android.ui.preview.PreviewImageActivity;
  117. import com.owncloud.android.ui.preview.PreviewImageFragment;
  118. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  119. import com.owncloud.android.ui.preview.PreviewTextFragment;
  120. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  121. import com.owncloud.android.utils.DataHolderUtil;
  122. import com.owncloud.android.utils.DisplayUtils;
  123. import com.owncloud.android.utils.ErrorMessageAdapter;
  124. import com.owncloud.android.utils.FileSortOrder;
  125. import com.owncloud.android.utils.MimeTypeUtil;
  126. import com.owncloud.android.utils.PermissionUtil;
  127. import com.owncloud.android.utils.PushUtils;
  128. import com.owncloud.android.utils.ThemeUtils;
  129. import org.greenrobot.eventbus.EventBus;
  130. import org.greenrobot.eventbus.Subscribe;
  131. import org.greenrobot.eventbus.ThreadMode;
  132. import org.parceler.Parcels;
  133. import java.io.File;
  134. import java.util.ArrayList;
  135. import java.util.Collection;
  136. import java.util.List;
  137. import java.util.Locale;
  138. import javax.inject.Inject;
  139. import androidx.annotation.NonNull;
  140. import androidx.annotation.StringRes;
  141. import androidx.appcompat.app.AlertDialog;
  142. import androidx.appcompat.widget.SearchView;
  143. import androidx.core.content.ContextCompat;
  144. import androidx.core.view.MenuItemCompat;
  145. import androidx.fragment.app.Fragment;
  146. import androidx.fragment.app.FragmentManager;
  147. import androidx.fragment.app.FragmentTransaction;
  148. import static com.owncloud.android.datamodel.OCFile.PATH_SEPARATOR;
  149. /**
  150. * Displays, what files the user has available in his ownCloud. This is the main view.
  151. */
  152. public class FileDisplayActivity extends FileActivity
  153. implements FileFragment.ContainerActivity,
  154. OnEnforceableRefreshListener, SortingOrderDialogFragment.OnSortingOrderListener,
  155. SendShareDialog.SendShareDialogDownloader, Injectable {
  156. public static final String RESTART = "RESTART";
  157. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  158. private UploadFinishReceiver mUploadFinishReceiver;
  159. private DownloadFinishReceiver mDownloadFinishReceiver;
  160. private RemoteOperationResult mLastSslUntrustedServerResult;
  161. private boolean mDualPane;
  162. private View mLeftFragmentContainer;
  163. private View mRightFragmentContainer;
  164. public static final String TAG_PUBLIC_LINK = "PUBLIC_LINK";
  165. public static final String FTAG_CHOOSER_DIALOG = "CHOOSER_DIALOG";
  166. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  167. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  168. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  169. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  170. public static final String DRAWER_MENU_ID = "DRAWER_MENU_ID";
  171. public static final int REQUEST_CODE__SELECT_CONTENT_FROM_APPS = REQUEST_CODE__LAST_SHARED + 1;
  172. public static final int REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM = REQUEST_CODE__LAST_SHARED + 2;
  173. public static final int REQUEST_CODE__MOVE_FILES = REQUEST_CODE__LAST_SHARED + 3;
  174. public static final int REQUEST_CODE__COPY_FILES = REQUEST_CODE__LAST_SHARED + 4;
  175. public static final int REQUEST_CODE__UPLOAD_FROM_CAMERA = REQUEST_CODE__LAST_SHARED + 5;
  176. protected static final long DELAY_TO_REQUEST_REFRESH_OPERATION_LATER = DELAY_TO_REQUEST_OPERATIONS_LATER + 350;
  177. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  178. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  179. public static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  180. public static final String TEXT_PREVIEW = "TEXT_PREVIEW";
  181. private OCFile mWaitingToPreview;
  182. private boolean mSyncInProgress;
  183. private OCFile mWaitingToSend;
  184. private Collection<MenuItem> mDrawerMenuItemstoShowHideList;
  185. private MediaServiceBinder mMediaServiceBinder;
  186. private MediaServiceConnection mMediaServiceConnection;
  187. public static final String KEY_IS_SEARCH_OPEN = "IS_SEARCH_OPEN";
  188. public static final String KEY_SEARCH_QUERY = "SEARCH_QUERY";
  189. private String searchQuery = "";
  190. private boolean searchOpen;
  191. private SearchView searchView;
  192. @Inject
  193. AppPreferences preferences;
  194. @Inject
  195. AppInfo appInfo;
  196. @Inject
  197. ConnectivityService connectivityService;
  198. @Override
  199. protected void onCreate(Bundle savedInstanceState) {
  200. Log_OC.v(TAG, "onCreate() start");
  201. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
  202. // Set the default theme to replace the launch screen theme.
  203. setTheme(R.style.Theme_ownCloud_Toolbar_Drawer);
  204. /// Load of saved instance state
  205. if (savedInstanceState != null) {
  206. mWaitingToPreview = savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  207. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  208. mWaitingToSend = savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
  209. searchQuery = savedInstanceState.getString(KEY_SEARCH_QUERY);
  210. searchOpen = savedInstanceState.getBoolean(FileDisplayActivity.KEY_IS_SEARCH_OPEN, false);
  211. } else {
  212. mWaitingToPreview = null;
  213. mSyncInProgress = false;
  214. mWaitingToSend = null;
  215. }
  216. /// USER INTERFACE
  217. // Inflate and set the layout view
  218. setContentView(R.layout.files);
  219. // setup toolbar
  220. setupToolbar();
  221. // setup drawer
  222. if (MainApp.isOnlyOnDevice()) {
  223. setupDrawer(R.id.nav_on_device);
  224. } else {
  225. setupDrawer(R.id.nav_all_files);
  226. }
  227. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  228. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  229. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  230. // Action bar setup
  231. getSupportActionBar().setHomeButtonEnabled(true);
  232. // Init Fragment without UI to retain AsyncTask across configuration changes
  233. FragmentManager fm = getSupportFragmentManager();
  234. TaskRetainerFragment taskRetainerFragment =
  235. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  236. if (taskRetainerFragment == null) {
  237. taskRetainerFragment = new TaskRetainerFragment();
  238. fm.beginTransaction()
  239. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  240. } // else, Fragment already created and retained across configuration change
  241. if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
  242. handleOpenFileViaIntent(getIntent());
  243. }
  244. }
  245. @Override
  246. protected void onPostCreate(Bundle savedInstanceState) {
  247. super.onPostCreate(savedInstanceState);
  248. if (!PermissionUtil.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  249. // Check if we should show an explanation
  250. if (PermissionUtil.shouldShowRequestPermissionRationale(this,
  251. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  252. // Show explanation to the user and then request permission
  253. Snackbar snackbar = Snackbar.make(findViewById(R.id.ListLayout), R.string.permission_storage_access,
  254. Snackbar.LENGTH_INDEFINITE)
  255. .setAction(R.string.common_ok, new View.OnClickListener() {
  256. @Override
  257. public void onClick(View v) {
  258. PermissionUtil.requestWriteExternalStoreagePermission(FileDisplayActivity.this);
  259. }
  260. });
  261. ThemeUtils.colorSnackbar(this, snackbar);
  262. snackbar.show();
  263. } else {
  264. // No explanation needed, request the permission.
  265. PermissionUtil.requestWriteExternalStoreagePermission(this);
  266. }
  267. }
  268. if (getIntent().getParcelableExtra(OCFileListFragment.SEARCH_EVENT) != null) {
  269. switchToSearchFragment(savedInstanceState);
  270. int menuId = getIntent().getIntExtra(DRAWER_MENU_ID, -1);
  271. if (menuId != -1) {
  272. setupDrawer(menuId);
  273. }
  274. } else {
  275. createMinFragments(savedInstanceState);
  276. refreshList(true);
  277. }
  278. setIndeterminate(mSyncInProgress);
  279. // always AFTER setContentView(...) in onCreate(); to work around bug in its implementation
  280. upgradeNotificationForInstantUpload();
  281. checkOutdatedServer();
  282. }
  283. private Activity getActivity() {
  284. return this;
  285. }
  286. /**
  287. * For Android 7+.
  288. * Opens a pop up info for the new instant upload and disabled the old instant upload.
  289. */
  290. private void upgradeNotificationForInstantUpload() {
  291. // check for Android 6+ if legacy instant upload is activated --> disable + show info
  292. if (preferences.instantPictureUploadEnabled() || preferences.instantVideoUploadEnabled()) {
  293. preferences.removeLegacyPreferences();
  294. // show info pop-up
  295. new AlertDialog.Builder(this, R.style.Theme_ownCloud_Dialog)
  296. .setTitle(R.string.drawer_synced_folders)
  297. .setMessage(R.string.synced_folders_new_info)
  298. .setPositiveButton(R.string.drawer_open, new DialogInterface.OnClickListener() {
  299. public void onClick(DialogInterface dialog, int which) {
  300. // show instant upload
  301. Intent syncedFoldersIntent = new Intent(getApplicationContext(), SyncedFoldersActivity.class);
  302. dialog.dismiss();
  303. startActivity(syncedFoldersIntent);
  304. }
  305. })
  306. .setNegativeButton(R.string.drawer_close, new DialogInterface.OnClickListener() {
  307. public void onClick(DialogInterface dialog, int which) {
  308. dialog.dismiss();
  309. }
  310. })
  311. .setIcon(R.drawable.nav_synced_folders)
  312. .show();
  313. }
  314. }
  315. private void checkOutdatedServer() {
  316. Account account = getAccount();
  317. if (getResources().getBoolean(R.bool.show_outdated_server_warning) && account != null) {
  318. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  319. int lastSeenVersion = arbitraryDataProvider.getIntegerValue(account,
  320. AppPreferencesImpl.AUTO_PREF__LAST_SEEN_VERSION_CODE);
  321. if (BuildConfig.VERSION_CODE > lastSeenVersion) {
  322. OwnCloudVersion serverVersion = AccountUtils.getServerVersionForAccount(account, this);
  323. if (serverVersion == null) {
  324. serverVersion = getCapabilities().getVersion();
  325. }
  326. if (MainApp.OUTDATED_SERVER_VERSION.compareTo(serverVersion) >= 0) {
  327. DisplayUtils.showServerOutdatedSnackbar(this);
  328. }
  329. arbitraryDataProvider.storeOrUpdateKeyValue(
  330. account.name,
  331. AppPreferencesImpl.AUTO_PREF__LAST_SEEN_VERSION_CODE,
  332. appInfo.getFormattedVersionCode()
  333. );
  334. }
  335. }
  336. }
  337. @Override
  338. public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
  339. @NonNull int[] grantResults) {
  340. switch (requestCode) {
  341. case PermissionUtil.PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
  342. // If request is cancelled, result arrays are empty.
  343. if (grantResults.length > 0
  344. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  345. // permission was granted
  346. EventBus.getDefault().post(new TokenPushEvent());
  347. refreshList(true);
  348. // toggle on is save since this is the only scenario this code gets accessed
  349. } else {
  350. // permission denied --> do nothing
  351. return;
  352. }
  353. return;
  354. }
  355. case PermissionUtil.PERMISSIONS_CAMERA: {
  356. // If request is cancelled, result arrays are empty.
  357. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  358. // permission was granted
  359. getFileOperationsHelper()
  360. .uploadFromCamera(this, FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA);
  361. } else {
  362. // permission denied
  363. return;
  364. }
  365. return;
  366. }
  367. default:
  368. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  369. }
  370. }
  371. /**
  372. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  373. */
  374. @Override
  375. protected void onAccountSet(boolean stateWasRecovered) {
  376. super.onAccountSet(stateWasRecovered);
  377. if (getAccount() != null) {
  378. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  379. // current Account
  380. OCFile file = getFile();
  381. // get parent from path
  382. String parentPath = "";
  383. if (file != null) {
  384. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  385. // upload in progress - right now, files are not inserted in the local
  386. // cache until the upload is successful get parent from path
  387. parentPath = file.getRemotePath().substring(0,
  388. file.getRemotePath().lastIndexOf(file.getFileName()));
  389. if (getStorageManager().getFileByPath(parentPath) == null) {
  390. file = null; // not able to know the directory where the file is uploading
  391. }
  392. } else {
  393. file = getStorageManager().getFileByPath(file.getRemotePath());
  394. // currentDir = null if not in the current Account
  395. }
  396. }
  397. if (file == null) {
  398. // fall back to root folder
  399. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  400. }
  401. setFile(file);
  402. if (mAccountWasSet) {
  403. setAccountInDrawer(getAccount());
  404. setupDrawer();
  405. }
  406. if (!stateWasRecovered) {
  407. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  408. initFragmentsWithFile();
  409. if (file.isFolder() && TextUtils.isEmpty(searchQuery)) {
  410. startSyncFolderOperation(file, false);
  411. }
  412. } else {
  413. updateFragmentsVisibility(!file.isFolder());
  414. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  415. }
  416. }
  417. }
  418. private void switchToSearchFragment(Bundle savedInstanceState) {
  419. if (savedInstanceState == null) {
  420. OCFileListFragment listOfFiles = new OCFileListFragment();
  421. Bundle args = new Bundle();
  422. args.putParcelable(OCFileListFragment.SEARCH_EVENT,
  423. getIntent().getParcelableExtra(OCFileListFragment.SEARCH_EVENT));
  424. args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
  425. listOfFiles.setArguments(args);
  426. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  427. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  428. transaction.commit();
  429. } else {
  430. getSupportFragmentManager().findFragmentByTag(TAG_LIST_OF_FILES);
  431. }
  432. }
  433. private void createMinFragments(Bundle savedInstanceState) {
  434. if (savedInstanceState == null) {
  435. OCFileListFragment listOfFiles = new OCFileListFragment();
  436. Bundle args = new Bundle();
  437. args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
  438. listOfFiles.setArguments(args);
  439. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  440. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  441. transaction.commit();
  442. } else {
  443. getSupportFragmentManager().findFragmentByTag(TAG_LIST_OF_FILES);
  444. }
  445. }
  446. private void initFragmentsWithFile() {
  447. if (getAccount() != null && getFile() != null) {
  448. /// First fragment
  449. OCFileListFragment listOfFiles = getListOfFilesFragment();
  450. if (listOfFiles != null && TextUtils.isEmpty(searchQuery)) {
  451. listOfFiles.listDirectory(getCurrentDir(), getFile(), MainApp.isOnlyOnDevice(), false);
  452. } else {
  453. Log_OC.e(TAG, "Still have a chance to lose the initialization of list fragment >(");
  454. }
  455. /// Second fragment
  456. if (mDualPane) {
  457. OCFile file = getFile();
  458. Fragment secondFragment = getSecondFragment();
  459. if (secondFragment == null) {
  460. secondFragment = chooseInitialSecondFragment(file);
  461. }
  462. if (secondFragment != null) {
  463. setSecondFragment(secondFragment);
  464. updateFragmentsVisibility(true);
  465. updateActionBarTitleAndHomeButton(file);
  466. } else {
  467. cleanSecondFragment();
  468. if (file.isDown() && MimeTypeUtil.isVCard(file.getMimeType())) {
  469. startContactListFragment(file);
  470. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  471. startTextPreview(file, false);
  472. }
  473. }
  474. } else {
  475. cleanSecondFragment();
  476. }
  477. } else {
  478. Log_OC.e(TAG, "initFragments() called with invalid NULLs!");
  479. if (getAccount() == null) {
  480. Log_OC.e(TAG, "\t account is NULL");
  481. }
  482. if (getFile() == null) {
  483. Log_OC.e(TAG, "\t file is NULL");
  484. }
  485. }
  486. }
  487. //Is called with the flag FLAG_ACTIVITY_SINGLE_TOP and set the new file and intent
  488. @Override
  489. protected void onNewIntent(Intent intent) {
  490. super.onNewIntent(intent);
  491. if (ACTION_DETAILS.equalsIgnoreCase(intent.getAction())) {
  492. setIntent(intent);
  493. setFile(intent.getParcelableExtra(EXTRA_FILE));
  494. } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  495. handleOpenFileViaIntent(intent);
  496. } else if (RESTART.equals(intent.getAction())) {
  497. finish();
  498. startActivity(intent);
  499. } else // Verify the action and get the query
  500. if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
  501. String query = intent.getStringExtra(SearchManager.QUERY);
  502. setIntent(intent);
  503. Log_OC.w(TAG, "Ignored Intent requesting to query for " + query);
  504. } else if (UsersAndGroupsSearchProvider.ACTION_SHARE_WITH.equals(intent.getAction())) {
  505. Uri data = intent.getData();
  506. String dataString = intent.getDataString();
  507. String shareWith = dataString.substring(dataString.lastIndexOf('/') + 1);
  508. ArrayList<String> existingSharees = new ArrayList<>();
  509. for (OCShare share : getStorageManager().getSharesWithForAFile(getFile().getRemotePath(),
  510. getAccount().name)) {
  511. existingSharees.add(share.getShareType() + "_" + share.getShareWith());
  512. }
  513. String dataAuthority = data.getAuthority();
  514. ShareType shareType = UsersAndGroupsSearchProvider.getShareType(dataAuthority);
  515. if (!existingSharees.contains(shareType + "_" + shareWith)) {
  516. doShareWith(shareWith, shareType);
  517. }
  518. } else {
  519. Log_OC.e(TAG, String.format(Locale.US, "Unexpected intent %s", intent));
  520. }
  521. }
  522. private void doShareWith(String shareeName, ShareType shareType) {
  523. getFileOperationsHelper().shareFileWithSharee(getFile(), shareeName, shareType,
  524. getAppropriatePermissions(shareType));
  525. }
  526. private int getAppropriatePermissions(ShareType shareType) {
  527. // check if the Share is FEDERATED
  528. boolean isFederated = ShareType.FEDERATED.equals(shareType);
  529. if (getFile().isSharedWithMe()) {
  530. return OCShare.READ_PERMISSION_FLAG; // minimum permissions
  531. } else if (isFederated) {
  532. return getFile().isFolder() ? OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 :
  533. OCShare.FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9;
  534. } else {
  535. return getFile().isFolder() ? OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER :
  536. OCShare.MAXIMUM_PERMISSIONS_FOR_FILE;
  537. }
  538. }
  539. private Fragment chooseInitialSecondFragment(OCFile file) {
  540. Fragment secondFragment = null;
  541. if (file != null && !file.isFolder()) {
  542. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)) {
  543. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  544. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  545. secondFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  546. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  547. secondFragment = null;
  548. } else {
  549. secondFragment = FileDetailFragment.newInstance(file, getAccount());
  550. }
  551. }
  552. return secondFragment;
  553. }
  554. /**
  555. * Replaces the second fragment managed by the activity with the received as
  556. * a parameter.
  557. *
  558. * Assumes never will be more than two fragments managed at the same time.
  559. *
  560. * @param fragment New second Fragment to set.
  561. */
  562. private void setSecondFragment(Fragment fragment) {
  563. if (searchView != null) {
  564. searchView.post(new Runnable() {
  565. @Override
  566. public void run() {
  567. searchView.setQuery(searchQuery, true);
  568. }
  569. });
  570. }
  571. setDrawerIndicatorEnabled(false);
  572. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  573. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  574. transaction.commit();
  575. }
  576. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  577. if (mDualPane) {
  578. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  579. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  580. }
  581. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  582. mRightFragmentContainer.setVisibility(View.VISIBLE);
  583. }
  584. } else if (existsSecondFragment) {
  585. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  586. mLeftFragmentContainer.setVisibility(View.GONE);
  587. }
  588. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  589. mRightFragmentContainer.setVisibility(View.VISIBLE);
  590. }
  591. } else {
  592. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  593. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  594. }
  595. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  596. mRightFragmentContainer.setVisibility(View.GONE);
  597. }
  598. }
  599. }
  600. public OCFileListFragment getListOfFilesFragment() {
  601. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  602. FileDisplayActivity.TAG_LIST_OF_FILES);
  603. if (listOfFiles != null) {
  604. return (OCFileListFragment) listOfFiles;
  605. }
  606. Log_OC.e(TAG, "Access to unexisting list of files fragment!!");
  607. return null;
  608. }
  609. public FileFragment getSecondFragment() {
  610. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  611. if (second != null) {
  612. return (FileFragment) second;
  613. }
  614. return null;
  615. }
  616. protected void cleanSecondFragment() {
  617. Fragment second = getSecondFragment();
  618. if (second != null) {
  619. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  620. tr.remove(second);
  621. tr.commit();
  622. }
  623. updateFragmentsVisibility(false);
  624. updateActionBarTitleAndHomeButton(null);
  625. }
  626. public void refreshListOfFilesFragment(boolean fromSearch) {
  627. OCFileListFragment fileListFragment = getListOfFilesFragment();
  628. if (fileListFragment != null) {
  629. fileListFragment.listDirectory(MainApp.isOnlyOnDevice(), fromSearch);
  630. setupToolbar();
  631. }
  632. }
  633. public void resetSearchView() {
  634. OCFileListFragment fileListFragment = getListOfFilesFragment();
  635. if (fileListFragment != null) {
  636. fileListFragment.setSearchFragment(false);
  637. }
  638. }
  639. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  640. boolean success) {
  641. FileFragment secondFragment = getSecondFragment();
  642. boolean waitedPreview = mWaitingToPreview != null
  643. && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath);
  644. if (secondFragment instanceof FileDetailFragment) {
  645. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  646. OCFile fileInFragment = detailsFragment.getFile();
  647. if (fileInFragment != null &&
  648. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  649. // the user browsed to other file ; forget the automatic preview
  650. mWaitingToPreview = null;
  651. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  652. // grant that the right panel updates the progress bar
  653. detailsFragment.listenForTransferProgress();
  654. detailsFragment.updateFileDetails(true, false);
  655. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  656. // update the right panel
  657. boolean detailsFragmentChanged = false;
  658. if (waitedPreview) {
  659. if (success) {
  660. // update the file from database, for the local storage path
  661. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  662. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  663. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  664. .isMediaStreamingSupported();
  665. startMediaPreview(mWaitingToPreview, 0, true, true, streaming);
  666. detailsFragmentChanged = true;
  667. } else if (MimeTypeUtil.isVCard(mWaitingToPreview.getMimeType())) {
  668. startContactListFragment(mWaitingToPreview);
  669. detailsFragmentChanged = true;
  670. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  671. startTextPreview(mWaitingToPreview, true);
  672. detailsFragmentChanged = true;
  673. } else {
  674. getFileOperationsHelper().openFile(mWaitingToPreview);
  675. }
  676. }
  677. mWaitingToPreview = null;
  678. }
  679. if (!detailsFragmentChanged) {
  680. detailsFragment.updateFileDetails(false, success);
  681. }
  682. }
  683. }
  684. }
  685. @Override
  686. public boolean onPrepareOptionsMenu(Menu menu) {
  687. boolean drawerOpen = isDrawerOpen();
  688. for (MenuItem menuItem : mDrawerMenuItemstoShowHideList) {
  689. menuItem.setVisible(!drawerOpen);
  690. }
  691. return super.onPrepareOptionsMenu(menu);
  692. }
  693. @Override
  694. public boolean onCreateOptionsMenu(Menu menu) {
  695. MenuInflater inflater = getMenuInflater();
  696. inflater.inflate(R.menu.main_menu, menu);
  697. menu.findItem(R.id.action_create_dir).setVisible(false);
  698. menu.findItem(R.id.action_select_all).setVisible(false);
  699. MenuItem searchMenuItem = menu.findItem(R.id.action_search);
  700. searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
  701. searchMenuItem.setVisible(false);
  702. // hacky as no default way is provided
  703. int fontColor = ThemeUtils.fontColor(this);
  704. EditText editText = searchView.findViewById(androidx.appcompat.R.id.search_src_text);
  705. editText.setHintTextColor(fontColor);
  706. editText.setTextColor(fontColor);
  707. ImageView searchClose = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
  708. searchClose.setColorFilter(ThemeUtils.fontColor(this));
  709. // populate list of menu items to show/hide when drawer is opened/closed
  710. mDrawerMenuItemstoShowHideList = new ArrayList<>(4);
  711. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sort));
  712. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sync_account));
  713. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_switch_view));
  714. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_search));
  715. //focus the SearchView
  716. if (!TextUtils.isEmpty(searchQuery)) {
  717. searchView.post(new Runnable() {
  718. @Override
  719. public void run() {
  720. searchView.setIconified(false);
  721. searchView.setQuery(searchQuery, true);
  722. searchView.clearFocus();
  723. }
  724. });
  725. }
  726. final View mSearchEditFrame = searchView
  727. .findViewById(androidx.appcompat.R.id.search_edit_frame);
  728. searchView.setOnCloseListener(new SearchView.OnCloseListener() {
  729. @Override
  730. public boolean onClose() {
  731. if (TextUtils.isEmpty(searchView.getQuery().toString())) {
  732. searchView.onActionViewCollapsed();
  733. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable()); // order matters
  734. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  735. mDrawerToggle.syncState();
  736. if (getListOfFilesFragment() != null) {
  737. getListOfFilesFragment().setSearchFragment(false);
  738. getListOfFilesFragment().refreshDirectory();
  739. }
  740. } else {
  741. searchView.post(new Runnable() {
  742. @Override
  743. public void run() {
  744. searchView.setQuery("", true);
  745. }
  746. });
  747. }
  748. return true;
  749. }
  750. });
  751. ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
  752. vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  753. int oldVisibility = -1;
  754. @Override
  755. public void onGlobalLayout() {
  756. int currentVisibility = mSearchEditFrame.getVisibility();
  757. if (currentVisibility != oldVisibility) {
  758. if (currentVisibility == View.VISIBLE) {
  759. setDrawerIndicatorEnabled(false);
  760. }
  761. oldVisibility = currentVisibility;
  762. }
  763. }
  764. });
  765. return super.onCreateOptionsMenu(menu);
  766. }
  767. @Override
  768. public boolean onOptionsItemSelected(MenuItem item) {
  769. boolean retval = true;
  770. switch (item.getItemId()) {
  771. case R.id.action_sync_account: {
  772. startSynchronization();
  773. break;
  774. }
  775. case android.R.id.home: {
  776. FileFragment second = getSecondFragment();
  777. OCFile currentDir = getCurrentDir();
  778. if (isDrawerOpen()) {
  779. closeDrawer();
  780. } else if ((currentDir != null && currentDir.getParentId() != 0) ||
  781. (second != null && second.getFile() != null) || isSearchOpen()) {
  782. onBackPressed();
  783. } else {
  784. openDrawer();
  785. }
  786. break;
  787. }
  788. case R.id.action_sort: {
  789. FragmentManager fm = getSupportFragmentManager();
  790. FragmentTransaction ft = fm.beginTransaction();
  791. ft.addToBackStack(null);
  792. SortingOrderDialogFragment mSortingOrderDialogFragment = SortingOrderDialogFragment.newInstance(
  793. preferences.getSortOrderByFolder(getListOfFilesFragment().getCurrentFile()));
  794. mSortingOrderDialogFragment.show(ft, SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT);
  795. break;
  796. }
  797. case R.id.action_switch_view: {
  798. if (isGridView()) {
  799. item.setTitle(getString(R.string.action_switch_grid_view));
  800. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_module));
  801. getListOfFilesFragment().setListAsPreferred();
  802. } else {
  803. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  804. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_list));
  805. getListOfFilesFragment().setGridAsPreferred();
  806. }
  807. break;
  808. }
  809. case R.id.action_select_all: {
  810. getListOfFilesFragment().selectAllFiles(true);
  811. break;
  812. }
  813. default:
  814. retval = super.onOptionsItemSelected(item);
  815. break;
  816. }
  817. return retval;
  818. }
  819. private void startSynchronization() {
  820. Log_OC.d(TAG, "Got to start sync");
  821. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  822. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  823. ContentResolver.cancelSync(null, MainApp.getAuthority());
  824. // cancel the current synchronizations of any ownCloud account
  825. Bundle bundle = new Bundle();
  826. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  827. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  828. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  829. MainApp.getAuthority());
  830. ContentResolver.requestSync(
  831. getAccount(),
  832. MainApp.getAuthority(), bundle);
  833. } else {
  834. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  835. MainApp.getAuthority() + " with new API");
  836. SyncRequest.Builder builder = new SyncRequest.Builder();
  837. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  838. builder.setExpedited(true);
  839. builder.setManual(true);
  840. builder.syncOnce();
  841. // Fix bug in Android Lollipop when you click on refresh the whole account
  842. Bundle extras = new Bundle();
  843. builder.setExtras(extras);
  844. SyncRequest request = builder.build();
  845. ContentResolver.requestSync(request);
  846. }
  847. }
  848. /**
  849. * Called, when the user selected something for uploading
  850. */
  851. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  852. @Override
  853. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  854. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS &&
  855. (resultCode == RESULT_OK ||
  856. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  857. requestUploadOfContentFromApps(data, resultCode);
  858. } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM &&
  859. (resultCode == RESULT_OK ||
  860. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE ||
  861. resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING ||
  862. resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) {
  863. requestUploadOfFilesFromFileSystem(data, resultCode);
  864. } else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA &&
  865. (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  866. new CheckAvailableSpaceTask(new CheckAvailableSpaceTask.CheckAvailableSpaceListener() {
  867. @Override
  868. public void onCheckAvailableSpaceStart() {
  869. Log_OC.d(this, "onCheckAvailableSpaceStart");
  870. }
  871. @Override
  872. public void onCheckAvailableSpaceFinish(boolean hasEnoughSpaceAvailable, String... filesToUpload) {
  873. Log_OC.d(this, "onCheckAvailableSpaceFinish");
  874. if (hasEnoughSpaceAvailable) {
  875. File file = new File(filesToUpload[0]);
  876. File renamedFile = new File(file.getParent() + PATH_SEPARATOR + FileOperationsHelper.getCapturedImageName());
  877. if (!file.renameTo(renamedFile)) {
  878. DisplayUtils.showSnackMessage(getActivity(), "Fail to upload taken image!");
  879. return;
  880. }
  881. requestUploadOfFilesFromFileSystem(new String[]{renamedFile.getAbsolutePath()},
  882. FileUploader.LOCAL_BEHAVIOUR_MOVE);
  883. }
  884. }
  885. }, new String[]{FileOperationsHelper.createImageFile(getActivity()).getAbsolutePath()}).execute();
  886. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  887. exitSelectionMode();
  888. final Intent fData = data;
  889. getHandler().postDelayed(
  890. new Runnable() {
  891. @Override
  892. public void run() {
  893. requestMoveOperation(fData);
  894. }
  895. },
  896. DELAY_TO_REQUEST_OPERATIONS_LATER
  897. );
  898. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  899. exitSelectionMode();
  900. final Intent fData = data;
  901. getHandler().postDelayed(
  902. new Runnable() {
  903. @Override
  904. public void run() {
  905. requestCopyOperation(fData);
  906. }
  907. },
  908. DELAY_TO_REQUEST_OPERATIONS_LATER
  909. );
  910. } else {
  911. super.onActivityResult(requestCode, resultCode, data);
  912. }
  913. }
  914. private void exitSelectionMode() {
  915. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  916. if (ocFileListFragment != null) {
  917. ocFileListFragment.exitSelectionMode();
  918. }
  919. }
  920. private void requestUploadOfFilesFromFileSystem(Intent data, int resultCode) {
  921. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  922. int behaviour;
  923. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) {
  924. behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE;
  925. } else {
  926. behaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
  927. }
  928. requestUploadOfFilesFromFileSystem(filePaths, behaviour);
  929. }
  930. private void requestUploadOfFilesFromFileSystem(String[] filePaths, int resultCode) {
  931. if (filePaths != null) {
  932. String[] remotePaths = new String[filePaths.length];
  933. String remotePathBase = getCurrentDir().getRemotePath();
  934. for (int j = 0; j < remotePaths.length; j++) {
  935. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  936. }
  937. int behaviour;
  938. switch (resultCode) {
  939. case UploadFilesActivity.RESULT_OK_AND_MOVE:
  940. behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE;
  941. break;
  942. case UploadFilesActivity.RESULT_OK_AND_DELETE:
  943. behaviour = FileUploader.LOCAL_BEHAVIOUR_DELETE;
  944. break;
  945. case UploadFilesActivity.RESULT_OK_AND_DO_NOTHING:
  946. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  947. break;
  948. default:
  949. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  950. break;
  951. }
  952. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  953. requester.uploadNewFile(
  954. this,
  955. getAccount(),
  956. filePaths,
  957. remotePaths,
  958. null, // MIME type will be detected from file name
  959. behaviour,
  960. false, // do not create parent folder if not existent
  961. UploadFileOperation.CREATED_BY_USER,
  962. false,
  963. false
  964. );
  965. } else {
  966. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  967. DisplayUtils.showSnackMessage(this, R.string.filedisplay_no_file_selected);
  968. }
  969. }
  970. private void requestUploadOfContentFromApps(Intent contentIntent, int resultCode) {
  971. ArrayList<Parcelable> streamsToUpload = new ArrayList<>();
  972. //getClipData is only supported on api level 16+, Jelly Bean
  973. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  974. contentIntent.getClipData() != null &&
  975. contentIntent.getClipData().getItemCount() > 0) {
  976. for (int i = 0; i < contentIntent.getClipData().getItemCount(); i++) {
  977. streamsToUpload.add(contentIntent.getClipData().getItemAt(i).getUri());
  978. }
  979. } else {
  980. streamsToUpload.add(contentIntent.getData());
  981. }
  982. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  983. FileUploader.LOCAL_BEHAVIOUR_COPY;
  984. OCFile currentDir = getCurrentDir();
  985. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  986. UriUploader uploader = new UriUploader(
  987. this,
  988. streamsToUpload,
  989. remotePath,
  990. getAccount(),
  991. behaviour,
  992. false, // Not show waiting dialog while file is being copied from private storage
  993. null // Not needed copy temp task listener
  994. );
  995. uploader.uploadUris();
  996. }
  997. /**
  998. * Request the operation for moving the file/folder from one path to another
  999. *
  1000. * @param data Intent received
  1001. */
  1002. private void requestMoveOperation(Intent data) {
  1003. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  1004. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  1005. getFileOperationsHelper().moveFiles(files, folderToMoveAt);
  1006. }
  1007. /**
  1008. * Request the operation for copying the file/folder from one path to another
  1009. *
  1010. * @param data Intent received
  1011. */
  1012. private void requestCopyOperation(Intent data) {
  1013. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  1014. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  1015. getFileOperationsHelper().copyFiles(files, folderToMoveAt);
  1016. }
  1017. private boolean isSearchOpen() {
  1018. if (searchView == null) {
  1019. return false;
  1020. } else {
  1021. View mSearchEditFrame = searchView.findViewById(androidx.appcompat.R.id.search_edit_frame);
  1022. return mSearchEditFrame != null && mSearchEditFrame.getVisibility() == View.VISIBLE;
  1023. }
  1024. }
  1025. private void revertBottomNavigationBarToAllFiles() {
  1026. if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
  1027. BottomNavigationView bottomNavigationView = getListOfFilesFragment().getView()
  1028. .findViewById(R.id.bottom_navigation_view);
  1029. if (bottomNavigationView.getMenu().findItem(R.id.nav_bar_settings).isChecked()) {
  1030. bottomNavigationView.getMenu().findItem(R.id.nav_bar_files).setChecked(true);
  1031. }
  1032. }
  1033. }
  1034. @Override
  1035. public void onBackPressed() {
  1036. boolean isDrawerOpen = isDrawerOpen();
  1037. boolean isSearchOpen = isSearchOpen();
  1038. /*
  1039. * BackPressed priority/hierarchy:
  1040. * 1. close search view if opened
  1041. * 2. close drawer if opened
  1042. * 3. close FAB if open (only if drawer isn't open)
  1043. * 4. navigate up (only if drawer and FAB aren't open)
  1044. */
  1045. if (isSearchOpen && searchView != null) {
  1046. searchView.setQuery("", true);
  1047. searchView.onActionViewCollapsed();
  1048. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  1049. } else if (isDrawerOpen) {
  1050. // close drawer first
  1051. super.onBackPressed();
  1052. } else {
  1053. // all closed
  1054. //if PreviewImageActivity called this activity and mDualPane==false then calls PreviewImageActivity again
  1055. if (ACTION_DETAILS.equalsIgnoreCase(getIntent().getAction()) && !mDualPane) {
  1056. getIntent().setAction(null);
  1057. getIntent().putExtra(EXTRA_FILE, (OCFile) null);
  1058. startImagePreview(getFile(), false);
  1059. }
  1060. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1061. if (mDualPane || getSecondFragment() == null) {
  1062. OCFile currentDir = getCurrentDir();
  1063. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  1064. finish();
  1065. return;
  1066. }
  1067. if (listOfFiles != null) { // should never be null, indeed
  1068. listOfFiles.onBrowseUp();
  1069. }
  1070. }
  1071. if (listOfFiles != null) { // should never be null, indeed
  1072. setFile(listOfFiles.getCurrentFile());
  1073. }
  1074. cleanSecondFragment();
  1075. }
  1076. }
  1077. @Override
  1078. protected void onSaveInstanceState(Bundle outState) {
  1079. // responsibility of restore is preferred in onCreate() before than in
  1080. // onRestoreInstanceState when there are Fragments involved
  1081. Log_OC.v(TAG, "onSaveInstanceState() start");
  1082. super.onSaveInstanceState(outState);
  1083. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  1084. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  1085. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  1086. // mRefreshSharesInProgress);
  1087. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  1088. if (searchView != null) {
  1089. outState.putBoolean(KEY_IS_SEARCH_OPEN, !searchView.isIconified());
  1090. }
  1091. outState.putString(KEY_SEARCH_QUERY, searchQuery);
  1092. Log_OC.v(TAG, "onSaveInstanceState() end");
  1093. }
  1094. @Override
  1095. protected void onResume() {
  1096. Log_OC.v(TAG, "onResume() start");
  1097. super.onResume();
  1098. OCFile startFile = null;
  1099. if (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) != null) {
  1100. startFile = getIntent().getParcelableExtra(EXTRA_FILE);
  1101. setFile(startFile);
  1102. }
  1103. revertBottomNavigationBarToAllFiles();
  1104. // refresh list of files
  1105. if (searchView != null && !TextUtils.isEmpty(searchQuery)) {
  1106. searchView.setQuery(searchQuery, false);
  1107. } else if (getListOfFilesFragment() != null && !getListOfFilesFragment().isSearchFragment()
  1108. && startFile == null) {
  1109. refreshListOfFilesFragment(false);
  1110. } else {
  1111. getListOfFilesFragment().listDirectory(startFile, false, false);
  1112. updateActionBarTitleAndHomeButton(startFile);
  1113. }
  1114. // Listen for sync messages
  1115. if (getListOfFilesFragment() != null && !getListOfFilesFragment().isSearchFragment()) {
  1116. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  1117. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  1118. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  1119. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  1120. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  1121. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  1122. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  1123. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  1124. // syncIntentFilter);
  1125. }
  1126. // Listen for upload messages
  1127. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  1128. mUploadFinishReceiver = new UploadFinishReceiver();
  1129. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  1130. // Listen for download messages
  1131. IntentFilter downloadIntentFilter = new IntentFilter(
  1132. FileDownloader.getDownloadAddedMessage());
  1133. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  1134. mDownloadFinishReceiver = new DownloadFinishReceiver();
  1135. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  1136. // setup drawer
  1137. int menuItemId = getIntent().getIntExtra(FileDisplayActivity.DRAWER_MENU_ID, -1);
  1138. if (menuItemId == -1) {
  1139. if (MainApp.isOnlyOnDevice()) {
  1140. setDrawerMenuItemChecked(R.id.nav_on_device);
  1141. } else {
  1142. setDrawerMenuItemChecked(R.id.nav_all_files);
  1143. }
  1144. } else {
  1145. setDrawerMenuItemChecked(menuItemId);
  1146. }
  1147. Log_OC.v(TAG, "onResume() end");
  1148. }
  1149. @Override
  1150. protected void onPause() {
  1151. Log_OC.v(TAG, "onPause() start");
  1152. if (mSyncBroadcastReceiver != null) {
  1153. unregisterReceiver(mSyncBroadcastReceiver);
  1154. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  1155. mSyncBroadcastReceiver = null;
  1156. }
  1157. if (mUploadFinishReceiver != null) {
  1158. unregisterReceiver(mUploadFinishReceiver);
  1159. mUploadFinishReceiver = null;
  1160. }
  1161. if (mDownloadFinishReceiver != null) {
  1162. unregisterReceiver(mDownloadFinishReceiver);
  1163. mDownloadFinishReceiver = null;
  1164. }
  1165. super.onPause();
  1166. Log_OC.v(TAG, "onPause() end");
  1167. }
  1168. @Override
  1169. public void onSortingOrderChosen(FileSortOrder selection) {
  1170. getListOfFilesFragment().sortFiles(selection);
  1171. }
  1172. @Override
  1173. public void downloadFile(OCFile file, String packageName, String activityName) {
  1174. startDownloadForSending(file, OCFileListFragment.DOWNLOAD_SEND, packageName, activityName);
  1175. }
  1176. private class SyncBroadcastReceiver extends BroadcastReceiver {
  1177. /**
  1178. * {@link BroadcastReceiver} to enable syncing feedback in UI
  1179. */
  1180. @Override
  1181. public void onReceive(Context context, Intent intent) {
  1182. try {
  1183. String event = intent.getAction();
  1184. Log_OC.d(TAG, "Received broadcast " + event);
  1185. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  1186. String synchFolderRemotePath =
  1187. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  1188. RemoteOperationResult synchResult = (RemoteOperationResult)
  1189. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1190. boolean sameAccount = getAccount() != null &&
  1191. accountName.equals(getAccount().name) && getStorageManager() != null;
  1192. if (sameAccount) {
  1193. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  1194. mSyncInProgress = true;
  1195. } else {
  1196. OCFile currentFile = (getFile() == null) ? null :
  1197. getStorageManager().getFileByPath(getFile().getRemotePath());
  1198. OCFile currentDir = (getCurrentDir() == null) ? null :
  1199. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  1200. if (currentDir == null) {
  1201. // current folder was removed from the server
  1202. DisplayUtils.showSnackMessage(
  1203. getActivity(),
  1204. R.string.sync_current_folder_was_removed,
  1205. synchFolderRemotePath
  1206. );
  1207. browseToRoot();
  1208. } else {
  1209. if (currentFile == null && !getFile().isFolder()) {
  1210. // currently selected file was removed in the server, and now we
  1211. // know it
  1212. cleanSecondFragment();
  1213. currentFile = currentDir;
  1214. }
  1215. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  1216. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1217. if (fileListFragment != null) {
  1218. fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false);
  1219. }
  1220. }
  1221. setFile(currentFile);
  1222. }
  1223. mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  1224. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
  1225. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) &&
  1226. synchResult != null) {
  1227. if (synchResult.isSuccess()) {
  1228. hideInfoBox();
  1229. } else {
  1230. // TODO refactor and make common
  1231. if (checkForRemoteOperationError(synchResult)) {
  1232. requestCredentialsUpdate(context);
  1233. } else {
  1234. switch (synchResult.getCode()) {
  1235. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1236. showUntrustedCertDialog(synchResult);
  1237. break;
  1238. case MAINTENANCE_MODE:
  1239. showInfoBox(R.string.maintenance_mode);
  1240. break;
  1241. case NO_NETWORK_CONNECTION:
  1242. showInfoBox(R.string.offline_mode);
  1243. break;
  1244. case HOST_NOT_AVAILABLE:
  1245. showInfoBox(R.string.host_not_available);
  1246. break;
  1247. default:
  1248. // nothing to do
  1249. break;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. removeStickyBroadcast(intent);
  1255. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1256. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1257. setIndeterminate(mSyncInProgress);
  1258. setBackgroundText();
  1259. }
  1260. }
  1261. if (synchResult != null && synchResult.getCode().equals(
  1262. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  1263. mLastSslUntrustedServerResult = synchResult;
  1264. }
  1265. } catch (RuntimeException e) {
  1266. // avoid app crashes after changing the serial id of RemoteOperationResult
  1267. // in owncloud library with broadcast notifications pending to process
  1268. removeStickyBroadcast(intent);
  1269. try {
  1270. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1271. } catch (RuntimeException re) {
  1272. // we did not send this intent, so ignoring
  1273. Log_OC.i(TAG, "Ignoring error deleting data");
  1274. }
  1275. }
  1276. }
  1277. }
  1278. private boolean checkForRemoteOperationError(RemoteOperationResult syncResult) {
  1279. return ResultCode.UNAUTHORIZED.equals(syncResult.getCode()) ||
  1280. (syncResult.isException() && syncResult.getException()
  1281. instanceof AuthenticatorException);
  1282. }
  1283. /**
  1284. * Show a text message on screen view for notifying user if content is
  1285. * loading or folder is empty
  1286. */
  1287. private void setBackgroundText() {
  1288. final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1289. if (ocFileListFragment != null) {
  1290. if (mSyncInProgress) {
  1291. ocFileListFragment.setEmptyListLoadingMessage();
  1292. } else {
  1293. ocFileListFragment.setEmptyListMessage(ExtendedListFragment.SearchType.NO_SEARCH);
  1294. }
  1295. } else {
  1296. Log_OC.e(TAG, "OCFileListFragment is null");
  1297. }
  1298. }
  1299. /**
  1300. * Once the file upload has finished -> update view
  1301. */
  1302. private class UploadFinishReceiver extends BroadcastReceiver {
  1303. /**
  1304. * Once the file upload has finished -> update view
  1305. *
  1306. * {@link BroadcastReceiver} to enable upload feedback in UI
  1307. */
  1308. @Override
  1309. public void onReceive(Context context, Intent intent) {
  1310. try {
  1311. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1312. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1313. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1314. OCFile currentDir = getCurrentDir();
  1315. boolean isDescendant = currentDir != null && uploadedRemotePath != null &&
  1316. uploadedRemotePath.startsWith(currentDir.getRemotePath());
  1317. if (sameAccount && isDescendant) {
  1318. String linkedToRemotePath =
  1319. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1320. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1321. refreshListOfFilesFragment(false);
  1322. }
  1323. }
  1324. boolean uploadWasFine = intent.getBooleanExtra(
  1325. FileUploader.EXTRA_UPLOAD_RESULT,
  1326. false);
  1327. boolean renamedInUpload = getFile().getRemotePath().
  1328. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1329. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1330. renamedInUpload;
  1331. FileFragment details = getSecondFragment();
  1332. if (sameAccount && sameFile && details instanceof FileDetailFragment) {
  1333. if (uploadWasFine) {
  1334. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1335. } else {
  1336. //TODO remove upload progress bar after upload failed.
  1337. Log_OC.d(TAG, "Remove upload progress bar after upload failed");
  1338. }
  1339. if (renamedInUpload) {
  1340. String newName = new File(uploadedRemotePath).getName();
  1341. DisplayUtils.showSnackMessage(
  1342. getActivity(),
  1343. R.string.filedetails_renamed_in_upload_msg,
  1344. newName
  1345. );
  1346. }
  1347. if (uploadWasFine || getFile().fileExists()) {
  1348. ((FileDetailFragment) details).updateFileDetails(false, true);
  1349. } else {
  1350. cleanSecondFragment();
  1351. }
  1352. // Force the preview if the file is an image or text file
  1353. if (uploadWasFine) {
  1354. OCFile ocFile = getFile();
  1355. if (PreviewImageFragment.canBePreviewed(ocFile)) {
  1356. startImagePreview(getFile(), true);
  1357. } else if (PreviewTextFragment.canBePreviewed(ocFile)) {
  1358. startTextPreview(ocFile, true);
  1359. }
  1360. // TODO what about other kind of previews?
  1361. }
  1362. }
  1363. setIndeterminate(false);
  1364. } finally {
  1365. if (intent != null) {
  1366. removeStickyBroadcast(intent);
  1367. }
  1368. }
  1369. }
  1370. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1371. private boolean isAscendant(String linkedToRemotePath) {
  1372. OCFile currentDir = getCurrentDir();
  1373. return currentDir != null && currentDir.getRemotePath().startsWith(linkedToRemotePath);
  1374. }
  1375. }
  1376. /**
  1377. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1378. *
  1379. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1380. * current folder.
  1381. */
  1382. private class DownloadFinishReceiver extends BroadcastReceiver {
  1383. @Override
  1384. public void onReceive(Context context, Intent intent) {
  1385. try {
  1386. boolean sameAccount = isSameAccount(intent);
  1387. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1388. String downloadBehaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
  1389. boolean isDescendant = isDescendant(downloadedRemotePath);
  1390. if (sameAccount && isDescendant) {
  1391. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1392. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1393. refreshListOfFilesFragment(false);
  1394. }
  1395. refreshSecondFragment(
  1396. intent.getAction(),
  1397. downloadedRemotePath,
  1398. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  1399. }
  1400. if (mWaitingToSend != null) {
  1401. // update file after downloading
  1402. mWaitingToSend = getStorageManager().getFileByRemoteId(mWaitingToSend.getRemoteId());
  1403. if (mWaitingToSend != null && mWaitingToSend.isDown() && downloadBehaviour != null) {
  1404. switch (downloadBehaviour) {
  1405. case OCFileListFragment.DOWNLOAD_SEND:
  1406. String packageName = intent.getStringExtra(SendShareDialog.PACKAGE_NAME);
  1407. String activityName = intent.getStringExtra(SendShareDialog.ACTIVITY_NAME);
  1408. sendDownloadedFile(packageName, activityName);
  1409. break;
  1410. default:
  1411. // do nothing
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. } finally {
  1417. if (intent != null) {
  1418. removeStickyBroadcast(intent);
  1419. }
  1420. }
  1421. }
  1422. private boolean isDescendant(String downloadedRemotePath) {
  1423. OCFile currentDir = getCurrentDir();
  1424. return currentDir != null &&
  1425. downloadedRemotePath != null &&
  1426. downloadedRemotePath.startsWith(currentDir.getRemotePath());
  1427. }
  1428. private boolean isAscendant(String linkedToRemotePath) {
  1429. OCFile currentDir = getCurrentDir();
  1430. return currentDir != null &&
  1431. currentDir.getRemotePath().startsWith(linkedToRemotePath);
  1432. }
  1433. private boolean isSameAccount(Intent intent) {
  1434. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1435. return accountName != null && getAccount() != null && accountName.equals(getAccount().name);
  1436. }
  1437. }
  1438. public void browseToRoot() {
  1439. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1440. if (listOfFiles != null) { // should never be null, indeed
  1441. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1442. listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice(), false);
  1443. setFile(listOfFiles.getCurrentFile());
  1444. startSyncFolderOperation(root, false);
  1445. }
  1446. cleanSecondFragment();
  1447. }
  1448. /**
  1449. * {@inheritDoc}
  1450. * Updates action bar and second fragment, if in dual pane mode.
  1451. */
  1452. @Override
  1453. public void onBrowsedDownTo(OCFile directory) {
  1454. setFile(directory);
  1455. cleanSecondFragment();
  1456. // Sync Folder
  1457. startSyncFolderOperation(directory, false);
  1458. }
  1459. /**
  1460. * Shows the information of the {@link OCFile} received as a
  1461. * parameter in the second fragment.
  1462. *
  1463. * @param file {@link OCFile} whose details will be shown
  1464. */
  1465. @Override
  1466. public void showDetails(OCFile file) {
  1467. showDetails(file, 0);
  1468. }
  1469. /**
  1470. * Shows the information of the {@link OCFile} received as a
  1471. * parameter in the second fragment.
  1472. *
  1473. * @param file {@link OCFile} whose details will be shown
  1474. * @param activeTab the active tab in the details view
  1475. */
  1476. public void showDetails(OCFile file, int activeTab) {
  1477. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount(), activeTab);
  1478. setSecondFragment(detailFragment);
  1479. updateFragmentsVisibility(true);
  1480. updateActionBarTitleAndHomeButton(file);
  1481. setFile(file);
  1482. }
  1483. @Override
  1484. public void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1485. if (chosenFile == null) {
  1486. chosenFile = getFile(); // if no file is passed, current file decides
  1487. }
  1488. if (mDualPane) {
  1489. // in dual pane mode, keep the focus of title an action bar in the current folder
  1490. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1491. } else {
  1492. super.updateActionBarTitleAndHomeButton(chosenFile);
  1493. }
  1494. }
  1495. @Override
  1496. public boolean isDrawerIndicatorAvailable() {
  1497. return isRoot(getCurrentDir());
  1498. }
  1499. @Override
  1500. protected ServiceConnection newTransferenceServiceConnection() {
  1501. return new ListServiceConnection();
  1502. }
  1503. /**
  1504. * Defines callbacks for service binding, passed to bindService()
  1505. */
  1506. private class ListServiceConnection implements ServiceConnection {
  1507. @Override
  1508. public void onServiceConnected(ComponentName component, IBinder service) {
  1509. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1510. Log_OC.d(TAG, "Download service connected");
  1511. mDownloaderBinder = (FileDownloaderBinder) service;
  1512. if (mWaitingToPreview != null && getStorageManager() != null) {
  1513. // update the file
  1514. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1515. if (mWaitingToPreview != null && !mWaitingToPreview.isDown()) {
  1516. requestForDownload();
  1517. }
  1518. }
  1519. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1520. FileUploader.class))) {
  1521. Log_OC.d(TAG, "Upload service connected");
  1522. mUploaderBinder = (FileUploaderBinder) service;
  1523. } else {
  1524. return;
  1525. }
  1526. // a new chance to get the mDownloadBinder through
  1527. // getFileDownloadBinder() - THIS IS A MESS
  1528. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1529. if (listOfFiles != null && (getIntent() == null ||
  1530. (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) == null))) {
  1531. listOfFiles.listDirectory(MainApp.isOnlyOnDevice(), false);
  1532. }
  1533. FileFragment secondFragment = getSecondFragment();
  1534. if (secondFragment instanceof FileDetailFragment) {
  1535. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1536. detailFragment.listenForTransferProgress();
  1537. detailFragment.updateFileDetails(false, false);
  1538. }
  1539. }
  1540. @Override
  1541. public void onServiceDisconnected(ComponentName component) {
  1542. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1543. Log_OC.d(TAG, "Download service disconnected");
  1544. mDownloaderBinder = null;
  1545. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1546. Log_OC.d(TAG, "Upload service disconnected");
  1547. mUploaderBinder = null;
  1548. }
  1549. }
  1550. }
  1551. private MediaServiceConnection newMediaConnection(){
  1552. return new MediaServiceConnection();
  1553. }
  1554. /** Defines callbacks for service binding, passed to bindService() */
  1555. private class MediaServiceConnection implements ServiceConnection {
  1556. @Override
  1557. public void onServiceConnected(ComponentName component, IBinder service) {
  1558. if (component.equals(new ComponentName(FileDisplayActivity.this, MediaService.class))) {
  1559. Log_OC.d(TAG, "Media service connected");
  1560. mMediaServiceBinder = (MediaServiceBinder) service;
  1561. }else {
  1562. return;
  1563. }
  1564. }
  1565. @Override
  1566. public void onServiceDisconnected(ComponentName component) {
  1567. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1568. MediaService.class))) {
  1569. Log_OC.e(TAG, "Media service disconnected");
  1570. mMediaServiceBinder = null;
  1571. }
  1572. }
  1573. }
  1574. /**
  1575. * Updates the view associated to the activity after the finish of some operation over files
  1576. * in the current account.
  1577. *
  1578. * @param operation Removal operation performed.
  1579. * @param result Result of the removal.
  1580. */
  1581. @Override
  1582. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1583. super.onRemoteOperationFinish(operation, result);
  1584. if (operation instanceof RemoveFileOperation) {
  1585. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1586. } else if (operation instanceof RenameFileOperation) {
  1587. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1588. } else if (operation instanceof SynchronizeFileOperation) {
  1589. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1590. } else if (operation instanceof CreateFolderOperation) {
  1591. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1592. } else if (operation instanceof MoveFileOperation) {
  1593. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1594. } else if (operation instanceof CopyFileOperation) {
  1595. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1596. } else if (operation instanceof CreateShareViaLinkOperation) {
  1597. onCreateShareViaLinkOperationFinish((CreateShareViaLinkOperation) operation, result);
  1598. } else if (operation instanceof CreateShareWithShareeOperation) {
  1599. onUpdateShareInformation(result, R.string.sharee_add_failed);
  1600. } else if (operation instanceof UpdateShareViaLinkOperation) {
  1601. onUpdateShareInformation(result, R.string.updating_share_failed);
  1602. } else if (operation instanceof UpdateSharePermissionsOperation) {
  1603. onUpdateShareInformation(result, R.string.updating_share_failed);
  1604. } else if (operation instanceof UnshareOperation) {
  1605. onUpdateShareInformation(result, R.string.unsharing_failed);
  1606. } else if (operation instanceof RestoreFileVersionRemoteOperation) {
  1607. onRestoreFileVersionOperationFinish(result);
  1608. } else if (operation instanceof UpdateNoteForShareOperation) {
  1609. onUpdateNoteForShareOperationFinish(result);
  1610. }
  1611. }
  1612. private void refreshShowDetails() {
  1613. FileFragment details = getSecondFragment();
  1614. if (details != null) {
  1615. OCFile file = details.getFile();
  1616. if (file != null) {
  1617. file = getStorageManager().getFileByPath(file.getRemotePath());
  1618. if (details instanceof PreviewMediaFragment) {
  1619. // Refresh OCFile of the fragment
  1620. ((PreviewMediaFragment) details).updateFile(file);
  1621. } else if (details instanceof PreviewTextFragment) {
  1622. // Refresh OCFile of the fragment
  1623. ((PreviewTextFragment) details).updateFile(file);
  1624. } else {
  1625. showDetails(file);
  1626. }
  1627. }
  1628. supportInvalidateOptionsMenu();
  1629. }
  1630. }
  1631. /**
  1632. * Updates the view associated to the activity after the finish of an operation trying to
  1633. * remove a file.
  1634. *
  1635. * @param operation Removal operation performed.
  1636. * @param result Result of the removal.
  1637. */
  1638. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1639. RemoteOperationResult result) {
  1640. if (!operation.isInBackground()) {
  1641. DisplayUtils.showSnackMessage(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation,
  1642. getResources()));
  1643. }
  1644. if (result.isSuccess()) {
  1645. OCFile removedFile = operation.getFile();
  1646. tryStopPlaying(removedFile);
  1647. FileFragment second = getSecondFragment();
  1648. // check if file is still available, if so do nothing
  1649. boolean fileAvailable = getStorageManager().fileExists(removedFile.getFileId());
  1650. if (second != null && !fileAvailable && removedFile.equals(second.getFile())) {
  1651. if (second instanceof PreviewMediaFragment) {
  1652. ((PreviewMediaFragment) second).stopPreview(true);
  1653. }
  1654. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1655. cleanSecondFragment();
  1656. }
  1657. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1658. refreshListOfFilesFragment(false);
  1659. }
  1660. supportInvalidateOptionsMenu();
  1661. } else {
  1662. if (result.isSslRecoverableException()) {
  1663. mLastSslUntrustedServerResult = result;
  1664. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1665. }
  1666. }
  1667. }
  1668. private void onRestoreFileVersionOperationFinish(RemoteOperationResult result) {
  1669. if (result.isSuccess()) {
  1670. OCFile file = getFile();
  1671. // delete old local copy
  1672. if (file.isDown()) {
  1673. List<OCFile> list = new ArrayList<>();
  1674. list.add(file);
  1675. getFileOperationsHelper().removeFiles(list, true, true);
  1676. // download new version, only if file was previously download
  1677. getFileOperationsHelper().syncFile(file);
  1678. }
  1679. OCFile parent = getStorageManager().getFileById(file.getParentId());
  1680. startSyncFolderOperation(parent, true, true);
  1681. if (getSecondFragment() instanceof FileDetailFragment) {
  1682. FileDetailFragment fileDetailFragment = (FileDetailFragment) getSecondFragment();
  1683. fileDetailFragment.getFileDetailActivitiesFragment().reload();
  1684. }
  1685. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_successfully);
  1686. } else {
  1687. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_error);
  1688. }
  1689. }
  1690. public void setMediaServiceConnection() {
  1691. mMediaServiceConnection = newMediaConnection();// mediaServiceConnection;
  1692. bindService(new Intent(this, MediaService.class), mMediaServiceConnection, Context.BIND_AUTO_CREATE);
  1693. }
  1694. private void tryStopPlaying(OCFile file) {
  1695. if (mMediaServiceConnection != null && MimeTypeUtil.isAudio(file) && mMediaServiceBinder.isPlaying(file)) {
  1696. mMediaServiceBinder.pause();
  1697. }
  1698. }
  1699. /**
  1700. * Updates the view associated to the activity after the finish of an operation trying to move a
  1701. * file.
  1702. *
  1703. * @param operation Move operation performed.
  1704. * @param result Result of the move operation.
  1705. */
  1706. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1707. RemoteOperationResult result) {
  1708. if (result.isSuccess()) {
  1709. refreshListOfFilesFragment(false);
  1710. } else {
  1711. try {
  1712. DisplayUtils.showSnackMessage(
  1713. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1714. );
  1715. } catch (NotFoundException e) {
  1716. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1717. }
  1718. }
  1719. }
  1720. private void onCreateShareViaLinkOperationFinish(CreateShareViaLinkOperation operation,
  1721. RemoteOperationResult result) {
  1722. FileDetailFragment fileDetailFragment = getShareFileFragment();
  1723. if (result.isSuccess()) {
  1724. updateFileFromDB();
  1725. // if share to user and share via link multiple ocshares are returned,
  1726. // therefore filtering for public_link
  1727. String link = "";
  1728. for (Object object : result.getData()) {
  1729. OCShare shareLink = (OCShare) object;
  1730. if (TAG_PUBLIC_LINK.equalsIgnoreCase(shareLink.getShareType().name())) {
  1731. link = shareLink.getShareLink();
  1732. break;
  1733. }
  1734. }
  1735. copyAndShareFileLink(this, link);
  1736. if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
  1737. fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
  1738. fileDetailFragment.getFileDetailSharingFragment().onUpdateShareInformation(result, getFile());
  1739. }
  1740. refreshListOfFilesFragment(false);
  1741. } else {
  1742. // Detect Failure (403) --> maybe needs password
  1743. String password = operation.getPassword();
  1744. if (result.getCode() == RemoteOperationResult.ResultCode.SHARE_FORBIDDEN &&
  1745. TextUtils.isEmpty(password) &&
  1746. getCapabilities().getFilesSharingPublicEnabled().isUnknown()) {
  1747. // Was tried without password, but not sure that it's optional.
  1748. // Try with password before giving up; see also ShareFileFragment#OnShareViaLinkListener
  1749. if (fileDetailFragment != null && fileDetailFragment.isAdded()) { // only if added to the view hierarchy
  1750. fileDetailFragment
  1751. .getFileDetailSharingFragment()
  1752. .requestPasswordForShareViaLink(true,
  1753. getCapabilities().getFilesSharingPublicAskForOptionalPassword()
  1754. .isTrue());
  1755. }
  1756. } else {
  1757. if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
  1758. fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
  1759. }
  1760. Snackbar snackbar = Snackbar.make(
  1761. findViewById(android.R.id.content),
  1762. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1763. Snackbar.LENGTH_LONG
  1764. );
  1765. ThemeUtils.colorSnackbar(this, snackbar);
  1766. snackbar.show();
  1767. }
  1768. }
  1769. }
  1770. private void onUpdateNoteForShareOperationFinish(RemoteOperationResult result) {
  1771. FileDetailFragment fileDetailFragment = getShareFileFragment();
  1772. if (result.isSuccess()) {
  1773. if (fileDetailFragment != null && fileDetailFragment.getFileDetailSharingFragment() != null) {
  1774. fileDetailFragment.getFileDetailSharingFragment().refreshPublicShareFromDB();
  1775. fileDetailFragment.getFileDetailSharingFragment().onUpdateShareInformation(result, getFile());
  1776. }
  1777. } else {
  1778. DisplayUtils.showSnackMessage(this, R.string.note_could_not_sent);
  1779. }
  1780. }
  1781. private void onUpdateShareInformation(RemoteOperationResult result, @StringRes int defaultError) {
  1782. Snackbar snackbar;
  1783. Fragment fileDetailFragment = getSecondFragment();
  1784. if (result.isSuccess()) {
  1785. updateFileFromDB();
  1786. refreshListOfFilesFragment(false);
  1787. } else if (fileDetailFragment.getView() != null) {
  1788. String errorResponse;
  1789. if (result.getData() != null && result.getData().size() > 0) {
  1790. errorResponse = result.getData().get(0).toString();
  1791. } else {
  1792. errorResponse = "";
  1793. }
  1794. if (!TextUtils.isEmpty(errorResponse)) {
  1795. snackbar = Snackbar.make(fileDetailFragment.getView(), errorResponse, Snackbar.LENGTH_LONG);
  1796. } else {
  1797. snackbar = Snackbar.make(fileDetailFragment.getView(), defaultError, Snackbar.LENGTH_LONG);
  1798. }
  1799. ThemeUtils.colorSnackbar(this, snackbar);
  1800. snackbar.show();
  1801. }
  1802. if (fileDetailFragment instanceof FileDetailFragment) {
  1803. ((FileDetailFragment) fileDetailFragment).getFileDetailSharingFragment()
  1804. .onUpdateShareInformation(result, getFile());
  1805. }
  1806. }
  1807. /**
  1808. * Shortcut to get access to the {@link FileDetailFragment} instance, if any
  1809. *
  1810. * @return A {@link FileDetailFragment} instance, or null
  1811. */
  1812. private FileDetailFragment getShareFileFragment() {
  1813. Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_SECOND_FRAGMENT);
  1814. if (fragment instanceof FileDetailFragment) {
  1815. return (FileDetailFragment) fragment;
  1816. } else {
  1817. return null;
  1818. }
  1819. }
  1820. /**
  1821. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1822. * file.
  1823. *
  1824. * @param operation Copy operation performed.
  1825. * @param result Result of the copy operation.
  1826. */
  1827. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1828. if (result.isSuccess()) {
  1829. refreshListOfFilesFragment(false);
  1830. } else {
  1831. try {
  1832. DisplayUtils.showSnackMessage(
  1833. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1834. );
  1835. } catch (NotFoundException e) {
  1836. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1837. }
  1838. }
  1839. }
  1840. /**
  1841. * Updates the view associated to the activity after the finish of an operation trying to rename
  1842. * a file.
  1843. *
  1844. * @param operation Renaming operation performed.
  1845. * @param result Result of the renaming.
  1846. */
  1847. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1848. RemoteOperationResult result) {
  1849. OCFile renamedFile = operation.getFile();
  1850. if (result.isSuccess()) {
  1851. FileFragment details = getSecondFragment();
  1852. if (details != null) {
  1853. if (details instanceof FileDetailFragment &&
  1854. renamedFile.equals(details.getFile())) {
  1855. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1856. showDetails(renamedFile);
  1857. } else if (details instanceof PreviewMediaFragment &&
  1858. renamedFile.equals(details.getFile())) {
  1859. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1860. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1861. int position = ((PreviewMediaFragment) details).getPosition();
  1862. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  1863. .isMediaStreamingSupported();
  1864. startMediaPreview(renamedFile, position, true, true, streaming);
  1865. } else {
  1866. getFileOperationsHelper().openFile(renamedFile);
  1867. }
  1868. } else if (details instanceof PreviewTextFragment &&
  1869. renamedFile.equals(details.getFile())) {
  1870. ((PreviewTextFragment) details).updateFile(renamedFile);
  1871. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1872. startTextPreview(renamedFile, true);
  1873. } else {
  1874. getFileOperationsHelper().openFile(renamedFile);
  1875. }
  1876. }
  1877. }
  1878. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1879. refreshListOfFilesFragment(false);
  1880. }
  1881. } else {
  1882. DisplayUtils.showSnackMessage(
  1883. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1884. );
  1885. if (result.isSslRecoverableException()) {
  1886. mLastSslUntrustedServerResult = result;
  1887. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1888. }
  1889. }
  1890. }
  1891. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1892. RemoteOperationResult result) {
  1893. if (result.isSuccess() && operation.transferWasRequested()) {
  1894. OCFile syncedFile = operation.getLocalFile();
  1895. onTransferStateChanged(syncedFile, true, true);
  1896. supportInvalidateOptionsMenu();
  1897. refreshShowDetails();
  1898. }
  1899. }
  1900. /**
  1901. * Updates the view associated to the activity after the finish of an operation trying create a
  1902. * new folder
  1903. *
  1904. * @param operation Creation operation performed.
  1905. * @param result Result of the creation.
  1906. */
  1907. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1908. RemoteOperationResult result) {
  1909. if (result.isSuccess()) {
  1910. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1911. if (fileListFragment != null) {
  1912. fileListFragment.onItemClicked(getStorageManager().getFileByPath(operation.getRemotePath()));
  1913. }
  1914. } else {
  1915. try {
  1916. if (ResultCode.FOLDER_ALREADY_EXISTS == result.getCode()) {
  1917. DisplayUtils.showSnackMessage(this, R.string.folder_already_exists);
  1918. } else {
  1919. DisplayUtils.showSnackMessage(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation,
  1920. getResources()));
  1921. }
  1922. } catch (NotFoundException e) {
  1923. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1924. }
  1925. }
  1926. }
  1927. /**
  1928. * {@inheritDoc}
  1929. */
  1930. @Override
  1931. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1932. refreshListOfFilesFragment(false);
  1933. FileFragment details = getSecondFragment();
  1934. if (details instanceof FileDetailFragment &&
  1935. file.equals(details.getFile())) {
  1936. if (downloading || uploading) {
  1937. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1938. } else {
  1939. if (!file.fileExists()) {
  1940. cleanSecondFragment();
  1941. } else {
  1942. ((FileDetailFragment) details).updateFileDetails(false, true);
  1943. }
  1944. }
  1945. }
  1946. }
  1947. private void requestForDownload() {
  1948. Account account = getAccount();
  1949. //if (!mWaitingToPreview.isDownloading()) {
  1950. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1951. Intent i = new Intent(this, FileDownloader.class);
  1952. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1953. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1954. startService(i);
  1955. }
  1956. }
  1957. @Override
  1958. public void onSavedCertificate() {
  1959. startSyncFolderOperation(getCurrentDir(), false);
  1960. }
  1961. /**
  1962. * Starts an operation to refresh the requested folder.
  1963. *
  1964. * The operation is run in a new background thread created on the fly.
  1965. *
  1966. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1967. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1968. * synchronized too.
  1969. *
  1970. * @param folder Folder to refresh.
  1971. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1972. * didn't change.
  1973. */
  1974. public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
  1975. startSyncFolderOperation(folder, ignoreETag, false);
  1976. }
  1977. /**
  1978. * Starts an operation to refresh the requested folder.
  1979. *
  1980. * The operation is run in a new background thread created on the fly.
  1981. *
  1982. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1983. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1984. * synchronized too.
  1985. *
  1986. * @param folder Folder to refresh.
  1987. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1988. * didn't change.
  1989. * @param ignoreFocus reloads file list even without focus, e.g. on tablet mode, focus can still be in detail view
  1990. */
  1991. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag, boolean ignoreFocus) {
  1992. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1993. // or if the method is called from a dialog that is being dismissed
  1994. if (TextUtils.isEmpty(searchQuery)) {
  1995. getHandler().postDelayed(
  1996. new Runnable() {
  1997. @Override
  1998. public void run() {
  1999. if (ignoreFocus || hasWindowFocus()) {
  2000. long currentSyncTime = System.currentTimeMillis();
  2001. mSyncInProgress = true;
  2002. // perform folder synchronization
  2003. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  2004. currentSyncTime,
  2005. false,
  2006. ignoreETag,
  2007. getStorageManager(),
  2008. getAccount(),
  2009. getApplicationContext()
  2010. );
  2011. synchFolderOp.execute(
  2012. getAccount(),
  2013. MainApp.getAppContext(),
  2014. FileDisplayActivity.this,
  2015. null,
  2016. null
  2017. );
  2018. setIndeterminate(true);
  2019. setBackgroundText();
  2020. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  2021. // another window floating over
  2022. }
  2023. },
  2024. DELAY_TO_REQUEST_REFRESH_OPERATION_LATER
  2025. );
  2026. }
  2027. }
  2028. private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
  2029. Account account = getAccount();
  2030. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  2031. Intent i = new Intent(this, FileDownloader.class);
  2032. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  2033. i.putExtra(FileDownloader.EXTRA_FILE, file);
  2034. i.putExtra(SendShareDialog.PACKAGE_NAME, packageName);
  2035. i.putExtra(SendShareDialog.ACTIVITY_NAME, activityName);
  2036. i.putExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR, downloadBehaviour);
  2037. startService(i);
  2038. }
  2039. }
  2040. private void sendDownloadedFile(String packageName, String activityName) {
  2041. if (mWaitingToSend != null) {
  2042. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  2043. sendIntent.setType(mWaitingToSend.getMimeType());
  2044. sendIntent.putExtra(Intent.EXTRA_STREAM, mWaitingToSend.getExposedFileUri(this));
  2045. sendIntent.putExtra(Intent.ACTION_SEND, true);
  2046. sendIntent.setComponent(new ComponentName(packageName, activityName));
  2047. // Show dialog
  2048. String sendTitle = getString(R.string.activity_chooser_send_file_title);
  2049. startActivity(Intent.createChooser(sendIntent, sendTitle));
  2050. } else {
  2051. Log_OC.e(TAG, "Trying to send a NULL OCFile");
  2052. }
  2053. mWaitingToSend = null;
  2054. }
  2055. /**
  2056. * Requests the download of the received {@link OCFile} , updates the UI
  2057. * to monitor the download progress and prepares the activity to send the file
  2058. * when the download finishes.
  2059. *
  2060. * @param file {@link OCFile} to download and preview.
  2061. * @param packageName
  2062. * @param activityName
  2063. */
  2064. public void startDownloadForSending(OCFile file, String downloadBehaviour, String packageName,
  2065. String activityName) {
  2066. mWaitingToSend = file;
  2067. requestForDownload(mWaitingToSend, downloadBehaviour, packageName, activityName);
  2068. boolean hasSecondFragment = getSecondFragment() != null;
  2069. updateFragmentsVisibility(hasSecondFragment);
  2070. }
  2071. /**
  2072. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  2073. *
  2074. * @param file Image {@link OCFile} to show.
  2075. */
  2076. public void startImagePreview(OCFile file, boolean showPreview) {
  2077. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  2078. showDetailsIntent.putExtra(EXTRA_FILE, file);
  2079. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  2080. if (showPreview) {
  2081. startActivity(showDetailsIntent);
  2082. } else {
  2083. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2084. getUserAccountManager(),
  2085. connectivityService);
  2086. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  2087. }
  2088. }
  2089. /**
  2090. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  2091. *
  2092. * @param file Image {@link OCFile} to show.
  2093. */
  2094. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  2095. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  2096. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  2097. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  2098. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  2099. if (showPreview) {
  2100. startActivity(showDetailsIntent);
  2101. } else {
  2102. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2103. getUserAccountManager(),
  2104. connectivityService);
  2105. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  2106. }
  2107. }
  2108. /**
  2109. * Stars the preview of an already down media {@link OCFile}.
  2110. *
  2111. * @param file Media {@link OCFile} to preview.
  2112. * @param startPlaybackPosition Media position where the playback will be started,
  2113. * in milliseconds.
  2114. * @param autoplay When 'true', the playback will start without user
  2115. * interactions.
  2116. */
  2117. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview,
  2118. boolean streamMedia) {
  2119. if (showPreview && file.isDown() && !file.isDownloading() || streamMedia) {
  2120. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  2121. setSecondFragment(mediaFragment);
  2122. updateFragmentsVisibility(true);
  2123. updateActionBarTitleAndHomeButton(file);
  2124. setFile(file);
  2125. } else {
  2126. Intent previewIntent = new Intent();
  2127. previewIntent.putExtra(EXTRA_FILE, file);
  2128. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  2129. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  2130. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2131. getUserAccountManager(),
  2132. connectivityService);
  2133. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2134. }
  2135. }
  2136. /**
  2137. * Stars the preview of a text file {@link OCFile}.
  2138. *
  2139. * @param file Text {@link OCFile} to preview.
  2140. */
  2141. public void startTextPreview(OCFile file, boolean showPreview) {
  2142. if (showPreview) {
  2143. Bundle args = new Bundle();
  2144. args.putParcelable(EXTRA_FILE, file);
  2145. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  2146. args.putBoolean(EXTRA_SEARCH, searchOpen);
  2147. args.putString(EXTRA_SEARCH_QUERY, searchQuery);
  2148. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  2149. PreviewTextFragment.class.getName(), args);
  2150. setSecondFragment(textPreviewFragment);
  2151. updateFragmentsVisibility(true);
  2152. updateActionBarTitleAndHomeButton(file);
  2153. setFile(file);
  2154. } else {
  2155. Intent previewIntent = new Intent();
  2156. previewIntent.putExtra(EXTRA_FILE, file);
  2157. previewIntent.putExtra(TEXT_PREVIEW, true);
  2158. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2159. getUserAccountManager(),
  2160. connectivityService);
  2161. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2162. }
  2163. }
  2164. public void startContactListFragment(OCFile file) {
  2165. Intent intent = new Intent(this, ContactsPreferenceActivity.class);
  2166. intent.putExtra(ContactListFragment.FILE_NAME, Parcels.wrap(file));
  2167. intent.putExtra(ContactListFragment.ACCOUNT, Parcels.wrap(getAccount()));
  2168. startActivity(intent);
  2169. }
  2170. /**
  2171. * Requests the download of the received {@link OCFile} , updates the UI
  2172. * to monitor the download progress and prepares the activity to preview
  2173. * or open the file when the download finishes.
  2174. *
  2175. * @param file {@link OCFile} to download and preview.
  2176. */
  2177. public void startDownloadForPreview(OCFile file) {
  2178. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  2179. setSecondFragment(detailFragment);
  2180. mWaitingToPreview = file;
  2181. requestForDownload();
  2182. updateFragmentsVisibility(true);
  2183. updateActionBarTitleAndHomeButton(file);
  2184. setFile(file);
  2185. }
  2186. /**
  2187. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  2188. *
  2189. * @param file {@link OCFile} file which operation are wanted to be cancel
  2190. */
  2191. public void cancelTransference(OCFile file) {
  2192. getFileOperationsHelper().cancelTransference(file);
  2193. if (mWaitingToPreview != null &&
  2194. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  2195. mWaitingToPreview = null;
  2196. }
  2197. if (mWaitingToSend != null &&
  2198. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  2199. mWaitingToSend = null;
  2200. }
  2201. onTransferStateChanged(file, false, false);
  2202. }
  2203. /**
  2204. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  2205. *
  2206. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  2207. */
  2208. public void cancelTransference(Collection<OCFile> files) {
  2209. for (OCFile file : files) {
  2210. cancelTransference(file);
  2211. }
  2212. }
  2213. @Override
  2214. public void onRefresh(boolean ignoreETag) {
  2215. refreshList(ignoreETag);
  2216. }
  2217. @Override
  2218. public void onRefresh() {
  2219. refreshList(true);
  2220. }
  2221. private void refreshList(boolean ignoreETag) {
  2222. OCFileListFragment listOfFiles = getListOfFilesFragment();
  2223. if (listOfFiles != null && !listOfFiles.isSearchFragment()) {
  2224. OCFile folder = listOfFiles.getCurrentFile();
  2225. if (folder != null) {
  2226. startSyncFolderOperation(folder, ignoreETag);
  2227. }
  2228. }
  2229. }
  2230. private boolean isGridView() {
  2231. return getListOfFilesFragment().isGridEnabled();
  2232. }
  2233. public void allFilesOption() {
  2234. browseToRoot();
  2235. }
  2236. public void setActionBarTitle(@StringRes final int title) {
  2237. runOnUiThread(new Runnable() {
  2238. @Override
  2239. public void run() {
  2240. if (getSupportActionBar() != null) {
  2241. ThemeUtils.setColoredTitle(getSupportActionBar(), title, getBaseContext());
  2242. }
  2243. }
  2244. });
  2245. }
  2246. @Override
  2247. public void showFiles(boolean onDeviceOnly) {
  2248. super.showFiles(onDeviceOnly);
  2249. if (onDeviceOnly) {
  2250. setActionBarTitle(R.string.drawer_item_on_device);
  2251. }
  2252. getListOfFilesFragment().refreshDirectory();
  2253. }
  2254. @Subscribe(threadMode = ThreadMode.MAIN)
  2255. public void onMessageEvent(SyncEventFinished event) {
  2256. Bundle bundle = event.getIntent().getExtras();
  2257. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  2258. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  2259. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  2260. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  2261. .isMediaStreamingSupported();
  2262. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  2263. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  2264. (boolean) bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true, streaming);
  2265. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  2266. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  2267. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  2268. true);
  2269. } else {
  2270. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  2271. }
  2272. }
  2273. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2274. public void onMessageEvent(TokenPushEvent event) {
  2275. if (!preferences.isKeysReInitEnabled()) {
  2276. PushUtils.reinitKeys(getUserAccountManager());
  2277. } else {
  2278. PushUtils.pushRegistrationToServer(getUserAccountManager(), preferences.getPushToken());
  2279. }
  2280. }
  2281. @Override
  2282. public void onStart() {
  2283. super.onStart();
  2284. EventBus.getDefault().post(new TokenPushEvent());
  2285. checkForNewDevVersionNecessary(findViewById(R.id.root_layout), getApplicationContext());
  2286. }
  2287. @Override
  2288. protected void onRestart() {
  2289. super.onRestart();
  2290. checkForNewDevVersionNecessary(findViewById(R.id.root_layout), getApplicationContext());
  2291. }
  2292. public void setSearchQuery(String query) {
  2293. searchQuery = query;
  2294. }
  2295. private void handleOpenFileViaIntent(Intent intent) {
  2296. showLoadingDialog("Retrieving file…");
  2297. String accountName = intent.getStringExtra("KEY_ACCOUNT");
  2298. Account newAccount = getUserAccountManager().getAccountByName(accountName);
  2299. if (newAccount == null) {
  2300. dismissLoadingDialog();
  2301. DisplayUtils.showSnackMessage(this, "Associated account not found!");
  2302. return;
  2303. }
  2304. setAccount(newAccount);
  2305. String fileId = String.valueOf(intent.getStringExtra("KEY_FILE_ID"));
  2306. if ("null".equals(fileId)) {
  2307. dismissLoadingDialog();
  2308. DisplayUtils.showSnackMessage(this, "Error retrieving file");
  2309. return;
  2310. }
  2311. AccountManager am = AccountManager.get(this);
  2312. String userId = am.getUserData(getAccount(), AccountUtils.Constants.KEY_USER_ID);
  2313. FileDataStorageManager storageManager = getStorageManager();
  2314. if (storageManager == null) {
  2315. storageManager = new FileDataStorageManager(newAccount, getContentResolver());
  2316. }
  2317. FetchRemoteFileTask fetchRemoteFileTask = new FetchRemoteFileTask(newAccount,
  2318. fileId,
  2319. userId,
  2320. storageManager,
  2321. this);
  2322. fetchRemoteFileTask.execute();
  2323. }
  2324. }