FileDisplayActivity.java 105 KB

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