FileDisplayActivity.java 116 KB

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