FileDisplayActivity.java 106 KB

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