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