FileDisplayActivity.java 105 KB

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