FileDisplayActivity.java 107 KB

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