FileDisplayActivity.java 82 KB

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