FileDisplayActivity.java 88 KB

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