FileDisplayActivity.java 113 KB

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