FileDisplayActivity.java 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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) 2015 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. */
  22. package com.owncloud.android.ui.activity;
  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.res.Resources.NotFoundException;
  37. import android.database.Cursor;
  38. import android.net.Uri;
  39. import android.os.Build;
  40. import android.os.Bundle;
  41. import android.os.IBinder;
  42. import android.preference.PreferenceManager;
  43. import android.provider.OpenableColumns;
  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.GravityCompat;
  49. import android.support.v7.app.AlertDialog;
  50. import android.view.Menu;
  51. import android.view.MenuInflater;
  52. import android.view.MenuItem;
  53. import android.view.View;
  54. import android.widget.ProgressBar;
  55. import android.widget.RelativeLayout;
  56. import android.widget.Toast;
  57. import com.owncloud.android.MainApp;
  58. import com.owncloud.android.R;
  59. import com.owncloud.android.datamodel.FileDataStorageManager;
  60. import com.owncloud.android.datamodel.OCFile;
  61. import com.owncloud.android.files.services.FileDownloader;
  62. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  63. import com.owncloud.android.files.services.FileUploader;
  64. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  65. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  66. import com.owncloud.android.lib.common.operations.RemoteOperation;
  67. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  68. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  69. import com.owncloud.android.lib.common.utils.Log_OC;
  70. import com.owncloud.android.operations.CopyFileOperation;
  71. import com.owncloud.android.operations.CreateFolderOperation;
  72. import com.owncloud.android.operations.MoveFileOperation;
  73. import com.owncloud.android.operations.RefreshFolderOperation;
  74. import com.owncloud.android.operations.RemoveFileOperation;
  75. import com.owncloud.android.operations.RenameFileOperation;
  76. import com.owncloud.android.operations.SynchronizeFileOperation;
  77. import com.owncloud.android.services.observer.FileObserverService;
  78. import com.owncloud.android.syncadapter.FileSyncAdapter;
  79. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  80. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  81. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  82. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  83. import com.owncloud.android.ui.dialog.UploadSourceDialogFragment;
  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.preview.PreviewImageActivity;
  88. import com.owncloud.android.ui.preview.PreviewImageFragment;
  89. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  90. import com.owncloud.android.ui.preview.PreviewTextFragment;
  91. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  92. import com.owncloud.android.utils.DisplayUtils;
  93. import com.owncloud.android.utils.ErrorMessageAdapter;
  94. import com.owncloud.android.utils.FileStorageUtils;
  95. import com.owncloud.android.utils.UriUtils;
  96. import java.io.File;
  97. /**
  98. * Displays, what files the user has available in his ownCloud.
  99. */
  100. public class FileDisplayActivity extends HookActivity
  101. implements FileFragment.ContainerActivity,
  102. OnSslUntrustedCertListener, OnEnforceableRefreshListener {
  103. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  104. private UploadFinishReceiver mUploadFinishReceiver;
  105. private DownloadFinishReceiver mDownloadFinishReceiver;
  106. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  107. private boolean mDualPane;
  108. private View mLeftFragmentContainer;
  109. private View mRightFragmentContainer;
  110. private ProgressBar mProgressBar;
  111. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  112. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  113. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  114. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  115. public static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  116. public static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  117. public static final int ACTION_MOVE_FILES = 3;
  118. public static final int ACTION_COPY_FILES = 4;
  119. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  120. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  121. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  122. private OCFile mWaitingToPreview;
  123. private boolean mSyncInProgress = false;
  124. private static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
  125. private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER";
  126. private static String DIALOG_UPLOAD_SOURCE = "DIALOG_UPLOAD_SOURCE";
  127. private static String DIALOG_CERT_NOT_SAVED = "DIALOG_CERT_NOT_SAVED";
  128. private OCFile mWaitingToSend;
  129. @Override
  130. protected void onCreate(Bundle savedInstanceState) {
  131. Log_OC.v(TAG, "onCreate() start");
  132. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
  133. // is valid
  134. /// grant that FileObserverService is watching favorite files
  135. if (savedInstanceState == null) {
  136. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  137. startService(initObserversIntent);
  138. }
  139. /// Load of saved instance state
  140. if(savedInstanceState != null) {
  141. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(
  142. FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  143. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  144. mWaitingToSend = (OCFile) savedInstanceState.getParcelable(
  145. FileDisplayActivity.KEY_WAITING_TO_SEND);
  146. } else {
  147. mWaitingToPreview = null;
  148. mSyncInProgress = false;
  149. mWaitingToSend = null;
  150. }
  151. /// USER INTERFACE
  152. // Inflate and set the layout view
  153. setContentView(R.layout.files);
  154. // Navigation Drawer
  155. initDrawer();
  156. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  157. mProgressBar.setIndeterminateDrawable(
  158. ContextCompat.getDrawable(this,
  159. R.drawable.actionbar_progress_indeterminate_horizontal));
  160. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  161. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  162. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  163. if (savedInstanceState == null) {
  164. createMinFragments();
  165. }
  166. // Action bar setup
  167. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS,
  168. // according to the official
  169. // documentation
  170. // enable ActionBar app icon to behave as action to toggle nav drawer
  171. //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  172. getSupportActionBar().setHomeButtonEnabled(true);
  173. mProgressBar.setIndeterminate(mSyncInProgress);
  174. // always AFTER setContentView(...) ; to work around bug in its implementation
  175. setBackgroundText();
  176. Log_OC.v(TAG, "onCreate() end");
  177. }
  178. @Override
  179. protected void onStart() {
  180. Log_OC.v(TAG, "onStart() start");
  181. super.onStart();
  182. Log_OC.v(TAG, "onStart() end");
  183. }
  184. @Override
  185. protected void onStop() {
  186. Log_OC.v(TAG, "onStop() start");
  187. super.onStop();
  188. Log_OC.v(TAG, "onStop() end");
  189. }
  190. @Override
  191. protected void onDestroy() {
  192. Log_OC.v(TAG, "onDestroy() start");
  193. super.onDestroy();
  194. Log_OC.v(TAG, "onDestroy() end");
  195. }
  196. /**
  197. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  198. */
  199. @Override
  200. protected void onAccountSet(boolean stateWasRecovered) {
  201. super.onAccountSet(stateWasRecovered);
  202. if (getAccount() != null) {
  203. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  204. // current Account
  205. OCFile file = getFile();
  206. // get parent from path
  207. String parentPath = "";
  208. if (file != null) {
  209. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  210. // upload in progress - right now, files are not inserted in the local
  211. // cache until the upload is successful get parent from path
  212. parentPath = file.getRemotePath().substring(0,
  213. file.getRemotePath().lastIndexOf(file.getFileName()));
  214. if (getStorageManager().getFileByPath(parentPath) == null)
  215. file = null; // not able to know the directory where the file is uploading
  216. } else {
  217. file = getStorageManager().getFileByPath(file.getRemotePath());
  218. // currentDir = null if not in the current Account
  219. }
  220. }
  221. if (file == null) {
  222. // fall back to root folder
  223. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  224. }
  225. setFile(file);
  226. if (mAccountWasSet) {
  227. setUsernameInDrawer((RelativeLayout) findViewById(R.id.left_drawer), getAccount());
  228. }
  229. if (!stateWasRecovered) {
  230. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  231. initFragmentsWithFile();
  232. if (file.isFolder()) {
  233. startSyncFolderOperation(file, false);
  234. }
  235. } else {
  236. updateFragmentsVisibility(!file.isFolder());
  237. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  238. }
  239. }
  240. }
  241. private void createMinFragments() {
  242. OCFileListFragment listOfFiles = new OCFileListFragment();
  243. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  244. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  245. transaction.commit();
  246. }
  247. private void initFragmentsWithFile() {
  248. if (getAccount() != null && getFile() != null) {
  249. /// First fragment
  250. OCFileListFragment listOfFiles = getListOfFilesFragment();
  251. if (listOfFiles != null) {
  252. listOfFiles.listDirectory(getCurrentDir());
  253. // TODO Enable when "On Device" is recovered
  254. // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
  255. } else {
  256. Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  257. }
  258. /// Second fragment
  259. OCFile file = getFile();
  260. Fragment secondFragment = chooseInitialSecondFragment(file);
  261. if (secondFragment != null) {
  262. setSecondFragment(secondFragment);
  263. updateFragmentsVisibility(true);
  264. updateActionBarTitleAndHomeButton(file);
  265. } else {
  266. cleanSecondFragment();
  267. if (file.isDown() && PreviewTextFragment.canBePreviewed(file))
  268. startTextPreview(file);
  269. }
  270. } else {
  271. Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
  272. if (getAccount() == null) {
  273. Log_OC.wtf(TAG, "\t account is NULL");
  274. }
  275. if (getFile() == null) {
  276. Log_OC.wtf(TAG, "\t file is NULL");
  277. }
  278. }
  279. }
  280. private Fragment chooseInitialSecondFragment(OCFile file) {
  281. Fragment secondFragment = null;
  282. if (file != null && !file.isFolder()) {
  283. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  284. && file.getLastSyncDateForProperties() > 0 // temporal fix
  285. ) {
  286. int startPlaybackPosition =
  287. getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  288. boolean autoplay =
  289. getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  290. secondFragment = new PreviewMediaFragment(file, getAccount(),
  291. startPlaybackPosition, autoplay);
  292. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  293. secondFragment = null;
  294. } else {
  295. secondFragment = FileDetailFragment.newInstance(file, getAccount());
  296. }
  297. }
  298. return secondFragment;
  299. }
  300. /**
  301. * Replaces the second fragment managed by the activity with the received as
  302. * a parameter.
  303. * <p/>
  304. * Assumes never will be more than two fragments managed at the same time.
  305. *
  306. * @param fragment New second Fragment to set.
  307. */
  308. private void setSecondFragment(Fragment fragment) {
  309. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  310. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  311. transaction.commit();
  312. }
  313. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  314. if (mDualPane) {
  315. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  316. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  317. }
  318. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  319. mRightFragmentContainer.setVisibility(View.VISIBLE);
  320. }
  321. } else if (existsSecondFragment) {
  322. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  323. mLeftFragmentContainer.setVisibility(View.GONE);
  324. }
  325. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  326. mRightFragmentContainer.setVisibility(View.VISIBLE);
  327. }
  328. } else {
  329. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  330. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  331. }
  332. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  333. mRightFragmentContainer.setVisibility(View.GONE);
  334. }
  335. }
  336. }
  337. private OCFileListFragment getListOfFilesFragment() {
  338. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  339. FileDisplayActivity.TAG_LIST_OF_FILES);
  340. if (listOfFiles != null) {
  341. return (OCFileListFragment) listOfFiles;
  342. }
  343. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  344. return null;
  345. }
  346. public FileFragment getSecondFragment() {
  347. Fragment second = getSupportFragmentManager().findFragmentByTag(
  348. FileDisplayActivity.TAG_SECOND_FRAGMENT);
  349. if (second != null) {
  350. return (FileFragment) second;
  351. }
  352. return null;
  353. }
  354. protected void cleanSecondFragment() {
  355. Fragment second = getSecondFragment();
  356. if (second != null) {
  357. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  358. tr.remove(second);
  359. tr.commit();
  360. }
  361. updateFragmentsVisibility(false);
  362. updateActionBarTitleAndHomeButton(null);
  363. }
  364. protected void refreshListOfFilesFragment() {
  365. OCFileListFragment fileListFragment = getListOfFilesFragment();
  366. if (fileListFragment != null) {
  367. fileListFragment.listDirectory();
  368. // TODO Enable when "On Device" is recovered ?
  369. // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
  370. }
  371. }
  372. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  373. boolean success) {
  374. FileFragment secondFragment = getSecondFragment();
  375. boolean waitedPreview = (mWaitingToPreview != null &&
  376. mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  377. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  378. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  379. OCFile fileInFragment = detailsFragment.getFile();
  380. if (fileInFragment != null &&
  381. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  382. // the user browsed to other file ; forget the automatic preview
  383. mWaitingToPreview = null;
  384. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  385. // grant that the right panel updates the progress bar
  386. detailsFragment.listenForTransferProgress();
  387. detailsFragment.updateFileDetails(true, false);
  388. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  389. // update the right panel
  390. boolean detailsFragmentChanged = false;
  391. if (waitedPreview) {
  392. if (success) {
  393. mWaitingToPreview = getStorageManager().getFileById(
  394. mWaitingToPreview.getFileId()); // update the file from database,
  395. // for the local storage path
  396. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  397. startMediaPreview(mWaitingToPreview, 0, true);
  398. detailsFragmentChanged = true;
  399. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  400. startTextPreview(mWaitingToPreview);
  401. detailsFragmentChanged = true;
  402. } else {
  403. getFileOperationsHelper().openFile(mWaitingToPreview);
  404. }
  405. }
  406. mWaitingToPreview = null;
  407. }
  408. if (!detailsFragmentChanged) {
  409. detailsFragment.updateFileDetails(false, (success));
  410. }
  411. }
  412. }
  413. }
  414. @Override
  415. public boolean onPrepareOptionsMenu(Menu menu) {
  416. boolean drawerOpen = mDrawerLayout.isDrawerOpen(GravityCompat.START);
  417. menu.findItem(R.id.action_upload).setVisible(!drawerOpen);
  418. menu.findItem(R.id.action_create_dir).setVisible(!drawerOpen);
  419. menu.findItem(R.id.action_sort).setVisible(!drawerOpen);
  420. menu.findItem(R.id.action_sync_account).setVisible(!drawerOpen);
  421. menu.findItem(R.id.action_switch_view).setVisible(!drawerOpen);
  422. return super.onPrepareOptionsMenu(menu);
  423. }
  424. @Override
  425. public boolean onCreateOptionsMenu(Menu menu) {
  426. MenuInflater inflater = getMenuInflater();
  427. inflater.inflate(R.menu.main_menu, menu);
  428. return true;
  429. }
  430. @Override
  431. public boolean onOptionsItemSelected(MenuItem item) {
  432. boolean retval = true;
  433. switch (item.getItemId()) {
  434. case R.id.action_create_dir: {
  435. CreateFolderDialogFragment dialog =
  436. CreateFolderDialogFragment.newInstance(getCurrentDir());
  437. dialog.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
  438. break;
  439. }
  440. case R.id.action_sync_account: {
  441. startSynchronization();
  442. break;
  443. }
  444. case R.id.action_upload: {
  445. UploadSourceDialogFragment dialog =
  446. UploadSourceDialogFragment.newInstance(getAccount());
  447. dialog.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE);
  448. break;
  449. }
  450. case android.R.id.home: {
  451. FileFragment second = getSecondFragment();
  452. OCFile currentDir = getCurrentDir();
  453. if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
  454. mDrawerLayout.closeDrawer(GravityCompat.START);
  455. } else if((currentDir != null && currentDir.getParentId() != 0) ||
  456. (second != null && second.getFile() != null)) {
  457. onBackPressed();
  458. } else {
  459. mDrawerLayout.openDrawer(GravityCompat.START);
  460. }
  461. break;
  462. }
  463. case R.id.action_sort: {
  464. SharedPreferences appPreferences = PreferenceManager
  465. .getDefaultSharedPreferences(this);
  466. // Read sorting order, default to sort by name ascending
  467. Integer sortOrder = appPreferences
  468. .getInt("sortOrder", FileStorageUtils.SORT_NAME);
  469. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  470. builder.setTitle(R.string.actionbar_sort_title)
  471. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder ,
  472. new DialogInterface.OnClickListener() {
  473. public void onClick(DialogInterface dialog, int which) {
  474. switch (which){
  475. case 0:
  476. sortByName(true);
  477. break;
  478. case 1:
  479. sortByDate(false);
  480. break;
  481. }
  482. dialog.dismiss();
  483. }
  484. });
  485. builder.create().show();
  486. break;
  487. }
  488. case R.id.action_switch_view:{
  489. if (isGridView()){
  490. item.setTitle(getString(R.string.action_switch_grid_view));
  491. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  492. R.drawable.ic_view_module));
  493. getListOfFilesFragment().setListAsPreferred();
  494. } else {
  495. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  496. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  497. R.drawable.ic_view_list));
  498. getListOfFilesFragment().setGridAsPreferred();
  499. }
  500. return true;
  501. }
  502. default:
  503. retval = super.onOptionsItemSelected(item);
  504. }
  505. return retval;
  506. }
  507. private void startSynchronization() {
  508. Log_OC.d(TAG, "Got to start sync");
  509. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  510. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  511. ContentResolver.cancelSync(null, MainApp.getAuthority());
  512. // cancel the current synchronizations of any ownCloud account
  513. Bundle bundle = new Bundle();
  514. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  515. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  516. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  517. MainApp.getAuthority());
  518. ContentResolver.requestSync(
  519. getAccount(),
  520. MainApp.getAuthority(), bundle);
  521. } else {
  522. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  523. MainApp.getAuthority() + " with new API");
  524. SyncRequest.Builder builder = new SyncRequest.Builder();
  525. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  526. builder.setExpedited(true);
  527. builder.setManual(true);
  528. builder.syncOnce();
  529. // Fix bug in Android Lollipop when you click on refresh the whole account
  530. Bundle extras = new Bundle();
  531. builder.setExtras(extras);
  532. SyncRequest request = builder.build();
  533. ContentResolver.requestSync(request);
  534. }
  535. }
  536. /**
  537. * Called, when the user selected something for uploading
  538. *
  539. */
  540. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  541. @Override
  542. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  543. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK ||
  544. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  545. //getClipData is only supported on api level 16+, Jelly Bean
  546. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  547. data.getClipData() != null &&
  548. data.getClipData().getItemCount() > 0) {
  549. for( int i = 0; i < data.getClipData().getItemCount(); i++){
  550. Intent intent = new Intent();
  551. intent.setData(data.getClipData().getItemAt(i).getUri());
  552. requestSimpleUpload(intent, resultCode);
  553. }
  554. } else {
  555. requestSimpleUpload(data, resultCode);
  556. }
  557. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK ||
  558. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  559. requestMultipleUpload(data, resultCode);
  560. } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK){
  561. final Intent fData = data;
  562. final int fResultCode = resultCode;
  563. getHandler().postDelayed(
  564. new Runnable() {
  565. @Override
  566. public void run() {
  567. requestMoveOperation(fData, fResultCode);
  568. }
  569. },
  570. DELAY_TO_REQUEST_OPERATIONS_LATER
  571. );
  572. } else if (requestCode == ACTION_COPY_FILES && resultCode == RESULT_OK) {
  573. final Intent fData = data;
  574. final int fResultCode = resultCode;
  575. getHandler().postDelayed(
  576. new Runnable() {
  577. @Override
  578. public void run() {
  579. requestCopyOperation(fData, fResultCode);
  580. }
  581. },
  582. DELAY_TO_REQUEST_OPERATIONS_LATER
  583. );
  584. } else {
  585. super.onActivityResult(requestCode, resultCode, data);
  586. }
  587. }
  588. private void requestMultipleUpload(Intent data, int resultCode) {
  589. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  590. if (filePaths != null) {
  591. String[] remotePaths = new String[filePaths.length];
  592. String remotePathBase = getCurrentDir().getRemotePath();
  593. for (int j = 0; j< remotePaths.length; j++) {
  594. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  595. }
  596. Intent i = new Intent(this, FileUploader.class);
  597. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  598. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  599. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  600. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  601. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  602. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  603. startService(i);
  604. } else {
  605. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  606. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected),
  607. Toast.LENGTH_LONG);
  608. t.show();
  609. return;
  610. }
  611. }
  612. private void requestSimpleUpload(Intent data, int resultCode) {
  613. String filePath = null;
  614. String mimeType = null;
  615. Uri selectedImageUri = data.getData();
  616. try {
  617. mimeType = getContentResolver().getType(selectedImageUri);
  618. String fileManagerString = selectedImageUri.getPath();
  619. String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);
  620. if (selectedImagePath != null)
  621. filePath = selectedImagePath;
  622. else
  623. filePath = fileManagerString;
  624. } catch (Exception e) {
  625. Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
  626. "Intent.ACTION_GET_CONTENT", e);
  627. } finally {
  628. if (filePath == null) {
  629. Log_OC.e(TAG, "Couldn't resolve path to file");
  630. Toast t = Toast.makeText(
  631. this, getString(R.string.filedisplay_unexpected_bad_get_content),
  632. Toast.LENGTH_LONG
  633. );
  634. t.show();
  635. return;
  636. }
  637. }
  638. Intent i = new Intent(this, FileUploader.class);
  639. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  640. OCFile currentDir = getCurrentDir();
  641. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  642. if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  643. Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
  644. try {
  645. if (cursor != null && cursor.moveToFirst()) {
  646. String displayName = cursor.getString(cursor.getColumnIndex(
  647. OpenableColumns.DISPLAY_NAME));
  648. Log_OC.v(TAG, "Display Name: " + displayName );
  649. displayName.replace(File.separatorChar, '_');
  650. displayName.replace(File.pathSeparatorChar, '_');
  651. remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);
  652. }
  653. // and what happens in case of error?; wrong target name for the upload
  654. } finally {
  655. cursor.close();
  656. }
  657. } else {
  658. remotePath += new File(filePath).getName();
  659. }
  660. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
  661. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
  662. i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
  663. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  664. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  665. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  666. startService(i);
  667. }
  668. /**
  669. * Request the operation for moving the file/folder from one path to another
  670. *
  671. * @param data Intent received
  672. * @param resultCode Result code received
  673. */
  674. private void requestMoveOperation(Intent data, int resultCode) {
  675. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  676. OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  677. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  678. }
  679. /**
  680. * Request the operation for copying the file/folder from one path to another
  681. *
  682. * @param data Intent received
  683. * @param resultCode Result code received
  684. */
  685. private void requestCopyOperation(Intent data, int resultCode) {
  686. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  687. OCFile targetFile = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  688. getFileOperationsHelper().copyFile(folderToMoveAt, targetFile);
  689. }
  690. @Override
  691. public void onBackPressed() {
  692. if (!isDrawerOpen()){
  693. OCFileListFragment listOfFiles = getListOfFilesFragment();
  694. if (mDualPane || getSecondFragment() == null) {
  695. OCFile currentDir = getCurrentDir();
  696. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  697. finish();
  698. return;
  699. }
  700. if (listOfFiles != null) { // should never be null, indeed
  701. listOfFiles.onBrowseUp();
  702. }
  703. }
  704. if (listOfFiles != null) { // should never be null, indeed
  705. setFile(listOfFiles.getCurrentFile());
  706. }
  707. cleanSecondFragment();
  708. } else {
  709. super.onBackPressed();
  710. }
  711. }
  712. @Override
  713. protected void onSaveInstanceState(Bundle outState) {
  714. // responsibility of restore is preferred in onCreate() before than in
  715. // onRestoreInstanceState when there are Fragments involved
  716. Log_OC.v(TAG, "onSaveInstanceState() start");
  717. super.onSaveInstanceState(outState);
  718. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  719. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  720. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  721. // mRefreshSharesInProgress);
  722. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  723. Log_OC.v(TAG, "onSaveInstanceState() end");
  724. }
  725. @Override
  726. protected void onResume() {
  727. Log_OC.v(TAG, "onResume() start");
  728. super.onResume();
  729. // refresh Navigation Drawer account list
  730. mNavigationDrawerAdapter.updateAccountList();
  731. // refresh list of files
  732. refreshListOfFilesFragment();
  733. // Listen for sync messages
  734. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  735. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  736. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  737. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  738. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  739. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  740. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  741. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  742. // syncIntentFilter);
  743. // Listen for upload messages
  744. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  745. mUploadFinishReceiver = new UploadFinishReceiver();
  746. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  747. // Listen for download messages
  748. IntentFilter downloadIntentFilter = new IntentFilter(
  749. FileDownloader.getDownloadAddedMessage());
  750. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  751. mDownloadFinishReceiver = new DownloadFinishReceiver();
  752. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  753. Log_OC.v(TAG, "onResume() end");
  754. }
  755. @Override
  756. protected void onPause() {
  757. Log_OC.v(TAG, "onPause() start");
  758. if (mSyncBroadcastReceiver != null) {
  759. unregisterReceiver(mSyncBroadcastReceiver);
  760. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  761. mSyncBroadcastReceiver = null;
  762. }
  763. if (mUploadFinishReceiver != null) {
  764. unregisterReceiver(mUploadFinishReceiver);
  765. mUploadFinishReceiver = null;
  766. }
  767. if (mDownloadFinishReceiver != null) {
  768. unregisterReceiver(mDownloadFinishReceiver);
  769. mDownloadFinishReceiver = null;
  770. }
  771. super.onPause();
  772. Log_OC.v(TAG, "onPause() end");
  773. }
  774. private class SyncBroadcastReceiver extends BroadcastReceiver {
  775. /**
  776. * {@link BroadcastReceiver} to enable syncing feedback in UI
  777. */
  778. @Override
  779. public void onReceive(Context context, Intent intent) {
  780. try {
  781. String event = intent.getAction();
  782. Log_OC.d(TAG, "Received broadcast " + event);
  783. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  784. String synchFolderRemotePath =
  785. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  786. RemoteOperationResult synchResult =
  787. (RemoteOperationResult)intent.getSerializableExtra(
  788. FileSyncAdapter.EXTRA_RESULT);
  789. boolean sameAccount = (getAccount() != null &&
  790. accountName.equals(getAccount().name) && getStorageManager() != null);
  791. if (sameAccount) {
  792. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  793. mSyncInProgress = true;
  794. } else {
  795. OCFile currentFile = (getFile() == null) ? null :
  796. getStorageManager().getFileByPath(getFile().getRemotePath());
  797. OCFile currentDir = (getCurrentDir() == null) ? null :
  798. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  799. if (currentDir == null) {
  800. // current folder was removed from the server
  801. Toast.makeText( FileDisplayActivity.this,
  802. String.format(
  803. getString(R.string.
  804. sync_current_folder_was_removed),
  805. synchFolderRemotePath),
  806. Toast.LENGTH_LONG)
  807. .show();
  808. browseToRoot();
  809. } else {
  810. if (currentFile == null && !getFile().isFolder()) {
  811. // currently selected file was removed in the server, and now we
  812. // know it
  813. cleanSecondFragment();
  814. currentFile = currentDir;
  815. }
  816. if (synchFolderRemotePath != null &&
  817. currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  818. OCFileListFragment fileListFragment = getListOfFilesFragment();
  819. if (fileListFragment != null) {
  820. fileListFragment.listDirectory();
  821. // TODO Enable when "On Device" is recovered ?
  822. // fileListFragment.listDirectory(currentDir,
  823. // MainApp.getOnlyOnDevice());
  824. }
  825. }
  826. setFile(currentFile);
  827. }
  828. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  829. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
  830. .equals(event));
  831. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  832. equals(event) &&/// TODO refactor and make common
  833. synchResult != null && !synchResult.isSuccess() &&
  834. (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  835. synchResult.isIdPRedirection() ||
  836. (synchResult.isException() && synchResult.getException()
  837. instanceof AuthenticatorException))) {
  838. requestCredentialsUpdate(context);
  839. }
  840. }
  841. removeStickyBroadcast(intent);
  842. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  843. mProgressBar.setIndeterminate(mSyncInProgress);
  844. //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
  845. //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
  846. /*|| mRefreshSharesInProgress*/ //);
  847. setBackgroundText();
  848. }
  849. if (synchResult != null) {
  850. if (synchResult.getCode().equals(
  851. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  852. mLastSslUntrustedServerResult = synchResult;
  853. }
  854. }
  855. } catch (RuntimeException e) {
  856. // avoid app crashes after changing the serial id of RemoteOperationResult
  857. // in owncloud library with broadcast notifications pending to process
  858. removeStickyBroadcast(intent);
  859. }
  860. }
  861. }
  862. /**
  863. * Show a text message on screen view for notifying user if content is
  864. * loading or folder is empty
  865. */
  866. private void setBackgroundText() {
  867. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  868. if (ocFileListFragment != null) {
  869. int message = R.string.file_list_loading;
  870. if (!mSyncInProgress) {
  871. // In case file list is empty
  872. message = R.string.file_list_empty;
  873. }
  874. ocFileListFragment.setMessageForEmptyList(getString(message));
  875. } else {
  876. Log_OC.e(TAG, "OCFileListFragment is null");
  877. }
  878. }
  879. /**
  880. * Once the file upload has finished -> update view
  881. */
  882. private class UploadFinishReceiver extends BroadcastReceiver {
  883. /**
  884. * Once the file upload has finished -> update view
  885. *
  886. * @author David A. Velasco
  887. * {@link BroadcastReceiver} to enable upload feedback in UI
  888. */
  889. @Override
  890. public void onReceive(Context context, Intent intent) {
  891. try {
  892. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  893. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  894. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  895. OCFile currentDir = getCurrentDir();
  896. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  897. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  898. if (sameAccount && isDescendant) {
  899. String linkedToRemotePath =
  900. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  901. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  902. refreshListOfFilesFragment();
  903. }
  904. }
  905. boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT,
  906. false);
  907. boolean renamedInUpload = getFile().getRemotePath().
  908. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  909. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  910. renamedInUpload;
  911. FileFragment details = getSecondFragment();
  912. boolean detailFragmentIsShown = (details != null &&
  913. details instanceof FileDetailFragment);
  914. if (sameAccount && sameFile && detailFragmentIsShown) {
  915. if (uploadWasFine) {
  916. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  917. }
  918. if (renamedInUpload) {
  919. String newName = (new File(uploadedRemotePath)).getName();
  920. Toast msg = Toast.makeText(
  921. context,
  922. String.format(
  923. getString(R.string.filedetails_renamed_in_upload_msg),
  924. newName),
  925. Toast.LENGTH_LONG);
  926. msg.show();
  927. }
  928. if (uploadWasFine || getFile().fileExists()) {
  929. ((FileDetailFragment) details).updateFileDetails(false, true);
  930. } else {
  931. cleanSecondFragment();
  932. }
  933. // Force the preview if the file is an image or text file
  934. if (uploadWasFine) {
  935. OCFile ocFile = getFile();
  936. if (PreviewImageFragment.canBePreviewed(ocFile))
  937. startImagePreview(getFile());
  938. else if (PreviewTextFragment.canBePreviewed(ocFile))
  939. startTextPreview(ocFile);
  940. // TODO what about other kind of previews?
  941. }
  942. }
  943. mProgressBar.setIndeterminate(false);
  944. } finally {
  945. if (intent != null) {
  946. removeStickyBroadcast(intent);
  947. }
  948. }
  949. }
  950. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  951. private boolean isAscendant(String linkedToRemotePath) {
  952. OCFile currentDir = getCurrentDir();
  953. return (
  954. currentDir != null &&
  955. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  956. );
  957. }
  958. }
  959. /**
  960. * Class waiting for broadcast events from the {@link FileDownloader} service.
  961. *
  962. * Updates the UI when a download is started or finished, provided that it is relevant for the
  963. * current folder.
  964. */
  965. private class DownloadFinishReceiver extends BroadcastReceiver {
  966. @Override
  967. public void onReceive(Context context, Intent intent) {
  968. try {
  969. boolean sameAccount = isSameAccount(intent);
  970. String downloadedRemotePath =
  971. intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  972. boolean isDescendant = isDescendant(downloadedRemotePath);
  973. if (sameAccount && isDescendant) {
  974. String linkedToRemotePath =
  975. intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  976. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  977. refreshListOfFilesFragment();
  978. }
  979. refreshSecondFragment(
  980. intent.getAction(),
  981. downloadedRemotePath,
  982. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
  983. );
  984. }
  985. if (mWaitingToSend != null) {
  986. mWaitingToSend =
  987. getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  988. if (mWaitingToSend.isDown()) {
  989. sendDownloadedFile();
  990. }
  991. }
  992. } finally {
  993. if (intent != null) {
  994. removeStickyBroadcast(intent);
  995. }
  996. }
  997. }
  998. private boolean isDescendant(String downloadedRemotePath) {
  999. OCFile currentDir = getCurrentDir();
  1000. return (
  1001. currentDir != null &&
  1002. downloadedRemotePath != null &&
  1003. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1004. );
  1005. }
  1006. private boolean isAscendant(String linkedToRemotePath) {
  1007. OCFile currentDir = getCurrentDir();
  1008. return (
  1009. currentDir != null &&
  1010. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1011. );
  1012. }
  1013. private boolean isSameAccount(Intent intent) {
  1014. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1015. return (accountName != null && getAccount() != null &&
  1016. accountName.equals(getAccount().name));
  1017. }
  1018. }
  1019. public void browseToRoot() {
  1020. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1021. if (listOfFiles != null) { // should never be null, indeed
  1022. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1023. listOfFiles.listDirectory(root);
  1024. // TODO Enable when "On Device" is recovered ?
  1025. // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
  1026. setFile(listOfFiles.getCurrentFile());
  1027. startSyncFolderOperation(root, false);
  1028. }
  1029. cleanSecondFragment();
  1030. }
  1031. /**
  1032. * {@inheritDoc}
  1033. * <p/>
  1034. * Updates action bar and second fragment, if in dual pane mode.
  1035. */
  1036. @Override
  1037. public void onBrowsedDownTo(OCFile directory) {
  1038. setFile(directory);
  1039. cleanSecondFragment();
  1040. // Sync Folder
  1041. startSyncFolderOperation(directory, false);
  1042. }
  1043. /**
  1044. * Shows the information of the {@link OCFile} received as a
  1045. * parameter in the second fragment.
  1046. *
  1047. * @param file {@link OCFile} whose details will be shown
  1048. */
  1049. @Override
  1050. public void showDetails(OCFile file) {
  1051. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1052. setSecondFragment(detailFragment);
  1053. updateFragmentsVisibility(true);
  1054. updateActionBarTitleAndHomeButton(file);
  1055. setFile(file);
  1056. }
  1057. @Override
  1058. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1059. if (mDualPane) {
  1060. // in dual pane mode, keep the focus of title an action bar in the current folder
  1061. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1062. } else {
  1063. super.updateActionBarTitleAndHomeButton(chosenFile);
  1064. }
  1065. }
  1066. @Override
  1067. protected ServiceConnection newTransferenceServiceConnection() {
  1068. return new ListServiceConnection();
  1069. }
  1070. /**
  1071. * Defines callbacks for service binding, passed to bindService()
  1072. */
  1073. private class ListServiceConnection implements ServiceConnection {
  1074. @Override
  1075. public void onServiceConnected(ComponentName component, IBinder service) {
  1076. if (component.equals(new ComponentName(
  1077. FileDisplayActivity.this, FileDownloader.class))) {
  1078. Log_OC.d(TAG, "Download service connected");
  1079. mDownloaderBinder = (FileDownloaderBinder) service;
  1080. if (mWaitingToPreview != null)
  1081. if (getStorageManager() != null) {
  1082. // update the file
  1083. mWaitingToPreview =
  1084. getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1085. if (!mWaitingToPreview.isDown()) {
  1086. requestForDownload();
  1087. }
  1088. }
  1089. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1090. FileUploader.class))) {
  1091. Log_OC.d(TAG, "Upload service connected");
  1092. mUploaderBinder = (FileUploaderBinder) service;
  1093. } else {
  1094. return;
  1095. }
  1096. // a new chance to get the mDownloadBinder through
  1097. // getFileDownloadBinder() - THIS IS A MESS
  1098. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1099. if (listOfFiles != null) {
  1100. listOfFiles.listDirectory();
  1101. // TODO Enable when "On Device" is recovered ?
  1102. // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
  1103. }
  1104. FileFragment secondFragment = getSecondFragment();
  1105. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1106. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1107. detailFragment.listenForTransferProgress();
  1108. detailFragment.updateFileDetails(false, false);
  1109. }
  1110. }
  1111. @Override
  1112. public void onServiceDisconnected(ComponentName component) {
  1113. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1114. FileDownloader.class))) {
  1115. Log_OC.d(TAG, "Download service disconnected");
  1116. mDownloaderBinder = null;
  1117. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1118. FileUploader.class))) {
  1119. Log_OC.d(TAG, "Upload service disconnected");
  1120. mUploaderBinder = null;
  1121. }
  1122. }
  1123. }
  1124. @Override
  1125. public void onSavedCertificate() {
  1126. startSyncFolderOperation(getCurrentDir(), false);
  1127. }
  1128. @Override
  1129. public void onFailedSavingCertificate() {
  1130. ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
  1131. R.string.ssl_validator_not_saved, new String[]{}, R.string.common_ok, -1, -1
  1132. );
  1133. dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
  1134. }
  1135. @Override
  1136. public void onCancelCertificate() {
  1137. // nothing to do
  1138. }
  1139. /**
  1140. * Updates the view associated to the activity after the finish of some operation over files
  1141. * in the current account.
  1142. *
  1143. * @param operation Removal operation performed.
  1144. * @param result Result of the removal.
  1145. */
  1146. @Override
  1147. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1148. super.onRemoteOperationFinish(operation, result);
  1149. if (operation instanceof RemoveFileOperation) {
  1150. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1151. } else if (operation instanceof RenameFileOperation) {
  1152. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1153. } else if (operation instanceof SynchronizeFileOperation) {
  1154. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1155. } else if (operation instanceof CreateFolderOperation) {
  1156. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1157. } else if (operation instanceof MoveFileOperation) {
  1158. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1159. } else if (operation instanceof CopyFileOperation) {
  1160. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1161. }
  1162. }
  1163. private void refreshShowDetails() {
  1164. FileFragment details = getSecondFragment();
  1165. if (details != null) {
  1166. OCFile file = details.getFile();
  1167. if (file != null) {
  1168. file = getStorageManager().getFileByPath(file.getRemotePath());
  1169. if (details instanceof PreviewMediaFragment) {
  1170. // Refresh OCFile of the fragment
  1171. ((PreviewMediaFragment) details).updateFile(file);
  1172. } else if (details instanceof PreviewTextFragment) {
  1173. // Refresh OCFile of the fragment
  1174. ((PreviewTextFragment) details).updateFile(file);
  1175. } else {
  1176. showDetails(file);
  1177. }
  1178. }
  1179. invalidateOptionsMenu();
  1180. }
  1181. }
  1182. /**
  1183. * Updates the view associated to the activity after the finish of an operation trying to
  1184. * remove a file.
  1185. *
  1186. * @param operation Removal operation performed.
  1187. * @param result Result of the removal.
  1188. */
  1189. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1190. RemoteOperationResult result) {
  1191. Toast msg = Toast.makeText(this,
  1192. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1193. Toast.LENGTH_LONG);
  1194. msg.show();
  1195. if (result.isSuccess()) {
  1196. OCFile removedFile = operation.getFile();
  1197. FileFragment second = getSecondFragment();
  1198. if (second != null && removedFile.equals(second.getFile())) {
  1199. if (second instanceof PreviewMediaFragment) {
  1200. ((PreviewMediaFragment) second).stopPreview(true);
  1201. }
  1202. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1203. cleanSecondFragment();
  1204. }
  1205. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())){
  1206. refreshListOfFilesFragment();
  1207. }
  1208. invalidateOptionsMenu();
  1209. } else {
  1210. if (result.isSslRecoverableException()) {
  1211. mLastSslUntrustedServerResult = result;
  1212. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1213. }
  1214. }
  1215. }
  1216. /**
  1217. * Updates the view associated to the activity after the finish of an operation trying to move a
  1218. * file.
  1219. *
  1220. * @param operation Move operation performed.
  1221. * @param result Result of the move operation.
  1222. */
  1223. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1224. RemoteOperationResult result) {
  1225. if (result.isSuccess()) {
  1226. refreshListOfFilesFragment();
  1227. } else {
  1228. try {
  1229. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1230. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1231. Toast.LENGTH_LONG);
  1232. msg.show();
  1233. } catch (NotFoundException e) {
  1234. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1235. }
  1236. }
  1237. }
  1238. /**
  1239. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1240. * file.
  1241. *
  1242. * @param operation Copy operation performed.
  1243. * @param result Result of the copy operation.
  1244. */
  1245. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1246. if (result.isSuccess()) {
  1247. refreshListOfFilesFragment();
  1248. } else {
  1249. try {
  1250. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1251. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1252. Toast.LENGTH_LONG);
  1253. msg.show();
  1254. } catch (NotFoundException e) {
  1255. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * Updates the view associated to the activity after the finish of an operation trying to rename
  1261. * a file.
  1262. *
  1263. * @param operation Renaming operation performed.
  1264. * @param result Result of the renaming.
  1265. */
  1266. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1267. RemoteOperationResult result) {
  1268. OCFile renamedFile = operation.getFile();
  1269. if (result.isSuccess()) {
  1270. FileFragment details = getSecondFragment();
  1271. if (details != null) {
  1272. if (details instanceof FileDetailFragment &&
  1273. renamedFile.equals(details.getFile()) ) {
  1274. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1275. showDetails(renamedFile);
  1276. } else if (details instanceof PreviewMediaFragment &&
  1277. renamedFile.equals(details.getFile())) {
  1278. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1279. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1280. int position = ((PreviewMediaFragment) details).getPosition();
  1281. startMediaPreview(renamedFile, position, true);
  1282. } else {
  1283. getFileOperationsHelper().openFile(renamedFile);
  1284. }
  1285. } else if (details instanceof PreviewTextFragment &&
  1286. renamedFile.equals(details.getFile())) {
  1287. ((PreviewTextFragment) details).updateFile(renamedFile);
  1288. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1289. startTextPreview(renamedFile);
  1290. } else {
  1291. getFileOperationsHelper().openFile(renamedFile);
  1292. }
  1293. }
  1294. }
  1295. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())){
  1296. refreshListOfFilesFragment();
  1297. }
  1298. } else {
  1299. Toast msg = Toast.makeText(this,
  1300. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1301. Toast.LENGTH_LONG);
  1302. msg.show();
  1303. if (result.isSslRecoverableException()) {
  1304. mLastSslUntrustedServerResult = result;
  1305. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1306. }
  1307. }
  1308. }
  1309. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1310. RemoteOperationResult result) {
  1311. if (result.isSuccess()) {
  1312. if (operation.transferWasRequested()) {
  1313. OCFile syncedFile = operation.getLocalFile();
  1314. onTransferStateChanged(syncedFile, true, true);
  1315. invalidateOptionsMenu();
  1316. refreshShowDetails();
  1317. }
  1318. }
  1319. }
  1320. /**
  1321. * Updates the view associated to the activity after the finish of an operation trying create a
  1322. * new folder
  1323. *
  1324. * @param operation Creation operation performed.
  1325. * @param result Result of the creation.
  1326. */
  1327. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1328. RemoteOperationResult result) {
  1329. if (result.isSuccess()) {
  1330. refreshListOfFilesFragment();
  1331. } else {
  1332. try {
  1333. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1334. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1335. Toast.LENGTH_LONG);
  1336. msg.show();
  1337. } catch (NotFoundException e) {
  1338. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1339. }
  1340. }
  1341. }
  1342. /**
  1343. * {@inheritDoc}
  1344. */
  1345. @Override
  1346. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1347. refreshListOfFilesFragment();
  1348. FileFragment details = getSecondFragment();
  1349. if (details != null && details instanceof FileDetailFragment &&
  1350. file.equals(details.getFile()) ) {
  1351. if (downloading || uploading) {
  1352. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1353. } else {
  1354. if (!file.fileExists()) {
  1355. cleanSecondFragment();
  1356. } else {
  1357. ((FileDetailFragment) details).updateFileDetails(false, true);
  1358. }
  1359. }
  1360. }
  1361. }
  1362. private void requestForDownload() {
  1363. Account account = getAccount();
  1364. //if (!mWaitingToPreview.isDownloading()) {
  1365. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1366. Intent i = new Intent(this, FileDownloader.class);
  1367. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1368. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1369. startService(i);
  1370. }
  1371. }
  1372. private OCFile getCurrentDir() {
  1373. OCFile file = getFile();
  1374. if (file != null) {
  1375. if (file.isFolder()) {
  1376. return file;
  1377. } else if (getStorageManager() != null) {
  1378. String parentPath = file.getRemotePath().substring(0,
  1379. file.getRemotePath().lastIndexOf(file.getFileName()));
  1380. return getStorageManager().getFileByPath(parentPath);
  1381. }
  1382. }
  1383. return null;
  1384. }
  1385. /**
  1386. * Starts an operation to refresh the requested folder.
  1387. *
  1388. * The operation is run in a new background thread created on the fly.
  1389. *
  1390. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1391. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1392. * synchronized too.
  1393. *
  1394. * @param folder Folder to refresh.
  1395. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1396. * didn't change.
  1397. */
  1398. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag) {
  1399. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1400. // or if the method is called from a dialog that is being dismissed
  1401. getHandler().postDelayed(
  1402. new Runnable() {
  1403. @Override
  1404. public void run() {
  1405. if (hasWindowFocus()) {
  1406. long currentSyncTime = System.currentTimeMillis();
  1407. mSyncInProgress = true;
  1408. // perform folder synchronization
  1409. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1410. currentSyncTime,
  1411. false,
  1412. getFileOperationsHelper().isSharedSupported(),
  1413. ignoreETag,
  1414. getStorageManager(),
  1415. getAccount(),
  1416. getApplicationContext()
  1417. );
  1418. synchFolderOp.execute(
  1419. getAccount(),
  1420. MainApp.getAppContext(),
  1421. FileDisplayActivity.this,
  1422. null,
  1423. null
  1424. );
  1425. mProgressBar.setIndeterminate(true);
  1426. setBackgroundText();
  1427. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1428. // another window floating over
  1429. }
  1430. },
  1431. DELAY_TO_REQUEST_OPERATIONS_LATER
  1432. );
  1433. }
  1434. /**
  1435. * Show untrusted cert dialog
  1436. */
  1437. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1438. // Show a dialog with the certificate info
  1439. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
  1440. (CertificateCombinedException) result.getException());
  1441. FragmentManager fm = getSupportFragmentManager();
  1442. FragmentTransaction ft = fm.beginTransaction();
  1443. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1444. }
  1445. private void requestForDownload(OCFile file) {
  1446. Account account = getAccount();
  1447. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1448. Intent i = new Intent(this, FileDownloader.class);
  1449. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1450. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1451. startService(i);
  1452. }
  1453. }
  1454. private void sendDownloadedFile() {
  1455. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1456. mWaitingToSend = null;
  1457. }
  1458. /**
  1459. * Requests the download of the received {@link OCFile} , updates the UI
  1460. * to monitor the download progress and prepares the activity to send the file
  1461. * when the download finishes.
  1462. *
  1463. * @param file {@link OCFile} to download and preview.
  1464. */
  1465. public void startDownloadForSending(OCFile file) {
  1466. mWaitingToSend = file;
  1467. requestForDownload(mWaitingToSend);
  1468. boolean hasSecondFragment = (getSecondFragment() != null);
  1469. updateFragmentsVisibility(hasSecondFragment);
  1470. }
  1471. /**
  1472. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1473. *
  1474. * @param file Image {@link OCFile} to show.
  1475. */
  1476. public void startImagePreview(OCFile file) {
  1477. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1478. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1479. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1480. startActivity(showDetailsIntent);
  1481. }
  1482. /**
  1483. * Stars the preview of an already down media {@link OCFile}.
  1484. *
  1485. * @param file Media {@link OCFile} to preview.
  1486. * @param startPlaybackPosition Media position where the playback will be started,
  1487. * in milliseconds.
  1488. * @param autoplay When 'true', the playback will start without user
  1489. * interactions.
  1490. */
  1491. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1492. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition,
  1493. autoplay);
  1494. setSecondFragment(mediaFragment);
  1495. updateFragmentsVisibility(true);
  1496. updateActionBarTitleAndHomeButton(file);
  1497. setFile(file);
  1498. }
  1499. /**
  1500. * Stars the preview of a text file {@link OCFile}.
  1501. *
  1502. * @param file Text {@link OCFile} to preview.
  1503. */
  1504. public void startTextPreview(OCFile file) {
  1505. Bundle args = new Bundle();
  1506. args.putParcelable(EXTRA_FILE, file);
  1507. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1508. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1509. PreviewTextFragment.class.getName(), args);
  1510. setSecondFragment(textPreviewFragment);
  1511. updateFragmentsVisibility(true);
  1512. //updateNavigationElementsInActionBar(file);
  1513. setFile(file);
  1514. }
  1515. /**
  1516. * Requests the download of the received {@link OCFile} , updates the UI
  1517. * to monitor the download progress and prepares the activity to preview
  1518. * or open the file when the download finishes.
  1519. *
  1520. * @param file {@link OCFile} to download and preview.
  1521. */
  1522. public void startDownloadForPreview(OCFile file) {
  1523. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1524. setSecondFragment(detailFragment);
  1525. mWaitingToPreview = file;
  1526. requestForDownload();
  1527. updateFragmentsVisibility(true);
  1528. updateActionBarTitleAndHomeButton(file);
  1529. setFile(file);
  1530. }
  1531. public void cancelTransference(OCFile file) {
  1532. getFileOperationsHelper().cancelTransference(file);
  1533. if (mWaitingToPreview != null &&
  1534. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1535. mWaitingToPreview = null;
  1536. }
  1537. if (mWaitingToSend != null &&
  1538. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1539. mWaitingToSend = null;
  1540. }
  1541. onTransferStateChanged(file, false, false);
  1542. }
  1543. @Override
  1544. public void onRefresh(boolean ignoreETag) {
  1545. refreshList(ignoreETag);
  1546. }
  1547. @Override
  1548. public void onRefresh() {
  1549. refreshList(true);
  1550. }
  1551. private void refreshList(boolean ignoreETag) {
  1552. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1553. if (listOfFiles != null) {
  1554. OCFile folder = listOfFiles.getCurrentFile();
  1555. if (folder != null) {
  1556. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1557. listDirectory(mFile);*/
  1558. startSyncFolderOperation(folder, ignoreETag);
  1559. }
  1560. }
  1561. }
  1562. private void sortByDate(boolean ascending) {
  1563. getListOfFilesFragment().sortByDate(ascending);
  1564. }
  1565. private void sortBySize(boolean ascending) {
  1566. getListOfFilesFragment().sortBySize(ascending);
  1567. }
  1568. private void sortByName(boolean ascending) {
  1569. getListOfFilesFragment().sortByName(ascending);
  1570. }
  1571. private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
  1572. public void allFilesOption() {
  1573. browseToRoot();
  1574. }
  1575. }