FileDisplayActivity.java 116 KB

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