FileDisplayActivity.java 106 KB

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