FileDisplayActivity.java 75 KB

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