FileDisplayActivity.java 109 KB

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