FileDisplayActivity.java 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2016 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.Manifest;
  23. import android.accounts.Account;
  24. import android.accounts.AuthenticatorException;
  25. import android.annotation.TargetApi;
  26. import android.app.Activity;
  27. import android.content.BroadcastReceiver;
  28. import android.content.ComponentName;
  29. import android.content.ContentResolver;
  30. import android.content.Context;
  31. import android.content.DialogInterface;
  32. import android.content.Intent;
  33. import android.content.IntentFilter;
  34. import android.content.ServiceConnection;
  35. import android.content.SharedPreferences;
  36. import android.content.SyncRequest;
  37. import android.content.pm.PackageManager;
  38. import android.content.res.Resources.NotFoundException;
  39. import android.os.Build;
  40. import android.os.Bundle;
  41. import android.os.IBinder;
  42. import android.os.Parcelable;
  43. import android.support.design.widget.BottomNavigationView;
  44. import android.support.design.widget.Snackbar;
  45. import android.support.v4.app.Fragment;
  46. import android.support.v4.app.FragmentManager;
  47. import android.support.v4.app.FragmentTransaction;
  48. import android.support.v4.content.ContextCompat;
  49. import android.support.v4.view.MenuItemCompat;
  50. import android.support.v7.app.AlertDialog;
  51. import android.support.v7.widget.SearchView;
  52. import android.text.TextUtils;
  53. import android.view.Menu;
  54. import android.view.MenuInflater;
  55. import android.view.MenuItem;
  56. import android.view.View;
  57. import android.view.ViewTreeObserver;
  58. import android.widget.EditText;
  59. import android.widget.ImageView;
  60. import com.owncloud.android.MainApp;
  61. import com.owncloud.android.R;
  62. import com.owncloud.android.datamodel.FileDataStorageManager;
  63. import com.owncloud.android.datamodel.OCFile;
  64. import com.owncloud.android.datamodel.VirtualFolderType;
  65. import com.owncloud.android.db.PreferenceManager;
  66. import com.owncloud.android.files.services.FileDownloader;
  67. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  68. import com.owncloud.android.files.services.FileUploader;
  69. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  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.media.MediaService;
  75. import com.owncloud.android.media.MediaServiceBinder;
  76. import com.owncloud.android.operations.CopyFileOperation;
  77. import com.owncloud.android.operations.CreateFolderOperation;
  78. import com.owncloud.android.operations.MoveFileOperation;
  79. import com.owncloud.android.operations.RefreshFolderOperation;
  80. import com.owncloud.android.operations.RemoveFileOperation;
  81. import com.owncloud.android.operations.RenameFileOperation;
  82. import com.owncloud.android.operations.SynchronizeFileOperation;
  83. import com.owncloud.android.operations.UploadFileOperation;
  84. import com.owncloud.android.services.observer.FileObserverService;
  85. import com.owncloud.android.syncadapter.FileSyncAdapter;
  86. import com.owncloud.android.ui.dialog.SendShareDialog;
  87. import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
  88. import com.owncloud.android.ui.events.SyncEventFinished;
  89. import com.owncloud.android.ui.events.TokenPushEvent;
  90. import com.owncloud.android.ui.fragment.ExtendedListFragment;
  91. import com.owncloud.android.ui.fragment.FileDetailFragment;
  92. import com.owncloud.android.ui.fragment.FileFragment;
  93. import com.owncloud.android.ui.fragment.OCFileListFragment;
  94. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  95. import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment;
  96. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  97. import com.owncloud.android.ui.helpers.UriUploader;
  98. import com.owncloud.android.ui.preview.PreviewImageActivity;
  99. import com.owncloud.android.ui.preview.PreviewImageFragment;
  100. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  101. import com.owncloud.android.ui.preview.PreviewTextFragment;
  102. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  103. import com.owncloud.android.utils.DataHolderUtil;
  104. import com.owncloud.android.utils.DisplayUtils;
  105. import com.owncloud.android.utils.ErrorMessageAdapter;
  106. import com.owncloud.android.utils.FileSortOrder;
  107. import com.owncloud.android.utils.MimeTypeUtil;
  108. import com.owncloud.android.utils.PermissionUtil;
  109. import com.owncloud.android.utils.PushUtils;
  110. import com.owncloud.android.utils.ThemeUtils;
  111. import org.greenrobot.eventbus.EventBus;
  112. import org.greenrobot.eventbus.Subscribe;
  113. import org.greenrobot.eventbus.ThreadMode;
  114. import org.parceler.Parcels;
  115. import java.io.File;
  116. import java.util.ArrayList;
  117. import java.util.Collection;
  118. import static com.owncloud.android.db.PreferenceManager.getSortOrder;
  119. /**
  120. * Displays, what files the user has available in his ownCloud. This is the main view.
  121. */
  122. public class FileDisplayActivity extends HookActivity
  123. implements FileFragment.ContainerActivity,
  124. OnEnforceableRefreshListener, SortingOrderDialogFragment.OnSortingOrderListener {
  125. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  126. private UploadFinishReceiver mUploadFinishReceiver;
  127. private DownloadFinishReceiver mDownloadFinishReceiver;
  128. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  129. private boolean mDualPane;
  130. private View mLeftFragmentContainer;
  131. private View mRightFragmentContainer;
  132. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  133. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  134. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  135. private static final String KEY_SEARCH_QUERY = "KEY_SEARCH_QUERY";
  136. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  137. public static final String DRAWER_MENU_ID = "DRAWER_MENU_ID";
  138. public static final int REQUEST_CODE__SELECT_CONTENT_FROM_APPS = REQUEST_CODE__LAST_SHARED + 1;
  139. public static final int REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM = REQUEST_CODE__LAST_SHARED + 2;
  140. public static final int REQUEST_CODE__MOVE_FILES = REQUEST_CODE__LAST_SHARED + 3;
  141. public static final int REQUEST_CODE__COPY_FILES = REQUEST_CODE__LAST_SHARED + 4;
  142. protected static final long DELAY_TO_REQUEST_REFRESH_OPERATION_LATER = DELAY_TO_REQUEST_OPERATIONS_LATER + 350;
  143. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  144. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  145. public static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  146. public static final String TEXT_PREVIEW = "TEXT_PREVIEW";
  147. private OCFile mWaitingToPreview;
  148. private boolean mSyncInProgress = false;
  149. private OCFile mWaitingToSend;
  150. private Collection<MenuItem> mDrawerMenuItemstoShowHideList;
  151. private MediaServiceBinder mMediaServiceBinder = null;
  152. private MediaServiceConnection mMediaServiceConnection = null;
  153. private String searchQuery;
  154. private SearchView searchView;
  155. @Override
  156. protected void onCreate(Bundle savedInstanceState) {
  157. Log_OC.v(TAG, "onCreate() start");
  158. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
  159. // is valid
  160. /// grant that FileObserverService is watching favorite files
  161. if (savedInstanceState == null) {
  162. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  163. startService(initObserversIntent);
  164. }
  165. /// Load of saved instance state
  166. if (savedInstanceState != null) {
  167. mWaitingToPreview = savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  168. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  169. mWaitingToSend = savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
  170. searchQuery = savedInstanceState.getString(KEY_SEARCH_QUERY);
  171. } else {
  172. mWaitingToPreview = null;
  173. mSyncInProgress = false;
  174. mWaitingToSend = null;
  175. }
  176. /// USER INTERFACE
  177. // Inflate and set the layout view
  178. setContentView(R.layout.files);
  179. // setup toolbar
  180. setupToolbar();
  181. // setup drawer
  182. if (MainApp.isOnlyOnDevice()) {
  183. setupDrawer(R.id.nav_on_device);
  184. } else {
  185. setupDrawer(R.id.nav_all_files);
  186. }
  187. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  188. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  189. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  190. // Action bar setup
  191. getSupportActionBar().setHomeButtonEnabled(true);
  192. // Init Fragment without UI to retain AsyncTask across configuration changes
  193. FragmentManager fm = getSupportFragmentManager();
  194. TaskRetainerFragment taskRetainerFragment =
  195. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  196. if (taskRetainerFragment == null) {
  197. taskRetainerFragment = new TaskRetainerFragment();
  198. fm.beginTransaction()
  199. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  200. } // else, Fragment already created and retained across configuration change
  201. Log_OC.v(TAG, "onCreate() end");
  202. }
  203. @Override
  204. protected void onPostCreate(Bundle savedInstanceState) {
  205. super.onPostCreate(savedInstanceState);
  206. if (!PermissionUtil.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  207. // Check if we should show an explanation
  208. if (PermissionUtil.shouldShowRequestPermissionRationale(this,
  209. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  210. // Show explanation to the user and then request permission
  211. Snackbar snackbar = Snackbar.make(findViewById(R.id.ListLayout), R.string.permission_storage_access,
  212. Snackbar.LENGTH_INDEFINITE)
  213. .setAction(R.string.common_ok, new View.OnClickListener() {
  214. @Override
  215. public void onClick(View v) {
  216. PermissionUtil.requestWriteExternalStoreagePermission(FileDisplayActivity.this);
  217. }
  218. });
  219. ThemeUtils.colorSnackbar(this, snackbar);
  220. snackbar.show();
  221. } else {
  222. // No explanation needed, request the permission.
  223. PermissionUtil.requestWriteExternalStoreagePermission(this);
  224. }
  225. }
  226. if (getIntent().getParcelableExtra(OCFileListFragment.SEARCH_EVENT) != null) {
  227. switchToSearchFragment(savedInstanceState);
  228. int menuId = getIntent().getIntExtra(DRAWER_MENU_ID, -1);
  229. if (menuId != -1) {
  230. setupDrawer(menuId);
  231. }
  232. } else {
  233. createMinFragments(savedInstanceState);
  234. refreshList(true);
  235. }
  236. setIndeterminate(mSyncInProgress);
  237. // always AFTER setContentView(...) in onCreate(); to work around bug in its implementation
  238. upgradeNotificationForInstantUpload();
  239. }
  240. private Activity getActivity() {
  241. return this;
  242. }
  243. /**
  244. * For Android 7+.
  245. * Opens a pop up info for the new instant upload and disabled the old instant upload.
  246. */
  247. private void upgradeNotificationForInstantUpload() {
  248. // check for Android 6+ if legacy instant upload is activated --> disable + show info
  249. if (PreferenceManager.instantPictureUploadEnabled(this) ||
  250. PreferenceManager.instantPictureUploadEnabled(this)) {
  251. // remove legacy shared preferences
  252. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
  253. editor.remove("instant_uploading")
  254. .remove("instant_video_uploading")
  255. .remove("instant_upload_path")
  256. .remove("instant_upload_path_use_subfolders")
  257. .remove("instant_upload_on_wifi")
  258. .remove("instant_upload_on_charging")
  259. .remove("instant_video_upload_path")
  260. .remove("instant_video_upload_path_use_subfolders")
  261. .remove("instant_video_upload_on_wifi")
  262. .remove("instant_video_uploading")
  263. .remove("instant_video_upload_on_charging")
  264. .remove("prefs_instant_behaviour").apply();
  265. // show info pop-up
  266. new AlertDialog.Builder(this, R.style.Theme_ownCloud_Dialog)
  267. .setTitle(R.string.drawer_synced_folders)
  268. .setMessage(R.string.synced_folders_new_info)
  269. .setPositiveButton(R.string.drawer_open, new DialogInterface.OnClickListener() {
  270. public void onClick(DialogInterface dialog, int which) {
  271. // show instant upload
  272. Intent syncedFoldersIntent = new Intent(getApplicationContext(), SyncedFoldersActivity.class);
  273. dialog.dismiss();
  274. startActivity(syncedFoldersIntent);
  275. }
  276. })
  277. .setNegativeButton(R.string.drawer_close, new DialogInterface.OnClickListener() {
  278. public void onClick(DialogInterface dialog, int which) {
  279. dialog.dismiss();
  280. }
  281. })
  282. .setIcon(R.drawable.nav_synced_folders)
  283. .show();
  284. }
  285. }
  286. @Override
  287. public void onRequestPermissionsResult(int requestCode,
  288. String permissions[], int[] grantResults) {
  289. switch (requestCode) {
  290. case PermissionUtil.PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
  291. // If request is cancelled, result arrays are empty.
  292. if (grantResults.length > 0
  293. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  294. // permission was granted
  295. EventBus.getDefault().post(new TokenPushEvent());
  296. refreshList(true);
  297. // toggle on is save since this is the only scenario this code gets accessed
  298. } else {
  299. // permission denied --> do nothing
  300. return;
  301. }
  302. return;
  303. }
  304. default:
  305. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  306. }
  307. }
  308. /**
  309. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  310. */
  311. @Override
  312. protected void onAccountSet(boolean stateWasRecovered) {
  313. super.onAccountSet(stateWasRecovered);
  314. if (getAccount() != null) {
  315. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  316. // current Account
  317. OCFile file = getFile();
  318. // get parent from path
  319. String parentPath = "";
  320. if (file != null) {
  321. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  322. // upload in progress - right now, files are not inserted in the local
  323. // cache until the upload is successful get parent from path
  324. parentPath = file.getRemotePath().substring(0,
  325. file.getRemotePath().lastIndexOf(file.getFileName()));
  326. if (getStorageManager().getFileByPath(parentPath) == null) {
  327. file = null; // not able to know the directory where the file is uploading
  328. }
  329. } else {
  330. file = getStorageManager().getFileByPath(file.getRemotePath());
  331. // currentDir = null if not in the current Account
  332. }
  333. }
  334. if (file == null) {
  335. // fall back to root folder
  336. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  337. }
  338. setFile(file);
  339. if (mAccountWasSet) {
  340. setAccountInDrawer(getAccount());
  341. setupDrawer();
  342. }
  343. if (!stateWasRecovered) {
  344. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  345. initFragmentsWithFile();
  346. if (file.isFolder() && TextUtils.isEmpty(searchQuery)) {
  347. startSyncFolderOperation(file, false);
  348. }
  349. } else {
  350. updateFragmentsVisibility(!file.isFolder());
  351. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  352. }
  353. }
  354. }
  355. private void switchToSearchFragment(Bundle savedInstanceState) {
  356. if (savedInstanceState == null) {
  357. OCFileListFragment listOfFiles = new OCFileListFragment();
  358. Bundle args = new Bundle();
  359. args.putParcelable(OCFileListFragment.SEARCH_EVENT,
  360. getIntent().getParcelableExtra(OCFileListFragment.SEARCH_EVENT));
  361. args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
  362. listOfFiles.setArguments(args);
  363. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  364. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  365. transaction.commit();
  366. } else {
  367. getSupportFragmentManager().findFragmentByTag(TAG_LIST_OF_FILES);
  368. }
  369. }
  370. private void createMinFragments(Bundle savedInstanceState) {
  371. if (savedInstanceState == null) {
  372. OCFileListFragment listOfFiles = new OCFileListFragment();
  373. Bundle args = new Bundle();
  374. args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
  375. listOfFiles.setArguments(args);
  376. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  377. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  378. transaction.commit();
  379. } else {
  380. getSupportFragmentManager().findFragmentByTag(TAG_LIST_OF_FILES);
  381. }
  382. }
  383. private void initFragmentsWithFile() {
  384. if (getAccount() != null && getFile() != null) {
  385. /// First fragment
  386. OCFileListFragment listOfFiles = getListOfFilesFragment();
  387. if (listOfFiles != null && TextUtils.isEmpty(searchQuery)) {
  388. listOfFiles.listDirectory(getCurrentDir(), MainApp.isOnlyOnDevice(), false);
  389. } else {
  390. Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  391. }
  392. /// Second fragment
  393. OCFile file = getFile();
  394. Fragment secondFragment = getSecondFragment();
  395. if (secondFragment == null) {
  396. secondFragment = chooseInitialSecondFragment(file);
  397. }
  398. if (secondFragment != null) {
  399. setSecondFragment(secondFragment);
  400. updateFragmentsVisibility(true);
  401. updateActionBarTitleAndHomeButton(file);
  402. } else {
  403. cleanSecondFragment();
  404. if (file.isDown() && MimeTypeUtil.isVCard(file.getMimetype())) {
  405. startContactListFragment(file);
  406. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  407. startTextPreview(file, false);
  408. }
  409. }
  410. } else {
  411. Log_OC.e(TAG, "initFragments() called with invalid NULLs!");
  412. if (getAccount() == null) {
  413. Log_OC.e(TAG, "\t account is NULL");
  414. }
  415. if (getFile() == null) {
  416. Log_OC.e(TAG, "\t file is NULL");
  417. }
  418. }
  419. }
  420. //Is called with the flag FLAG_ACTIVITY_SINGLE_TOP and set the new file and intent
  421. @Override
  422. protected void onNewIntent(Intent intent) {
  423. super.onNewIntent(intent);
  424. if (intent.getAction() != null && intent.getAction().equalsIgnoreCase(ACTION_DETAILS)) {
  425. setIntent(intent);
  426. setFile(intent.getParcelableExtra(EXTRA_FILE));
  427. }
  428. }
  429. private Fragment chooseInitialSecondFragment(OCFile file) {
  430. Fragment secondFragment = null;
  431. if (file != null && !file.isFolder()) {
  432. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)) {
  433. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  434. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  435. secondFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  436. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  437. secondFragment = null;
  438. } else {
  439. secondFragment = FileDetailFragment.newInstance(file, getAccount());
  440. }
  441. }
  442. return secondFragment;
  443. }
  444. /**
  445. * Replaces the second fragment managed by the activity with the received as
  446. * a parameter.
  447. * <p/>
  448. * Assumes never will be more than two fragments managed at the same time.
  449. *
  450. * @param fragment New second Fragment to set.
  451. */
  452. private void setSecondFragment(Fragment fragment) {
  453. if (searchView != null) {
  454. searchView.post(new Runnable() {
  455. @Override
  456. public void run() {
  457. searchView.setQuery("", true);
  458. }
  459. });
  460. }
  461. setDrawerIndicatorEnabled(false);
  462. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  463. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  464. transaction.commit();
  465. }
  466. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  467. if (mDualPane) {
  468. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  469. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  470. }
  471. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  472. mRightFragmentContainer.setVisibility(View.VISIBLE);
  473. }
  474. } else if (existsSecondFragment) {
  475. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  476. mLeftFragmentContainer.setVisibility(View.GONE);
  477. }
  478. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  479. mRightFragmentContainer.setVisibility(View.VISIBLE);
  480. }
  481. } else {
  482. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  483. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  484. }
  485. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  486. mRightFragmentContainer.setVisibility(View.GONE);
  487. }
  488. }
  489. }
  490. private OCFileListFragment getListOfFilesFragment() {
  491. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  492. FileDisplayActivity.TAG_LIST_OF_FILES);
  493. if (listOfFiles != null) {
  494. return (OCFileListFragment) listOfFiles;
  495. }
  496. Log_OC.e(TAG, "Access to unexisting list of files fragment!!");
  497. return null;
  498. }
  499. public FileFragment getSecondFragment() {
  500. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  501. if (second != null) {
  502. return (FileFragment) second;
  503. }
  504. return null;
  505. }
  506. protected void cleanSecondFragment() {
  507. Fragment second = getSecondFragment();
  508. if (second != null) {
  509. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  510. tr.remove(second);
  511. tr.commit();
  512. }
  513. updateFragmentsVisibility(false);
  514. updateActionBarTitleAndHomeButton(null);
  515. }
  516. public void refreshListOfFilesFragment(boolean fromSearch) {
  517. OCFileListFragment fileListFragment = getListOfFilesFragment();
  518. if (fileListFragment != null) {
  519. fileListFragment.listDirectory(MainApp.isOnlyOnDevice(), fromSearch);
  520. }
  521. }
  522. public void resetSearchView() {
  523. OCFileListFragment fileListFragment = getListOfFilesFragment();
  524. if (fileListFragment != null) {
  525. fileListFragment.setSearchFragment(false);
  526. }
  527. }
  528. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  529. boolean success) {
  530. FileFragment secondFragment = getSecondFragment();
  531. boolean waitedPreview = (mWaitingToPreview != null &&
  532. mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  533. if (secondFragment instanceof FileDetailFragment) {
  534. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  535. OCFile fileInFragment = detailsFragment.getFile();
  536. if (fileInFragment != null &&
  537. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  538. // the user browsed to other file ; forget the automatic preview
  539. mWaitingToPreview = null;
  540. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  541. // grant that the right panel updates the progress bar
  542. detailsFragment.listenForTransferProgress();
  543. detailsFragment.updateFileDetails(true, false);
  544. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  545. // update the right panel
  546. boolean detailsFragmentChanged = false;
  547. if (waitedPreview) {
  548. if (success) {
  549. mWaitingToPreview = getStorageManager().getFileById(
  550. mWaitingToPreview.getFileId()); // update the file from database,
  551. // for the local storage path
  552. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  553. startMediaPreview(mWaitingToPreview, 0, true, true);
  554. detailsFragmentChanged = true;
  555. } else if (MimeTypeUtil.isVCard(mWaitingToPreview.getMimetype())) {
  556. startContactListFragment(mWaitingToPreview);
  557. detailsFragmentChanged = true;
  558. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  559. startTextPreview(mWaitingToPreview, true);
  560. detailsFragmentChanged = true;
  561. } else {
  562. getFileOperationsHelper().openFile(mWaitingToPreview);
  563. }
  564. }
  565. mWaitingToPreview = null;
  566. }
  567. if (!detailsFragmentChanged) {
  568. detailsFragment.updateFileDetails(false, (success));
  569. }
  570. }
  571. }
  572. }
  573. @Override
  574. public boolean onPrepareOptionsMenu(Menu menu) {
  575. boolean drawerOpen = isDrawerOpen();
  576. for (MenuItem menuItem : mDrawerMenuItemstoShowHideList) {
  577. menuItem.setVisible(!drawerOpen);
  578. }
  579. return super.onPrepareOptionsMenu(menu);
  580. }
  581. @Override
  582. public boolean onCreateOptionsMenu(Menu menu) {
  583. MenuInflater inflater = getMenuInflater();
  584. inflater.inflate(R.menu.main_menu, menu);
  585. menu.findItem(R.id.action_create_dir).setVisible(false);
  586. final MenuItem item = menu.findItem(R.id.action_search);
  587. searchView = (SearchView) MenuItemCompat.getActionView(item);
  588. // hacky as no default way is provided
  589. int fontColor = ThemeUtils.fontColor();
  590. EditText editText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
  591. editText.setHintTextColor(fontColor);
  592. editText.setTextColor(fontColor);
  593. ImageView searchClose = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
  594. searchClose.setColorFilter(ThemeUtils.fontColor());
  595. // populate list of menu items to show/hide when drawer is opened/closed
  596. mDrawerMenuItemstoShowHideList = new ArrayList<>(4);
  597. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sort));
  598. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_sync_account));
  599. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_switch_view));
  600. mDrawerMenuItemstoShowHideList.add(menu.findItem(R.id.action_search));
  601. //focus the SearchView
  602. if (!TextUtils.isEmpty(searchQuery)) {
  603. searchView.post(new Runnable() {
  604. @Override
  605. public void run() {
  606. searchView.setIconified(false);
  607. searchView.setQuery(searchQuery, true);
  608. searchView.clearFocus();
  609. }
  610. });
  611. }
  612. final View mSearchEditFrame = searchView
  613. .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
  614. searchView.setOnCloseListener(new SearchView.OnCloseListener() {
  615. @Override
  616. public boolean onClose() {
  617. if (TextUtils.isEmpty(searchView.getQuery().toString())) {
  618. searchView.onActionViewCollapsed();
  619. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable()); // order matters
  620. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  621. mDrawerToggle.syncState();
  622. } else {
  623. searchView.post(new Runnable() {
  624. @Override
  625. public void run() {
  626. searchView.setQuery("", true);
  627. }
  628. });
  629. }
  630. return true;
  631. }
  632. });
  633. ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
  634. vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  635. int oldVisibility = -1;
  636. @Override
  637. public void onGlobalLayout() {
  638. int currentVisibility = mSearchEditFrame.getVisibility();
  639. if (currentVisibility != oldVisibility) {
  640. if (currentVisibility == View.VISIBLE) {
  641. setDrawerIndicatorEnabled(false);
  642. }
  643. oldVisibility = currentVisibility;
  644. }
  645. }
  646. });
  647. return true;
  648. }
  649. @Override
  650. public boolean onOptionsItemSelected(MenuItem item) {
  651. boolean retval = true;
  652. switch (item.getItemId()) {
  653. case R.id.action_sync_account: {
  654. startSynchronization();
  655. break;
  656. }
  657. case android.R.id.home: {
  658. FileFragment second = getSecondFragment();
  659. OCFile currentDir = getCurrentDir();
  660. if (isDrawerOpen()) {
  661. closeDrawer();
  662. } else if ((currentDir != null && currentDir.getParentId() != 0) ||
  663. (second != null && second.getFile() != null) || isSearchOpen()) {
  664. onBackPressed();
  665. } else {
  666. openDrawer();
  667. }
  668. break;
  669. }
  670. case R.id.action_sort: {
  671. FragmentManager fm = getSupportFragmentManager();
  672. FragmentTransaction ft = fm.beginTransaction();
  673. ft.addToBackStack(null);
  674. SortingOrderDialogFragment mSortingOrderDialogFragment = SortingOrderDialogFragment.newInstance(
  675. getSortOrder(this, getListOfFilesFragment().getCurrentFile()));
  676. mSortingOrderDialogFragment.show(ft, SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT);
  677. break;
  678. }
  679. case R.id.action_switch_view: {
  680. if (isGridView()) {
  681. item.setTitle(getString(R.string.action_switch_grid_view));
  682. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_module));
  683. getListOfFilesFragment().setListAsPreferred();
  684. } else {
  685. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  686. item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_list));
  687. getListOfFilesFragment().setGridAsPreferred();
  688. }
  689. break;
  690. }
  691. case R.id.action_select_all: {
  692. getListOfFilesFragment().selectAllFiles(true);
  693. break;
  694. }
  695. default:
  696. retval = super.onOptionsItemSelected(item);
  697. break;
  698. }
  699. return retval;
  700. }
  701. private void startSynchronization() {
  702. Log_OC.d(TAG, "Got to start sync");
  703. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  704. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  705. ContentResolver.cancelSync(null, MainApp.getAuthority());
  706. // cancel the current synchronizations of any ownCloud account
  707. Bundle bundle = new Bundle();
  708. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  709. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  710. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  711. MainApp.getAuthority());
  712. ContentResolver.requestSync(
  713. getAccount(),
  714. MainApp.getAuthority(), bundle);
  715. } else {
  716. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  717. MainApp.getAuthority() + " with new API");
  718. SyncRequest.Builder builder = new SyncRequest.Builder();
  719. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  720. builder.setExpedited(true);
  721. builder.setManual(true);
  722. builder.syncOnce();
  723. // Fix bug in Android Lollipop when you click on refresh the whole account
  724. Bundle extras = new Bundle();
  725. builder.setExtras(extras);
  726. SyncRequest request = builder.build();
  727. ContentResolver.requestSync(request);
  728. }
  729. }
  730. /**
  731. * Called, when the user selected something for uploading
  732. */
  733. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  734. @Override
  735. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  736. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS &&
  737. (resultCode == RESULT_OK ||
  738. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  739. requestUploadOfContentFromApps(data, resultCode);
  740. } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM &&
  741. (resultCode == RESULT_OK ||
  742. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE ||
  743. resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING ||
  744. resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) {
  745. requestUploadOfFilesFromFileSystem(data, resultCode);
  746. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  747. final Intent fData = data;
  748. getHandler().postDelayed(
  749. new Runnable() {
  750. @Override
  751. public void run() {
  752. requestMoveOperation(fData);
  753. }
  754. },
  755. DELAY_TO_REQUEST_OPERATIONS_LATER
  756. );
  757. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  758. final Intent fData = data;
  759. getHandler().postDelayed(
  760. new Runnable() {
  761. @Override
  762. public void run() {
  763. requestCopyOperation(fData);
  764. }
  765. },
  766. DELAY_TO_REQUEST_OPERATIONS_LATER
  767. );
  768. } else {
  769. super.onActivityResult(requestCode, resultCode, data);
  770. }
  771. }
  772. private void requestUploadOfFilesFromFileSystem(Intent data, int resultCode) {
  773. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  774. if (filePaths != null) {
  775. String[] remotePaths = new String[filePaths.length];
  776. String remotePathBase = getCurrentDir().getRemotePath();
  777. for (int j = 0; j < remotePaths.length; j++) {
  778. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  779. }
  780. // default, as fallback
  781. int behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  782. switch (resultCode) {
  783. case UploadFilesActivity.RESULT_OK_AND_MOVE:
  784. behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE;
  785. break;
  786. case UploadFilesActivity.RESULT_OK_AND_DELETE:
  787. behaviour = FileUploader.LOCAL_BEHAVIOUR_DELETE;
  788. break;
  789. case UploadFilesActivity.RESULT_OK_AND_DO_NOTHING:
  790. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  791. break;
  792. }
  793. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  794. requester.uploadNewFile(
  795. this,
  796. getAccount(),
  797. filePaths,
  798. remotePaths,
  799. null, // MIME type will be detected from file name
  800. behaviour,
  801. false, // do not create parent folder if not existent
  802. UploadFileOperation.CREATED_BY_USER,
  803. false,
  804. false
  805. );
  806. } else {
  807. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  808. DisplayUtils.showSnackMessage(this, R.string.filedisplay_no_file_selected);
  809. }
  810. }
  811. private void requestUploadOfContentFromApps(Intent contentIntent, int resultCode) {
  812. ArrayList<Parcelable> streamsToUpload = new ArrayList<>();
  813. //getClipData is only supported on api level 16+, Jelly Bean
  814. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  815. contentIntent.getClipData() != null &&
  816. contentIntent.getClipData().getItemCount() > 0) {
  817. for (int i = 0; i < contentIntent.getClipData().getItemCount(); i++) {
  818. streamsToUpload.add(contentIntent.getClipData().getItemAt(i).getUri());
  819. }
  820. } else {
  821. streamsToUpload.add(contentIntent.getData());
  822. }
  823. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  824. FileUploader.LOCAL_BEHAVIOUR_COPY;
  825. OCFile currentDir = getCurrentDir();
  826. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  827. UriUploader uploader = new UriUploader(
  828. this,
  829. streamsToUpload,
  830. remotePath,
  831. getAccount(),
  832. behaviour,
  833. false, // Not show waiting dialog while file is being copied from private storage
  834. null // Not needed copy temp task listener
  835. );
  836. uploader.uploadUris();
  837. }
  838. /**
  839. * Request the operation for moving the file/folder from one path to another
  840. *
  841. * @param data Intent received
  842. */
  843. private void requestMoveOperation(Intent data) {
  844. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  845. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  846. getFileOperationsHelper().moveFiles(files, folderToMoveAt);
  847. }
  848. /**
  849. * Request the operation for copying the file/folder from one path to another
  850. *
  851. * @param data Intent received
  852. */
  853. private void requestCopyOperation(Intent data) {
  854. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  855. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  856. getFileOperationsHelper().copyFiles(files, folderToMoveAt);
  857. }
  858. private boolean isSearchOpen() {
  859. final View mSearchEditFrame = searchView.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
  860. return (mSearchEditFrame != null && mSearchEditFrame.getVisibility() == View.VISIBLE);
  861. }
  862. private void revertBottomNavigationBarToAllFiles() {
  863. if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
  864. BottomNavigationView bottomNavigationView = getListOfFilesFragment().getView()
  865. .findViewById(R.id.bottom_navigation_view);
  866. if (bottomNavigationView.getMenu().findItem(R.id.nav_bar_settings).isChecked()) {
  867. bottomNavigationView.getMenu().findItem(R.id.nav_bar_files).setChecked(true);
  868. }
  869. }
  870. }
  871. @Override
  872. public void onBackPressed() {
  873. boolean isFabOpen = isFabOpen();
  874. boolean isDrawerOpen = isDrawerOpen();
  875. boolean isSearchOpen = isSearchOpen();
  876. /*
  877. * BackPressed priority/hierarchy:
  878. * 1. close search view if opened
  879. * 2. close drawer if opened
  880. * 3. close FAB if open (only if drawer isn't open)
  881. * 4. navigate up (only if drawer and FAB aren't open)
  882. */
  883. if (isSearchOpen && searchView != null) {
  884. searchView.setQuery("", true);
  885. searchView.onActionViewCollapsed();
  886. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  887. } else if (isDrawerOpen && isFabOpen) {
  888. // close drawer first
  889. super.onBackPressed();
  890. } else if (isDrawerOpen && !isFabOpen) {
  891. // close drawer
  892. super.onBackPressed();
  893. } else if (!isDrawerOpen && isFabOpen) {
  894. // close fab
  895. getListOfFilesFragment().getFabMain().collapse();
  896. } else {
  897. // all closed
  898. //if PreviewImageActivity called this activity and mDualPane==false then calls PreviewImageActivity again
  899. if ((getIntent().getAction() != null && getIntent().getAction().equalsIgnoreCase(ACTION_DETAILS)) && !mDualPane) {
  900. getIntent().setAction(null);
  901. getIntent().putExtra(EXTRA_FILE, (OCFile) null);
  902. startImagePreview(getFile(), false);
  903. }
  904. OCFileListFragment listOfFiles = getListOfFilesFragment();
  905. if (mDualPane || getSecondFragment() == null) {
  906. OCFile currentDir = getCurrentDir();
  907. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  908. finish();
  909. return;
  910. }
  911. if (listOfFiles != null) { // should never be null, indeed
  912. listOfFiles.onBrowseUp();
  913. }
  914. }
  915. if (listOfFiles != null) { // should never be null, indeed
  916. setFile(listOfFiles.getCurrentFile());
  917. }
  918. cleanSecondFragment();
  919. }
  920. }
  921. @Override
  922. protected void onSaveInstanceState(Bundle outState) {
  923. // responsibility of restore is preferred in onCreate() before than in
  924. // onRestoreInstanceState when there are Fragments involved
  925. Log_OC.v(TAG, "onSaveInstanceState() start");
  926. super.onSaveInstanceState(outState);
  927. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  928. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  929. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  930. // mRefreshSharesInProgress);
  931. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  932. if (searchView != null) {
  933. outState.putString(KEY_SEARCH_QUERY, searchView.getQuery().toString());
  934. }
  935. Log_OC.v(TAG, "onSaveInstanceState() end");
  936. }
  937. @Override
  938. protected void onResume() {
  939. Log_OC.v(TAG, "onResume() start");
  940. super.onResume();
  941. OCFile startFile = null;
  942. if (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) != null) {
  943. startFile = getIntent().getParcelableExtra(EXTRA_FILE);
  944. setFile(startFile);
  945. }
  946. revertBottomNavigationBarToAllFiles();
  947. // refresh list of files
  948. if (searchView != null && !TextUtils.isEmpty(searchQuery)) {
  949. searchView.setQuery(searchQuery, true);
  950. } else if (getListOfFilesFragment() != null && !getListOfFilesFragment().getIsSearchFragment()
  951. && startFile == null) {
  952. refreshListOfFilesFragment(false);
  953. } else {
  954. getListOfFilesFragment().listDirectory(startFile, false, false);
  955. updateActionBarTitleAndHomeButton(startFile);
  956. }
  957. // Listen for sync messages
  958. if (getListOfFilesFragment() != null && !getListOfFilesFragment().getIsSearchFragment()) {
  959. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  960. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  961. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  962. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  963. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  964. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  965. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  966. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  967. // syncIntentFilter);
  968. }
  969. // Listen for upload messages
  970. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  971. mUploadFinishReceiver = new UploadFinishReceiver();
  972. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  973. // Listen for download messages
  974. IntentFilter downloadIntentFilter = new IntentFilter(
  975. FileDownloader.getDownloadAddedMessage());
  976. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  977. mDownloadFinishReceiver = new DownloadFinishReceiver();
  978. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  979. Log_OC.v(TAG, "onResume() end");
  980. }
  981. @Override
  982. protected void onPause() {
  983. Log_OC.v(TAG, "onPause() start");
  984. if (mSyncBroadcastReceiver != null) {
  985. unregisterReceiver(mSyncBroadcastReceiver);
  986. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  987. mSyncBroadcastReceiver = null;
  988. }
  989. if (mUploadFinishReceiver != null) {
  990. unregisterReceiver(mUploadFinishReceiver);
  991. mUploadFinishReceiver = null;
  992. }
  993. if (mDownloadFinishReceiver != null) {
  994. unregisterReceiver(mDownloadFinishReceiver);
  995. mDownloadFinishReceiver = null;
  996. }
  997. super.onPause();
  998. Log_OC.v(TAG, "onPause() end");
  999. }
  1000. public boolean isFabOpen() {
  1001. return (getListOfFilesFragment() != null
  1002. && getListOfFilesFragment().getFabMain() != null
  1003. && getListOfFilesFragment().getFabMain().isExpanded());
  1004. }
  1005. @Override
  1006. public void onSortingOrderChosen(FileSortOrder selection) {
  1007. getListOfFilesFragment().sortFiles(selection);
  1008. }
  1009. private class SyncBroadcastReceiver extends BroadcastReceiver {
  1010. /**
  1011. * {@link BroadcastReceiver} to enable syncing feedback in UI
  1012. */
  1013. @Override
  1014. public void onReceive(Context context, Intent intent) {
  1015. try {
  1016. String event = intent.getAction();
  1017. Log_OC.d(TAG, "Received broadcast " + event);
  1018. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  1019. String synchFolderRemotePath =
  1020. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  1021. RemoteOperationResult synchResult = (RemoteOperationResult)
  1022. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1023. boolean sameAccount = (getAccount() != null &&
  1024. accountName.equals(getAccount().name) && getStorageManager() != null);
  1025. if (sameAccount) {
  1026. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  1027. mSyncInProgress = true;
  1028. } else {
  1029. OCFile currentFile = (getFile() == null) ? null :
  1030. getStorageManager().getFileByPath(getFile().getRemotePath());
  1031. OCFile currentDir = (getCurrentDir() == null) ? null :
  1032. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  1033. if (currentDir == null) {
  1034. // current folder was removed from the server
  1035. DisplayUtils.showSnackMessage(
  1036. getActivity(),
  1037. R.string.sync_current_folder_was_removed,
  1038. synchFolderRemotePath
  1039. );
  1040. browseToRoot();
  1041. } else {
  1042. if (currentFile == null && !getFile().isFolder()) {
  1043. // currently selected file was removed in the server, and now we
  1044. // know it
  1045. cleanSecondFragment();
  1046. currentFile = currentDir;
  1047. }
  1048. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  1049. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1050. if (fileListFragment != null) {
  1051. fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false);
  1052. }
  1053. }
  1054. setFile(currentFile);
  1055. }
  1056. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  1057. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  1058. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) &&
  1059. synchResult != null && !synchResult.isSuccess()) {
  1060. /// TODO refactor and make common
  1061. if (checkForRemoteOperationError(synchResult)) {
  1062. requestCredentialsUpdate(context);
  1063. } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(
  1064. synchResult.getCode())) {
  1065. showUntrustedCertDialog(synchResult);
  1066. }
  1067. }
  1068. removeStickyBroadcast(intent);
  1069. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1070. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1071. setIndeterminate(mSyncInProgress);
  1072. setBackgroundText();
  1073. }
  1074. }
  1075. if (synchResult != null && synchResult.getCode().equals(
  1076. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  1077. mLastSslUntrustedServerResult = synchResult;
  1078. }
  1079. } catch (RuntimeException e) {
  1080. // avoid app crashes after changing the serial id of RemoteOperationResult
  1081. // in owncloud library with broadcast notifications pending to process
  1082. removeStickyBroadcast(intent);
  1083. try {
  1084. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1085. } catch (RuntimeException re) {
  1086. // we did not send this intent, so ignoring
  1087. Log_OC.i(TAG, "Ignoring error deleting data");
  1088. }
  1089. }
  1090. }
  1091. }
  1092. private boolean checkForRemoteOperationError(RemoteOperationResult syncResult) {
  1093. return ResultCode.UNAUTHORIZED.equals(syncResult.getCode()) ||
  1094. (syncResult.isException() && syncResult.getException()
  1095. instanceof AuthenticatorException);
  1096. }
  1097. /**
  1098. * Show a text message on screen view for notifying user if content is
  1099. * loading or folder is empty
  1100. */
  1101. private void setBackgroundText() {
  1102. final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1103. if (ocFileListFragment != null) {
  1104. if (mSyncInProgress) {
  1105. ocFileListFragment.setEmptyListLoadingMessage();
  1106. } else {
  1107. ocFileListFragment.setEmptyListMessage(ExtendedListFragment.SearchType.NO_SEARCH);
  1108. }
  1109. } else {
  1110. Log_OC.e(TAG, "OCFileListFragment is null");
  1111. }
  1112. }
  1113. /**
  1114. * Once the file upload has finished -> update view
  1115. */
  1116. private class UploadFinishReceiver extends BroadcastReceiver {
  1117. /**
  1118. * Once the file upload has finished -> update view
  1119. *
  1120. * {@link BroadcastReceiver} to enable upload feedback in UI
  1121. */
  1122. @Override
  1123. public void onReceive(Context context, Intent intent) {
  1124. try {
  1125. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1126. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1127. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1128. OCFile currentDir = getCurrentDir();
  1129. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  1130. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  1131. if (sameAccount && isDescendant) {
  1132. String linkedToRemotePath =
  1133. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1134. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1135. refreshListOfFilesFragment(false);
  1136. }
  1137. }
  1138. boolean uploadWasFine = intent.getBooleanExtra(
  1139. FileUploader.EXTRA_UPLOAD_RESULT,
  1140. false);
  1141. boolean renamedInUpload = getFile().getRemotePath().
  1142. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1143. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1144. renamedInUpload;
  1145. FileFragment details = getSecondFragment();
  1146. boolean detailFragmentIsShown = (details instanceof FileDetailFragment);
  1147. if (sameAccount && sameFile && detailFragmentIsShown) {
  1148. if (uploadWasFine) {
  1149. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1150. } else {
  1151. //TODO remove upload progress bar after upload failed.
  1152. Log_OC.d(TAG, "Remove upload progress bar after upload failed");
  1153. }
  1154. if (renamedInUpload) {
  1155. String newName = (new File(uploadedRemotePath)).getName();
  1156. DisplayUtils.showSnackMessage(
  1157. getActivity(),
  1158. R.string.filedetails_renamed_in_upload_msg,
  1159. newName
  1160. );
  1161. }
  1162. if (uploadWasFine || getFile().fileExists()) {
  1163. ((FileDetailFragment) details).updateFileDetails(false, true);
  1164. } else {
  1165. cleanSecondFragment();
  1166. }
  1167. // Force the preview if the file is an image or text file
  1168. if (uploadWasFine) {
  1169. OCFile ocFile = getFile();
  1170. if (PreviewImageFragment.canBePreviewed(ocFile)) {
  1171. startImagePreview(getFile(), true);
  1172. } else if (PreviewTextFragment.canBePreviewed(ocFile)) {
  1173. startTextPreview(ocFile, true);
  1174. }
  1175. // TODO what about other kind of previews?
  1176. }
  1177. }
  1178. setIndeterminate(false);
  1179. } finally {
  1180. if (intent != null) {
  1181. removeStickyBroadcast(intent);
  1182. }
  1183. }
  1184. }
  1185. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1186. private boolean isAscendant(String linkedToRemotePath) {
  1187. OCFile currentDir = getCurrentDir();
  1188. return (
  1189. currentDir != null &&
  1190. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1191. );
  1192. }
  1193. }
  1194. /**
  1195. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1196. * <p/>
  1197. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1198. * current folder.
  1199. */
  1200. private class DownloadFinishReceiver extends BroadcastReceiver {
  1201. @Override
  1202. public void onReceive(Context context, Intent intent) {
  1203. try {
  1204. boolean sameAccount = isSameAccount(intent);
  1205. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1206. String downloadBehaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
  1207. boolean isDescendant = isDescendant(downloadedRemotePath);
  1208. if (sameAccount && isDescendant) {
  1209. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1210. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1211. refreshListOfFilesFragment(false);
  1212. }
  1213. refreshSecondFragment(
  1214. intent.getAction(),
  1215. downloadedRemotePath,
  1216. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  1217. }
  1218. if (mWaitingToSend != null) {
  1219. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1220. if (mWaitingToSend.isDown() && downloadBehaviour != null) {
  1221. switch (downloadBehaviour) {
  1222. case OCFileListFragment.DOWNLOAD_SEND:
  1223. String packageName = intent.getStringExtra(SendShareDialog.PACKAGE_NAME);
  1224. String activityName = intent.getStringExtra(SendShareDialog.ACTIVITY_NAME);
  1225. sendDownloadedFile(packageName, activityName);
  1226. break;
  1227. default:
  1228. // do nothing
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. } finally {
  1234. if (intent != null) {
  1235. removeStickyBroadcast(intent);
  1236. }
  1237. }
  1238. }
  1239. private boolean isDescendant(String downloadedRemotePath) {
  1240. OCFile currentDir = getCurrentDir();
  1241. return (
  1242. currentDir != null &&
  1243. downloadedRemotePath != null &&
  1244. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1245. );
  1246. }
  1247. private boolean isAscendant(String linkedToRemotePath) {
  1248. OCFile currentDir = getCurrentDir();
  1249. return (
  1250. currentDir != null &&
  1251. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1252. );
  1253. }
  1254. private boolean isSameAccount(Intent intent) {
  1255. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1256. return (accountName != null && getAccount() != null &&
  1257. accountName.equals(getAccount().name));
  1258. }
  1259. }
  1260. public void browseToRoot() {
  1261. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1262. if (listOfFiles != null) { // should never be null, indeed
  1263. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1264. listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice(), false);
  1265. setFile(listOfFiles.getCurrentFile());
  1266. startSyncFolderOperation(root, false);
  1267. }
  1268. cleanSecondFragment();
  1269. }
  1270. /**
  1271. * {@inheritDoc}
  1272. * Updates action bar and second fragment, if in dual pane mode.
  1273. */
  1274. @Override
  1275. public void onBrowsedDownTo(OCFile directory) {
  1276. setFile(directory);
  1277. cleanSecondFragment();
  1278. // Sync Folder
  1279. startSyncFolderOperation(directory, false);
  1280. }
  1281. /**
  1282. * Shows the information of the {@link OCFile} received as a
  1283. * parameter in the second fragment.
  1284. *
  1285. * @param file {@link OCFile} whose details will be shown
  1286. */
  1287. @Override
  1288. public void showDetails(OCFile file) {
  1289. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1290. setSecondFragment(detailFragment);
  1291. updateFragmentsVisibility(true);
  1292. updateActionBarTitleAndHomeButton(file);
  1293. setFile(file);
  1294. }
  1295. @Override
  1296. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1297. if (chosenFile == null) {
  1298. chosenFile = getFile(); // if no file is passed, current file decides
  1299. }
  1300. if (mDualPane) {
  1301. // in dual pane mode, keep the focus of title an action bar in the current folder
  1302. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1303. } else {
  1304. super.updateActionBarTitleAndHomeButton(chosenFile);
  1305. }
  1306. }
  1307. @Override
  1308. public boolean isDrawerIndicatorAvailable() {
  1309. return isRoot(getCurrentDir());
  1310. }
  1311. @Override
  1312. protected ServiceConnection newTransferenceServiceConnection() {
  1313. return new ListServiceConnection();
  1314. }
  1315. /**
  1316. * Defines callbacks for service binding, passed to bindService()
  1317. */
  1318. private class ListServiceConnection implements ServiceConnection {
  1319. @Override
  1320. public void onServiceConnected(ComponentName component, IBinder service) {
  1321. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1322. Log_OC.d(TAG, "Download service connected");
  1323. mDownloaderBinder = (FileDownloaderBinder) service;
  1324. if (mWaitingToPreview != null && getStorageManager() != null) {
  1325. // update the file
  1326. mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1327. if (!mWaitingToPreview.isDown()) {
  1328. requestForDownload();
  1329. }
  1330. }
  1331. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1332. FileUploader.class))) {
  1333. Log_OC.d(TAG, "Upload service connected");
  1334. mUploaderBinder = (FileUploaderBinder) service;
  1335. } else {
  1336. return;
  1337. }
  1338. // a new chance to get the mDownloadBinder through
  1339. // getFileDownloadBinder() - THIS IS A MESS
  1340. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1341. if (listOfFiles != null && (getIntent() == null ||
  1342. (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) == null))) {
  1343. listOfFiles.listDirectory(MainApp.isOnlyOnDevice(), false);
  1344. }
  1345. FileFragment secondFragment = getSecondFragment();
  1346. if (secondFragment instanceof FileDetailFragment) {
  1347. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1348. detailFragment.listenForTransferProgress();
  1349. detailFragment.updateFileDetails(false, false);
  1350. }
  1351. }
  1352. @Override
  1353. public void onServiceDisconnected(ComponentName component) {
  1354. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1355. Log_OC.d(TAG, "Download service disconnected");
  1356. mDownloaderBinder = null;
  1357. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1358. Log_OC.d(TAG, "Upload service disconnected");
  1359. mUploaderBinder = null;
  1360. }
  1361. }
  1362. }
  1363. private MediaServiceConnection newMediaConnection(){
  1364. return new MediaServiceConnection();
  1365. }
  1366. /** Defines callbacks for service binding, passed to bindService() */
  1367. private class MediaServiceConnection implements ServiceConnection {
  1368. @Override
  1369. public void onServiceConnected(ComponentName component, IBinder service) {
  1370. if (component.equals(new ComponentName(FileDisplayActivity.this, MediaService.class))) {
  1371. Log_OC.d(TAG, "Media service connected");
  1372. mMediaServiceBinder = (MediaServiceBinder) service;
  1373. }else {
  1374. return;
  1375. }
  1376. }
  1377. @Override
  1378. public void onServiceDisconnected(ComponentName component) {
  1379. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1380. MediaService.class))) {
  1381. Log_OC.e(TAG, "Media service disconnected");
  1382. mMediaServiceBinder = null;
  1383. }
  1384. }
  1385. }
  1386. /**
  1387. * Updates the view associated to the activity after the finish of some operation over files
  1388. * in the current account.
  1389. *
  1390. * @param operation Removal operation performed.
  1391. * @param result Result of the removal.
  1392. */
  1393. @Override
  1394. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1395. super.onRemoteOperationFinish(operation, result);
  1396. if (operation instanceof RemoveFileOperation) {
  1397. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1398. } else if (operation instanceof RenameFileOperation) {
  1399. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1400. } else if (operation instanceof SynchronizeFileOperation) {
  1401. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1402. } else if (operation instanceof CreateFolderOperation) {
  1403. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1404. } else if (operation instanceof MoveFileOperation) {
  1405. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1406. } else if (operation instanceof CopyFileOperation) {
  1407. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1408. }
  1409. }
  1410. private void refreshShowDetails() {
  1411. FileFragment details = getSecondFragment();
  1412. if (details != null) {
  1413. OCFile file = details.getFile();
  1414. if (file != null) {
  1415. file = getStorageManager().getFileByPath(file.getRemotePath());
  1416. if (details instanceof PreviewMediaFragment) {
  1417. // Refresh OCFile of the fragment
  1418. ((PreviewMediaFragment) details).updateFile(file);
  1419. } else if (details instanceof PreviewTextFragment) {
  1420. // Refresh OCFile of the fragment
  1421. ((PreviewTextFragment) details).updateFile(file);
  1422. } else {
  1423. showDetails(file);
  1424. }
  1425. }
  1426. supportInvalidateOptionsMenu();
  1427. }
  1428. }
  1429. /**
  1430. * Updates the view associated to the activity after the finish of an operation trying to
  1431. * remove a file.
  1432. *
  1433. * @param operation Removal operation performed.
  1434. * @param result Result of the removal.
  1435. */
  1436. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1437. RemoteOperationResult result) {
  1438. DisplayUtils.showSnackMessage(
  1439. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1440. );
  1441. if (result.isSuccess()) {
  1442. OCFile removedFile = operation.getFile();
  1443. tryStopPlaying(removedFile);
  1444. FileFragment second = getSecondFragment();
  1445. if (second != null && removedFile.equals(second.getFile())) {
  1446. if (second instanceof PreviewMediaFragment) {
  1447. ((PreviewMediaFragment) second).stopPreview(true);
  1448. }
  1449. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1450. cleanSecondFragment();
  1451. }
  1452. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1453. refreshListOfFilesFragment(false);
  1454. }
  1455. supportInvalidateOptionsMenu();
  1456. } else {
  1457. if (result.isSslRecoverableException()) {
  1458. mLastSslUntrustedServerResult = result;
  1459. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1460. }
  1461. }
  1462. }
  1463. public void setMediaServiceConnection() {
  1464. mMediaServiceConnection = newMediaConnection();// mediaServiceConnection;
  1465. bindService(new Intent(this, MediaService.class), mMediaServiceConnection, Context.BIND_AUTO_CREATE);
  1466. }
  1467. private void tryStopPlaying(OCFile file) {
  1468. if (mMediaServiceConnection != null && MimeTypeUtil.isAudio(file) && mMediaServiceBinder.isPlaying(file)) {
  1469. mMediaServiceBinder.pause();
  1470. }
  1471. }
  1472. /**
  1473. * Updates the view associated to the activity after the finish of an operation trying to move a
  1474. * file.
  1475. *
  1476. * @param operation Move operation performed.
  1477. * @param result Result of the move operation.
  1478. */
  1479. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1480. RemoteOperationResult result) {
  1481. if (result.isSuccess()) {
  1482. refreshListOfFilesFragment(false);
  1483. } else {
  1484. try {
  1485. DisplayUtils.showSnackMessage(
  1486. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1487. );
  1488. } catch (NotFoundException e) {
  1489. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1490. }
  1491. }
  1492. }
  1493. /**
  1494. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1495. * file.
  1496. *
  1497. * @param operation Copy operation performed.
  1498. * @param result Result of the copy operation.
  1499. */
  1500. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1501. if (result.isSuccess()) {
  1502. refreshListOfFilesFragment(false);
  1503. } else {
  1504. try {
  1505. DisplayUtils.showSnackMessage(
  1506. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1507. );
  1508. } catch (NotFoundException e) {
  1509. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1510. }
  1511. }
  1512. }
  1513. /**
  1514. * Updates the view associated to the activity after the finish of an operation trying to rename
  1515. * a file.
  1516. *
  1517. * @param operation Renaming operation performed.
  1518. * @param result Result of the renaming.
  1519. */
  1520. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1521. RemoteOperationResult result) {
  1522. OCFile renamedFile = operation.getFile();
  1523. if (result.isSuccess()) {
  1524. FileFragment details = getSecondFragment();
  1525. if (details != null) {
  1526. if (details instanceof FileDetailFragment &&
  1527. renamedFile.equals(details.getFile())) {
  1528. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1529. showDetails(renamedFile);
  1530. } else if (details instanceof PreviewMediaFragment &&
  1531. renamedFile.equals(details.getFile())) {
  1532. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1533. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1534. int position = ((PreviewMediaFragment) details).getPosition();
  1535. startMediaPreview(renamedFile, position, true, true);
  1536. } else {
  1537. getFileOperationsHelper().openFile(renamedFile);
  1538. }
  1539. } else if (details instanceof PreviewTextFragment &&
  1540. renamedFile.equals(details.getFile())) {
  1541. ((PreviewTextFragment) details).updateFile(renamedFile);
  1542. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1543. startTextPreview(renamedFile, true);
  1544. } else {
  1545. getFileOperationsHelper().openFile(renamedFile);
  1546. }
  1547. }
  1548. }
  1549. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1550. refreshListOfFilesFragment(false);
  1551. }
  1552. } else {
  1553. DisplayUtils.showSnackMessage(
  1554. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1555. );
  1556. if (result.isSslRecoverableException()) {
  1557. mLastSslUntrustedServerResult = result;
  1558. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1559. }
  1560. }
  1561. }
  1562. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1563. RemoteOperationResult result) {
  1564. if (result.isSuccess() && operation.transferWasRequested()) {
  1565. OCFile syncedFile = operation.getLocalFile();
  1566. onTransferStateChanged(syncedFile, true, true);
  1567. supportInvalidateOptionsMenu();
  1568. refreshShowDetails();
  1569. }
  1570. }
  1571. /**
  1572. * Updates the view associated to the activity after the finish of an operation trying create a
  1573. * new folder
  1574. *
  1575. * @param operation Creation operation performed.
  1576. * @param result Result of the creation.
  1577. */
  1578. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1579. RemoteOperationResult result) {
  1580. if (result.isSuccess()) {
  1581. refreshListOfFilesFragment(false);
  1582. } else {
  1583. try {
  1584. DisplayUtils.showSnackMessage(
  1585. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  1586. );
  1587. } catch (NotFoundException e) {
  1588. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1589. }
  1590. }
  1591. }
  1592. /**
  1593. * {@inheritDoc}
  1594. */
  1595. @Override
  1596. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1597. refreshListOfFilesFragment(false);
  1598. FileFragment details = getSecondFragment();
  1599. if (details instanceof FileDetailFragment &&
  1600. file.equals(details.getFile())) {
  1601. if (downloading || uploading) {
  1602. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1603. } else {
  1604. if (!file.fileExists()) {
  1605. cleanSecondFragment();
  1606. } else {
  1607. ((FileDetailFragment) details).updateFileDetails(false, true);
  1608. }
  1609. }
  1610. }
  1611. }
  1612. private void requestForDownload() {
  1613. Account account = getAccount();
  1614. //if (!mWaitingToPreview.isDownloading()) {
  1615. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1616. Intent i = new Intent(this, FileDownloader.class);
  1617. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1618. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1619. startService(i);
  1620. }
  1621. }
  1622. @Override
  1623. public void onSavedCertificate() {
  1624. startSyncFolderOperation(getCurrentDir(), false);
  1625. }
  1626. /**
  1627. * Starts an operation to refresh the requested folder.
  1628. * <p/>
  1629. * The operation is run in a new background thread created on the fly.
  1630. * <p/>
  1631. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1632. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1633. * synchronized too.
  1634. *
  1635. * @param folder Folder to refresh.
  1636. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1637. * didn't change.
  1638. */
  1639. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag) {
  1640. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1641. // or if the method is called from a dialog that is being dismissed
  1642. if (TextUtils.isEmpty(searchQuery)) {
  1643. getHandler().postDelayed(
  1644. new Runnable() {
  1645. @Override
  1646. public void run() {
  1647. if (hasWindowFocus()) {
  1648. long currentSyncTime = System.currentTimeMillis();
  1649. mSyncInProgress = true;
  1650. // perform folder synchronization
  1651. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1652. currentSyncTime,
  1653. false,
  1654. getFileOperationsHelper().isSharedSupported(),
  1655. ignoreETag,
  1656. getStorageManager(),
  1657. getAccount(),
  1658. getApplicationContext()
  1659. );
  1660. synchFolderOp.execute(
  1661. getAccount(),
  1662. MainApp.getAppContext(),
  1663. FileDisplayActivity.this,
  1664. null,
  1665. null
  1666. );
  1667. setIndeterminate(true);
  1668. setBackgroundText();
  1669. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1670. // another window floating over
  1671. }
  1672. },
  1673. DELAY_TO_REQUEST_REFRESH_OPERATION_LATER
  1674. );
  1675. }
  1676. }
  1677. private void requestForDownload(OCFile file, String downloadBehaviour, String packageName, String activityName) {
  1678. Account account = getAccount();
  1679. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1680. Intent i = new Intent(this, FileDownloader.class);
  1681. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1682. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1683. i.putExtra(SendShareDialog.PACKAGE_NAME, packageName);
  1684. i.putExtra(SendShareDialog.ACTIVITY_NAME, activityName);
  1685. i.putExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR, downloadBehaviour);
  1686. startService(i);
  1687. }
  1688. }
  1689. private void sendDownloadedFile(String packageName, String activityName) {
  1690. if (mWaitingToSend != null) {
  1691. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  1692. sendIntent.setType(mWaitingToSend.getMimetype());
  1693. sendIntent.putExtra(Intent.EXTRA_STREAM, mWaitingToSend.getExposedFileUri(this));
  1694. sendIntent.putExtra(Intent.ACTION_SEND, true);
  1695. sendIntent.setComponent(new ComponentName(packageName, activityName));
  1696. // Show dialog
  1697. String sendTitle = getString(R.string.activity_chooser_send_file_title);
  1698. startActivity(Intent.createChooser(sendIntent, sendTitle));
  1699. } else {
  1700. Log_OC.e(TAG, "Trying to send a NULL OCFile");
  1701. }
  1702. mWaitingToSend = null;
  1703. }
  1704. /**
  1705. * Requests the download of the received {@link OCFile} , updates the UI
  1706. * to monitor the download progress and prepares the activity to send the file
  1707. * when the download finishes.
  1708. *
  1709. * @param file {@link OCFile} to download and preview.
  1710. * @param packageName
  1711. * @param activityName
  1712. */
  1713. public void startDownloadForSending(OCFile file, String downloadBehaviour, String packageName,
  1714. String activityName) {
  1715. mWaitingToSend = file;
  1716. requestForDownload(mWaitingToSend, downloadBehaviour, packageName, activityName);
  1717. boolean hasSecondFragment = (getSecondFragment() != null);
  1718. updateFragmentsVisibility(hasSecondFragment);
  1719. }
  1720. /**
  1721. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1722. *
  1723. * @param file Image {@link OCFile} to show.
  1724. */
  1725. public void startImagePreview(OCFile file, boolean showPreview) {
  1726. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1727. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1728. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1729. if (showPreview) {
  1730. startActivity(showDetailsIntent);
  1731. } else {
  1732. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1733. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1734. }
  1735. }
  1736. /**
  1737. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1738. *
  1739. * @param file Image {@link OCFile} to show.
  1740. */
  1741. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  1742. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1743. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  1744. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1745. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  1746. if (showPreview) {
  1747. startActivity(showDetailsIntent);
  1748. } else {
  1749. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1750. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1751. }
  1752. }
  1753. /**
  1754. * Stars the preview of an already down media {@link OCFile}.
  1755. *
  1756. * @param file Media {@link OCFile} to preview.
  1757. * @param startPlaybackPosition Media position where the playback will be started,
  1758. * in milliseconds.
  1759. * @param autoplay When 'true', the playback will start without user
  1760. * interactions.
  1761. */
  1762. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview) {
  1763. if (showPreview && file.isDown() && !file.isDownloading()) {
  1764. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  1765. setSecondFragment(mediaFragment);
  1766. updateFragmentsVisibility(true);
  1767. updateActionBarTitleAndHomeButton(file);
  1768. setFile(file);
  1769. } else {
  1770. Intent previewIntent = new Intent();
  1771. previewIntent.putExtra(EXTRA_FILE, file);
  1772. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  1773. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  1774. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1775. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1776. }
  1777. }
  1778. /**
  1779. * Stars the preview of a text file {@link OCFile}.
  1780. *
  1781. * @param file Text {@link OCFile} to preview.
  1782. */
  1783. public void startTextPreview(OCFile file, boolean showPreview) {
  1784. if (showPreview) {
  1785. Bundle args = new Bundle();
  1786. args.putParcelable(EXTRA_FILE, file);
  1787. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1788. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1789. PreviewTextFragment.class.getName(), args);
  1790. setSecondFragment(textPreviewFragment);
  1791. updateFragmentsVisibility(true);
  1792. updateActionBarTitleAndHomeButton(file);
  1793. setFile(file);
  1794. } else {
  1795. Intent previewIntent = new Intent();
  1796. previewIntent.putExtra(EXTRA_FILE, file);
  1797. previewIntent.putExtra(TEXT_PREVIEW, true);
  1798. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1799. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1800. }
  1801. }
  1802. public void startContactListFragment(OCFile file) {
  1803. Intent intent = new Intent(this, ContactsPreferenceActivity.class);
  1804. intent.putExtra(ContactListFragment.FILE_NAME, Parcels.wrap(file));
  1805. intent.putExtra(ContactListFragment.ACCOUNT, Parcels.wrap(getAccount()));
  1806. startActivity(intent);
  1807. }
  1808. /**
  1809. * Requests the download of the received {@link OCFile} , updates the UI
  1810. * to monitor the download progress and prepares the activity to preview
  1811. * or open the file when the download finishes.
  1812. *
  1813. * @param file {@link OCFile} to download and preview.
  1814. */
  1815. public void startDownloadForPreview(OCFile file) {
  1816. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1817. setSecondFragment(detailFragment);
  1818. mWaitingToPreview = file;
  1819. requestForDownload();
  1820. updateFragmentsVisibility(true);
  1821. updateActionBarTitleAndHomeButton(file);
  1822. setFile(file);
  1823. }
  1824. /**
  1825. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  1826. *
  1827. * @param file {@link OCFile} file which operation are wanted to be cancel
  1828. */
  1829. public void cancelTransference(OCFile file) {
  1830. getFileOperationsHelper().cancelTransference(file);
  1831. if (mWaitingToPreview != null &&
  1832. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1833. mWaitingToPreview = null;
  1834. }
  1835. if (mWaitingToSend != null &&
  1836. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1837. mWaitingToSend = null;
  1838. }
  1839. onTransferStateChanged(file, false, false);
  1840. }
  1841. /**
  1842. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  1843. *
  1844. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  1845. */
  1846. public void cancelTransference(Collection<OCFile> files) {
  1847. for (OCFile file : files) {
  1848. cancelTransference(file);
  1849. }
  1850. }
  1851. @Override
  1852. public void onRefresh(boolean ignoreETag) {
  1853. refreshList(ignoreETag);
  1854. }
  1855. @Override
  1856. public void onRefresh() {
  1857. refreshList(true);
  1858. }
  1859. private void refreshList(boolean ignoreETag) {
  1860. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1861. if (listOfFiles != null && !listOfFiles.getIsSearchFragment()) {
  1862. OCFile folder = listOfFiles.getCurrentFile();
  1863. if (folder != null) {
  1864. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1865. listDirectory(mFile);*/
  1866. startSyncFolderOperation(folder, ignoreETag);
  1867. }
  1868. }
  1869. }
  1870. private boolean isGridView() {
  1871. return getListOfFilesFragment().isGridEnabled();
  1872. }
  1873. public void allFilesOption() {
  1874. browseToRoot();
  1875. }
  1876. @Override
  1877. public void showFiles(boolean onDeviceOnly) {
  1878. super.showFiles(onDeviceOnly);
  1879. getListOfFilesFragment().refreshDirectory();
  1880. }
  1881. @Subscribe(threadMode = ThreadMode.MAIN)
  1882. public void onMessageEvent(SyncEventFinished event) {
  1883. Bundle bundle = event.getIntent().getExtras();
  1884. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  1885. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  1886. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  1887. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  1888. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  1889. (boolean)bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true);
  1890. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  1891. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  1892. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  1893. true);
  1894. } else {
  1895. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  1896. }
  1897. }
  1898. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1899. public void onMessageEvent(TokenPushEvent event) {
  1900. PushUtils.pushRegistrationToServer();
  1901. }
  1902. @Override
  1903. public void onStart() {
  1904. super.onStart();
  1905. EventBus.getDefault().post(new TokenPushEvent());
  1906. }
  1907. }