FileDisplayActivity.java 53 KB

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