FileDisplayActivity.java 113 KB

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