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