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