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