FileDisplayActivity.java 112 KB

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