FileDisplayActivity.java 106 KB

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