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