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