FileDisplayActivity.java 58 KB

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