FileDisplayActivity.java 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.ui.activity;
  19. import java.io.File;
  20. import android.accounts.Account;
  21. import android.app.AlertDialog;
  22. import android.app.Dialog;
  23. import android.app.ProgressDialog;
  24. import android.content.BroadcastReceiver;
  25. import android.content.ComponentName;
  26. import android.content.ContentResolver;
  27. import android.content.Context;
  28. import android.content.DialogInterface;
  29. import android.content.Intent;
  30. import android.content.IntentFilter;
  31. import android.content.ServiceConnection;
  32. import android.content.SharedPreferences;
  33. import android.content.res.Resources.NotFoundException;
  34. import android.database.Cursor;
  35. import android.net.Uri;
  36. import android.os.Bundle;
  37. import android.os.Handler;
  38. import android.os.IBinder;
  39. import android.preference.PreferenceManager;
  40. import android.provider.MediaStore;
  41. import android.support.v4.app.Fragment;
  42. import android.support.v4.app.FragmentManager;
  43. import android.support.v4.app.FragmentTransaction;
  44. import android.util.Log;
  45. import android.view.View;
  46. import android.view.ViewGroup;
  47. import android.widget.ArrayAdapter;
  48. import android.widget.TextView;
  49. import android.widget.Toast;
  50. import com.actionbarsherlock.app.ActionBar;
  51. import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
  52. import com.actionbarsherlock.view.Menu;
  53. import com.actionbarsherlock.view.MenuInflater;
  54. import com.actionbarsherlock.view.MenuItem;
  55. import com.actionbarsherlock.view.Window;
  56. import com.owncloud.android.Log_OC;
  57. import com.owncloud.android.R;
  58. import com.owncloud.android.authentication.AccountAuthenticator;
  59. import com.owncloud.android.datamodel.FileDataStorageManager;
  60. import com.owncloud.android.datamodel.OCFile;
  61. import com.owncloud.android.files.services.FileDownloader;
  62. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  63. import com.owncloud.android.files.services.FileObserverService;
  64. import com.owncloud.android.files.services.FileUploader;
  65. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  66. import com.owncloud.android.operations.CreateFolderOperation;
  67. import com.owncloud.android.operations.OnRemoteOperationListener;
  68. import com.owncloud.android.operations.RemoteOperation;
  69. import com.owncloud.android.operations.RemoteOperationResult;
  70. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  71. import com.owncloud.android.operations.RemoveFileOperation;
  72. import com.owncloud.android.operations.RenameFileOperation;
  73. import com.owncloud.android.operations.SynchronizeFileOperation;
  74. import com.owncloud.android.operations.SynchronizeFolderOperation;
  75. import com.owncloud.android.syncadapter.FileSyncService;
  76. import com.owncloud.android.ui.dialog.EditNameDialog;
  77. import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
  78. import com.owncloud.android.ui.dialog.LoadingDialog;
  79. import com.owncloud.android.ui.dialog.SslValidatorDialog;
  80. import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
  81. import com.owncloud.android.ui.fragment.FileDetailFragment;
  82. import com.owncloud.android.ui.fragment.FileFragment;
  83. import com.owncloud.android.ui.fragment.OCFileListFragment;
  84. import com.owncloud.android.ui.preview.PreviewImageActivity;
  85. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  86. import com.owncloud.android.ui.preview.PreviewVideoActivity;
  87. /**
  88. * Displays, what files the user has available in his ownCloud.
  89. *
  90. * @author Bartek Przybylski
  91. * @author David A. Velasco
  92. */
  93. public class FileDisplayActivity extends FileActivity implements
  94. OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
  95. private ArrayAdapter<String> mDirectories;
  96. /** Access point to the cached database for the current ownCloud {@link Account} */
  97. private FileDataStorageManager mStorageManager = null;
  98. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  99. private UploadFinishReceiver mUploadFinishReceiver;
  100. private DownloadFinishReceiver mDownloadFinishReceiver;
  101. private FileDownloaderBinder mDownloaderBinder = null;
  102. private FileUploaderBinder mUploaderBinder = null;
  103. private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
  104. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  105. private boolean mDualPane;
  106. private View mLeftFragmentContainer;
  107. private View mRightFragmentContainer;
  108. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  109. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  110. public static final int DIALOG_SHORT_WAIT = 0;
  111. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
  112. private static final int DIALOG_SSL_VALIDATOR = 2;
  113. private static final int DIALOG_CERT_NOT_SAVED = 3;
  114. private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
  115. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  116. private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  117. private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  118. private static final String TAG = FileDisplayActivity.class.getSimpleName();
  119. private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
  120. private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  121. private OCFile mWaitingToPreview;
  122. private Handler mHandler;
  123. private boolean mSyncInProgress = false;
  124. @Override
  125. protected void onCreate(Bundle savedInstanceState) {
  126. Log_OC.d(TAG, "onCreate() start");
  127. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  128. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
  129. mHandler = new Handler();
  130. /// bindings to transference services
  131. mUploadConnection = new ListServiceConnection();
  132. mDownloadConnection = new ListServiceConnection();
  133. bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
  134. bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
  135. // PIN CODE request ; best location is to decide, let's try this first
  136. if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
  137. requestPinCode();
  138. }
  139. /// file observer
  140. Intent observer_intent = new Intent(this, FileObserverService.class);
  141. observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
  142. startService(observer_intent);
  143. /// Load of saved instance state
  144. if(savedInstanceState != null) {
  145. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  146. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  147. } else {
  148. mWaitingToPreview = null;
  149. mSyncInProgress = false;
  150. }
  151. /// USER INTERFACE
  152. // Inflate and set the layout view
  153. setContentView(R.layout.files);
  154. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  155. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  156. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  157. if (savedInstanceState == null) {
  158. createMinFragments();
  159. }
  160. // Action bar setup
  161. mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
  162. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
  163. setSupportProgressBarIndeterminateVisibility(mSyncInProgress); // always AFTER setContentView(...) ; to work around bug in its implementation
  164. Log_OC.d(TAG, "onCreate() end");
  165. }
  166. @Override
  167. protected void onDestroy() {
  168. super.onDestroy();
  169. if (mDownloadConnection != null)
  170. unbindService(mDownloadConnection);
  171. if (mUploadConnection != null)
  172. unbindService(mUploadConnection);
  173. }
  174. /**
  175. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  176. */
  177. @Override
  178. protected void onAccountSet(boolean stateWasRecovered) {
  179. if (getAccount() != null) {
  180. mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
  181. /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
  182. OCFile file = getFile();
  183. if (file != null) {
  184. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  185. // upload in progress - right now, files are not inserted in the local cache until the upload is successful
  186. if (mStorageManager.getFileById(file.getParentId()) == null) {
  187. file = null; // not able to know the directory where the file is uploading
  188. }
  189. } else {
  190. file = mStorageManager.getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
  191. }
  192. }
  193. if (file == null) {
  194. // fall back to root folder
  195. file = mStorageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null
  196. }
  197. setFile(file);
  198. setNavigationListWithFolder(file);
  199. if (!stateWasRecovered) {
  200. Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
  201. initFragmentsWithFile();
  202. } else {
  203. updateFragmentsVisibility(!file.isFolder());
  204. updateNavigationElementsInActionBar(file.isFolder() ? null : file);
  205. }
  206. } else {
  207. Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
  208. }
  209. }
  210. private void setNavigationListWithFolder(OCFile file) {
  211. mDirectories.clear();
  212. OCFile fileIt = file;
  213. while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
  214. if (fileIt.isFolder()) {
  215. mDirectories.add(fileIt.getFileName());
  216. }
  217. fileIt = mStorageManager.getFileById(fileIt.getParentId());
  218. }
  219. mDirectories.add(OCFile.PATH_SEPARATOR);
  220. }
  221. private void createMinFragments() {
  222. OCFileListFragment listOfFiles = new OCFileListFragment();
  223. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  224. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  225. transaction.commit();
  226. }
  227. private void initFragmentsWithFile() {
  228. if (getAccount() != null && getFile() != null) {
  229. /// First fragment
  230. OCFileListFragment listOfFiles = getListOfFilesFragment();
  231. if (listOfFiles != null) {
  232. listOfFiles.listDirectory(getCurrentDir());
  233. } else {
  234. Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  235. }
  236. /// Second fragment
  237. OCFile file = getFile();
  238. Fragment secondFragment = chooseInitialSecondFragment(file);
  239. if (secondFragment != null) {
  240. setSecondFragment(secondFragment);
  241. updateFragmentsVisibility(true);
  242. updateNavigationElementsInActionBar(file);
  243. } else {
  244. cleanSecondFragment();
  245. }
  246. } else {
  247. Log.wtf(TAG, "initFragments() called with invalid NULLs!");
  248. if (getAccount() == null) {
  249. Log.wtf(TAG, "\t account is NULL");
  250. }
  251. if (getFile() == null) {
  252. Log.wtf(TAG, "\t file is NULL");
  253. }
  254. }
  255. }
  256. private Fragment chooseInitialSecondFragment(OCFile file) {
  257. Fragment secondFragment = null;
  258. if (file != null && !file.isFolder()) {
  259. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  260. && file.getLastSyncDateForProperties() > 0 // temporal fix
  261. ) {
  262. int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  263. boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  264. secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  265. } else {
  266. secondFragment = new FileDetailFragment(file, getAccount());
  267. }
  268. }
  269. return secondFragment;
  270. }
  271. /**
  272. * Replaces the second fragment managed by the activity with the received as
  273. * a parameter.
  274. *
  275. * Assumes never will be more than two fragments managed at the same time.
  276. *
  277. * @param fragment New second Fragment to set.
  278. */
  279. private void setSecondFragment(Fragment fragment) {
  280. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  281. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  282. transaction.commit();
  283. }
  284. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  285. if (mDualPane) {
  286. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  287. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  288. }
  289. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  290. mRightFragmentContainer.setVisibility(View.VISIBLE);
  291. }
  292. } else if (existsSecondFragment) {
  293. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  294. mLeftFragmentContainer.setVisibility(View.GONE);
  295. }
  296. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  297. mRightFragmentContainer.setVisibility(View.VISIBLE);
  298. }
  299. } else {
  300. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  301. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  302. }
  303. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  304. mRightFragmentContainer.setVisibility(View.GONE);
  305. }
  306. }
  307. }
  308. private OCFileListFragment getListOfFilesFragment() {
  309. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
  310. if (listOfFiles != null) {
  311. return (OCFileListFragment)listOfFiles;
  312. }
  313. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  314. return null;
  315. }
  316. protected FileFragment getSecondFragment() {
  317. Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
  318. if (second != null) {
  319. return (FileFragment)second;
  320. }
  321. return null;
  322. }
  323. public void cleanSecondFragment() {
  324. Fragment second = getSecondFragment();
  325. if (second != null) {
  326. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  327. tr.remove(second);
  328. tr.commit();
  329. }
  330. updateFragmentsVisibility(false);
  331. updateNavigationElementsInActionBar(null);
  332. }
  333. protected void refeshListOfFilesFragment() {
  334. OCFileListFragment fileListFragment = getListOfFilesFragment();
  335. if (fileListFragment != null) {
  336. fileListFragment.listDirectory();
  337. }
  338. }
  339. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
  340. FileFragment secondFragment = getSecondFragment();
  341. boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  342. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  343. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  344. OCFile fileInFragment = detailsFragment.getFile();
  345. if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  346. // the user browsed to other file ; forget the automatic preview
  347. mWaitingToPreview = null;
  348. } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
  349. // grant that the right panel updates the progress bar
  350. detailsFragment.listenForTransferProgress();
  351. detailsFragment.updateFileDetails(true, false);
  352. } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
  353. // update the right panel
  354. boolean detailsFragmentChanged = false;
  355. if (waitedPreview) {
  356. if (success) {
  357. mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
  358. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  359. startMediaPreview(mWaitingToPreview, 0, true);
  360. detailsFragmentChanged = true;
  361. } else {
  362. openFile(mWaitingToPreview);
  363. }
  364. }
  365. mWaitingToPreview = null;
  366. }
  367. if (!detailsFragmentChanged) {
  368. detailsFragment.updateFileDetails(false, (success));
  369. }
  370. }
  371. }
  372. }
  373. @Override
  374. public boolean onCreateOptionsMenu(Menu menu) {
  375. MenuInflater inflater = getSherlock().getMenuInflater();
  376. inflater.inflate(R.menu.main_menu, menu);
  377. return true;
  378. }
  379. @Override
  380. public boolean onOptionsItemSelected(MenuItem item) {
  381. boolean retval = true;
  382. switch (item.getItemId()) {
  383. case R.id.action_create_dir: {
  384. EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
  385. dialog.show(getSupportFragmentManager(), "createdirdialog");
  386. break;
  387. }
  388. case R.id.action_sync_account: {
  389. startSynchronization();
  390. break;
  391. }
  392. case R.id.action_upload: {
  393. showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
  394. break;
  395. }
  396. case R.id.action_settings: {
  397. Intent settingsIntent = new Intent(this, Preferences.class);
  398. startActivity(settingsIntent);
  399. break;
  400. }
  401. case android.R.id.home: {
  402. FileFragment second = getSecondFragment();
  403. OCFile currentDir = getCurrentDir();
  404. if((currentDir != null && currentDir.getParentId() != 0) ||
  405. (second != null && second.getFile() != null)) {
  406. onBackPressed();
  407. }
  408. break;
  409. }
  410. default:
  411. retval = super.onOptionsItemSelected(item);
  412. }
  413. return retval;
  414. }
  415. private void startSynchronization() {
  416. ContentResolver.cancelSync(null, AccountAuthenticator.AUTHORITY); // cancel the current synchronizations of any ownCloud account
  417. Bundle bundle = new Bundle();
  418. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  419. ContentResolver.requestSync(
  420. getAccount(),
  421. AccountAuthenticator.AUTHORITY, bundle);
  422. }
  423. @Override
  424. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  425. if (itemPosition != 0) {
  426. String targetPath = "";
  427. for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
  428. targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
  429. }
  430. targetPath = OCFile.PATH_SEPARATOR + targetPath;
  431. OCFile targetFolder = mStorageManager.getFileByPath(targetPath);
  432. if (targetFolder != null) {
  433. browseTo(targetFolder);
  434. }
  435. // the next operation triggers a new call to this method, but it's necessary to
  436. // ensure that the name exposed in the action bar is the current directory when the
  437. // user selected it in the navigation list
  438. getSupportActionBar().setSelectedNavigationItem(0);
  439. }
  440. return true;
  441. }
  442. /**
  443. * Called, when the user selected something for uploading
  444. */
  445. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  446. super.onActivityResult(requestCode, resultCode, data);
  447. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  448. requestSimpleUpload(data, resultCode);
  449. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  450. requestMultipleUpload(data, resultCode);
  451. }
  452. }
  453. private void requestMultipleUpload(Intent data, int resultCode) {
  454. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  455. if (filePaths != null) {
  456. String[] remotePaths = new String[filePaths.length];
  457. String remotePathBase = "";
  458. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  459. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  460. }
  461. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  462. remotePathBase += OCFile.PATH_SEPARATOR;
  463. for (int j = 0; j< remotePaths.length; j++) {
  464. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  465. }
  466. Intent i = new Intent(this, FileUploader.class);
  467. i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  468. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  469. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  470. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  471. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  472. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  473. startService(i);
  474. } else {
  475. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  476. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  477. t.show();
  478. return;
  479. }
  480. }
  481. private void requestSimpleUpload(Intent data, int resultCode) {
  482. String filepath = null;
  483. try {
  484. Uri selectedImageUri = data.getData();
  485. String filemanagerstring = selectedImageUri.getPath();
  486. String selectedImagePath = getPath(selectedImageUri);
  487. if (selectedImagePath != null)
  488. filepath = selectedImagePath;
  489. else
  490. filepath = filemanagerstring;
  491. } catch (Exception e) {
  492. Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  493. e.printStackTrace();
  494. } finally {
  495. if (filepath == null) {
  496. Log_OC.e(TAG, "Couldnt resolve path to file");
  497. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  498. t.show();
  499. return;
  500. }
  501. }
  502. Intent i = new Intent(this, FileUploader.class);
  503. i.putExtra(FileUploader.KEY_ACCOUNT,
  504. getAccount());
  505. String remotepath = new String();
  506. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  507. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  508. }
  509. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  510. remotepath += OCFile.PATH_SEPARATOR;
  511. remotepath += new File(filepath).getName();
  512. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  513. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  514. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  515. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  516. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  517. startService(i);
  518. }
  519. @Override
  520. public void onBackPressed() {
  521. OCFileListFragment listOfFiles = getListOfFilesFragment();
  522. if (mDualPane || getSecondFragment() == null) {
  523. if (listOfFiles != null) { // should never be null, indeed
  524. if (mDirectories.getCount() <= 1) {
  525. finish();
  526. return;
  527. }
  528. int levelsUp = listOfFiles.onBrowseUp();
  529. for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
  530. popDirname();
  531. }
  532. }
  533. }
  534. if (listOfFiles != null) { // should never be null, indeed
  535. setFile(listOfFiles.getCurrentFile());
  536. }
  537. cleanSecondFragment();
  538. }
  539. @Override
  540. protected void onSaveInstanceState(Bundle outState) {
  541. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  542. Log_OC.e(TAG, "onSaveInstanceState() start");
  543. super.onSaveInstanceState(outState);
  544. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  545. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  546. Log_OC.d(TAG, "onSaveInstanceState() end");
  547. }
  548. @Override
  549. protected void onResume() {
  550. super.onResume();
  551. Log_OC.e(TAG, "onResume() start");
  552. // Listen for sync messages
  553. IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
  554. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  555. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  556. // Listen for upload messages
  557. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
  558. mUploadFinishReceiver = new UploadFinishReceiver();
  559. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  560. // Listen for download messages
  561. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
  562. downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
  563. mDownloadFinishReceiver = new DownloadFinishReceiver();
  564. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  565. Log_OC.d(TAG, "onResume() end");
  566. }
  567. @Override
  568. protected void onPause() {
  569. super.onPause();
  570. Log_OC.e(TAG, "onPause() start");
  571. if (mSyncBroadcastReceiver != null) {
  572. unregisterReceiver(mSyncBroadcastReceiver);
  573. mSyncBroadcastReceiver = null;
  574. }
  575. if (mUploadFinishReceiver != null) {
  576. unregisterReceiver(mUploadFinishReceiver);
  577. mUploadFinishReceiver = null;
  578. }
  579. if (mDownloadFinishReceiver != null) {
  580. unregisterReceiver(mDownloadFinishReceiver);
  581. mDownloadFinishReceiver = null;
  582. }
  583. Log_OC.d(TAG, "onPause() end");
  584. }
  585. @Override
  586. protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
  587. if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
  588. ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
  589. }
  590. }
  591. @Override
  592. protected Dialog onCreateDialog(int id) {
  593. Dialog dialog = null;
  594. AlertDialog.Builder builder;
  595. switch (id) {
  596. case DIALOG_SHORT_WAIT: {
  597. ProgressDialog working_dialog = new ProgressDialog(this);
  598. working_dialog.setMessage(getResources().getString(
  599. R.string.wait_a_moment));
  600. working_dialog.setIndeterminate(true);
  601. working_dialog.setCancelable(false);
  602. dialog = working_dialog;
  603. break;
  604. }
  605. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  606. String[] items = null;
  607. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  608. getString(R.string.actionbar_upload_from_apps),
  609. getString(R.string.actionbar_failed_instant_upload) };
  610. String[] commonItems = { getString(R.string.actionbar_upload_files),
  611. getString(R.string.actionbar_upload_from_apps) };
  612. if (InstantUploadActivity.IS_ENABLED)
  613. items = allTheItems;
  614. else
  615. items = commonItems;
  616. builder = new AlertDialog.Builder(this);
  617. builder.setTitle(R.string.actionbar_upload);
  618. builder.setItems(items, new DialogInterface.OnClickListener() {
  619. public void onClick(DialogInterface dialog, int item) {
  620. if (item == 0) {
  621. // if (!mDualPane) {
  622. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  623. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
  624. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  625. // } else {
  626. // TODO create and handle new fragment
  627. // LocalFileListFragment
  628. // }
  629. } else if (item == 1) {
  630. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  631. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  632. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  633. ACTION_SELECT_CONTENT_FROM_APPS);
  634. } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
  635. Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
  636. action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
  637. startActivity(action);
  638. }
  639. }
  640. });
  641. dialog = builder.create();
  642. break;
  643. }
  644. case DIALOG_SSL_VALIDATOR: {
  645. dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
  646. break;
  647. }
  648. case DIALOG_CERT_NOT_SAVED: {
  649. builder = new AlertDialog.Builder(this);
  650. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  651. builder.setCancelable(false);
  652. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  653. @Override
  654. public void onClick(DialogInterface dialog, int which) {
  655. dialog.dismiss();
  656. };
  657. });
  658. dialog = builder.create();
  659. break;
  660. }
  661. default:
  662. dialog = null;
  663. }
  664. return dialog;
  665. }
  666. /**
  667. * Show loading dialog
  668. */
  669. public void showLoadingDialog() {
  670. // Construct dialog
  671. LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
  672. FragmentManager fm = getSupportFragmentManager();
  673. FragmentTransaction ft = fm.beginTransaction();
  674. loading.show(ft, DIALOG_WAIT_TAG);
  675. }
  676. /**
  677. * Dismiss loading dialog
  678. */
  679. public void dismissLoadingDialog(){
  680. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
  681. if (frag != null) {
  682. LoadingDialog loading = (LoadingDialog) frag;
  683. loading.dismiss();
  684. }
  685. }
  686. /**
  687. * Translates a content URI of an image to a physical path
  688. * on the disk
  689. * @param uri The URI to resolve
  690. * @return The path to the image or null if it could not be found
  691. */
  692. public String getPath(Uri uri) {
  693. String[] projection = { MediaStore.Images.Media.DATA };
  694. Cursor cursor = managedQuery(uri, projection, null, null, null);
  695. if (cursor != null) {
  696. int column_index = cursor
  697. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  698. cursor.moveToFirst();
  699. return cursor.getString(column_index);
  700. }
  701. return null;
  702. }
  703. /**
  704. * Pushes a directory to the drop down list
  705. * @param directory to push
  706. * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
  707. */
  708. public void pushDirname(OCFile directory) {
  709. if(!directory.isFolder()){
  710. throw new IllegalArgumentException("Only directories may be pushed!");
  711. }
  712. mDirectories.insert(directory.getFileName(), 0);
  713. setFile(directory);
  714. }
  715. /**
  716. * Pops a directory name from the drop down list
  717. * @return True, unless the stack is empty
  718. */
  719. public boolean popDirname() {
  720. mDirectories.remove(mDirectories.getItem(0));
  721. return !mDirectories.isEmpty();
  722. }
  723. // Custom array adapter to override text colors
  724. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  725. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  726. super(ctx, view);
  727. }
  728. public View getView(int position, View convertView, ViewGroup parent) {
  729. View v = super.getView(position, convertView, parent);
  730. ((TextView) v).setTextColor(getResources().getColorStateList(
  731. android.R.color.white));
  732. return v;
  733. }
  734. public View getDropDownView(int position, View convertView,
  735. ViewGroup parent) {
  736. View v = super.getDropDownView(position, convertView, parent);
  737. ((TextView) v).setTextColor(getResources().getColorStateList(
  738. android.R.color.white));
  739. return v;
  740. }
  741. }
  742. private class SyncBroadcastReceiver extends BroadcastReceiver {
  743. /**
  744. * {@link BroadcastReceiver} to enable syncing feedback in UI
  745. */
  746. @Override
  747. public void onReceive(Context context, Intent intent) {
  748. boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);
  749. String accountName = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);
  750. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
  751. Log_OC.d(TAG, "sync of account " + accountName + " is in_progress: " + inProgress);
  752. if (getAccount() != null && accountName.equals(getAccount().name)) {
  753. String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
  754. OCFile currentFile = (getFile() == null) ? null : mStorageManager.getFileByPath(getFile().getRemotePath());
  755. OCFile currentDir = (getCurrentDir() == null) ? null : mStorageManager.getFileByPath(getCurrentDir().getRemotePath());
  756. if (currentDir == null) {
  757. // current folder was removed from the server
  758. Toast.makeText( FileDisplayActivity.this,
  759. String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
  760. Toast.LENGTH_LONG)
  761. .show();
  762. browseToRoot();
  763. } else {
  764. if (currentFile == null && !getFile().isFolder()) {
  765. // currently selected file was removed in the server, and now we know it
  766. cleanSecondFragment();
  767. currentFile = currentDir;
  768. }
  769. if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  770. OCFileListFragment fileListFragment = getListOfFilesFragment();
  771. if (fileListFragment != null) {
  772. fileListFragment.listDirectory(currentDir);
  773. }
  774. }
  775. setFile(currentFile);
  776. }
  777. setSupportProgressBarIndeterminateVisibility(inProgress);
  778. removeStickyBroadcast(intent);
  779. mSyncInProgress = inProgress;
  780. }
  781. if (synchResult != null) {
  782. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  783. mLastSslUntrustedServerResult = synchResult;
  784. showDialog(DIALOG_SSL_VALIDATOR);
  785. }
  786. }
  787. }
  788. }
  789. private class UploadFinishReceiver extends BroadcastReceiver {
  790. /**
  791. * Once the file upload has finished -> update view
  792. * @author David A. Velasco
  793. * {@link BroadcastReceiver} to enable upload feedback in UI
  794. */
  795. @Override
  796. public void onReceive(Context context, Intent intent) {
  797. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  798. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  799. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  800. OCFile currentDir = getCurrentDir();
  801. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  802. if (sameAccount && isDescendant) {
  803. refeshListOfFilesFragment();
  804. }
  805. }
  806. }
  807. /**
  808. * Class waiting for broadcast events from the {@link FielDownloader} service.
  809. *
  810. * Updates the UI when a download is started or finished, provided that it is relevant for the
  811. * current folder.
  812. */
  813. private class DownloadFinishReceiver extends BroadcastReceiver {
  814. @Override
  815. public void onReceive(Context context, Intent intent) {
  816. boolean sameAccount = isSameAccount(context, intent);
  817. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  818. boolean isDescendant = isDescendant(downloadedRemotePath);
  819. if (sameAccount && isDescendant) {
  820. refeshListOfFilesFragment();
  821. refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  822. }
  823. removeStickyBroadcast(intent);
  824. }
  825. private boolean isDescendant(String downloadedRemotePath) {
  826. OCFile currentDir = getCurrentDir();
  827. return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
  828. }
  829. private boolean isSameAccount(Context context, Intent intent) {
  830. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  831. return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
  832. }
  833. }
  834. /**
  835. * {@inheritDoc}
  836. */
  837. @Override
  838. public FileDataStorageManager getStorageManager() {
  839. return mStorageManager;
  840. }
  841. public void browseToRoot() {
  842. OCFileListFragment listOfFiles = getListOfFilesFragment();
  843. if (listOfFiles != null) { // should never be null, indeed
  844. while (mDirectories.getCount() > 1) {
  845. popDirname();
  846. }
  847. OCFile root = mStorageManager.getFileByPath(OCFile.ROOT_PATH);
  848. listOfFiles.listDirectory(root);
  849. setFile(listOfFiles.getCurrentFile());
  850. startSyncFolderOperation(root);
  851. }
  852. cleanSecondFragment();
  853. }
  854. public void browseTo(OCFile folder) {
  855. if (folder == null || !folder.isFolder()) {
  856. throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
  857. }
  858. OCFileListFragment listOfFiles = getListOfFilesFragment();
  859. if (listOfFiles != null) {
  860. setNavigationListWithFolder(folder);
  861. listOfFiles.listDirectory(folder);
  862. setFile(listOfFiles.getCurrentFile());
  863. startSyncFolderOperation(folder);
  864. } else {
  865. Log_OC.e(TAG, "Unexpected null when accessing list fragment");
  866. }
  867. cleanSecondFragment();
  868. }
  869. /**
  870. * {@inheritDoc}
  871. *
  872. * Updates action bar and second fragment, if in dual pane mode.
  873. */
  874. @Override
  875. public void onBrowsedDownTo(OCFile directory) {
  876. pushDirname(directory);
  877. cleanSecondFragment();
  878. // Sync Folder
  879. startSyncFolderOperation(directory);
  880. }
  881. /**
  882. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  883. *
  884. * @param file Image {@link OCFile} to show.
  885. */
  886. @Override
  887. public void startImagePreview(OCFile file) {
  888. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  889. showDetailsIntent.putExtra(EXTRA_FILE, file);
  890. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  891. startActivity(showDetailsIntent);
  892. }
  893. /**
  894. * Stars the preview of an already down media {@link OCFile}.
  895. *
  896. * @param file Media {@link OCFile} to preview.
  897. * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
  898. * @param autoplay When 'true', the playback will start without user interactions.
  899. */
  900. @Override
  901. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  902. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
  903. setSecondFragment(mediaFragment);
  904. updateFragmentsVisibility(true);
  905. updateNavigationElementsInActionBar(file);
  906. setFile(file);
  907. }
  908. /**
  909. * Requests the download of the received {@link OCFile} , updates the UI
  910. * to monitor the download progress and prepares the activity to preview
  911. * or open the file when the download finishes.
  912. *
  913. * @param file {@link OCFile} to download and preview.
  914. */
  915. @Override
  916. public void startDownloadForPreview(OCFile file) {
  917. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  918. setSecondFragment(detailFragment);
  919. mWaitingToPreview = file;
  920. requestForDownload();
  921. updateFragmentsVisibility(true);
  922. updateNavigationElementsInActionBar(file);
  923. setFile(file);
  924. }
  925. /**
  926. * Shows the information of the {@link OCFile} received as a
  927. * parameter in the second fragment.
  928. *
  929. * @param file {@link OCFile} whose details will be shown
  930. */
  931. @Override
  932. public void showDetails(OCFile file) {
  933. Fragment detailFragment = new FileDetailFragment(file, getAccount());
  934. setSecondFragment(detailFragment);
  935. updateFragmentsVisibility(true);
  936. updateNavigationElementsInActionBar(file);
  937. setFile(file);
  938. }
  939. /**
  940. * TODO
  941. */
  942. private void updateNavigationElementsInActionBar(OCFile chosenFile) {
  943. ActionBar actionBar = getSupportActionBar();
  944. if (chosenFile == null || mDualPane) {
  945. // only list of files - set for browsing through folders
  946. OCFile currentDir = getCurrentDir();
  947. actionBar.setDisplayHomeAsUpEnabled(currentDir != null && currentDir.getParentId() != 0);
  948. actionBar.setDisplayShowTitleEnabled(false);
  949. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
  950. actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
  951. } else {
  952. actionBar.setDisplayHomeAsUpEnabled(true);
  953. actionBar.setDisplayShowTitleEnabled(true);
  954. actionBar.setTitle(chosenFile.getFileName());
  955. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  956. }
  957. }
  958. // private void updateDisplayHomeAtSync(){
  959. // ActionBar actionBar = getSupportActionBar();
  960. // OCFile currentDir = getCurrentDir();
  961. // if (currentDir.getParentId() != DataStorageManager.ROOT_PARENT_ID) {
  962. // actionBar.setHomeButtonEnabled(!mSyncInProgress);
  963. // actionBar.setDisplayHomeAsUpEnabled(!mSyncInProgress);
  964. // }
  965. // else {
  966. // actionBar.setHomeButtonEnabled(true);
  967. // actionBar.setDisplayHomeAsUpEnabled(false);
  968. // }
  969. // }
  970. //
  971. /**
  972. * {@inheritDoc}
  973. */
  974. @Override
  975. public void onFileStateChanged() {
  976. refeshListOfFilesFragment();
  977. updateNavigationElementsInActionBar(getSecondFragment().getFile());
  978. }
  979. /**
  980. * {@inheritDoc}
  981. */
  982. @Override
  983. public FileDownloaderBinder getFileDownloaderBinder() {
  984. return mDownloaderBinder;
  985. }
  986. /**
  987. * {@inheritDoc}
  988. */
  989. @Override
  990. public FileUploaderBinder getFileUploaderBinder() {
  991. return mUploaderBinder;
  992. }
  993. /** Defines callbacks for service binding, passed to bindService() */
  994. private class ListServiceConnection implements ServiceConnection {
  995. @Override
  996. public void onServiceConnected(ComponentName component, IBinder service) {
  997. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  998. Log_OC.d(TAG, "Download service connected");
  999. mDownloaderBinder = (FileDownloaderBinder) service;
  1000. if (mWaitingToPreview != null) {
  1001. requestForDownload();
  1002. }
  1003. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1004. Log_OC.d(TAG, "Upload service connected");
  1005. mUploaderBinder = (FileUploaderBinder) service;
  1006. } else {
  1007. return;
  1008. }
  1009. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1010. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1011. if (listOfFiles != null) {
  1012. listOfFiles.listDirectory();
  1013. }
  1014. FileFragment secondFragment = getSecondFragment();
  1015. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1016. FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
  1017. detailFragment.listenForTransferProgress();
  1018. detailFragment.updateFileDetails(false, false);
  1019. }
  1020. }
  1021. @Override
  1022. public void onServiceDisconnected(ComponentName component) {
  1023. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1024. Log_OC.d(TAG, "Download service disconnected");
  1025. mDownloaderBinder = null;
  1026. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1027. Log_OC.d(TAG, "Upload service disconnected");
  1028. mUploaderBinder = null;
  1029. }
  1030. }
  1031. };
  1032. /**
  1033. * Launch an intent to request the PIN code to the user before letting him use the app
  1034. */
  1035. private void requestPinCode() {
  1036. boolean pinStart = false;
  1037. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1038. pinStart = appPrefs.getBoolean("set_pincode", false);
  1039. if (pinStart) {
  1040. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1041. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1042. startActivity(i);
  1043. }
  1044. }
  1045. @Override
  1046. public void onSavedCertificate() {
  1047. startSynchronization();
  1048. }
  1049. @Override
  1050. public void onFailedSavingCertificate() {
  1051. showDialog(DIALOG_CERT_NOT_SAVED);
  1052. }
  1053. /**
  1054. * Updates the view associated to the activity after the finish of some operation over files
  1055. * in the current account.
  1056. *
  1057. * @param operation Removal operation performed.
  1058. * @param result Result of the removal.
  1059. */
  1060. @Override
  1061. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1062. if (operation instanceof RemoveFileOperation) {
  1063. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1064. } else if (operation instanceof RenameFileOperation) {
  1065. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1066. } else if (operation instanceof SynchronizeFileOperation) {
  1067. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1068. } else if (operation instanceof CreateFolderOperation) {
  1069. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  1070. }
  1071. }
  1072. /**
  1073. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1074. * file.
  1075. *
  1076. * @param operation Removal operation performed.
  1077. * @param result Result of the removal.
  1078. */
  1079. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1080. dismissLoadingDialog();
  1081. if (result.isSuccess()) {
  1082. Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
  1083. msg.show();
  1084. OCFile removedFile = operation.getFile();
  1085. getSecondFragment();
  1086. FileFragment second = getSecondFragment();
  1087. if (second != null && removedFile.equals(second.getFile())) {
  1088. cleanSecondFragment();
  1089. }
  1090. if (mStorageManager.getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1091. refeshListOfFilesFragment();
  1092. }
  1093. } else {
  1094. Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
  1095. msg.show();
  1096. if (result.isSslRecoverableException()) {
  1097. mLastSslUntrustedServerResult = result;
  1098. showDialog(DIALOG_SSL_VALIDATOR);
  1099. }
  1100. }
  1101. }
  1102. /**
  1103. * Updates the view associated to the activity after the finish of an operation trying create a new folder
  1104. *
  1105. * @param operation Creation operation performed.
  1106. * @param result Result of the creation.
  1107. */
  1108. private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
  1109. if (result.isSuccess()) {
  1110. dismissLoadingDialog();
  1111. refeshListOfFilesFragment();
  1112. } else {
  1113. dismissLoadingDialog();
  1114. try {
  1115. Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
  1116. msg.show();
  1117. } catch (NotFoundException e) {
  1118. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  1119. }
  1120. }
  1121. }
  1122. /**
  1123. * Updates the view associated to the activity after the finish of an operation trying to rename a
  1124. * file.
  1125. *
  1126. * @param operation Renaming operation performed.
  1127. * @param result Result of the renaming.
  1128. */
  1129. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  1130. dismissLoadingDialog();
  1131. OCFile renamedFile = operation.getFile();
  1132. if (result.isSuccess()) {
  1133. if (mDualPane) {
  1134. FileFragment details = getSecondFragment();
  1135. if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1136. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1137. }
  1138. }
  1139. if (mStorageManager.getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1140. refeshListOfFilesFragment();
  1141. }
  1142. } else {
  1143. if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
  1144. Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
  1145. msg.show();
  1146. // TODO throw again the new rename dialog
  1147. } else {
  1148. Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
  1149. msg.show();
  1150. if (result.isSslRecoverableException()) {
  1151. mLastSslUntrustedServerResult = result;
  1152. showDialog(DIALOG_SSL_VALIDATOR);
  1153. }
  1154. }
  1155. }
  1156. }
  1157. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1158. dismissLoadingDialog();
  1159. OCFile syncedFile = operation.getLocalFile();
  1160. if (!result.isSuccess()) {
  1161. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1162. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1163. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1164. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
  1165. startActivity(i);
  1166. }
  1167. } else {
  1168. if (operation.transferWasRequested()) {
  1169. refeshListOfFilesFragment();
  1170. onTransferStateChanged(syncedFile, true, true);
  1171. } else {
  1172. Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
  1173. msg.show();
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * {@inheritDoc}
  1179. */
  1180. @Override
  1181. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1182. if (mDualPane) {
  1183. FileFragment details = getSecondFragment();
  1184. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1185. if (downloading || uploading) {
  1186. ((FileDetailFragment)details).updateFileDetails(file, getAccount());
  1187. } else {
  1188. ((FileDetailFragment)details).updateFileDetails(false, true);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. public void onDismiss(EditNameDialog dialog) {
  1194. if (dialog.getResult()) {
  1195. String newDirectoryName = dialog.getNewFilename().trim();
  1196. Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
  1197. if (newDirectoryName.length() > 0) {
  1198. String path = getCurrentDir().getRemotePath();
  1199. // Create directory
  1200. path += newDirectoryName + OCFile.PATH_SEPARATOR;
  1201. RemoteOperation operation = new CreateFolderOperation(path, false, mStorageManager);
  1202. operation.execute( getAccount(),
  1203. FileDisplayActivity.this,
  1204. FileDisplayActivity.this,
  1205. mHandler,
  1206. FileDisplayActivity.this);
  1207. showLoadingDialog();
  1208. }
  1209. }
  1210. }
  1211. private void requestForDownload() {
  1212. Account account = getAccount();
  1213. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1214. Intent i = new Intent(this, FileDownloader.class);
  1215. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1216. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1217. startService(i);
  1218. }
  1219. }
  1220. private OCFile getCurrentDir() {
  1221. OCFile file = getFile();
  1222. if (file != null) {
  1223. if (file.isFolder()) {
  1224. return file;
  1225. } else if (mStorageManager != null) {
  1226. return mStorageManager.getFileById(file.getParentId());
  1227. }
  1228. }
  1229. return null;
  1230. }
  1231. public void startSyncFolderOperation(OCFile folder) {
  1232. long currentSyncTime = System.currentTimeMillis();
  1233. mSyncInProgress = true;
  1234. // perform folder synchronization
  1235. RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
  1236. currentSyncTime,
  1237. false,
  1238. false,
  1239. getStorageManager(),
  1240. getAccount(),
  1241. getApplicationContext()
  1242. );
  1243. synchFolderOp.execute(getAccount(), this, null, null, this);
  1244. setSupportProgressBarIndeterminateVisibility(true);
  1245. }
  1246. // public void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
  1247. // int childCount = viewGroup.getChildCount();
  1248. // for (int i = 0; i < childCount; i++) {
  1249. // View view = viewGroup.getChildAt(i);
  1250. // view.setEnabled(enabled);
  1251. // view.setClickable(!enabled);
  1252. // if (view instanceof ViewGroup) {
  1253. // enableDisableViewGroup((ViewGroup) view, enabled);
  1254. // }
  1255. // }
  1256. // }
  1257. }