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