FileDisplayActivity.java 109 KB

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