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. @Deprecated
  538. OCFileListFragment getListOfFilesFragment() {
  539. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  540. FileDisplayActivity.TAG_LIST_OF_FILES);
  541. if (listOfFiles != null) {
  542. return (OCFileListFragment) listOfFiles;
  543. }
  544. Log_OC.e(TAG, "Access to unexisting list of files fragment!!");
  545. return null;
  546. }
  547. public @Nullable
  548. FileFragment getSecondFragment() {
  549. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  550. if (second != null) {
  551. return (FileFragment) second;
  552. }
  553. return null;
  554. }
  555. protected void cleanSecondFragment() {
  556. Fragment second = getSecondFragment();
  557. if (second != null) {
  558. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  559. tr.remove(second);
  560. tr.commit();
  561. }
  562. updateFragmentsVisibility(false);
  563. updateActionBarTitleAndHomeButton(null);
  564. }
  565. public void updateListOfFilesFragment(boolean fromSearch) {
  566. OCFileListFragment fileListFragment = getListOfFilesFragment();
  567. if (fileListFragment != null) {
  568. fileListFragment.listDirectory(MainApp.isOnlyOnDevice(), fromSearch);
  569. }
  570. }
  571. public void resetSearchView() {
  572. OCFileListFragment fileListFragment = getListOfFilesFragment();
  573. if (fileListFragment != null) {
  574. fileListFragment.setSearchFragment(false);
  575. }
  576. }
  577. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  578. boolean success) {
  579. FileFragment secondFragment = getSecondFragment();
  580. boolean waitedPreview = mWaitingToPreview != null
  581. && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath);
  582. if (secondFragment instanceof FileDetailFragment) {
  583. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  584. OCFile fileInFragment = detailsFragment.getFile();
  585. if (fileInFragment != null &&
  586. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  587. // the user browsed to other file ; forget the automatic preview
  588. mWaitingToPreview = null;
  589. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  590. // grant that the right panel updates the progress bar
  591. detailsFragment.listenForTransferProgress();
  592. detailsFragment.updateFileDetails(true, false);
  593. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  594. // update the right panel
  595. boolean detailsFragmentChanged = false;
  596. if (waitedPreview) {
  597. if (success) {
  598. // update the file from database, for the local storage path
  599. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  600. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  601. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  602. .isMediaStreamingSupported();
  603. startMediaPreview(mWaitingToPreview, 0, true, true, streaming);
  604. detailsFragmentChanged = true;
  605. } else if (MimeTypeUtil.isVCard(mWaitingToPreview.getMimeType())) {
  606. startContactListFragment(mWaitingToPreview);
  607. detailsFragmentChanged = true;
  608. } else if (PreviewTextFileFragment.canBePreviewed(mWaitingToPreview)) {
  609. startTextPreview(mWaitingToPreview, true);
  610. detailsFragmentChanged = true;
  611. } else {
  612. getFileOperationsHelper().openFile(mWaitingToPreview);
  613. }
  614. }
  615. mWaitingToPreview = null;
  616. }
  617. if (!detailsFragmentChanged) {
  618. detailsFragment.updateFileDetails(false, success);
  619. }
  620. }
  621. }
  622. }
  623. @Override
  624. public boolean onPrepareOptionsMenu(Menu menu) {
  625. boolean drawerOpen = isDrawerOpen();
  626. for (MenuItem menuItem : mDrawerMenuItemstoShowHideList) {
  627. menuItem.setVisible(!drawerOpen);
  628. }
  629. return super.onPrepareOptionsMenu(menu);
  630. }
  631. @Override
  632. public boolean onCreateOptionsMenu(Menu menu) {
  633. MenuInflater inflater = getMenuInflater();
  634. inflater.inflate(R.menu.activity_file_display, menu);
  635. menu.findItem(R.id.action_select_all).setVisible(false);
  636. MenuItem searchMenuItem = menu.findItem(R.id.action_search);
  637. searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
  638. searchMenuItem.setVisible(false);
  639. mSearchText.setOnClickListener(v -> {
  640. showSearchView();
  641. searchView.setIconified(false);
  642. });
  643. ThemeUtils.themeSearchView(searchView, this);
  644. // populate list of menu items to show/hide when drawer is opened/closed
  645. mDrawerMenuItemstoShowHideList = new ArrayList<>(1);
  646. mDrawerMenuItemstoShowHideList.add(searchMenuItem);
  647. //focus the SearchView
  648. if (!TextUtils.isEmpty(searchQuery)) {
  649. searchView.post(() -> {
  650. searchView.setIconified(false);
  651. searchView.setQuery(searchQuery, true);
  652. searchView.clearFocus();
  653. });
  654. }
  655. final View mSearchEditFrame = searchView
  656. .findViewById(androidx.appcompat.R.id.search_edit_frame);
  657. searchView.setOnCloseListener(() -> {
  658. if (TextUtils.isEmpty(searchView.getQuery().toString())) {
  659. searchView.onActionViewCollapsed();
  660. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable()); // order matters
  661. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  662. mDrawerToggle.syncState();
  663. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  664. if (ocFileListFragment != null) {
  665. ocFileListFragment.setSearchFragment(false);
  666. ocFileListFragment.refreshDirectory();
  667. }
  668. } else {
  669. searchView.post(() -> searchView.setQuery("", true));
  670. }
  671. return true;
  672. });
  673. ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
  674. vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  675. int oldVisibility = -1;
  676. @Override
  677. public void onGlobalLayout() {
  678. int currentVisibility = mSearchEditFrame.getVisibility();
  679. if (currentVisibility != oldVisibility) {
  680. if (currentVisibility == View.VISIBLE) {
  681. setDrawerIndicatorEnabled(false);
  682. }
  683. oldVisibility = currentVisibility;
  684. }
  685. }
  686. });
  687. return super.onCreateOptionsMenu(menu);
  688. }
  689. @Override
  690. public boolean onOptionsItemSelected(MenuItem item) {
  691. boolean retval = true;
  692. switch (item.getItemId()) {
  693. case android.R.id.home: {
  694. FileFragment second = getSecondFragment();
  695. OCFile currentDir = getCurrentDir();
  696. if (isDrawerOpen()) {
  697. closeDrawer();
  698. } else if (
  699. currentDir != null && currentDir.getParentId() != 0 ||
  700. second != null && second.getFile() != null ||
  701. isSearchOpen() ||
  702. second == null
  703. ) {
  704. onBackPressed();
  705. } else {
  706. openDrawer();
  707. }
  708. break;
  709. }
  710. case R.id.action_select_all: {
  711. OCFileListFragment fragment = getListOfFilesFragment();
  712. if (fragment != null) {
  713. fragment.selectAllFiles(true);
  714. }
  715. break;
  716. }
  717. default:
  718. retval = super.onOptionsItemSelected(item);
  719. break;
  720. }
  721. return retval;
  722. }
  723. /**
  724. * Called, when the user selected something for uploading
  725. */
  726. @Override
  727. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  728. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS &&
  729. (resultCode == RESULT_OK ||
  730. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  731. requestUploadOfContentFromApps(data, resultCode);
  732. } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM &&
  733. (resultCode == RESULT_OK ||
  734. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE ||
  735. resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING ||
  736. resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) {
  737. requestUploadOfFilesFromFileSystem(data, resultCode);
  738. } else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA &&
  739. (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  740. new CheckAvailableSpaceTask(new CheckAvailableSpaceTask.CheckAvailableSpaceListener() {
  741. @Override
  742. public void onCheckAvailableSpaceStart() {
  743. Log_OC.d(this, "onCheckAvailableSpaceStart");
  744. }
  745. @Override
  746. public void onCheckAvailableSpaceFinish(boolean hasEnoughSpaceAvailable, String... filesToUpload) {
  747. Log_OC.d(this, "onCheckAvailableSpaceFinish");
  748. if (hasEnoughSpaceAvailable) {
  749. File file = new File(filesToUpload[0]);
  750. File renamedFile = new File(file.getParent() + PATH_SEPARATOR + FileOperationsHelper.getCapturedImageName());
  751. if (!file.renameTo(renamedFile)) {
  752. DisplayUtils.showSnackMessage(getActivity(), "Fail to upload taken image!");
  753. return;
  754. }
  755. requestUploadOfFilesFromFileSystem(new String[]{renamedFile.getAbsolutePath()},
  756. FileUploader.LOCAL_BEHAVIOUR_MOVE);
  757. }
  758. }
  759. }, new String[]{FileOperationsHelper.createImageFile(getActivity()).getAbsolutePath()}).execute();
  760. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  761. exitSelectionMode();
  762. final Intent fData = data;
  763. getHandler().postDelayed(
  764. new Runnable() {
  765. @Override
  766. public void run() {
  767. requestMoveOperation(fData);
  768. }
  769. },
  770. DELAY_TO_REQUEST_OPERATIONS_LATER
  771. );
  772. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  773. exitSelectionMode();
  774. final Intent fData = data;
  775. getHandler().postDelayed(
  776. new Runnable() {
  777. @Override
  778. public void run() {
  779. requestCopyOperation(fData);
  780. }
  781. },
  782. DELAY_TO_REQUEST_OPERATIONS_LATER
  783. );
  784. } else {
  785. super.onActivityResult(requestCode, resultCode, data);
  786. }
  787. }
  788. private void exitSelectionMode() {
  789. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  790. if (ocFileListFragment != null) {
  791. ocFileListFragment.exitSelectionMode();
  792. }
  793. }
  794. private void requestUploadOfFilesFromFileSystem(Intent data, int resultCode) {
  795. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  796. requestUploadOfFilesFromFileSystem(filePaths, resultCode);
  797. }
  798. private void requestUploadOfFilesFromFileSystem(String[] filePaths, int resultCode) {
  799. if (filePaths != null) {
  800. String[] remotePaths = new String[filePaths.length];
  801. String remotePathBase = getCurrentDir().getRemotePath();
  802. for (int j = 0; j < remotePaths.length; j++) {
  803. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  804. }
  805. int behaviour;
  806. switch (resultCode) {
  807. case UploadFilesActivity.RESULT_OK_AND_MOVE:
  808. behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE;
  809. break;
  810. case UploadFilesActivity.RESULT_OK_AND_DELETE:
  811. behaviour = FileUploader.LOCAL_BEHAVIOUR_DELETE;
  812. break;
  813. case UploadFilesActivity.RESULT_OK_AND_DO_NOTHING:
  814. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  815. break;
  816. default:
  817. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  818. break;
  819. }
  820. FileUploader.uploadNewFile(
  821. this,
  822. getAccount(),
  823. filePaths,
  824. remotePaths,
  825. null, // MIME type will be detected from file name
  826. behaviour,
  827. false, // do not create parent folder if not existent
  828. UploadFileOperation.CREATED_BY_USER,
  829. false,
  830. false,
  831. FileUploader.NameCollisionPolicy.ASK_USER
  832. );
  833. } else {
  834. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  835. DisplayUtils.showSnackMessage(this, R.string.filedisplay_no_file_selected);
  836. }
  837. }
  838. private void requestUploadOfContentFromApps(Intent contentIntent, int resultCode) {
  839. ArrayList<Parcelable> streamsToUpload = new ArrayList<>();
  840. if (contentIntent.getClipData() != null && contentIntent.getClipData().getItemCount() > 0) {
  841. for (int i = 0; i < contentIntent.getClipData().getItemCount(); i++) {
  842. streamsToUpload.add(contentIntent.getClipData().getItemAt(i).getUri());
  843. }
  844. } else {
  845. streamsToUpload.add(contentIntent.getData());
  846. }
  847. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  848. FileUploader.LOCAL_BEHAVIOUR_COPY;
  849. OCFile currentDir = getCurrentDir();
  850. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  851. UriUploader uploader = new UriUploader(
  852. this,
  853. streamsToUpload,
  854. remotePath,
  855. getAccount(),
  856. behaviour,
  857. false, // Not show waiting dialog while file is being copied from private storage
  858. null // Not needed copy temp task listener
  859. );
  860. uploader.uploadUris();
  861. }
  862. /**
  863. * Request the operation for moving the file/folder from one path to another
  864. *
  865. * @param data Intent received
  866. */
  867. private void requestMoveOperation(Intent data) {
  868. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  869. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  870. getFileOperationsHelper().moveFiles(files, folderToMoveAt);
  871. }
  872. /**
  873. * Request the operation for copying the file/folder from one path to another
  874. *
  875. * @param data Intent received
  876. */
  877. private void requestCopyOperation(Intent data) {
  878. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  879. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  880. getFileOperationsHelper().copyFiles(files, folderToMoveAt);
  881. }
  882. private boolean isSearchOpen() {
  883. if (searchView == null) {
  884. return false;
  885. } else {
  886. View mSearchEditFrame = searchView.findViewById(androidx.appcompat.R.id.search_edit_frame);
  887. return mSearchEditFrame != null && mSearchEditFrame.getVisibility() == View.VISIBLE;
  888. }
  889. }
  890. /*
  891. * BackPressed priority/hierarchy:
  892. * 1. close search view if opened
  893. * 2. close drawer if opened
  894. * 3. close FAB if open (only if drawer isn't open)
  895. * 4. navigate up (only if drawer and FAB aren't open)
  896. */
  897. @Override
  898. public void onBackPressed() {
  899. boolean isDrawerOpen = isDrawerOpen();
  900. boolean isSearchOpen = isSearchOpen();
  901. Fragment leftFragment = getLeftFragment();
  902. if (leftFragment instanceof OCFileListFragment) {
  903. OCFileListFragment listOfFiles = (OCFileListFragment) leftFragment;
  904. if (isSearchOpen && searchView != null) {
  905. searchView.setQuery("", true);
  906. searchView.onActionViewCollapsed();
  907. searchView.clearFocus();
  908. // Remove the list to the original state
  909. listOfFiles.performSearch("", true);
  910. hideSearchView(getCurrentDir());
  911. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  912. } else if (isDrawerOpen) {
  913. // close drawer first
  914. super.onBackPressed();
  915. } else {
  916. // all closed
  917. if (mDualPane || getSecondFragment() == null) {
  918. OCFile currentDir = getCurrentDir();
  919. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  920. finish();
  921. return;
  922. }
  923. listOfFiles.onBrowseUp();
  924. }
  925. setFile(listOfFiles.getCurrentFile());
  926. listOfFiles.setFabVisible(true);
  927. listOfFiles.registerFabListener();
  928. showSortListGroup(true);
  929. cleanSecondFragment();
  930. }
  931. } else {
  932. // pop back
  933. hideSearchView(getCurrentDir());
  934. super.onBackPressed();
  935. }
  936. }
  937. @Override
  938. protected void onSaveInstanceState(@NonNull Bundle outState) {
  939. // responsibility of restore is preferred in onCreate() before than in
  940. // onRestoreInstanceState when there are Fragments involved
  941. Log_OC.v(TAG, "onSaveInstanceState() start");
  942. super.onSaveInstanceState(outState);
  943. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  944. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  945. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  946. // mRefreshSharesInProgress);
  947. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  948. if (searchView != null) {
  949. outState.putBoolean(KEY_IS_SEARCH_OPEN, !searchView.isIconified());
  950. }
  951. outState.putString(KEY_SEARCH_QUERY, searchQuery);
  952. Log_OC.v(TAG, "onSaveInstanceState() end");
  953. }
  954. @Override
  955. protected void onResume() {
  956. Log_OC.v(TAG, "onResume() start");
  957. super.onResume();
  958. // Instead of onPostCreate, starting the loading in onResume for children fragments
  959. Fragment leftFragment = getLeftFragment();
  960. if (!(leftFragment instanceof OCFileListFragment)) {
  961. return;
  962. }
  963. OCFileListFragment ocFileListFragment = (OCFileListFragment) leftFragment;
  964. ocFileListFragment.setLoading(mSyncInProgress);
  965. syncAndUpdateFolder(false);
  966. OCFile startFile = null;
  967. if (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) != null) {
  968. startFile = getIntent().getParcelableExtra(EXTRA_FILE);
  969. setFile(startFile);
  970. }
  971. // refresh list of files
  972. if (searchView != null && !TextUtils.isEmpty(searchQuery)) {
  973. searchView.setQuery(searchQuery, false);
  974. } else if (!ocFileListFragment.isSearchFragment() && startFile == null) {
  975. updateListOfFilesFragment(false);
  976. ocFileListFragment.registerFabListener();
  977. } else {
  978. ocFileListFragment.listDirectory(startFile, false, false);
  979. updateActionBarTitleAndHomeButton(startFile);
  980. }
  981. // Listen for sync messages
  982. if (!ocFileListFragment.isSearchFragment()) {
  983. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  984. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  985. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  986. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  987. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  988. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  989. localBroadcastManager.registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  990. }
  991. // Listen for upload messages
  992. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  993. mUploadFinishReceiver = new UploadFinishReceiver();
  994. localBroadcastManager.registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  995. // Listen for download messages
  996. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
  997. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  998. mDownloadFinishReceiver = new DownloadFinishReceiver();
  999. localBroadcastManager.registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  1000. // setup drawer
  1001. menuItemId = getIntent().getIntExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
  1002. if (menuItemId == -1) {
  1003. if (MainApp.isOnlyOnDevice()) {
  1004. setDrawerMenuItemChecked(R.id.nav_on_device);
  1005. setupToolbar();
  1006. } else {
  1007. setDrawerMenuItemChecked(R.id.nav_all_files);
  1008. setupHomeSearchToolbarWithSortAndListButtons();
  1009. }
  1010. } else {
  1011. if (menuItemId == R.id.nav_all_files) {
  1012. setupHomeSearchToolbarWithSortAndListButtons();
  1013. } else {
  1014. setupToolbar();
  1015. }
  1016. setDrawerMenuItemChecked(menuItemId);
  1017. }
  1018. if (ocFileListFragment instanceof PhotoFragment) {
  1019. updateActionBarTitleAndHomeButtonByString(getString(R.string.drawer_item_photos));
  1020. }
  1021. Log_OC.v(TAG, "onResume() end");
  1022. }
  1023. @Override
  1024. protected void onPause() {
  1025. Log_OC.v(TAG, "onPause() start");
  1026. if (mSyncBroadcastReceiver != null) {
  1027. localBroadcastManager.unregisterReceiver(mSyncBroadcastReceiver);
  1028. mSyncBroadcastReceiver = null;
  1029. }
  1030. if (mUploadFinishReceiver != null) {
  1031. localBroadcastManager.unregisterReceiver(mUploadFinishReceiver);
  1032. mUploadFinishReceiver = null;
  1033. }
  1034. if (mDownloadFinishReceiver != null) {
  1035. localBroadcastManager.unregisterReceiver(mDownloadFinishReceiver);
  1036. mDownloadFinishReceiver = null;
  1037. }
  1038. super.onPause();
  1039. Log_OC.v(TAG, "onPause() end");
  1040. }
  1041. @Override
  1042. public void onSortingOrderChosen(FileSortOrder selection) {
  1043. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1044. if (ocFileListFragment != null) {
  1045. ocFileListFragment.sortFiles(selection);
  1046. }
  1047. }
  1048. @Override
  1049. public void downloadFile(OCFile file, String packageName, String activityName) {
  1050. startDownloadForSending(file, OCFileListFragment.DOWNLOAD_SEND, packageName, activityName);
  1051. }
  1052. private class SyncBroadcastReceiver extends BroadcastReceiver {
  1053. /**
  1054. * {@link BroadcastReceiver} to enable syncing feedback in UI
  1055. */
  1056. @Override
  1057. public void onReceive(Context context, Intent intent) {
  1058. try {
  1059. String event = intent.getAction();
  1060. Log_OC.d(TAG, "Received broadcast " + event);
  1061. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  1062. String synchFolderRemotePath =
  1063. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  1064. RemoteOperationResult synchResult = (RemoteOperationResult)
  1065. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1066. boolean sameAccount = getAccount() != null &&
  1067. accountName.equals(getAccount().name) && getStorageManager() != null;
  1068. if (sameAccount) {
  1069. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  1070. mSyncInProgress = true;
  1071. } else {
  1072. OCFile currentFile = (getFile() == null) ? null :
  1073. getStorageManager().getFileByPath(getFile().getRemotePath());
  1074. OCFile currentDir = (getCurrentDir() == null) ? null :
  1075. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  1076. if (currentDir == null) {
  1077. // current folder was removed from the server
  1078. DisplayUtils.showSnackMessage(
  1079. getActivity(),
  1080. R.string.sync_current_folder_was_removed,
  1081. synchFolderRemotePath
  1082. );
  1083. browseToRoot();
  1084. } else {
  1085. if (currentFile == null && !getFile().isFolder()) {
  1086. // currently selected file was removed in the server, and now we
  1087. // know it
  1088. cleanSecondFragment();
  1089. currentFile = currentDir;
  1090. }
  1091. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  1092. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1093. if (fileListFragment != null) {
  1094. fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false);
  1095. }
  1096. }
  1097. setFile(currentFile);
  1098. }
  1099. mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  1100. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
  1101. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) &&
  1102. synchResult != null) {
  1103. if (synchResult.isSuccess()) {
  1104. hideInfoBox();
  1105. } else {
  1106. // TODO refactor and make common
  1107. if (checkForRemoteOperationError(synchResult)) {
  1108. requestCredentialsUpdate(context);
  1109. } else {
  1110. switch (synchResult.getCode()) {
  1111. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1112. showUntrustedCertDialog(synchResult);
  1113. break;
  1114. case MAINTENANCE_MODE:
  1115. showInfoBox(R.string.maintenance_mode);
  1116. break;
  1117. case NO_NETWORK_CONNECTION:
  1118. showInfoBox(R.string.offline_mode);
  1119. break;
  1120. case HOST_NOT_AVAILABLE:
  1121. showInfoBox(R.string.host_not_available);
  1122. break;
  1123. default:
  1124. // nothing to do
  1125. break;
  1126. }
  1127. }
  1128. }
  1129. }
  1130. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1131. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1132. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1133. if (ocFileListFragment != null) {
  1134. ocFileListFragment.setLoading(mSyncInProgress);
  1135. }
  1136. setBackgroundText();
  1137. }
  1138. }
  1139. if (synchResult != null && synchResult.getCode().equals(
  1140. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  1141. mLastSslUntrustedServerResult = synchResult;
  1142. }
  1143. } catch (RuntimeException e) {
  1144. // avoid app crashes after changing the serial id of RemoteOperationResult
  1145. // in owncloud library with broadcast notifications pending to process
  1146. try {
  1147. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1148. } catch (RuntimeException re) {
  1149. // we did not send this intent, so ignoring
  1150. Log_OC.i(TAG, "Ignoring error deleting data");
  1151. }
  1152. }
  1153. }
  1154. }
  1155. private boolean checkForRemoteOperationError(RemoteOperationResult syncResult) {
  1156. return ResultCode.UNAUTHORIZED.equals(syncResult.getCode()) ||
  1157. (syncResult.isException() && syncResult.getException()
  1158. instanceof AuthenticatorException);
  1159. }
  1160. /**
  1161. * Show a text message on screen view for notifying user if content is
  1162. * loading or folder is empty
  1163. */
  1164. private void setBackgroundText() {
  1165. final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1166. if (ocFileListFragment != null) {
  1167. if (mSyncInProgress ||
  1168. getFile().getFileLength() > 0 && getStorageManager().getFolderContent(getFile(), false).isEmpty()) {
  1169. ocFileListFragment.setEmptyListLoadingMessage();
  1170. } else {
  1171. if (MainApp.isOnlyOnDevice()) {
  1172. ocFileListFragment.setMessageForEmptyList(R.string.file_list_empty_headline,
  1173. R.string.file_list_empty_on_device,
  1174. R.drawable.ic_list_empty_folder,
  1175. true);
  1176. } else {
  1177. ocFileListFragment.setEmptyListMessage(ExtendedListFragment.SearchType.NO_SEARCH);
  1178. }
  1179. }
  1180. } else {
  1181. Log_OC.e(TAG, "OCFileListFragment is null");
  1182. }
  1183. }
  1184. /**
  1185. * Once the file upload has finished -> update view
  1186. */
  1187. private class UploadFinishReceiver extends BroadcastReceiver {
  1188. /**
  1189. * Once the file upload has finished -> update view
  1190. *
  1191. * {@link BroadcastReceiver} to enable upload feedback in UI
  1192. */
  1193. @Override
  1194. public void onReceive(Context context, Intent intent) {
  1195. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1196. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1197. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1198. OCFile currentDir = getCurrentDir();
  1199. boolean isDescendant = currentDir != null && uploadedRemotePath != null &&
  1200. uploadedRemotePath.startsWith(currentDir.getRemotePath());
  1201. if (sameAccount && isDescendant) {
  1202. String linkedToRemotePath =
  1203. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1204. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1205. updateListOfFilesFragment(false);
  1206. }
  1207. }
  1208. boolean uploadWasFine = intent.getBooleanExtra(
  1209. FileUploader.EXTRA_UPLOAD_RESULT,
  1210. false);
  1211. boolean renamedInUpload = getFile().getRemotePath().
  1212. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1213. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1214. renamedInUpload;
  1215. FileFragment details = getSecondFragment();
  1216. if (sameAccount && sameFile && details instanceof FileDetailFragment) {
  1217. if (uploadWasFine) {
  1218. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1219. } else {
  1220. //TODO remove upload progress bar after upload failed.
  1221. Log_OC.d(TAG, "Remove upload progress bar after upload failed");
  1222. }
  1223. if (renamedInUpload) {
  1224. String newName = new File(uploadedRemotePath).getName();
  1225. DisplayUtils.showSnackMessage(
  1226. getActivity(),
  1227. R.string.filedetails_renamed_in_upload_msg,
  1228. newName
  1229. );
  1230. }
  1231. if (uploadWasFine || getFile().fileExists()) {
  1232. ((FileDetailFragment) details).updateFileDetails(false, true);
  1233. } else {
  1234. cleanSecondFragment();
  1235. }
  1236. // Force the preview if the file is an image or text file
  1237. if (uploadWasFine) {
  1238. OCFile ocFile = getFile();
  1239. if (PreviewImageFragment.canBePreviewed(ocFile)) {
  1240. startImagePreview(getFile(), true);
  1241. } else if (PreviewTextFileFragment.canBePreviewed(ocFile)) {
  1242. startTextPreview(ocFile, true);
  1243. }
  1244. // TODO what about other kind of previews?
  1245. }
  1246. }
  1247. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1248. if (ocFileListFragment != null) {
  1249. ocFileListFragment.setLoading(false);
  1250. }
  1251. }
  1252. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1253. private boolean isAscendant(String linkedToRemotePath) {
  1254. OCFile currentDir = getCurrentDir();
  1255. return currentDir != null && currentDir.getRemotePath().startsWith(linkedToRemotePath);
  1256. }
  1257. }
  1258. /**
  1259. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1260. *
  1261. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1262. * current folder.
  1263. */
  1264. private class DownloadFinishReceiver extends BroadcastReceiver {
  1265. @Override
  1266. public void onReceive(Context context, Intent intent) {
  1267. boolean sameAccount = isSameAccount(intent);
  1268. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1269. String downloadBehaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
  1270. boolean isDescendant = isDescendant(downloadedRemotePath);
  1271. if (sameAccount && isDescendant) {
  1272. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1273. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1274. updateListOfFilesFragment(false);
  1275. }
  1276. refreshSecondFragment(
  1277. intent.getAction(),
  1278. downloadedRemotePath,
  1279. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  1280. }
  1281. if (mWaitingToSend != null) {
  1282. // update file after downloading
  1283. mWaitingToSend = getStorageManager().getFileByRemoteId(mWaitingToSend.getRemoteId());
  1284. if (mWaitingToSend != null && mWaitingToSend.isDown() && downloadBehaviour != null) {
  1285. switch (downloadBehaviour) {
  1286. case OCFileListFragment.DOWNLOAD_SEND:
  1287. String packageName = intent.getStringExtra(SendShareDialog.PACKAGE_NAME);
  1288. String activityName = intent.getStringExtra(SendShareDialog.ACTIVITY_NAME);
  1289. sendDownloadedFile(packageName, activityName);
  1290. break;
  1291. default:
  1292. // do nothing
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. private boolean isDescendant(String downloadedRemotePath) {
  1299. OCFile currentDir = getCurrentDir();
  1300. return currentDir != null &&
  1301. downloadedRemotePath != null &&
  1302. downloadedRemotePath.startsWith(currentDir.getRemotePath());
  1303. }
  1304. private boolean isAscendant(String linkedToRemotePath) {
  1305. OCFile currentDir = getCurrentDir();
  1306. return currentDir != null &&
  1307. currentDir.getRemotePath().startsWith(linkedToRemotePath);
  1308. }
  1309. private boolean isSameAccount(Intent intent) {
  1310. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1311. return accountName != null && getAccount() != null && accountName.equals(getAccount().name);
  1312. }
  1313. }
  1314. public void browseToRoot() {
  1315. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1316. if (listOfFiles != null) { // should never be null, indeed
  1317. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1318. listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice(), false);
  1319. setFile(listOfFiles.getCurrentFile());
  1320. startSyncFolderOperation(root, false);
  1321. }
  1322. cleanSecondFragment();
  1323. }
  1324. /**
  1325. * {@inheritDoc}
  1326. * Updates action bar and second fragment, if in dual pane mode.
  1327. */
  1328. @Override
  1329. public void onBrowsedDownTo(OCFile directory) {
  1330. setFile(directory);
  1331. cleanSecondFragment();
  1332. // Sync Folder
  1333. startSyncFolderOperation(directory, false);
  1334. }
  1335. /**
  1336. * Shows the information of the {@link OCFile} received as a
  1337. * parameter in the second fragment.
  1338. *
  1339. * @param file {@link OCFile} whose details will be shown
  1340. */
  1341. @Override
  1342. public void showDetails(OCFile file) {
  1343. showDetails(file, 0);
  1344. }
  1345. /**
  1346. * Shows the information of the {@link OCFile} received as a
  1347. * parameter in the second fragment.
  1348. *
  1349. * @param file {@link OCFile} whose details will be shown
  1350. * @param activeTab the active tab in the details view
  1351. */
  1352. public void showDetails(OCFile file, int activeTab) {
  1353. User currentUser = getUser().orElseThrow(RuntimeException::new);
  1354. Fragment detailFragment = FileDetailFragment.newInstance(file, currentUser, activeTab);
  1355. setSecondFragment(detailFragment);
  1356. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1357. if (listOfFiles != null) {
  1358. resetHeaderScrollingState();
  1359. showSortListGroup(false);
  1360. listOfFiles.setFabVisible(false);
  1361. }
  1362. updateFragmentsVisibility(true);
  1363. updateActionBarTitleAndHomeButton(file);
  1364. setFile(file);
  1365. }
  1366. private void resetHeaderScrollingState() {
  1367. AppBarLayout appBarLayout = findViewById(R.id.appbar);
  1368. if (appBarLayout != null) {
  1369. appBarLayout.setExpanded(true);
  1370. }
  1371. }
  1372. @Override
  1373. @Deprecated // in future no dual pane
  1374. public void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1375. if (chosenFile == null) {
  1376. chosenFile = getFile(); // if no file is passed, current file decides
  1377. }
  1378. if (mDualPane) {
  1379. // in dual pane mode, keep the focus of title an action bar in the current folder
  1380. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1381. } else {
  1382. super.updateActionBarTitleAndHomeButton(chosenFile);
  1383. }
  1384. }
  1385. @Override
  1386. public boolean isDrawerIndicatorAvailable() {
  1387. return isRoot(getCurrentDir());
  1388. }
  1389. @Override
  1390. protected ServiceConnection newTransferenceServiceConnection() {
  1391. return new ListServiceConnection();
  1392. }
  1393. /**
  1394. * Defines callbacks for service binding, passed to bindService()
  1395. */
  1396. private class ListServiceConnection implements ServiceConnection {
  1397. @Override
  1398. public void onServiceConnected(ComponentName component, IBinder service) {
  1399. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1400. Log_OC.d(TAG, "Download service connected");
  1401. mDownloaderBinder = (FileDownloaderBinder) service;
  1402. if (mWaitingToPreview != null && getStorageManager() != null) {
  1403. // update the file
  1404. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1405. if (mWaitingToPreview != null && !mWaitingToPreview.isDown()) {
  1406. requestForDownload();
  1407. }
  1408. }
  1409. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1410. FileUploader.class))) {
  1411. Log_OC.d(TAG, "Upload service connected");
  1412. mUploaderBinder = (FileUploaderBinder) service;
  1413. } else {
  1414. return;
  1415. }
  1416. // a new chance to get the mDownloadBinder through
  1417. // getFileDownloadBinder() - THIS IS A MESS
  1418. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1419. if (listOfFiles != null && (getIntent() == null ||
  1420. (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) == null))) {
  1421. listOfFiles.listDirectory(MainApp.isOnlyOnDevice(), false);
  1422. }
  1423. FileFragment secondFragment = getSecondFragment();
  1424. if (secondFragment instanceof FileDetailFragment) {
  1425. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1426. detailFragment.listenForTransferProgress();
  1427. detailFragment.updateFileDetails(false, false);
  1428. }
  1429. }
  1430. @Override
  1431. public void onServiceDisconnected(ComponentName component) {
  1432. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1433. Log_OC.d(TAG, "Download service disconnected");
  1434. mDownloaderBinder = null;
  1435. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1436. Log_OC.d(TAG, "Upload service disconnected");
  1437. mUploaderBinder = null;
  1438. }
  1439. }
  1440. }
  1441. /**
  1442. * Updates the view associated to the activity after the finish of some operation over files
  1443. * in the current account.
  1444. *
  1445. * @param operation Removal operation performed.
  1446. * @param result Result of the removal.
  1447. */
  1448. @Override
  1449. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1450. super.onRemoteOperationFinish(operation, result);
  1451. if (operation instanceof RemoveFileOperation) {
  1452. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1453. } else if (operation instanceof RenameFileOperation) {
  1454. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1455. } else if (operation instanceof SynchronizeFileOperation) {
  1456. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1457. } else if (operation instanceof CreateFolderOperation) {
  1458. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1459. } else if (operation instanceof MoveFileOperation) {
  1460. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1461. } else if (operation instanceof CopyFileOperation) {
  1462. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1463. } else if (operation instanceof RestoreFileVersionRemoteOperation) {
  1464. onRestoreFileVersionOperationFinish(result);
  1465. }
  1466. }
  1467. private void refreshShowDetails() {
  1468. FileFragment details = getSecondFragment();
  1469. if (details != null) {
  1470. OCFile file = details.getFile();
  1471. if (file != null) {
  1472. file = getStorageManager().getFileByPath(file.getRemotePath());
  1473. if (details instanceof PreviewMediaFragment) {
  1474. // Refresh OCFile of the fragment
  1475. ((PreviewMediaFragment) details).updateFile(file);
  1476. } else if (details instanceof PreviewTextFragment) {
  1477. // Refresh OCFile of the fragment
  1478. ((PreviewTextFileFragment) details).updateFile(file);
  1479. } else {
  1480. showDetails(file);
  1481. }
  1482. }
  1483. supportInvalidateOptionsMenu();
  1484. }
  1485. }
  1486. /**
  1487. * Updates the view associated to the activity after the finish of an operation trying to
  1488. * remove a file.
  1489. *
  1490. * @param operation Removal operation performed.
  1491. * @param result Result of the removal.
  1492. */
  1493. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1494. RemoteOperationResult result) {
  1495. if (!operation.isInBackground()) {
  1496. DisplayUtils.showSnackMessage(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation,
  1497. getResources()));
  1498. }
  1499. if (result.isSuccess()) {
  1500. OCFile removedFile = operation.getFile();
  1501. tryStopPlaying(removedFile);
  1502. FileFragment second = getSecondFragment();
  1503. // check if file is still available, if so do nothing
  1504. boolean fileAvailable = getStorageManager().fileExists(removedFile.getFileId());
  1505. if (second != null && !fileAvailable && removedFile.equals(second.getFile())) {
  1506. if (second instanceof PreviewMediaFragment) {
  1507. ((PreviewMediaFragment) second).stopPreview(true);
  1508. }
  1509. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1510. cleanSecondFragment();
  1511. }
  1512. OCFile parentFile = getStorageManager().getFileById(removedFile.getParentId());
  1513. if (parentFile != null && parentFile.equals(getCurrentDir())) {
  1514. updateListOfFilesFragment(false);
  1515. }
  1516. supportInvalidateOptionsMenu();
  1517. } else {
  1518. if (result.isSslRecoverableException()) {
  1519. mLastSslUntrustedServerResult = result;
  1520. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1521. }
  1522. }
  1523. }
  1524. private void onRestoreFileVersionOperationFinish(RemoteOperationResult result) {
  1525. if (result.isSuccess()) {
  1526. OCFile file = getFile();
  1527. // delete old local copy
  1528. if (file.isDown()) {
  1529. List<OCFile> list = new ArrayList<>();
  1530. list.add(file);
  1531. getFileOperationsHelper().removeFiles(list, true, true);
  1532. // download new version, only if file was previously download
  1533. getFileOperationsHelper().syncFile(file);
  1534. }
  1535. OCFile parent = getStorageManager().getFileById(file.getParentId());
  1536. startSyncFolderOperation(parent, true, true);
  1537. if (getSecondFragment() instanceof FileDetailFragment) {
  1538. FileDetailFragment fileDetailFragment = (FileDetailFragment) getSecondFragment();
  1539. fileDetailFragment.getFileDetailActivitiesFragment().reload();
  1540. }
  1541. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_successfully);
  1542. } else {
  1543. DisplayUtils.showSnackMessage(this, R.string.file_version_restored_error);
  1544. }
  1545. }
  1546. private void tryStopPlaying(OCFile file) {
  1547. // placeholder for stop-on-delete future code
  1548. if(mPlayerConnection != null) {
  1549. mPlayerConnection.stop(file);
  1550. }
  1551. }
  1552. /**
  1553. * Updates the view associated to the activity after the finish of an operation trying to move a
  1554. * file.
  1555. *
  1556. * @param operation Move operation performed.
  1557. * @param result Result of the move operation.
  1558. */
  1559. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1560. RemoteOperationResult result) {
  1561. if (result.isSuccess()) {
  1562. syncAndUpdateFolder(true);
  1563. } else {
  1564. try {
  1565. DisplayUtils.showSnackMessage(
  1566. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1567. );
  1568. } catch (NotFoundException e) {
  1569. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1570. }
  1571. }
  1572. }
  1573. /**
  1574. * Shortcut to get access to the {@link FileDetailFragment} instance, if any
  1575. *
  1576. * @return A {@link FileDetailFragment} instance, or null
  1577. */
  1578. private FileDetailFragment getShareFileFragment() {
  1579. Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_SECOND_FRAGMENT);
  1580. if (fragment instanceof FileDetailFragment) {
  1581. return (FileDetailFragment) fragment;
  1582. } else {
  1583. return null;
  1584. }
  1585. }
  1586. /**
  1587. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1588. * file.
  1589. *
  1590. * @param operation Copy operation performed.
  1591. * @param result Result of the copy operation.
  1592. */
  1593. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1594. if (result.isSuccess()) {
  1595. updateListOfFilesFragment(false);
  1596. } else {
  1597. try {
  1598. DisplayUtils.showSnackMessage(
  1599. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1600. );
  1601. } catch (NotFoundException e) {
  1602. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1603. }
  1604. }
  1605. }
  1606. /**
  1607. * Updates the view associated to the activity after the finish of an operation trying to rename
  1608. * a file.
  1609. *
  1610. * @param operation Renaming operation performed.
  1611. * @param result Result of the renaming.
  1612. */
  1613. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1614. RemoteOperationResult result) {
  1615. Optional<User> optionalUser = getUser();
  1616. OCFile renamedFile = operation.getFile();
  1617. if (result.isSuccess() && optionalUser.isPresent()) {
  1618. final User currentUser = optionalUser.get();
  1619. FileFragment details = getSecondFragment();
  1620. if (details != null) {
  1621. if (details instanceof FileDetailFragment &&
  1622. renamedFile.equals(details.getFile())) {
  1623. ((FileDetailFragment) details).updateFileDetails(renamedFile, currentUser);
  1624. showDetails(renamedFile);
  1625. } else if (details instanceof PreviewMediaFragment &&
  1626. renamedFile.equals(details.getFile())) {
  1627. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1628. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1629. int position = ((PreviewMediaFragment) details).getPosition();
  1630. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  1631. .isMediaStreamingSupported();
  1632. startMediaPreview(renamedFile, position, true, true, streaming);
  1633. } else {
  1634. getFileOperationsHelper().openFile(renamedFile);
  1635. }
  1636. } else if (details instanceof PreviewTextFragment &&
  1637. renamedFile.equals(details.getFile())) {
  1638. ((PreviewTextFileFragment) details).updateFile(renamedFile);
  1639. if (PreviewTextFileFragment.canBePreviewed(renamedFile)) {
  1640. startTextPreview(renamedFile, true);
  1641. } else {
  1642. getFileOperationsHelper().openFile(renamedFile);
  1643. }
  1644. }
  1645. }
  1646. OCFile file = getStorageManager().getFileById(renamedFile.getParentId());
  1647. if (file != null && file.equals(getCurrentDir())) {
  1648. updateListOfFilesFragment(false);
  1649. }
  1650. } else {
  1651. DisplayUtils.showSnackMessage(
  1652. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1653. );
  1654. if (result.isSslRecoverableException()) {
  1655. mLastSslUntrustedServerResult = result;
  1656. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1657. }
  1658. }
  1659. }
  1660. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1661. RemoteOperationResult result) {
  1662. if (result.isSuccess() && operation.transferWasRequested()) {
  1663. OCFile syncedFile = operation.getLocalFile();
  1664. onTransferStateChanged(syncedFile, true, true);
  1665. supportInvalidateOptionsMenu();
  1666. refreshShowDetails();
  1667. }
  1668. }
  1669. /**
  1670. * Updates the view associated to the activity after the finish of an operation trying create a
  1671. * new folder
  1672. *
  1673. * @param operation Creation operation performed.
  1674. * @param result Result of the creation.
  1675. */
  1676. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1677. RemoteOperationResult result) {
  1678. if (result.isSuccess()) {
  1679. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1680. if (fileListFragment != null) {
  1681. fileListFragment.onItemClicked(getStorageManager().getFileByPath(operation.getRemotePath()));
  1682. }
  1683. } else {
  1684. try {
  1685. if (ResultCode.FOLDER_ALREADY_EXISTS == result.getCode()) {
  1686. DisplayUtils.showSnackMessage(this, R.string.folder_already_exists);
  1687. } else {
  1688. DisplayUtils.showSnackMessage(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation,
  1689. getResources()));
  1690. }
  1691. } catch (NotFoundException e) {
  1692. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1693. }
  1694. }
  1695. }
  1696. /**
  1697. * {@inheritDoc}
  1698. */
  1699. @Override
  1700. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1701. updateListOfFilesFragment(false);
  1702. FileFragment details = getSecondFragment();
  1703. Optional<User> optionalUser = getUser();
  1704. if (details instanceof FileDetailFragment && file.equals(details.getFile()) && optionalUser.isPresent()) {
  1705. final User currentUser = optionalUser.get();
  1706. if (downloading || uploading) {
  1707. ((FileDetailFragment) details).updateFileDetails(file, currentUser);
  1708. } else {
  1709. if (!file.fileExists()) {
  1710. cleanSecondFragment();
  1711. } else {
  1712. ((FileDetailFragment) details).updateFileDetails(false, true);
  1713. }
  1714. }
  1715. }
  1716. }
  1717. private void requestForDownload() {
  1718. User user = getUser().orElseThrow(RuntimeException::new);
  1719. //if (!mWaitingToPreview.isDownloading()) {
  1720. if (!mDownloaderBinder.isDownloading(user, mWaitingToPreview)) {
  1721. Intent i = new Intent(this, FileDownloader.class);
  1722. i.putExtra(FileDownloader.EXTRA_USER, user);
  1723. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1724. startService(i);
  1725. }
  1726. }
  1727. @Override
  1728. public void onSavedCertificate() {
  1729. startSyncFolderOperation(getCurrentDir(), false);
  1730. }
  1731. /**
  1732. * Starts an operation to refresh the requested folder.
  1733. *
  1734. * The operation is run in a new background thread created on the fly.
  1735. *
  1736. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1737. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1738. * synchronized too.
  1739. *
  1740. * @param folder Folder to refresh.
  1741. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1742. * didn't change.
  1743. */
  1744. public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
  1745. startSyncFolderOperation(folder, ignoreETag, false);
  1746. }
  1747. /**
  1748. * Starts an operation to refresh the requested folder.
  1749. *
  1750. * The operation is run in a new background thread created on the fly.
  1751. *
  1752. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1753. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1754. * synchronized too.
  1755. *
  1756. * @param folder Folder to refresh.
  1757. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1758. * didn't change.
  1759. * @param ignoreFocus reloads file list even without focus, e.g. on tablet mode, focus can still be in detail view
  1760. */
  1761. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag, boolean ignoreFocus) {
  1762. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1763. // or if the method is called from a dialog that is being dismissed
  1764. if (TextUtils.isEmpty(searchQuery)) {
  1765. getHandler().postDelayed(
  1766. new Runnable() {
  1767. @Override
  1768. public void run() {
  1769. if (ignoreFocus || hasWindowFocus()) {
  1770. long currentSyncTime = System.currentTimeMillis();
  1771. mSyncInProgress = true;
  1772. // perform folder synchronization
  1773. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1774. currentSyncTime,
  1775. false,
  1776. ignoreETag,
  1777. getStorageManager(),
  1778. getAccount(),
  1779. getApplicationContext()
  1780. );
  1781. synchFolderOp.execute(
  1782. getAccount(),
  1783. MainApp.getAppContext(),
  1784. FileDisplayActivity.this,
  1785. null,
  1786. null
  1787. );
  1788. OCFileListFragment fragment = getListOfFilesFragment();
  1789. if (fragment != null) {
  1790. fragment.setLoading(true);
  1791. }
  1792. setBackgroundText();
  1793. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1794. // another window floating over
  1795. }
  1796. },
  1797. DELAY_TO_REQUEST_REFRESH_OPERATION_LATER
  1798. );
  1799. }
  1800. }
  1801. private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
  1802. final User currentUser = getUser().orElseThrow(RuntimeException::new);
  1803. if (!mDownloaderBinder.isDownloading(currentUser, mWaitingToPreview)) {
  1804. Intent i = new Intent(this, FileDownloader.class);
  1805. i.putExtra(FileDownloader.EXTRA_USER, currentUser);
  1806. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1807. i.putExtra(SendShareDialog.PACKAGE_NAME, packageName);
  1808. i.putExtra(SendShareDialog.ACTIVITY_NAME, activityName);
  1809. i.putExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR, downloadBehaviour);
  1810. startService(i);
  1811. }
  1812. }
  1813. private void sendDownloadedFile(String packageName, String activityName) {
  1814. if (mWaitingToSend != null) {
  1815. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  1816. sendIntent.setType(mWaitingToSend.getMimeType());
  1817. sendIntent.putExtra(Intent.EXTRA_STREAM, mWaitingToSend.getExposedFileUri(this));
  1818. sendIntent.putExtra(Intent.ACTION_SEND, true);
  1819. sendIntent.setComponent(new ComponentName(packageName, activityName));
  1820. // Show dialog
  1821. String sendTitle = getString(R.string.activity_chooser_send_file_title);
  1822. startActivity(Intent.createChooser(sendIntent, sendTitle));
  1823. } else {
  1824. Log_OC.e(TAG, "Trying to send a NULL OCFile");
  1825. }
  1826. mWaitingToSend = null;
  1827. }
  1828. /**
  1829. * Requests the download of the received {@link OCFile} , updates the UI
  1830. * to monitor the download progress and prepares the activity to send the file
  1831. * when the download finishes.
  1832. *
  1833. * @param file {@link OCFile} to download and preview.
  1834. * @param packageName
  1835. * @param activityName
  1836. */
  1837. public void startDownloadForSending(OCFile file, String downloadBehaviour, String packageName,
  1838. String activityName) {
  1839. mWaitingToSend = file;
  1840. requestForDownload(mWaitingToSend, downloadBehaviour, packageName, activityName);
  1841. boolean hasSecondFragment = getSecondFragment() != null;
  1842. updateFragmentsVisibility(hasSecondFragment);
  1843. }
  1844. /**
  1845. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1846. *
  1847. * @param file Image {@link OCFile} to show.
  1848. */
  1849. public void startImagePreview(OCFile file, boolean showPreview) {
  1850. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1851. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1852. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1853. if (showPreview) {
  1854. startActivity(showDetailsIntent);
  1855. } else {
  1856. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  1857. getUserAccountManager(),
  1858. connectivityService);
  1859. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1860. }
  1861. }
  1862. /**
  1863. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1864. *
  1865. * @param file Image {@link OCFile} to show.
  1866. */
  1867. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  1868. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1869. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  1870. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1871. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  1872. if (showPreview) {
  1873. startActivity(showDetailsIntent);
  1874. } else {
  1875. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  1876. getUserAccountManager(),
  1877. connectivityService);
  1878. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1879. }
  1880. }
  1881. /**
  1882. * Stars the preview of an already down media {@link OCFile}.
  1883. *
  1884. * @param file Media {@link OCFile} to preview.
  1885. * @param startPlaybackPosition Media position where the playback will be started,
  1886. * in milliseconds.
  1887. * @param autoplay When 'true', the playback will start without user
  1888. * interactions.
  1889. */
  1890. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview,
  1891. boolean streamMedia) {
  1892. Optional<User> user = getUser();
  1893. if (!user.isPresent()) {
  1894. return; // not reachable under normal conditions
  1895. }
  1896. if (showPreview && file.isDown() && !file.isDownloading() || streamMedia) {
  1897. showSortListGroup(false);
  1898. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, user.get(), startPlaybackPosition, autoplay);
  1899. setSecondFragment(mediaFragment);
  1900. updateFragmentsVisibility(true);
  1901. updateActionBarTitleAndHomeButton(file);
  1902. setFile(file);
  1903. } else {
  1904. Intent previewIntent = new Intent();
  1905. previewIntent.putExtra(EXTRA_FILE, file);
  1906. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  1907. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  1908. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  1909. getUserAccountManager(),
  1910. connectivityService);
  1911. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1912. }
  1913. }
  1914. /**
  1915. * Stars the preview of a text file {@link OCFile}.
  1916. *
  1917. * @param file Text {@link OCFile} to preview.
  1918. */
  1919. public void startTextPreview(OCFile file, boolean showPreview) {
  1920. if (showPreview) {
  1921. showSortListGroup(false);
  1922. Bundle args = new Bundle();
  1923. args.putParcelable(EXTRA_FILE, file);
  1924. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1925. args.putBoolean(EXTRA_SEARCH, searchOpen);
  1926. args.putString(EXTRA_SEARCH_QUERY, searchQuery);
  1927. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1928. PreviewTextFileFragment.class.getName(), args);
  1929. setLeftFragment(textPreviewFragment);
  1930. binding.rightFragmentContainer.setVisibility(View.GONE);
  1931. super.updateActionBarTitleAndHomeButton(file);
  1932. } else {
  1933. Intent previewIntent = new Intent();
  1934. previewIntent.putExtra(EXTRA_FILE, file);
  1935. previewIntent.putExtra(TEXT_PREVIEW, true);
  1936. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  1937. getUserAccountManager(),
  1938. connectivityService);
  1939. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1940. }
  1941. }
  1942. /**
  1943. * Starts rich workspace preview for a folder.
  1944. *
  1945. * @param folder {@link OCFile} to preview its rich workspace.
  1946. */
  1947. public void startRichWorkspacePreview(OCFile folder) {
  1948. showSortListGroup(false);
  1949. Bundle args = new Bundle();
  1950. args.putParcelable(EXTRA_FILE, folder);
  1951. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1952. PreviewTextStringFragment.class.getName(),
  1953. args);
  1954. setLeftFragment(textPreviewFragment);
  1955. binding.rightFragmentContainer.setVisibility(View.GONE);
  1956. super.updateActionBarTitleAndHomeButton(folder);
  1957. }
  1958. public void startContactListFragment(OCFile file) {
  1959. final User user = getUser().orElseThrow(RuntimeException::new);
  1960. ContactsPreferenceActivity.startActivityWithContactsFile(this, user, file);
  1961. }
  1962. /**
  1963. * Requests the download of the received {@link OCFile} , updates the UI
  1964. * to monitor the download progress and prepares the activity to preview
  1965. * or open the file when the download finishes.
  1966. *
  1967. * @param file {@link OCFile} to download and preview.
  1968. */
  1969. public void startDownloadForPreview(OCFile file) {
  1970. final User currentUser = getUser().orElseThrow(RuntimeException::new);
  1971. Fragment detailFragment = FileDetailFragment.newInstance(file, currentUser);
  1972. setSecondFragment(detailFragment);
  1973. mWaitingToPreview = file;
  1974. requestForDownload();
  1975. updateFragmentsVisibility(true);
  1976. updateActionBarTitleAndHomeButton(file);
  1977. setFile(file);
  1978. }
  1979. /**
  1980. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  1981. *
  1982. * @param file {@link OCFile} file which operation are wanted to be cancel
  1983. */
  1984. public void cancelTransference(OCFile file) {
  1985. getFileOperationsHelper().cancelTransference(file);
  1986. if (mWaitingToPreview != null &&
  1987. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1988. mWaitingToPreview = null;
  1989. }
  1990. if (mWaitingToSend != null &&
  1991. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1992. mWaitingToSend = null;
  1993. }
  1994. onTransferStateChanged(file, false, false);
  1995. }
  1996. /**
  1997. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  1998. *
  1999. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  2000. */
  2001. public void cancelTransference(Collection<OCFile> files) {
  2002. for (OCFile file : files) {
  2003. cancelTransference(file);
  2004. }
  2005. }
  2006. @Override
  2007. public void onRefresh(boolean ignoreETag) {
  2008. syncAndUpdateFolder(ignoreETag);
  2009. }
  2010. @Override
  2011. public void onRefresh() {
  2012. syncAndUpdateFolder(true);
  2013. }
  2014. private void syncAndUpdateFolder(boolean ignoreETag) {
  2015. OCFileListFragment listOfFiles = getListOfFilesFragment();
  2016. if (listOfFiles != null && !listOfFiles.isSearchFragment()) {
  2017. OCFile folder = listOfFiles.getCurrentFile();
  2018. if (folder != null) {
  2019. startSyncFolderOperation(folder, ignoreETag);
  2020. }
  2021. }
  2022. }
  2023. @Override
  2024. public void showFiles(boolean onDeviceOnly) {
  2025. super.showFiles(onDeviceOnly);
  2026. if (onDeviceOnly) {
  2027. updateActionBarTitleAndHomeButtonByString(getString(R.string.drawer_item_on_device));
  2028. }
  2029. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  2030. if (ocFileListFragment != null) {
  2031. ocFileListFragment.refreshDirectory();
  2032. }
  2033. }
  2034. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2035. public void onMessageEvent(final SearchEvent event) {
  2036. Fragment fragment;
  2037. if (SearchRemoteOperation.SearchType.PHOTO_SEARCH == event.searchType) {
  2038. Log_OC.d(this, "Switch to photo search fragment");
  2039. fragment = new PhotoFragment(true);
  2040. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  2041. transaction.replace(R.id.left_fragment_container, fragment, TAG_LIST_OF_FILES);
  2042. transaction.commit();
  2043. }
  2044. }
  2045. @Subscribe(threadMode = ThreadMode.MAIN)
  2046. public void onMessageEvent(SyncEventFinished event) {
  2047. Bundle bundle = event.getIntent().getExtras();
  2048. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  2049. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  2050. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  2051. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  2052. .isMediaStreamingSupported();
  2053. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  2054. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  2055. (boolean) bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true, streaming);
  2056. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  2057. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  2058. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  2059. true);
  2060. } else {
  2061. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  2062. }
  2063. }
  2064. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2065. public void onMessageEvent(TokenPushEvent event) {
  2066. if (!preferences.isKeysReInitEnabled()) {
  2067. PushUtils.reinitKeys(getUserAccountManager());
  2068. } else {
  2069. PushUtils.pushRegistrationToServer(getUserAccountManager(), preferences.getPushToken());
  2070. }
  2071. }
  2072. @Override
  2073. public void onStart() {
  2074. super.onStart();
  2075. final Optional<User> optionalUser = getUser();
  2076. final FileDataStorageManager storageManager = getStorageManager();
  2077. if (optionalUser.isPresent() && storageManager != null) {
  2078. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  2079. // current Account
  2080. OCFile file = getFile();
  2081. // get parent from path
  2082. String parentPath = "";
  2083. if (file != null) {
  2084. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  2085. // upload in progress - right now, files are not inserted in the local
  2086. // cache until the upload is successful get parent from path
  2087. parentPath = file.getRemotePath().substring(0,
  2088. file.getRemotePath().lastIndexOf(file.getFileName()));
  2089. if (storageManager.getFileByPath(parentPath) == null) {
  2090. file = null; // not able to know the directory where the file is uploading
  2091. }
  2092. } else {
  2093. file = storageManager.getFileByPath(file.getRemotePath());
  2094. // currentDir = null if not in the current Account
  2095. }
  2096. }
  2097. if (file == null) {
  2098. // fall back to root folder
  2099. file = storageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null
  2100. }
  2101. setFile(file);
  2102. User user = optionalUser.get();
  2103. setupDrawer();
  2104. mSwitchAccountButton.setTag(user.getAccountName());
  2105. DisplayUtils.setAvatar(user, this, getResources()
  2106. .getDimension(R.dimen.nav_drawer_menu_avatar_radius), getResources(),
  2107. mSwitchAccountButton, this);
  2108. final String lastDisplayedAccountName = mLastDisplayedAccount != null ? mLastDisplayedAccount.name : null;
  2109. final boolean accountChanged = !user.getAccountName().equals(lastDisplayedAccountName);
  2110. if (accountChanged) {
  2111. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  2112. initFragmentsWithFile(user, file);
  2113. if (file.isFolder() && TextUtils.isEmpty(searchQuery)) {
  2114. startSyncFolderOperation(file, false);
  2115. }
  2116. } else {
  2117. updateFragmentsVisibility(!file.isFolder());
  2118. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  2119. }
  2120. }
  2121. if (optionalUser.isPresent()) {
  2122. mLastDisplayedAccount = optionalUser.get().toPlatformAccount();
  2123. } else {
  2124. mLastDisplayedAccount = null;
  2125. }
  2126. EventBus.getDefault().post(new TokenPushEvent());
  2127. checkForNewDevVersionNecessary(getApplicationContext());
  2128. }
  2129. @Override
  2130. protected void onRestart() {
  2131. super.onRestart();
  2132. checkForNewDevVersionNecessary(getApplicationContext());
  2133. }
  2134. public void setSearchQuery(String query) {
  2135. searchQuery = query;
  2136. }
  2137. private void handleOpenFileViaIntent(Intent intent) {
  2138. showLoadingDialog(getString(R.string.retrieving_file));
  2139. String userName = intent.getStringExtra(KEY_ACCOUNT);
  2140. String fileId = intent.getStringExtra(KEY_FILE_ID);
  2141. if (userName == null && fileId == null && intent.getData() != null) {
  2142. openDeepLink(intent.getData());
  2143. } else {
  2144. Optional<User> optionalUser = userName == null ? getUser() : getUserAccountManager().getUser(userName);
  2145. if (optionalUser.isPresent()) {
  2146. openFile(optionalUser.get(), fileId);
  2147. } else {
  2148. dismissLoadingDialog();
  2149. DisplayUtils.showSnackMessage(this, getString(R.string.associated_account_not_found));
  2150. }
  2151. }
  2152. }
  2153. private void openDeepLink(Uri uri) {
  2154. DeepLinkHandler linkHandler = new DeepLinkHandler(getUserAccountManager());
  2155. DeepLinkHandler.Match match = linkHandler.parseDeepLink(uri);
  2156. if (match == null) {
  2157. dismissLoadingDialog();
  2158. DisplayUtils.showSnackMessage(this, getString(R.string.invalid_url));
  2159. } else if (match.getUsers().isEmpty()) {
  2160. dismissLoadingDialog();
  2161. DisplayUtils.showSnackMessage(this, getString(R.string.associated_account_not_found));
  2162. } else if (match.getUsers().size() == 1) {
  2163. openFile(match.getUsers().get(0), match.getFileId());
  2164. } else {
  2165. selectUserAndOpenFile(match.getUsers(), match.getFileId());
  2166. }
  2167. }
  2168. private void selectUserAndOpenFile(List<User> users, String fileId) {
  2169. final CharSequence[] userNames = new CharSequence[users.size()];
  2170. for (int i = 0; i < userNames.length; i++) {
  2171. userNames[i] = users.get(i).getAccountName();
  2172. }
  2173. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  2174. builder
  2175. .setTitle(R.string.common_choose_account)
  2176. .setItems(userNames, (dialog, which) -> {
  2177. User user = users.get(which);
  2178. openFile(user, fileId);
  2179. showLoadingDialog(getString(R.string.retrieving_file));
  2180. });
  2181. final AlertDialog dialog = builder.create();
  2182. dismissLoadingDialog();
  2183. dialog.show();
  2184. }
  2185. private void openFile(User user, String fileId) {
  2186. setUser(user);
  2187. if (fileId == null) {
  2188. dismissLoadingDialog();
  2189. DisplayUtils.showSnackMessage(this, getString(R.string.error_retrieving_file));
  2190. return;
  2191. }
  2192. FileDataStorageManager storageManager = getStorageManager();
  2193. if (storageManager == null) {
  2194. storageManager = new FileDataStorageManager(user.toPlatformAccount(), getContentResolver());
  2195. }
  2196. FetchRemoteFileTask fetchRemoteFileTask = new FetchRemoteFileTask(user.toPlatformAccount(),
  2197. fileId,
  2198. storageManager,
  2199. this);
  2200. fetchRemoteFileTask.execute();
  2201. }
  2202. }