FileDisplayActivity.java 75 KB

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