FileDisplayActivity.java 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  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.SyncEventFinished;
  88. import com.owncloud.android.ui.events.TokenPushEvent;
  89. import com.owncloud.android.ui.fragment.ExtendedListFragment;
  90. import com.owncloud.android.ui.fragment.FileDetailFragment;
  91. import com.owncloud.android.ui.fragment.FileFragment;
  92. import com.owncloud.android.ui.fragment.OCFileListFragment;
  93. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  94. import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment;
  95. import com.owncloud.android.ui.helpers.FileOperationsHelper;
  96. import com.owncloud.android.ui.helpers.UriUploader;
  97. import com.owncloud.android.ui.preview.PreviewImageActivity;
  98. import com.owncloud.android.ui.preview.PreviewImageFragment;
  99. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  100. import com.owncloud.android.ui.preview.PreviewTextFragment;
  101. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  102. import com.owncloud.android.utils.DataHolderUtil;
  103. import com.owncloud.android.utils.DisplayUtils;
  104. import com.owncloud.android.utils.ErrorMessageAdapter;
  105. import com.owncloud.android.utils.MimeTypeUtil;
  106. import com.owncloud.android.utils.PermissionUtil;
  107. import com.owncloud.android.utils.PushUtils;
  108. import com.owncloud.android.utils.ThemeUtils;
  109. import org.greenrobot.eventbus.EventBus;
  110. import org.greenrobot.eventbus.Subscribe;
  111. import org.greenrobot.eventbus.ThreadMode;
  112. import org.parceler.Parcels;
  113. import java.io.File;
  114. import java.util.ArrayList;
  115. import java.util.Collection;
  116. import static com.owncloud.android.db.PreferenceManager.getSortAscending;
  117. import static com.owncloud.android.db.PreferenceManager.getSortOrder;
  118. /**
  119. * Displays, what files the user has available in his ownCloud. This is the main view.
  120. */
  121. public class FileDisplayActivity extends HookActivity
  122. implements FileFragment.ContainerActivity,
  123. OnEnforceableRefreshListener, SortingOrderDialogFragment.OnSortingOrderListener {
  124. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  125. private UploadFinishReceiver mUploadFinishReceiver;
  126. private DownloadFinishReceiver mDownloadFinishReceiver;
  127. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  128. private boolean mDualPane;
  129. private View mLeftFragmentContainer;
  130. private View mRightFragmentContainer;
  131. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  132. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  133. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  134. private static final String KEY_SEARCH_QUERY = "KEY_SEARCH_QUERY";
  135. private static final String SORT_ORDER_DIALOG_TAG = "SORT_ORDER_DIALOG";
  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 = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
  591. editText.setHintTextColor(fontColor);
  592. editText.setTextColor(fontColor);
  593. ImageView searchClose = (ImageView) 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),
  676. getSortAscending(this)
  677. );
  678. mSortingOrderDialogFragment.show(ft, SORT_ORDER_DIALOG_TAG);
  679. break;
  680. }
  681. case R.id.action_switch_view: {
  682. if (isGridView()) {
  683. item.setTitle(getString(R.string.action_switch_grid_view));
  684. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  685. R.drawable.ic_view_module));
  686. getListOfFilesFragment().setListAsPreferred();
  687. } else {
  688. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  689. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  690. R.drawable.ic_view_list));
  691. getListOfFilesFragment().setGridAsPreferred();
  692. }
  693. break;
  694. }
  695. case R.id.action_select_all: {
  696. getListOfFilesFragment().selectAllFiles(true);
  697. break;
  698. }
  699. default:
  700. retval = super.onOptionsItemSelected(item);
  701. break;
  702. }
  703. return retval;
  704. }
  705. private void startSynchronization() {
  706. Log_OC.d(TAG, "Got to start sync");
  707. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  708. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  709. ContentResolver.cancelSync(null, MainApp.getAuthority());
  710. // cancel the current synchronizations of any ownCloud account
  711. Bundle bundle = new Bundle();
  712. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  713. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  714. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  715. MainApp.getAuthority());
  716. ContentResolver.requestSync(
  717. getAccount(),
  718. MainApp.getAuthority(), bundle);
  719. } else {
  720. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  721. MainApp.getAuthority() + " with new API");
  722. SyncRequest.Builder builder = new SyncRequest.Builder();
  723. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  724. builder.setExpedited(true);
  725. builder.setManual(true);
  726. builder.syncOnce();
  727. // Fix bug in Android Lollipop when you click on refresh the whole account
  728. Bundle extras = new Bundle();
  729. builder.setExtras(extras);
  730. SyncRequest request = builder.build();
  731. ContentResolver.requestSync(request);
  732. }
  733. }
  734. /**
  735. * Called, when the user selected something for uploading
  736. */
  737. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  738. @Override
  739. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  740. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS &&
  741. (resultCode == RESULT_OK ||
  742. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  743. requestUploadOfContentFromApps(data, resultCode);
  744. } else if (requestCode == REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM &&
  745. (resultCode == RESULT_OK ||
  746. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE ||
  747. resultCode == UploadFilesActivity.RESULT_OK_AND_DO_NOTHING ||
  748. resultCode == UploadFilesActivity.RESULT_OK_AND_DELETE)) {
  749. requestUploadOfFilesFromFileSystem(data, resultCode);
  750. } else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == RESULT_OK) {
  751. final Intent fData = data;
  752. getHandler().postDelayed(
  753. new Runnable() {
  754. @Override
  755. public void run() {
  756. requestMoveOperation(fData);
  757. }
  758. },
  759. DELAY_TO_REQUEST_OPERATIONS_LATER
  760. );
  761. } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) {
  762. final Intent fData = data;
  763. getHandler().postDelayed(
  764. new Runnable() {
  765. @Override
  766. public void run() {
  767. requestCopyOperation(fData);
  768. }
  769. },
  770. DELAY_TO_REQUEST_OPERATIONS_LATER
  771. );
  772. } else {
  773. super.onActivityResult(requestCode, resultCode, data);
  774. }
  775. }
  776. private void requestUploadOfFilesFromFileSystem(Intent data, int resultCode) {
  777. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  778. if (filePaths != null) {
  779. String[] remotePaths = new String[filePaths.length];
  780. String remotePathBase = getCurrentDir().getRemotePath();
  781. for (int j = 0; j < remotePaths.length; j++) {
  782. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  783. }
  784. // default, as fallback
  785. int behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  786. switch (resultCode) {
  787. case UploadFilesActivity.RESULT_OK_AND_MOVE:
  788. behaviour = FileUploader.LOCAL_BEHAVIOUR_MOVE;
  789. break;
  790. case UploadFilesActivity.RESULT_OK_AND_DELETE:
  791. behaviour = FileUploader.LOCAL_BEHAVIOUR_DELETE;
  792. break;
  793. case UploadFilesActivity.RESULT_OK_AND_DO_NOTHING:
  794. behaviour = FileUploader.LOCAL_BEHAVIOUR_FORGET;
  795. break;
  796. }
  797. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  798. requester.uploadNewFile(
  799. this,
  800. getAccount(),
  801. filePaths,
  802. remotePaths,
  803. null, // MIME type will be detected from file name
  804. behaviour,
  805. false, // do not create parent folder if not existent
  806. UploadFileOperation.CREATED_BY_USER,
  807. false,
  808. false
  809. );
  810. } else {
  811. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  812. DisplayUtils.showSnackMessage(this, R.string.filedisplay_no_file_selected);
  813. }
  814. }
  815. private void requestUploadOfContentFromApps(Intent contentIntent, int resultCode) {
  816. ArrayList<Parcelable> streamsToUpload = new ArrayList<>();
  817. //getClipData is only supported on api level 16+, Jelly Bean
  818. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  819. contentIntent.getClipData() != null &&
  820. contentIntent.getClipData().getItemCount() > 0) {
  821. for (int i = 0; i < contentIntent.getClipData().getItemCount(); i++) {
  822. streamsToUpload.add(contentIntent.getClipData().getItemAt(i).getUri());
  823. }
  824. } else {
  825. streamsToUpload.add(contentIntent.getData());
  826. }
  827. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  828. FileUploader.LOCAL_BEHAVIOUR_COPY;
  829. OCFile currentDir = getCurrentDir();
  830. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  831. UriUploader uploader = new UriUploader(
  832. this,
  833. streamsToUpload,
  834. remotePath,
  835. getAccount(),
  836. behaviour,
  837. false, // Not show waiting dialog while file is being copied from private storage
  838. null // Not needed copy temp task listener
  839. );
  840. uploader.uploadUris();
  841. }
  842. /**
  843. * Request the operation for moving the file/folder from one path to another
  844. *
  845. * @param data Intent received
  846. */
  847. private void requestMoveOperation(Intent data) {
  848. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  849. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  850. getFileOperationsHelper().moveFiles(files, folderToMoveAt);
  851. }
  852. /**
  853. * Request the operation for copying the file/folder from one path to another
  854. *
  855. * @param data Intent received
  856. */
  857. private void requestCopyOperation(Intent data) {
  858. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  859. ArrayList<OCFile> files = data.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  860. getFileOperationsHelper().copyFiles(files, folderToMoveAt);
  861. }
  862. private boolean isSearchOpen() {
  863. final View mSearchEditFrame = searchView.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
  864. return (mSearchEditFrame != null && mSearchEditFrame.getVisibility() == View.VISIBLE);
  865. }
  866. private void revertBottomNavigationBarToAllFiles() {
  867. if (getResources().getBoolean(R.bool.bottom_toolbar_enabled)) {
  868. BottomNavigationView bottomNavigationView = (BottomNavigationView) getListOfFilesFragment().getView()
  869. .findViewById(R.id.bottom_navigation_view);
  870. if (bottomNavigationView.getMenu().findItem(R.id.nav_bar_settings).isChecked()) {
  871. bottomNavigationView.getMenu().findItem(R.id.nav_bar_files).setChecked(true);
  872. }
  873. }
  874. }
  875. @Override
  876. public void onBackPressed() {
  877. boolean isFabOpen = isFabOpen();
  878. boolean isDrawerOpen = isDrawerOpen();
  879. boolean isSearchOpen = isSearchOpen();
  880. /*
  881. * BackPressed priority/hierarchy:
  882. * 1. close search view if opened
  883. * 2. close drawer if opened
  884. * 3. close FAB if open (only if drawer isn't open)
  885. * 4. navigate up (only if drawer and FAB aren't open)
  886. */
  887. if (isSearchOpen && searchView != null) {
  888. searchView.setQuery("", true);
  889. searchView.onActionViewCollapsed();
  890. setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  891. } else if (isDrawerOpen && isFabOpen) {
  892. // close drawer first
  893. super.onBackPressed();
  894. } else if (isDrawerOpen && !isFabOpen) {
  895. // close drawer
  896. super.onBackPressed();
  897. } else if (!isDrawerOpen && isFabOpen) {
  898. // close fab
  899. getListOfFilesFragment().getFabMain().collapse();
  900. } else {
  901. // all closed
  902. //if PreviewImageActivity called this activity and mDualPane==false then calls PreviewImageActivity again
  903. if ((getIntent().getAction() != null && getIntent().getAction().equalsIgnoreCase(ACTION_DETAILS)) && !mDualPane) {
  904. getIntent().setAction(null);
  905. getIntent().putExtra(EXTRA_FILE, (OCFile) null);
  906. startImagePreview(getFile(), false);
  907. }
  908. OCFileListFragment listOfFiles = getListOfFilesFragment();
  909. if (mDualPane || getSecondFragment() == null) {
  910. OCFile currentDir = getCurrentDir();
  911. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  912. finish();
  913. return;
  914. }
  915. if (listOfFiles != null) { // should never be null, indeed
  916. listOfFiles.onBrowseUp();
  917. }
  918. }
  919. if (listOfFiles != null) { // should never be null, indeed
  920. setFile(listOfFiles.getCurrentFile());
  921. }
  922. cleanSecondFragment();
  923. }
  924. }
  925. @Override
  926. protected void onSaveInstanceState(Bundle outState) {
  927. // responsibility of restore is preferred in onCreate() before than in
  928. // onRestoreInstanceState when there are Fragments involved
  929. Log_OC.v(TAG, "onSaveInstanceState() start");
  930. super.onSaveInstanceState(outState);
  931. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  932. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  933. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  934. // mRefreshSharesInProgress);
  935. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  936. if (searchView != null) {
  937. outState.putString(KEY_SEARCH_QUERY, searchView.getQuery().toString());
  938. }
  939. Log_OC.v(TAG, "onSaveInstanceState() end");
  940. }
  941. @Override
  942. protected void onResume() {
  943. Log_OC.v(TAG, "onResume() start");
  944. super.onResume();
  945. OCFile startFile = null;
  946. if (getIntent() != null && getIntent().getParcelableExtra(EXTRA_FILE) != null) {
  947. startFile = getIntent().getParcelableExtra(EXTRA_FILE);
  948. setFile(startFile);
  949. }
  950. revertBottomNavigationBarToAllFiles();
  951. // refresh list of files
  952. if (searchView != null && !TextUtils.isEmpty(searchQuery)) {
  953. searchView.setQuery(searchQuery, true);
  954. } else if (getListOfFilesFragment() != null && !getListOfFilesFragment().getIsSearchFragment()
  955. && startFile == null) {
  956. refreshListOfFilesFragment(false);
  957. } else {
  958. getListOfFilesFragment().listDirectory(startFile, false, false);
  959. updateActionBarTitleAndHomeButton(startFile);
  960. }
  961. // Listen for sync messages
  962. if (getListOfFilesFragment() != null && !getListOfFilesFragment().getIsSearchFragment()) {
  963. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  964. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  965. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  966. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  967. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  968. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  969. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  970. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  971. // syncIntentFilter);
  972. }
  973. // Listen for upload messages
  974. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  975. mUploadFinishReceiver = new UploadFinishReceiver();
  976. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  977. // Listen for download messages
  978. IntentFilter downloadIntentFilter = new IntentFilter(
  979. FileDownloader.getDownloadAddedMessage());
  980. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  981. mDownloadFinishReceiver = new DownloadFinishReceiver();
  982. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  983. Log_OC.v(TAG, "onResume() end");
  984. }
  985. @Override
  986. protected void onPause() {
  987. Log_OC.v(TAG, "onPause() start");
  988. if (mSyncBroadcastReceiver != null) {
  989. unregisterReceiver(mSyncBroadcastReceiver);
  990. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  991. mSyncBroadcastReceiver = null;
  992. }
  993. if (mUploadFinishReceiver != null) {
  994. unregisterReceiver(mUploadFinishReceiver);
  995. mUploadFinishReceiver = null;
  996. }
  997. if (mDownloadFinishReceiver != null) {
  998. unregisterReceiver(mDownloadFinishReceiver);
  999. mDownloadFinishReceiver = null;
  1000. }
  1001. super.onPause();
  1002. Log_OC.v(TAG, "onPause() end");
  1003. }
  1004. public boolean isFabOpen() {
  1005. return (getListOfFilesFragment() != null
  1006. && getListOfFilesFragment().getFabMain() != null
  1007. && getListOfFilesFragment().getFabMain().isExpanded());
  1008. }
  1009. @Override
  1010. public void onSortingOrderChosen(int selection) {
  1011. switch (selection) {
  1012. case SortingOrderDialogFragment.BY_NAME_ASC:
  1013. sortByName(true);
  1014. break;
  1015. case SortingOrderDialogFragment.BY_NAME_DESC:
  1016. sortByName(false);
  1017. break;
  1018. case SortingOrderDialogFragment.BY_MODIFICATION_DATE_ASC:
  1019. sortByDate(true);
  1020. break;
  1021. case SortingOrderDialogFragment.BY_MODIFICATION_DATE_DESC:
  1022. sortByDate(false);
  1023. break;
  1024. case SortingOrderDialogFragment.BY_SIZE_ASC:
  1025. sortBySize(true);
  1026. break;
  1027. case SortingOrderDialogFragment.BY_SIZE_DESC:
  1028. sortBySize(false);
  1029. break;
  1030. default: // defaulting to alphabetical-ascending
  1031. Log_OC.w(TAG, "Unknown sort order, defaulting to alphabetical-ascending!");
  1032. sortByName(true);
  1033. break;
  1034. }
  1035. }
  1036. private class SyncBroadcastReceiver extends BroadcastReceiver {
  1037. /**
  1038. * {@link BroadcastReceiver} to enable syncing feedback in UI
  1039. */
  1040. @Override
  1041. public void onReceive(Context context, Intent intent) {
  1042. try {
  1043. String event = intent.getAction();
  1044. Log_OC.d(TAG, "Received broadcast " + event);
  1045. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  1046. String synchFolderRemotePath =
  1047. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  1048. RemoteOperationResult synchResult = (RemoteOperationResult)
  1049. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1050. boolean sameAccount = (getAccount() != null &&
  1051. accountName.equals(getAccount().name) && getStorageManager() != null);
  1052. if (sameAccount) {
  1053. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  1054. mSyncInProgress = true;
  1055. } else {
  1056. OCFile currentFile = (getFile() == null) ? null :
  1057. getStorageManager().getFileByPath(getFile().getRemotePath());
  1058. OCFile currentDir = (getCurrentDir() == null) ? null :
  1059. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  1060. if (currentDir == null) {
  1061. // current folder was removed from the server
  1062. DisplayUtils.showSnackMessage(
  1063. getActivity(),
  1064. R.string.sync_current_folder_was_removed,
  1065. synchFolderRemotePath
  1066. );
  1067. browseToRoot();
  1068. } else {
  1069. if (currentFile == null && !getFile().isFolder()) {
  1070. // currently selected file was removed in the server, and now we
  1071. // know it
  1072. cleanSecondFragment();
  1073. currentFile = currentDir;
  1074. }
  1075. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  1076. OCFileListFragment fileListFragment = getListOfFilesFragment();
  1077. if (fileListFragment != null) {
  1078. fileListFragment.listDirectory(currentDir, MainApp.isOnlyOnDevice(), false);
  1079. }
  1080. }
  1081. setFile(currentFile);
  1082. }
  1083. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  1084. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  1085. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event) &&
  1086. synchResult != null && !synchResult.isSuccess()) {
  1087. /// TODO refactor and make common
  1088. if (checkForRemoteOperationError(synchResult)) {
  1089. requestCredentialsUpdate(context);
  1090. } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(
  1091. synchResult.getCode())) {
  1092. showUntrustedCertDialog(synchResult);
  1093. }
  1094. }
  1095. removeStickyBroadcast(intent);
  1096. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1097. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1098. setIndeterminate(mSyncInProgress);
  1099. setBackgroundText();
  1100. }
  1101. }
  1102. if (synchResult != null && synchResult.getCode().equals(
  1103. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  1104. mLastSslUntrustedServerResult = synchResult;
  1105. }
  1106. } catch (RuntimeException e) {
  1107. // avoid app crashes after changing the serial id of RemoteOperationResult
  1108. // in owncloud library with broadcast notifications pending to process
  1109. removeStickyBroadcast(intent);
  1110. try {
  1111. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1112. } catch (RuntimeException re) {
  1113. // we did not send this intent, so ignoring
  1114. }
  1115. }
  1116. }
  1117. }
  1118. private boolean checkForRemoteOperationError(RemoteOperationResult syncResult) {
  1119. return ResultCode.UNAUTHORIZED.equals(syncResult.getCode()) ||
  1120. (syncResult.isException() && syncResult.getException()
  1121. instanceof AuthenticatorException);
  1122. }
  1123. /**
  1124. * Show a text message on screen view for notifying user if content is
  1125. * loading or folder is empty
  1126. */
  1127. private void setBackgroundText() {
  1128. final OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  1129. if (ocFileListFragment != null) {
  1130. if (mSyncInProgress) {
  1131. ocFileListFragment.setEmptyListLoadingMessage();
  1132. } else {
  1133. ocFileListFragment.setEmptyListMessage(ExtendedListFragment.SearchType.NO_SEARCH);
  1134. }
  1135. } else {
  1136. Log_OC.e(TAG, "OCFileListFragment is null");
  1137. }
  1138. }
  1139. /**
  1140. * Once the file upload has finished -> update view
  1141. */
  1142. private class UploadFinishReceiver extends BroadcastReceiver {
  1143. /**
  1144. * Once the file upload has finished -> update view
  1145. *
  1146. * {@link BroadcastReceiver} to enable upload feedback in UI
  1147. */
  1148. @Override
  1149. public void onReceive(Context context, Intent intent) {
  1150. try {
  1151. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  1152. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  1153. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  1154. OCFile currentDir = getCurrentDir();
  1155. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  1156. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  1157. if (sameAccount && isDescendant) {
  1158. String linkedToRemotePath =
  1159. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  1160. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1161. refreshListOfFilesFragment(false);
  1162. }
  1163. }
  1164. boolean uploadWasFine = intent.getBooleanExtra(
  1165. FileUploader.EXTRA_UPLOAD_RESULT,
  1166. false);
  1167. boolean renamedInUpload = getFile().getRemotePath().
  1168. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  1169. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  1170. renamedInUpload;
  1171. FileFragment details = getSecondFragment();
  1172. boolean detailFragmentIsShown = (details instanceof FileDetailFragment);
  1173. if (sameAccount && sameFile && detailFragmentIsShown) {
  1174. if (uploadWasFine) {
  1175. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  1176. } else {
  1177. //TODO remove upload progress bar after upload failed.
  1178. Log_OC.d(TAG, "Remove upload progress bar after upload failed");
  1179. }
  1180. if (renamedInUpload) {
  1181. String newName = (new File(uploadedRemotePath)).getName();
  1182. DisplayUtils.showSnackMessage(
  1183. getActivity(),
  1184. R.string.filedetails_renamed_in_upload_msg,
  1185. newName
  1186. );
  1187. }
  1188. if (uploadWasFine || getFile().fileExists()) {
  1189. ((FileDetailFragment) details).updateFileDetails(false, true);
  1190. } else {
  1191. cleanSecondFragment();
  1192. }
  1193. // Force the preview if the file is an image or text file
  1194. if (uploadWasFine) {
  1195. OCFile ocFile = getFile();
  1196. if (PreviewImageFragment.canBePreviewed(ocFile)) {
  1197. startImagePreview(getFile(), true);
  1198. } else if (PreviewTextFragment.canBePreviewed(ocFile)) {
  1199. startTextPreview(ocFile, true);
  1200. }
  1201. // TODO what about other kind of previews?
  1202. }
  1203. }
  1204. setIndeterminate(false);
  1205. } finally {
  1206. if (intent != null) {
  1207. removeStickyBroadcast(intent);
  1208. }
  1209. }
  1210. }
  1211. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1212. private boolean isAscendant(String linkedToRemotePath) {
  1213. OCFile currentDir = getCurrentDir();
  1214. return (
  1215. currentDir != null &&
  1216. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1217. );
  1218. }
  1219. }
  1220. /**
  1221. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1222. * <p/>
  1223. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1224. * current folder.
  1225. */
  1226. private class DownloadFinishReceiver extends BroadcastReceiver {
  1227. @Override
  1228. public void onReceive(Context context, Intent intent) {
  1229. try {
  1230. boolean sameAccount = isSameAccount(intent);
  1231. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1232. String downloadBehaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
  1233. boolean isDescendant = isDescendant(downloadedRemotePath);
  1234. if (sameAccount && isDescendant) {
  1235. String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1236. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1237. refreshListOfFilesFragment(false);
  1238. }
  1239. refreshSecondFragment(
  1240. intent.getAction(),
  1241. downloadedRemotePath,
  1242. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  1243. }
  1244. if (mWaitingToSend != null) {
  1245. mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1246. if (mWaitingToSend.isDown() && downloadBehaviour != null) {
  1247. switch (downloadBehaviour) {
  1248. case OCFileListFragment.DOWNLOAD_SEND:
  1249. sendDownloadedFile();
  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, 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, true);
  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. /**
  1720. * Requests the download of the received {@link OCFile} , updates the UI
  1721. * to monitor the download progress and prepares the activity to send the file
  1722. * when the download finishes.
  1723. *
  1724. * @param file {@link OCFile} to download and preview.
  1725. */
  1726. public void startDownloadForSending(OCFile file, String downloadBehaviour) {
  1727. mWaitingToSend = file;
  1728. requestForDownload(mWaitingToSend, downloadBehaviour);
  1729. boolean hasSecondFragment = (getSecondFragment() != null);
  1730. updateFragmentsVisibility(hasSecondFragment);
  1731. }
  1732. /**
  1733. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1734. *
  1735. * @param file Image {@link OCFile} to show.
  1736. */
  1737. public void startImagePreview(OCFile file, boolean showPreview) {
  1738. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1739. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1740. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1741. if (showPreview) {
  1742. startActivity(showDetailsIntent);
  1743. } else {
  1744. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1745. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1746. }
  1747. }
  1748. /**
  1749. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1750. *
  1751. * @param file Image {@link OCFile} to show.
  1752. */
  1753. public void startImagePreview(OCFile file, VirtualFolderType type, boolean showPreview) {
  1754. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1755. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_FILE, file);
  1756. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1757. showDetailsIntent.putExtra(PreviewImageActivity.EXTRA_VIRTUAL_TYPE, type);
  1758. if (showPreview) {
  1759. startActivity(showDetailsIntent);
  1760. } else {
  1761. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1762. fileOperationsHelper.startSyncForFileAndIntent(file, showDetailsIntent);
  1763. }
  1764. }
  1765. /**
  1766. * Stars the preview of an already down media {@link OCFile}.
  1767. *
  1768. * @param file Media {@link OCFile} to preview.
  1769. * @param startPlaybackPosition Media position where the playback will be started,
  1770. * in milliseconds.
  1771. * @param autoplay When 'true', the playback will start without user
  1772. * interactions.
  1773. */
  1774. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay, boolean showPreview) {
  1775. if (showPreview && file.isDown() && !file.isDownloading()) {
  1776. Fragment mediaFragment = PreviewMediaFragment.newInstance(file, getAccount(), startPlaybackPosition, autoplay);
  1777. setSecondFragment(mediaFragment);
  1778. updateFragmentsVisibility(true);
  1779. updateActionBarTitleAndHomeButton(file);
  1780. setFile(file);
  1781. } else {
  1782. Intent previewIntent = new Intent();
  1783. previewIntent.putExtra(EXTRA_FILE, file);
  1784. previewIntent.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, startPlaybackPosition);
  1785. previewIntent.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, autoplay);
  1786. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1787. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1788. }
  1789. }
  1790. /**
  1791. * Stars the preview of a text file {@link OCFile}.
  1792. *
  1793. * @param file Text {@link OCFile} to preview.
  1794. */
  1795. public void startTextPreview(OCFile file, boolean showPreview) {
  1796. if (showPreview) {
  1797. Bundle args = new Bundle();
  1798. args.putParcelable(EXTRA_FILE, file);
  1799. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1800. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1801. PreviewTextFragment.class.getName(), args);
  1802. setSecondFragment(textPreviewFragment);
  1803. updateFragmentsVisibility(true);
  1804. updateActionBarTitleAndHomeButton(file);
  1805. setFile(file);
  1806. } else {
  1807. Intent previewIntent = new Intent();
  1808. previewIntent.putExtra(EXTRA_FILE, file);
  1809. previewIntent.putExtra(TEXT_PREVIEW, true);
  1810. FileOperationsHelper fileOperationsHelper = new FileOperationsHelper(this);
  1811. fileOperationsHelper.startSyncForFileAndIntent(file, previewIntent);
  1812. }
  1813. }
  1814. public void startContactListFragment(OCFile file) {
  1815. Intent intent = new Intent(this, ContactsPreferenceActivity.class);
  1816. intent.putExtra(ContactListFragment.FILE_NAME, Parcels.wrap(file));
  1817. intent.putExtra(ContactListFragment.ACCOUNT, Parcels.wrap(getAccount()));
  1818. startActivity(intent);
  1819. }
  1820. /**
  1821. * Requests the download of the received {@link OCFile} , updates the UI
  1822. * to monitor the download progress and prepares the activity to preview
  1823. * or open the file when the download finishes.
  1824. *
  1825. * @param file {@link OCFile} to download and preview.
  1826. */
  1827. public void startDownloadForPreview(OCFile file) {
  1828. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1829. setSecondFragment(detailFragment);
  1830. mWaitingToPreview = file;
  1831. requestForDownload();
  1832. updateFragmentsVisibility(true);
  1833. updateActionBarTitleAndHomeButton(file);
  1834. setFile(file);
  1835. }
  1836. /**
  1837. * Request stopping the upload/download operation in progress over the given {@link OCFile} file.
  1838. *
  1839. * @param file {@link OCFile} file which operation are wanted to be cancel
  1840. */
  1841. public void cancelTransference(OCFile file) {
  1842. getFileOperationsHelper().cancelTransference(file);
  1843. if (mWaitingToPreview != null &&
  1844. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1845. mWaitingToPreview = null;
  1846. }
  1847. if (mWaitingToSend != null &&
  1848. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1849. mWaitingToSend = null;
  1850. }
  1851. onTransferStateChanged(file, false, false);
  1852. }
  1853. /**
  1854. * Request stopping all upload/download operations in progress over the given {@link OCFile} files.
  1855. *
  1856. * @param files collection of {@link OCFile} files which operations are wanted to be cancel
  1857. */
  1858. public void cancelTransference(Collection<OCFile> files) {
  1859. for (OCFile file : files) {
  1860. cancelTransference(file);
  1861. }
  1862. }
  1863. @Override
  1864. public void onRefresh(boolean ignoreETag) {
  1865. refreshList(ignoreETag);
  1866. }
  1867. @Override
  1868. public void onRefresh() {
  1869. refreshList(true);
  1870. }
  1871. private void refreshList(boolean ignoreETag) {
  1872. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1873. if (listOfFiles != null && !listOfFiles.getIsSearchFragment()) {
  1874. OCFile folder = listOfFiles.getCurrentFile();
  1875. if (folder != null) {
  1876. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1877. listDirectory(mFile);*/
  1878. startSyncFolderOperation(folder, ignoreETag);
  1879. }
  1880. }
  1881. }
  1882. private void sortByDate(boolean ascending) {
  1883. getListOfFilesFragment().sortByDate(ascending);
  1884. }
  1885. private void sortBySize(boolean ascending) {
  1886. getListOfFilesFragment().sortBySize(ascending);
  1887. }
  1888. private void sortByName(boolean ascending) {
  1889. getListOfFilesFragment().sortByName(ascending);
  1890. }
  1891. private boolean isGridView() {
  1892. return getListOfFilesFragment().isGridEnabled();
  1893. }
  1894. public void allFilesOption() {
  1895. browseToRoot();
  1896. }
  1897. @Override
  1898. public void showFiles(boolean onDeviceOnly) {
  1899. super.showFiles(onDeviceOnly);
  1900. getListOfFilesFragment().refreshDirectory();
  1901. }
  1902. @Subscribe(threadMode = ThreadMode.MAIN)
  1903. public void onMessageEvent(SyncEventFinished event) {
  1904. Bundle bundle = event.getIntent().getExtras();
  1905. if (event.getIntent().getBooleanExtra(TEXT_PREVIEW, false)) {
  1906. startTextPreview((OCFile) bundle.get(EXTRA_FILE), true);
  1907. } else if (bundle.containsKey(PreviewVideoActivity.EXTRA_START_POSITION)) {
  1908. startMediaPreview((OCFile)bundle.get(EXTRA_FILE),
  1909. (int)bundle.get(PreviewVideoActivity.EXTRA_START_POSITION),
  1910. (boolean)bundle.get(PreviewVideoActivity.EXTRA_AUTOPLAY), true);
  1911. } else if (bundle.containsKey(PreviewImageActivity.EXTRA_VIRTUAL_TYPE)) {
  1912. startImagePreview((OCFile)bundle.get(EXTRA_FILE),
  1913. (VirtualFolderType)bundle.get(PreviewImageActivity.EXTRA_VIRTUAL_TYPE),
  1914. true);
  1915. } else {
  1916. startImagePreview((OCFile)bundle.get(EXTRA_FILE),true);
  1917. }
  1918. }
  1919. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1920. public void onMessageEvent(TokenPushEvent event) {
  1921. PushUtils.pushRegistrationToServer();
  1922. }
  1923. @Override
  1924. public void onStart() {
  1925. super.onStart();
  1926. EventBus.getDefault().post(new TokenPushEvent());
  1927. }
  1928. }