FileDisplayActivity.java 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727
  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. getListOfFilesFragment().setLoading(true);
  1943. setBackgroundText();
  1944. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1945. // another window floating over
  1946. }
  1947. },
  1948. DELAY_TO_REQUEST_REFRESH_OPERATION_LATER
  1949. );
  1950. }
  1951. }
  1952. private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
  1953. final User currentUser = getUser().orElseThrow(RuntimeException::new);
  1954. if (!mDownloaderBinder.isDownloading(currentUser.toPlatformAccount(), mWaitingToPreview)) {
  1955. Intent i = new Intent(this, FileDownloader.class);
  1956. i.putExtra(FileDownloader.EXTRA_USER, currentUser);
  1957. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1958. i.putExtra(SendShareDialog.PACKAGE_NAME, packageName);
  1959. i.putExtra(SendShareDialog.ACTIVITY_NAME, activityName);
  1960. i.putExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR, downloadBehaviour);
  1961. startService(i);
  1962. }
  1963. }
  1964. private void sendDownloadedFile(String packageName, String activityName) {
  1965. if (mWaitingToSend != null) {
  1966. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  1967. sendIntent.setType(mWaitingToSend.getMimeType());
  1968. sendIntent.putExtra(Intent.EXTRA_STREAM, mWaitingToSend.getExposedFileUri(this));
  1969. sendIntent.putExtra(Intent.ACTION_SEND, true);
  1970. sendIntent.setComponent(new ComponentName(packageName, activityName));
  1971. // Show dialog
  1972. String sendTitle = getString(R.string.activity_chooser_send_file_title);
  1973. startActivity(Intent.createChooser(sendIntent, sendTitle));
  1974. } else {
  1975. Log_OC.e(TAG, "Trying to send a NULL OCFile");
  1976. }
  1977. mWaitingToSend = null;
  1978. }
  1979. /**
  1980. * Requests the download of the received {@link OCFile} , updates the UI
  1981. * to monitor the download progress and prepares the activity to send the file
  1982. * when the download finishes.
  1983. *
  1984. * @param file {@link OCFile} to download and preview.
  1985. * @param packageName
  1986. * @param activityName
  1987. */
  1988. public void startDownloadForSending(OCFile file, String downloadBehaviour, String packageName,
  1989. String activityName) {
  1990. mWaitingToSend = file;
  1991. requestForDownload(mWaitingToSend, downloadBehaviour, packageName, activityName);
  1992. boolean hasSecondFragment = getSecondFragment() != null;
  1993. updateFragmentsVisibility(hasSecondFragment);
  1994. }
  1995. /**
  1996. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1997. *
  1998. * @param file Image {@link OCFile} to show.
  1999. */
  2000. public void startImagePreview(OCFile file, boolean showPreview) {
  2001. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  2002. showDetailsIntent.putExtra(EXTRA_FILE, file);
  2003. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  2004. if (showPreview) {
  2005. startActivity(showDetailsIntent);
  2006. } else {
  2007. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2008. getUserAccountManager(),
  2009. connectivityService);
  2010. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  2011. }
  2012. }
  2013. /**
  2014. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  2015. *
  2016. * @param file Image {@link OCFile} to show.
  2017. */
  2018. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  2019. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  2020. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  2021. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  2022. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  2023. if (showPreview) {
  2024. startActivity(showDetailsIntent);
  2025. } else {
  2026. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2027. getUserAccountManager(),
  2028. connectivityService);
  2029. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  2030. }
  2031. }
  2032. /**
  2033. * Stars the preview of an already down media {@link OCFile}.
  2034. *
  2035. * @param file Media {@link OCFile} to preview.
  2036. * @param startPlaybackPosition Media position where the playback will be started,
  2037. * in milliseconds.
  2038. * @param autoplay When 'true', the playback will start without user
  2039. * interactions.
  2040. */
  2041. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview,
  2042. boolean streamMedia) {
  2043. if (showPreview && file.isDown() && !file.isDownloading() || streamMedia) {
  2044. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  2045. setSecondFragment(mediaFragment);
  2046. updateFragmentsVisibility(true);
  2047. updateActionBarTitleAndHomeButton(file);
  2048. setFile(file);
  2049. } else {
  2050. Intent previewIntent = new Intent();
  2051. previewIntent.putExtra(EXTRA_FILE, file);
  2052. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  2053. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  2054. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2055. getUserAccountManager(),
  2056. connectivityService);
  2057. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2058. }
  2059. }
  2060. /**
  2061. * Stars the preview of a text file {@link OCFile}.
  2062. *
  2063. * @param file Text {@link OCFile} to preview.
  2064. */
  2065. public void startTextPreview(OCFile file, boolean showPreview) {
  2066. if (showPreview) {
  2067. Bundle args = new Bundle();
  2068. args.putParcelable(EXTRA_FILE, file);
  2069. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  2070. args.putBoolean(EXTRA_SEARCH, searchOpen);
  2071. args.putString(EXTRA_SEARCH_QUERY, searchQuery);
  2072. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  2073. PreviewTextFileFragment.class.getName(), args);
  2074. setSecondFragment(textPreviewFragment);
  2075. updateFragmentsVisibility(true);
  2076. updateActionBarTitleAndHomeButton(file);
  2077. setFile(file);
  2078. } else {
  2079. Intent previewIntent = new Intent();
  2080. previewIntent.putExtra(EXTRA_FILE, file);
  2081. previewIntent.putExtra(TEXT_PREVIEW, true);
  2082. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this,
  2083. getUserAccountManager(),
  2084. connectivityService);
  2085. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  2086. }
  2087. }
  2088. /**
  2089. * Stars rich workspace preview for a folder.
  2090. *
  2091. * @param folder {@link OCFile} to preview its rich workspace.
  2092. */
  2093. public void startRichWorkspacePreview(OCFile folder) {
  2094. Bundle args = new Bundle();
  2095. args.putParcelable(EXTRA_FILE, folder);
  2096. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  2097. PreviewTextStringFragment.class.getName(),
  2098. args);
  2099. setSecondFragment(textPreviewFragment);
  2100. updateFragmentsVisibility(true);
  2101. updateActionBarTitleAndHomeButton(folder);
  2102. setFile(folder);
  2103. }
  2104. public void startContactListFragment(OCFile file) {
  2105. final User user = getUser().orElseThrow(RuntimeException::new);
  2106. Intent intent = new Intent(this, ContactsPreferenceActivity.class);
  2107. intent.putExtra(ContactListFragment.FILE_NAME, Parcels.wrap(file));
  2108. intent.putExtra(ContactListFragment.USER, user);
  2109. startActivity(intent);
  2110. }
  2111. /**
  2112. * Requests the download of the received {@link OCFile} , updates the UI
  2113. * to monitor the download progress and prepares the activity to preview
  2114. * or open the file when the download finishes.
  2115. *
  2116. * @param file {@link OCFile} to download and preview.
  2117. */
  2118. public void startDownloadForPreview(OCFile file) {
  2119. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  2120. setSecondFragment(detailFragment);
  2121. mWaitingToPreview = file;
  2122. requestForDownload();
  2123. updateFragmentsVisibility(true);
  2124. updateActionBarTitleAndHomeButton(file);
  2125. setFile(file);
  2126. }
  2127. /**
  2128. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  2129. *
  2130. * @param file {@link OCFile} file which operation are wanted to be cancel
  2131. */
  2132. public void cancelTransference(OCFile file) {
  2133. getFileOperationsHelper().cancelTransference(file);
  2134. if (mWaitingToPreview != null &&
  2135. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  2136. mWaitingToPreview = null;
  2137. }
  2138. if (mWaitingToSend != null &&
  2139. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  2140. mWaitingToSend = null;
  2141. }
  2142. onTransferStateChanged(file, false, false);
  2143. }
  2144. /**
  2145. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  2146. *
  2147. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  2148. */
  2149. public void cancelTransference(Collection<OCFile> files) {
  2150. for (OCFile file : files) {
  2151. cancelTransference(file);
  2152. }
  2153. }
  2154. @Override
  2155. public void onRefresh(boolean ignoreETag) {
  2156. syncAndUpdateFolder(ignoreETag);
  2157. }
  2158. @Override
  2159. public void onRefresh() {
  2160. syncAndUpdateFolder(true);
  2161. }
  2162. private void syncAndUpdateFolder(boolean ignoreETag) {
  2163. OCFileListFragment listOfFiles = getListOfFilesFragment();
  2164. if (listOfFiles != null && !listOfFiles.isSearchFragment()) {
  2165. OCFile folder = listOfFiles.getCurrentFile();
  2166. if (folder != null) {
  2167. startSyncFolderOperation(folder, ignoreETag);
  2168. }
  2169. }
  2170. }
  2171. private boolean isGridView() {
  2172. return getListOfFilesFragment().isGridEnabled();
  2173. }
  2174. @Override
  2175. public void showFiles(boolean onDeviceOnly) {
  2176. super.showFiles(onDeviceOnly);
  2177. if (onDeviceOnly) {
  2178. updateActionBarTitleAndHomeButtonByString(getString(R.string.drawer_item_on_device));
  2179. }
  2180. getListOfFilesFragment().refreshDirectory();
  2181. }
  2182. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2183. public void onMessageEvent(final SearchEvent event) {
  2184. Fragment fragment;
  2185. if (SearchRemoteOperation.SearchType.PHOTO_SEARCH == event.searchType) {
  2186. Log_OC.d(this, "Switch to photo search fragment");
  2187. fragment = new PhotoFragment(true);
  2188. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  2189. transaction.replace(R.id.left_fragment_container, fragment, TAG_LIST_OF_FILES);
  2190. transaction.commit();
  2191. }
  2192. // else {
  2193. // Log_OC.d(this, "Switch to OCFileListFragment");
  2194. //
  2195. // fragment = new OCFileListFragment();
  2196. // }
  2197. }
  2198. @Subscribe(threadMode = ThreadMode.MAIN)
  2199. public void onMessageEvent(SyncEventFinished event) {
  2200. Bundle bundle = event.getIntent().getExtras();
  2201. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  2202. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  2203. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  2204. boolean streaming = AccountUtils.getServerVersionForAccount(getAccount(), this)
  2205. .isMediaStreamingSupported();
  2206. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  2207. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  2208. (boolean) bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true, streaming);
  2209. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  2210. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  2211. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  2212. true);
  2213. } else {
  2214. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  2215. }
  2216. }
  2217. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2218. public void onMessageEvent(TokenPushEvent event) {
  2219. if (!preferences.isKeysReInitEnabled()) {
  2220. PushUtils.reinitKeys(getUserAccountManager());
  2221. } else {
  2222. PushUtils.pushRegistrationToServer(getUserAccountManager(), preferences.getPushToken());
  2223. }
  2224. }
  2225. @Override
  2226. public void onStart() {
  2227. super.onStart();
  2228. final Optional<User> optionalUser = getUser();
  2229. final FileDataStorageManager storageManager = getStorageManager();
  2230. if (optionalUser.isPresent() && storageManager != null) {
  2231. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  2232. // current Account
  2233. OCFile file = getFile();
  2234. // get parent from path
  2235. String parentPath = "";
  2236. if (file != null) {
  2237. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  2238. // upload in progress - right now, files are not inserted in the local
  2239. // cache until the upload is successful get parent from path
  2240. parentPath = file.getRemotePath().substring(0,
  2241. file.getRemotePath().lastIndexOf(file.getFileName()));
  2242. if (storageManager.getFileByPath(parentPath) == null) {
  2243. file = null; // not able to know the directory where the file is uploading
  2244. }
  2245. } else {
  2246. file = storageManager.getFileByPath(file.getRemotePath());
  2247. // currentDir = null if not in the current Account
  2248. }
  2249. }
  2250. if (file == null) {
  2251. // fall back to root folder
  2252. file = storageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null
  2253. }
  2254. setFile(file);
  2255. User user = optionalUser.get();
  2256. setAccountInDrawer(user);
  2257. setupDrawer();
  2258. mSwitchAccountButton.setTag(user.getAccountName());
  2259. DisplayUtils.setAvatar(user, this, getResources()
  2260. .getDimension(R.dimen.nav_drawer_menu_avatar_radius), getResources(),
  2261. mSwitchAccountButton, this);
  2262. final String lastDisplayedAccountName = mLastDisplayedAccount != null ? mLastDisplayedAccount.name : null;
  2263. final boolean accountChanged = !user.getAccountName().equals(lastDisplayedAccountName);
  2264. if (accountChanged) {
  2265. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  2266. initFragmentsWithFile();
  2267. if (file.isFolder() && TextUtils.isEmpty(searchQuery)) {
  2268. startSyncFolderOperation(file, false);
  2269. }
  2270. } else {
  2271. updateFragmentsVisibility(!file.isFolder());
  2272. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  2273. }
  2274. }
  2275. if (optionalUser.isPresent()) {
  2276. mLastDisplayedAccount = optionalUser.get().toPlatformAccount();
  2277. } else {
  2278. mLastDisplayedAccount = null;
  2279. }
  2280. EventBus.getDefault().post(new TokenPushEvent());
  2281. checkForNewDevVersionNecessary(getApplicationContext());
  2282. }
  2283. @Override
  2284. protected void onRestart() {
  2285. super.onRestart();
  2286. checkForNewDevVersionNecessary(getApplicationContext());
  2287. }
  2288. public void setSearchQuery(String query) {
  2289. searchQuery = query;
  2290. }
  2291. private void handleOpenFileViaIntent(Intent intent) {
  2292. showLoadingDialog(getString(R.string.retrieving_file));
  2293. String userName = intent.getStringExtra(KEY_ACCOUNT);
  2294. String fileId = intent.getStringExtra(KEY_FILE_ID);
  2295. if (userName == null && fileId == null && intent.getData() != null) {
  2296. // Handle intent coming from URI
  2297. Pattern pattern = Pattern.compile("(.*)/index\\.php/([f])/([0-9]+)$");
  2298. Matcher matcher = pattern.matcher(intent.getData().toString());
  2299. if (matcher.matches()) {
  2300. String uri = matcher.group(1);
  2301. if ("f".equals(matcher.group(2))) {
  2302. fileId = matcher.group(3);
  2303. findAccountAndOpenFile(uri, fileId);
  2304. return;
  2305. }
  2306. } else {
  2307. dismissLoadingDialog();
  2308. DisplayUtils.showSnackMessage(this, getString(R.string.invalid_url));
  2309. return;
  2310. }
  2311. }
  2312. openFile(userName, fileId);
  2313. }
  2314. private void openFile(String userName, String fileId) {
  2315. Optional<User> optionalNewUser;
  2316. User user;
  2317. if (userName == null) {
  2318. optionalNewUser = getUser();
  2319. } else {
  2320. optionalNewUser = getUserAccountManager().getUser(userName);
  2321. }
  2322. if (optionalNewUser.isPresent()) {
  2323. user = optionalNewUser.get();
  2324. setUser(user);
  2325. updateAccountList();
  2326. } else {
  2327. dismissLoadingDialog();
  2328. DisplayUtils.showSnackMessage(this, getString(R.string.associated_account_not_found));
  2329. return;
  2330. }
  2331. if (fileId == null) {
  2332. dismissLoadingDialog();
  2333. DisplayUtils.showSnackMessage(this, getString(R.string.error_retrieving_file));
  2334. return;
  2335. }
  2336. FileDataStorageManager storageManager = getStorageManager();
  2337. if (storageManager == null) {
  2338. storageManager = new FileDataStorageManager(user.toPlatformAccount(), getContentResolver());
  2339. }
  2340. FetchRemoteFileTask fetchRemoteFileTask = new FetchRemoteFileTask(user.toPlatformAccount(),
  2341. fileId,
  2342. storageManager,
  2343. this);
  2344. fetchRemoteFileTask.execute();
  2345. }
  2346. private void findAccountAndOpenFile(String uri, String fileId) {
  2347. ArrayList<User> validUsers = new ArrayList<>();
  2348. for (User user : getUserAccountManager().getAllUsers()) {
  2349. if (user.getServer().getUri().toString().equals(uri)) {
  2350. validUsers.add(user);
  2351. }
  2352. }
  2353. if (validUsers.size() == 0) {
  2354. dismissLoadingDialog();
  2355. DisplayUtils.showSnackMessage(this, getString(R.string.associated_account_not_found));
  2356. return;
  2357. }
  2358. if (validUsers.size() == 1) {
  2359. openFile(validUsers.get(0).getAccountName(), fileId);
  2360. return;
  2361. }
  2362. ArrayList<String> validUserNames = new ArrayList<>();
  2363. for (User user : validUsers) {
  2364. validUserNames.add(user.getAccountName());
  2365. }
  2366. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  2367. builder
  2368. .setTitle(R.string.common_choose_account)
  2369. .setItems(validUserNames.toArray(new CharSequence[validUserNames.size()]),
  2370. new DialogInterface.OnClickListener() {
  2371. public void onClick(DialogInterface dialog, int which) {
  2372. openFile(validUsers.get(which).getAccountName(), fileId);
  2373. showLoadingDialog(getString(R.string.retrieving_file));
  2374. }
  2375. });
  2376. AlertDialog dialog = builder.create();
  2377. dismissLoadingDialog();
  2378. dialog.show();
  2379. }
  2380. }