FileDisplayActivity.java 112 KB

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