Refactored location of passcode check: a callback to rule them all
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 */
22
23 package com.owncloud.android.ui.activity;
24
25 import java.io.File;
26
27 import android.accounts.Account;
28 import android.accounts.AccountManager;
29 import android.accounts.AuthenticatorException;
30 import android.annotation.TargetApi;
31 import android.app.AlertDialog;
32 import android.content.BroadcastReceiver;
33 import android.content.ComponentName;
34 import android.content.ContentResolver;
35 import android.content.Context;
36 import android.content.DialogInterface;
37 import android.content.Intent;
38 import android.content.IntentFilter;
39 import android.content.ServiceConnection;
40 import android.content.SharedPreferences;
41 import android.content.SyncRequest;
42 import android.content.res.Resources.NotFoundException;
43 import android.database.Cursor;
44 import android.net.Uri;
45 import android.os.Build;
46 import android.os.Bundle;
47 import android.os.IBinder;
48 import android.preference.PreferenceManager;
49 import android.provider.OpenableColumns;
50 import android.support.v4.app.Fragment;
51 import android.support.v4.app.FragmentManager;
52 import android.support.v4.app.FragmentTransaction;
53 import android.view.View;
54 import android.view.ViewGroup;
55 import android.widget.ArrayAdapter;
56 import android.widget.TextView;
57 import android.widget.Toast;
58
59 import com.actionbarsherlock.app.ActionBar;
60 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
61 import com.actionbarsherlock.view.Menu;
62 import com.actionbarsherlock.view.MenuInflater;
63 import com.actionbarsherlock.view.MenuItem;
64 import com.actionbarsherlock.view.Window;
65 import com.owncloud.android.BuildConfig;
66 import com.owncloud.android.MainApp;
67 import com.owncloud.android.R;
68 import com.owncloud.android.authentication.PinCheck;
69 import com.owncloud.android.datamodel.OCFile;
70 import com.owncloud.android.files.services.FileDownloader;
71 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
72 import com.owncloud.android.files.services.FileUploader;
73 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
74 import com.owncloud.android.lib.common.OwnCloudAccount;
75 import com.owncloud.android.lib.common.OwnCloudClient;
76 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
77 import com.owncloud.android.lib.common.OwnCloudCredentials;
78 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
79 import com.owncloud.android.lib.common.network.CertificateCombinedException;
80 import com.owncloud.android.lib.common.operations.RemoteOperation;
81 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
82 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
83 import com.owncloud.android.lib.common.utils.Log_OC;
84 import com.owncloud.android.operations.CreateFolderOperation;
85 import com.owncloud.android.operations.CreateShareOperation;
86 import com.owncloud.android.operations.MoveFileOperation;
87 import com.owncloud.android.operations.RemoveFileOperation;
88 import com.owncloud.android.operations.RenameFileOperation;
89 import com.owncloud.android.operations.SynchronizeFileOperation;
90 import com.owncloud.android.operations.RefreshFolderOperation;
91 import com.owncloud.android.operations.UnshareLinkOperation;
92 import com.owncloud.android.services.observer.FileObserverService;
93 import com.owncloud.android.syncadapter.FileSyncAdapter;
94 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
95 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
96 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
97 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
98 import com.owncloud.android.ui.dialog.UploadSourceDialogFragment;
99 import com.owncloud.android.ui.fragment.FileDetailFragment;
100 import com.owncloud.android.ui.fragment.FileFragment;
101 import com.owncloud.android.ui.fragment.OCFileListFragment;
102 import com.owncloud.android.ui.preview.PreviewImageActivity;
103 import com.owncloud.android.ui.preview.PreviewImageFragment;
104 import com.owncloud.android.ui.preview.PreviewMediaFragment;
105 import com.owncloud.android.ui.preview.PreviewVideoActivity;
106 import com.owncloud.android.utils.DisplayUtils;
107 import com.owncloud.android.utils.ErrorMessageAdapter;
108 import com.owncloud.android.utils.FileStorageUtils;
109 import com.owncloud.android.utils.UriUtils;
110
111
112 /**
113 * Displays, what files the user has available in his ownCloud.
114 */
115
116 public class FileDisplayActivity extends HookActivity implements
117 FileFragment.ContainerActivity, OnNavigationListener,
118 OnSslUntrustedCertListener, OnEnforceableRefreshListener {
119
120 private ArrayAdapter<String> mDirectories;
121
122 private SyncBroadcastReceiver mSyncBroadcastReceiver;
123 private UploadFinishReceiver mUploadFinishReceiver;
124 private DownloadFinishReceiver mDownloadFinishReceiver;
125 private RemoteOperationResult mLastSslUntrustedServerResult = null;
126
127 private boolean mDualPane;
128 private View mLeftFragmentContainer;
129 private View mRightFragmentContainer;
130
131 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
134
135 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
136
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES = 2;
139 public static final int ACTION_MOVE_FILES = 3;
140
141 private static final String TAG = FileDisplayActivity.class.getSimpleName();
142
143 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
145
146 private OCFile mWaitingToPreview;
147
148 private boolean mSyncInProgress = false;
149
150 private static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
151 private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE = "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED = "DIALOG_CERT_NOT_SAVED";
154
155
156 private OCFile mWaitingToSend;
157
158 private Boolean mUnlocked = false;
159
160 @Override
161 protected void onCreate(Bundle savedInstanceState) {
162 Log_OC.d(TAG, "onCreate() start");
163 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
164
165 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
166
167 /* TODO remove
168 if (PinCheck.checkIfPinEntry()){
169 Intent i = new Intent(MainApp.getAppContext(), PinCodeActivity.class);
170 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
171 startActivity(i);
172 }
173 */
174
175 /// grant that FileObserverService is watching favorite files
176 if (savedInstanceState == null) {
177 Intent initObserversIntent = FileObserverService.makeInitIntent(this);
178 startService(initObserversIntent);
179 }
180
181 /// Load of saved instance state
182 if(savedInstanceState != null) {
183 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
184 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
185 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
186
187 } else {
188 mWaitingToPreview = null;
189 mSyncInProgress = false;
190 mWaitingToSend = null;
191 }
192
193 /// USER INTERFACE
194
195 // Inflate and set the layout view
196 setContentView(R.layout.files);
197 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
198 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
199 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
200 if (savedInstanceState == null) {
201 createMinFragments();
202 }
203
204 // Action bar setup
205 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
206 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
207 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208
209 setBackgroundText();
210
211 Log_OC.d(TAG, "onCreate() end");
212 }
213
214 @Override
215 protected void onStart() {
216 Log_OC.d(TAG, "onStart() start");
217 super.onStart();
218 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
219 Log_OC.d(TAG, "onStart() end");
220 }
221
222 @Override
223 protected void onDestroy() {
224 Log_OC.d(TAG, "onDestroy() start");
225 super.onDestroy();
226 Log_OC.d(TAG, "onDestroy() end");
227 }
228
229 /**
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 */
232 @Override
233 protected void onAccountSet(boolean stateWasRecovered) {
234 super.onAccountSet(stateWasRecovered);
235 if (getAccount() != null) {
236 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
237 OCFile file = getFile();
238 // get parent from path
239 String parentPath = "";
240 if (file != null) {
241 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
242 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
243 // get parent from path
244 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
245 if (getStorageManager().getFileByPath(parentPath) == null)
246 file = null; // not able to know the directory where the file is uploading
247 } else {
248 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
249 }
250 }
251 if (file == null) {
252 // fall back to root folder
253 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
254 }
255 setFile(file);
256 setNavigationListWithFolder(file);
257
258 if (!stateWasRecovered) {
259 Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
260 initFragmentsWithFile();
261 if (file.isFolder()) {
262 startSyncFolderOperation(file, false);
263 }
264
265 } else {
266 updateFragmentsVisibility(!file.isFolder());
267 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
268 }
269 }
270 }
271
272
273 private void setNavigationListWithFolder(OCFile file) {
274 mDirectories.clear();
275 OCFile fileIt = file;
276 String parentPath;
277 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
278 if (fileIt.isFolder()) {
279 mDirectories.add(fileIt.getFileName());
280 }
281 // get parent from path
282 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
283 fileIt = getStorageManager().getFileByPath(parentPath);
284 }
285 mDirectories.add(OCFile.PATH_SEPARATOR);
286 }
287
288
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles = new OCFileListFragment();
291 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
292 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
293 transaction.commit();
294 }
295
296 private void initFragmentsWithFile() {
297 if (getAccount() != null && getFile() != null) {
298 /// First fragment
299 OCFileListFragment listOfFiles = getListOfFilesFragment();
300 if (listOfFiles != null) {
301 listOfFiles.listDirectory(getCurrentDir());
302 } else {
303 Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
304 }
305
306 /// Second fragment
307 OCFile file = getFile();
308 Fragment secondFragment = chooseInitialSecondFragment(file);
309 if (secondFragment != null) {
310 setSecondFragment(secondFragment);
311 updateFragmentsVisibility(true);
312 updateNavigationElementsInActionBar(file);
313
314 } else {
315 cleanSecondFragment();
316 }
317
318 } else {
319 Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null) {
321 Log_OC.wtf(TAG, "\t account is NULL");
322 }
323 if (getFile() == null) {
324 Log_OC.wtf(TAG, "\t file is NULL");
325 }
326 }
327 }
328
329 private Fragment chooseInitialSecondFragment(OCFile file) {
330 Fragment secondFragment = null;
331 if (file != null && !file.isFolder()) {
332 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
333 && file.getLastSyncDateForProperties() > 0 // temporal fix
334 ) {
335 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
336 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
337 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
338
339 } else {
340 secondFragment = new FileDetailFragment(file, getAccount());
341 }
342 }
343 return secondFragment;
344 }
345
346
347 /**
348 * Replaces the second fragment managed by the activity with the received as
349 * a parameter.
350 *
351 * Assumes never will be more than two fragments managed at the same time.
352 *
353 * @param fragment New second Fragment to set.
354 */
355 private void setSecondFragment(Fragment fragment) {
356 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
357 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
358 transaction.commit();
359 }
360
361
362 private void updateFragmentsVisibility(boolean existsSecondFragment) {
363 if (mDualPane) {
364 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
365 mLeftFragmentContainer.setVisibility(View.VISIBLE);
366 }
367 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
368 mRightFragmentContainer.setVisibility(View.VISIBLE);
369 }
370
371 } else if (existsSecondFragment) {
372 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
373 mLeftFragmentContainer.setVisibility(View.GONE);
374 }
375 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
376 mRightFragmentContainer.setVisibility(View.VISIBLE);
377 }
378
379 } else {
380 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
381 mLeftFragmentContainer.setVisibility(View.VISIBLE);
382 }
383 if (mRightFragmentContainer.getVisibility() != View.GONE) {
384 mRightFragmentContainer.setVisibility(View.GONE);
385 }
386 }
387 }
388
389
390 private OCFileListFragment getListOfFilesFragment() {
391 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
392 if (listOfFiles != null) {
393 return (OCFileListFragment)listOfFiles;
394 }
395 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
396 return null;
397 }
398
399 public FileFragment getSecondFragment() {
400 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
401 if (second != null) {
402 return (FileFragment)second;
403 }
404 return null;
405 }
406
407 protected void cleanSecondFragment() {
408 Fragment second = getSecondFragment();
409 if (second != null) {
410 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
411 tr.remove(second);
412 tr.commit();
413 }
414 updateFragmentsVisibility(false);
415 updateNavigationElementsInActionBar(null);
416 }
417
418 protected void refreshListOfFilesFragment() {
419 OCFileListFragment fileListFragment = getListOfFilesFragment();
420 if (fileListFragment != null) {
421 fileListFragment.listDirectory();
422 }
423 }
424
425 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
426 FileFragment secondFragment = getSecondFragment();
427 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
428 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
429 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
430 OCFile fileInFragment = detailsFragment.getFile();
431 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview = null;
434
435 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment.listenForTransferProgress();
438 detailsFragment.updateFileDetails(true, false);
439
440 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged = false;
443 if (waitedPreview) {
444 if (success) {
445 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
446 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
447 startMediaPreview(mWaitingToPreview, 0, true);
448 detailsFragmentChanged = true;
449 } else {
450 getFileOperationsHelper().openFile(mWaitingToPreview);
451 }
452 }
453 mWaitingToPreview = null;
454 }
455 if (!detailsFragmentChanged) {
456 detailsFragment.updateFileDetails(false, (success));
457 }
458 }
459 }
460 }
461
462 @Override
463 public boolean onPrepareOptionsMenu(Menu menu) {
464 if (BuildConfig.DEBUG) {
465 menu.findItem(R.id.action_logger).setVisible(true);
466 } else {
467 menu.findItem(R.id.action_logger).setVisible(false);
468 }
469 return super.onPrepareOptionsMenu(menu);
470 }
471
472 @Override
473 public boolean onCreateOptionsMenu(Menu menu) {
474 MenuInflater inflater = getSherlock().getMenuInflater();
475 inflater.inflate(R.menu.main_menu, menu);
476 return true;
477 }
478
479 @Override
480 public boolean onOptionsItemSelected(MenuItem item) {
481 boolean retval = true;
482 switch (item.getItemId()) {
483 case R.id.action_create_dir: {
484 CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(getCurrentDir());
485 dialog.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
486 break;
487 }
488 case R.id.action_sync_account: {
489 startSynchronization();
490 break;
491 }
492 case R.id.action_upload: {
493 UploadSourceDialogFragment dialog = UploadSourceDialogFragment.newInstance(getAccount());
494 dialog.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE);
495
496 break;
497 }
498 case R.id.action_settings: {
499 Intent settingsIntent = new Intent(this, Preferences.class);
500 startActivity(settingsIntent);
501 break;
502 }
503 case R.id.action_logger: {
504 Intent loggerIntent = new Intent(getApplicationContext(),LogHistoryActivity.class);
505 startActivity(loggerIntent);
506 break;
507 }
508 case android.R.id.home: {
509 FileFragment second = getSecondFragment();
510 OCFile currentDir = getCurrentDir();
511 if((currentDir != null && currentDir.getParentId() != 0) ||
512 (second != null && second.getFile() != null)) {
513 onBackPressed();
514
515 }
516 break;
517 }
518 case R.id.action_sort: {
519 SharedPreferences appPreferences = PreferenceManager
520 .getDefaultSharedPreferences(this);
521
522 // Read sorting order, default to sort by name ascending
523 Integer sortOrder = appPreferences
524 .getInt("sortOrder", FileStorageUtils.SORT_NAME);
525
526 AlertDialog.Builder builder = new AlertDialog.Builder(this);
527 builder.setTitle(R.string.actionbar_sort_title)
528 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder , new DialogInterface.OnClickListener() {
529 public void onClick(DialogInterface dialog, int which) {
530
531 switch (which){
532 case 0:
533 sortByName(true);
534 break;
535 case 1:
536 sortByDate(false);
537 break;
538
539 }
540
541 dialog.dismiss();
542
543 }
544 });
545 builder.create().show();
546 break;
547 }
548 default:
549 retval = super.onOptionsItemSelected(item);
550 }
551 return retval;
552 }
553
554 private void startSynchronization() {
555 Log_OC.d(TAG, "Got to start sync");
556 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
557 Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
558 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
559 Bundle bundle = new Bundle();
560 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
561 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
562 Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
563 ContentResolver.requestSync(
564 getAccount(),
565 MainApp.getAuthority(), bundle);
566 } else {
567 Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
568 SyncRequest.Builder builder = new SyncRequest.Builder();
569 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
570 builder.setExpedited(true);
571 builder.setManual(true);
572 builder.syncOnce();
573
574 // Fix bug in Android Lollipop when you click on refresh the whole account
575 Bundle extras = new Bundle();
576 builder.setExtras(extras);
577
578 SyncRequest request = builder.build();
579 ContentResolver.requestSync(request);
580 }
581 }
582
583
584 @Override
585 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
586 if (itemPosition != 0) {
587 String targetPath = "";
588 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
589 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
590 }
591 targetPath = OCFile.PATH_SEPARATOR + targetPath;
592 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
593 if (targetFolder != null) {
594 browseTo(targetFolder);
595 }
596
597 // the next operation triggers a new call to this method, but it's necessary to
598 // ensure that the name exposed in the action bar is the current directory when the
599 // user selected it in the navigation list
600 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
601 getSupportActionBar().setSelectedNavigationItem(0);
602 }
603 return true;
604 }
605
606 /**
607 * Called, when the user selected something for uploading
608 *
609 */
610 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
611 @Override
612 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
613
614 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
615 //getClipData is only supported on api level 16+, Jelly Bean
616 if (data.getData() == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
617 for( int i = 0; i < data.getClipData().getItemCount(); i++){
618 Intent intent = new Intent();
619 intent.setData(data.getClipData().getItemAt(i).getUri());
620 requestSimpleUpload(intent, resultCode);
621 }
622 }else {
623 requestSimpleUpload(data, resultCode);
624 }
625 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
626 requestMultipleUpload(data, resultCode);
627
628 } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK){
629
630 final Intent fData = data;
631 final int fResultCode = resultCode;
632 getHandler().postDelayed(
633 new Runnable() {
634 @Override
635 public void run() {
636 requestMoveOperation(fData, fResultCode);
637 }
638 },
639 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
640 );
641
642 } else {
643 super.onActivityResult(requestCode, resultCode, data);
644 }
645
646 }
647
648 private void requestMultipleUpload(Intent data, int resultCode) {
649 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
650 if (filePaths != null) {
651 String[] remotePaths = new String[filePaths.length];
652 String remotePathBase = "";
653
654 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
655 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
656 }
657 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
658 remotePathBase += OCFile.PATH_SEPARATOR;
659 for (int j = 0; j< remotePaths.length; j++) {
660 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
661 }
662
663 Intent i = new Intent(this, FileUploader.class);
664 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
665 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
666 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
667 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
668 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
669 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
670 startService(i);
671
672 } else {
673 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
674 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
675 t.show();
676 return;
677 }
678 }
679
680
681 private void requestSimpleUpload(Intent data, int resultCode) {
682 String filePath = null;
683 String mimeType = null;
684
685 Uri selectedImageUri = data.getData();
686
687 try {
688 mimeType = getContentResolver().getType(selectedImageUri);
689
690 String fileManagerString = selectedImageUri.getPath();
691 String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);
692
693 if (selectedImagePath != null)
694 filePath = selectedImagePath;
695 else
696 filePath = fileManagerString;
697
698 } catch (Exception e) {
699 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
700
701 } finally {
702 if (filePath == null) {
703 Log_OC.e(TAG, "Couldn't resolve path to file");
704 Toast t = Toast.makeText(
705 this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG
706 );
707 t.show();
708 return;
709 }
710 }
711
712 Intent i = new Intent(this, FileUploader.class);
713 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
714 OCFile currentDir = getCurrentDir();
715 String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
716
717 if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
718 Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
719 try {
720 if (cursor != null && cursor.moveToFirst()) {
721 String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
722 Log_OC.v(TAG, "Display Name: " + displayName );
723
724 displayName.replace(File.separatorChar, '_');
725 displayName.replace(File.pathSeparatorChar, '_');
726 remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);
727
728 }
729 // and what happens in case of error?; wrong target name for the upload
730 } finally {
731 cursor.close();
732 }
733
734 } else {
735 remotePath += new File(filePath).getName();
736 }
737
738 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
739 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
740 i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
741 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
742 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
743 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
744 startService(i);
745 }
746
747 /**
748 * Request the operation for moving the file/folder from one path to another
749 *
750 * @param data Intent received
751 * @param resultCode Result code received
752 */
753 private void requestMoveOperation(Intent data, int resultCode) {
754 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
755 OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
756 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
757 }
758
759 @Override
760 public void onBackPressed() {
761 OCFileListFragment listOfFiles = getListOfFilesFragment();
762 if (mDualPane || getSecondFragment() == null) {
763 if (listOfFiles != null) { // should never be null, indeed
764 if (mDirectories.getCount() <= 1) {
765 finish();
766 return;
767 }
768 int levelsUp = listOfFiles.onBrowseUp();
769 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
770 popDirname();
771 }
772 }
773 }
774 if (listOfFiles != null) { // should never be null, indeed
775 setFile(listOfFiles.getCurrentFile());
776 }
777 cleanSecondFragment();
778
779 }
780
781 @Override
782 protected void onSaveInstanceState(Bundle outState) {
783 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
784 Log_OC.d(TAG, "onSaveInstanceState() start");
785 super.onSaveInstanceState(outState);
786 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
787 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
788 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
789 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
790
791 Log_OC.d(TAG, "onSaveInstanceState() end");
792 }
793
794
795
796 @Override
797 protected void onResume() {
798 Log_OC.d(TAG, "onResume() start");
799 super.onResume();
800
801 // refresh list of files
802 refreshListOfFilesFragment();
803
804 // Listen for sync messages
805 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
806 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
807 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
808 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
809 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
810 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
811 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
812 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
813
814 // Listen for upload messages
815 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
816 mUploadFinishReceiver = new UploadFinishReceiver();
817 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
818
819 // Listen for download messages
820 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
821 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
822 mDownloadFinishReceiver = new DownloadFinishReceiver();
823 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
824
825 Log_OC.d(TAG, "onResume() end");
826 }
827
828
829 @Override
830 protected void onPause() {
831 Log_OC.d(TAG, "onPause() start");
832 if (mSyncBroadcastReceiver != null) {
833 unregisterReceiver(mSyncBroadcastReceiver);
834 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
835 mSyncBroadcastReceiver = null;
836 }
837 if (mUploadFinishReceiver != null) {
838 unregisterReceiver(mUploadFinishReceiver);
839 mUploadFinishReceiver = null;
840 }
841 if (mDownloadFinishReceiver != null) {
842 unregisterReceiver(mDownloadFinishReceiver);
843 mDownloadFinishReceiver = null;
844 }
845
846 PinCheck.setUnlockTimestamp();
847
848 super.onPause();
849 Log_OC.d(TAG, "onPause() end");
850 }
851
852 /**
853 * Pushes a directory to the drop down list
854 * @param directory to push
855 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
856 */
857 public void pushDirname(OCFile directory) {
858 if(!directory.isFolder()){
859 throw new IllegalArgumentException("Only directories may be pushed!");
860 }
861 mDirectories.insert(directory.getFileName(), 0);
862 setFile(directory);
863 }
864
865 /**
866 * Pops a directory name from the drop down list
867 * @return True, unless the stack is empty
868 */
869 public boolean popDirname() {
870 mDirectories.remove(mDirectories.getItem(0));
871 return !mDirectories.isEmpty();
872 }
873
874 // Custom array adapter to override text colors
875 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
876
877 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
878 super(ctx, view);
879 }
880
881 public View getView(int position, View convertView, ViewGroup parent) {
882 View v = super.getView(position, convertView, parent);
883
884 ((TextView) v).setTextColor(getResources().getColorStateList(
885 android.R.color.white));
886
887 fixRoot((TextView) v );
888 return v;
889 }
890
891 public View getDropDownView(int position, View convertView,
892 ViewGroup parent) {
893 View v = super.getDropDownView(position, convertView, parent);
894
895 ((TextView) v).setTextColor(getResources().getColorStateList(
896 android.R.color.white));
897
898 fixRoot((TextView) v );
899 return v;
900 }
901
902 private void fixRoot(TextView v) {
903 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
904 v.setText(R.string.default_display_name_for_root_folder);
905 }
906 }
907
908 }
909
910 private class SyncBroadcastReceiver extends BroadcastReceiver {
911
912 /**
913 * {@link BroadcastReceiver} to enable syncing feedback in UI
914 */
915 @Override
916 public void onReceive(Context context, Intent intent) {
917 try {
918 String event = intent.getAction();
919 Log_OC.d(TAG, "Received broadcast " + event);
920 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
921 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
922 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
923 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
924
925 if (sameAccount) {
926
927 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
928 mSyncInProgress = true;
929
930 } else {
931 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
932 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
933
934 if (currentDir == null) {
935 // current folder was removed from the server
936 Toast.makeText( FileDisplayActivity.this,
937 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
938 Toast.LENGTH_LONG)
939 .show();
940 browseToRoot();
941
942 } else {
943 if (currentFile == null && !getFile().isFolder()) {
944 // currently selected file was removed in the server, and now we know it
945 cleanSecondFragment();
946 currentFile = currentDir;
947 }
948
949 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
950 OCFileListFragment fileListFragment = getListOfFilesFragment();
951 if (fileListFragment != null) {
952 fileListFragment.listDirectory(currentDir);
953 }
954 }
955 setFile(currentFile);
956 }
957
958 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
959
960 if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
961 equals(event) &&
962 /// TODO refactor and make common
963 synchResult != null && !synchResult.isSuccess() &&
964 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
965 synchResult.isIdPRedirection() ||
966 (synchResult.isException() && synchResult.getException()
967 instanceof AuthenticatorException))) {
968
969
970 try {
971 OwnCloudClient client;
972 OwnCloudAccount ocAccount =
973 new OwnCloudAccount(getAccount(), context);
974 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
975 removeClientFor(ocAccount));
976
977 if (client != null) {
978 OwnCloudCredentials cred = client.getCredentials();
979 if (cred != null) {
980 AccountManager am = AccountManager.get(context);
981 if (cred.authTokenExpires()) {
982 am.invalidateAuthToken(
983 getAccount().type,
984 cred.getAuthToken()
985 );
986 } else {
987 am.clearPassword(getAccount());
988 }
989 }
990 }
991 requestCredentialsUpdate();
992
993 } catch (AccountNotFoundException e) {
994 Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
995 }
996
997 }
998 }
999 removeStickyBroadcast(intent);
1000 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1001 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1002
1003 setBackgroundText();
1004
1005 }
1006
1007 if (synchResult != null) {
1008 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1009 mLastSslUntrustedServerResult = synchResult;
1010 }
1011 }
1012 } catch (RuntimeException e) {
1013 // avoid app crashes after changing the serial id of RemoteOperationResult
1014 // in owncloud library with broadcast notifications pending to process
1015 removeStickyBroadcast(intent);
1016 }
1017 }
1018 }
1019
1020 /**
1021 * Show a text message on screen view for notifying user if content is
1022 * loading or folder is empty
1023 */
1024 private void setBackgroundText() {
1025 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1026 if (ocFileListFragment != null) {
1027 int message = R.string.file_list_loading;
1028 if (!mSyncInProgress) {
1029 // In case file list is empty
1030 message = R.string.file_list_empty;
1031 }
1032 ocFileListFragment.setMessageForEmptyList(getString(message));
1033 } else {
1034 Log_OC.e(TAG, "OCFileListFragment is null");
1035 }
1036 }
1037
1038 /**
1039 * Once the file upload has finished -> update view
1040 */
1041 private class UploadFinishReceiver extends BroadcastReceiver {
1042 /**
1043 * Once the file upload has finished -> update view
1044 * @author David A. Velasco
1045 * {@link BroadcastReceiver} to enable upload feedback in UI
1046 */
1047 @Override
1048 public void onReceive(Context context, Intent intent) {
1049 try {
1050 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1051 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1052 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1053 OCFile currentDir = getCurrentDir();
1054 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1055 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1056
1057 if (sameAccount && isDescendant) {
1058 refreshListOfFilesFragment();
1059 }
1060
1061 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1062 boolean renamedInUpload = getFile().getRemotePath().
1063 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1064 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1065 renamedInUpload;
1066 FileFragment details = getSecondFragment();
1067 boolean detailFragmentIsShown = (details != null &&
1068 details instanceof FileDetailFragment);
1069
1070 if (sameAccount && sameFile && detailFragmentIsShown) {
1071 if (uploadWasFine) {
1072 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1073 }
1074 if (renamedInUpload) {
1075 String newName = (new File(uploadedRemotePath)).getName();
1076 Toast msg = Toast.makeText(
1077 context,
1078 String.format(
1079 getString(R.string.filedetails_renamed_in_upload_msg),
1080 newName),
1081 Toast.LENGTH_LONG);
1082 msg.show();
1083 }
1084 if (uploadWasFine || getFile().fileExists()) {
1085 ((FileDetailFragment)details).updateFileDetails(false, true);
1086 } else {
1087 cleanSecondFragment();
1088 }
1089
1090 // Force the preview if the file is an image
1091 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1092 startImagePreview(getFile());
1093 } // TODO what about other kind of previews?
1094 }
1095
1096 } finally {
1097 if (intent != null) {
1098 removeStickyBroadcast(intent);
1099 }
1100 }
1101
1102 }
1103
1104 }
1105
1106
1107 /**
1108 * Class waiting for broadcast events from the {@link FileDownloader} service.
1109 *
1110 * Updates the UI when a download is started or finished, provided that it is relevant for the
1111 * current folder.
1112 */
1113 private class DownloadFinishReceiver extends BroadcastReceiver {
1114
1115 //int refreshCounter = 0;
1116 @Override
1117 public void onReceive(Context context, Intent intent) {
1118 try {
1119 boolean sameAccount = isSameAccount(context, intent);
1120 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1121 boolean isDescendant = isDescendant(downloadedRemotePath);
1122
1123 if (sameAccount && isDescendant) {
1124 String linkedToRemotePath = intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
1125 if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
1126 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1127 refreshListOfFilesFragment();
1128 }
1129 refreshSecondFragment(
1130 intent.getAction(),
1131 downloadedRemotePath,
1132 intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
1133 );
1134 }
1135
1136 if (mWaitingToSend != null) {
1137 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
1138 if (mWaitingToSend.isDown()) {
1139 sendDownloadedFile();
1140 }
1141 }
1142
1143 } finally {
1144 if (intent != null) {
1145 removeStickyBroadcast(intent);
1146 }
1147 }
1148 }
1149
1150 private boolean isDescendant(String downloadedRemotePath) {
1151 OCFile currentDir = getCurrentDir();
1152 return (
1153 currentDir != null &&
1154 downloadedRemotePath != null &&
1155 downloadedRemotePath.startsWith(currentDir.getRemotePath())
1156 );
1157 }
1158
1159 private boolean isAscendant(String linkedToRemotePath) {
1160 OCFile currentDir = getCurrentDir();
1161 return (
1162 currentDir != null &&
1163 currentDir.getRemotePath().startsWith(linkedToRemotePath)
1164 );
1165 }
1166
1167 private boolean isSameAccount(Context context, Intent intent) {
1168 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1169 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1170 }
1171 }
1172
1173
1174 public void browseToRoot() {
1175 OCFileListFragment listOfFiles = getListOfFilesFragment();
1176 if (listOfFiles != null) { // should never be null, indeed
1177 while (mDirectories.getCount() > 1) {
1178 popDirname();
1179 }
1180 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1181 listOfFiles.listDirectory(root);
1182 setFile(listOfFiles.getCurrentFile());
1183 startSyncFolderOperation(root, false);
1184 }
1185 cleanSecondFragment();
1186 }
1187
1188
1189 public void browseTo(OCFile folder) {
1190 if (folder == null || !folder.isFolder()) {
1191 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1192 }
1193 OCFileListFragment listOfFiles = getListOfFilesFragment();
1194 if (listOfFiles != null) {
1195 setNavigationListWithFolder(folder);
1196 listOfFiles.listDirectory(folder);
1197 setFile(listOfFiles.getCurrentFile());
1198 startSyncFolderOperation(folder, false);
1199 } else {
1200 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1201 }
1202 cleanSecondFragment();
1203 }
1204
1205
1206 /**
1207 * {@inheritDoc}
1208 *
1209 * Updates action bar and second fragment, if in dual pane mode.
1210 */
1211 @Override
1212 public void onBrowsedDownTo(OCFile directory) {
1213 pushDirname(directory);
1214 cleanSecondFragment();
1215
1216 // Sync Folder
1217 startSyncFolderOperation(directory, false);
1218
1219 }
1220
1221 /**
1222 * Shows the information of the {@link OCFile} received as a
1223 * parameter in the second fragment.
1224 *
1225 * @param file {@link OCFile} whose details will be shown
1226 */
1227 @Override
1228 public void showDetails(OCFile file) {
1229 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1230 setSecondFragment(detailFragment);
1231 updateFragmentsVisibility(true);
1232 updateNavigationElementsInActionBar(file);
1233 setFile(file);
1234 }
1235
1236
1237 /**
1238 * TODO
1239 */
1240 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1241 ActionBar actionBar = getSupportActionBar();
1242
1243 // For adding content description tag to a title field in the action bar
1244 int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
1245
1246 if (chosenFile == null || mDualPane) {
1247 // only list of files - set for browsing through folders
1248 OCFile currentDir = getCurrentDir();
1249 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1250 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1251 actionBar.setDisplayShowTitleEnabled(!noRoot);
1252 if (!noRoot) {
1253 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1254 View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
1255 if (actionBarTitleView != null) { // it's null in Android 2.x
1256 actionBarTitleView.setContentDescription(getString(R.string.default_display_name_for_root_folder));
1257 }
1258 }
1259 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1260 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1261
1262 } else {
1263 actionBar.setDisplayHomeAsUpEnabled(true);
1264 actionBar.setDisplayShowTitleEnabled(true);
1265 actionBar.setTitle(chosenFile.getFileName());
1266 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1267 View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
1268 if (actionBarTitleView != null) { // it's null in Android 2.x
1269 getWindow().getDecorView().findViewById(actionBarTitleId).
1270 setContentDescription(chosenFile.getFileName());
1271 }
1272 }
1273 }
1274
1275
1276 @Override
1277 protected ServiceConnection newTransferenceServiceConnection() {
1278 return new ListServiceConnection();
1279 }
1280
1281 /** Defines callbacks for service binding, passed to bindService() */
1282 private class ListServiceConnection implements ServiceConnection {
1283
1284 @Override
1285 public void onServiceConnected(ComponentName component, IBinder service) {
1286 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1287 Log_OC.d(TAG, "Download service connected");
1288 mDownloaderBinder = (FileDownloaderBinder) service;
1289 if (mWaitingToPreview != null)
1290 if (getStorageManager() != null) {
1291 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1292 if (!mWaitingToPreview.isDown()) {
1293 requestForDownload();
1294 }
1295 }
1296
1297 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1298 Log_OC.d(TAG, "Upload service connected");
1299 mUploaderBinder = (FileUploaderBinder) service;
1300 } else {
1301 return;
1302 }
1303 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1304 OCFileListFragment listOfFiles = getListOfFilesFragment();
1305 if (listOfFiles != null) {
1306 listOfFiles.listDirectory();
1307 }
1308 FileFragment secondFragment = getSecondFragment();
1309 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1310 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1311 detailFragment.listenForTransferProgress();
1312 detailFragment.updateFileDetails(false, false);
1313 }
1314 }
1315
1316 @Override
1317 public void onServiceDisconnected(ComponentName component) {
1318 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1319 Log_OC.d(TAG, "Download service disconnected");
1320 mDownloaderBinder = null;
1321 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1322 Log_OC.d(TAG, "Upload service disconnected");
1323 mUploaderBinder = null;
1324 }
1325 }
1326 };
1327
1328 @Override
1329 public void onSavedCertificate() {
1330 startSyncFolderOperation(getCurrentDir(), false);
1331 }
1332
1333
1334 @Override
1335 public void onFailedSavingCertificate() {
1336 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
1337 R.string.ssl_validator_not_saved, new String[]{}, R.string.common_ok, -1, -1
1338 );
1339 dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
1340 }
1341
1342 @Override
1343 public void onCancelCertificate() {
1344 // nothing to do
1345 }
1346
1347 /**
1348 * Updates the view associated to the activity after the finish of some operation over files
1349 * in the current account.
1350 *
1351 * @param operation Removal operation performed.
1352 * @param result Result of the removal.
1353 */
1354 @Override
1355 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1356 super.onRemoteOperationFinish(operation, result);
1357
1358 if (operation instanceof RemoveFileOperation) {
1359 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1360
1361 } else if (operation instanceof RenameFileOperation) {
1362 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1363
1364 } else if (operation instanceof SynchronizeFileOperation) {
1365 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1366
1367 } else if (operation instanceof CreateFolderOperation) {
1368 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1369
1370 } else if (operation instanceof CreateShareOperation) {
1371 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1372
1373 } else if (operation instanceof UnshareLinkOperation) {
1374 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1375
1376 } else if (operation instanceof MoveFileOperation) {
1377 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1378 }
1379
1380 }
1381
1382
1383 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1384 if (result.isSuccess()) {
1385 refreshShowDetails();
1386 refreshListOfFilesFragment();
1387 }
1388 }
1389
1390
1391 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1392 if (result.isSuccess()) {
1393 refreshShowDetails();
1394 refreshListOfFilesFragment();
1395
1396 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1397 cleanSecondFragment();
1398 refreshListOfFilesFragment();
1399 }
1400 }
1401
1402 private void refreshShowDetails() {
1403 FileFragment details = getSecondFragment();
1404 if (details != null) {
1405 OCFile file = details.getFile();
1406 if (file != null) {
1407 file = getStorageManager().getFileByPath(file.getRemotePath());
1408 if (details instanceof PreviewMediaFragment) {
1409 // Refresh OCFile of the fragment
1410 ((PreviewMediaFragment) details).updateFile(file);
1411 } else {
1412 showDetails(file);
1413 }
1414 }
1415 invalidateOptionsMenu();
1416 }
1417 }
1418
1419 /**
1420 * Updates the view associated to the activity after the finish of an operation trying to remove a
1421 * file.
1422 *
1423 * @param operation Removal operation performed.
1424 * @param result Result of the removal.
1425 */
1426 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1427 dismissLoadingDialog();
1428
1429 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1430 Toast.LENGTH_LONG);
1431 msg.show();
1432
1433 if (result.isSuccess()) {
1434 OCFile removedFile = operation.getFile();
1435 FileFragment second = getSecondFragment();
1436 if (second != null && removedFile.equals(second.getFile())) {
1437 if (second instanceof PreviewMediaFragment) {
1438 ((PreviewMediaFragment)second).stopPreview(true);
1439 }
1440 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1441 cleanSecondFragment();
1442 }
1443 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1444 refreshListOfFilesFragment();
1445 }
1446 invalidateOptionsMenu();
1447 } else {
1448 if (result.isSslRecoverableException()) {
1449 mLastSslUntrustedServerResult = result;
1450 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1451 }
1452 }
1453 }
1454
1455
1456 /**
1457 * Updates the view associated to the activity after the finish of an operation trying to move a
1458 * file.
1459 *
1460 * @param operation Move operation performed.
1461 * @param result Result of the move operation.
1462 */
1463 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1464 if (result.isSuccess()) {
1465 dismissLoadingDialog();
1466 refreshListOfFilesFragment();
1467 } else {
1468 dismissLoadingDialog();
1469 try {
1470 Toast msg = Toast.makeText(FileDisplayActivity.this,
1471 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1472 Toast.LENGTH_LONG);
1473 msg.show();
1474
1475 } catch (NotFoundException e) {
1476 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1477 }
1478 }
1479 }
1480
1481
1482 /**
1483 * Updates the view associated to the activity after the finish of an operation trying to rename a
1484 * file.
1485 *
1486 * @param operation Renaming operation performed.
1487 * @param result Result of the renaming.
1488 */
1489 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1490 dismissLoadingDialog();
1491 OCFile renamedFile = operation.getFile();
1492 if (result.isSuccess()) {
1493 FileFragment details = getSecondFragment();
1494 if (details != null) {
1495 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1496 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1497 showDetails(renamedFile);
1498
1499 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1500 ((PreviewMediaFragment) details).updateFile(renamedFile);
1501 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1502 int position = ((PreviewMediaFragment)details).getPosition();
1503 startMediaPreview(renamedFile, position, true);
1504 } else {
1505 getFileOperationsHelper().openFile(renamedFile);
1506 }
1507 }
1508 }
1509
1510 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1511 refreshListOfFilesFragment();
1512 }
1513
1514 } else {
1515 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1516 Toast.LENGTH_LONG);
1517 msg.show();
1518
1519 if (result.isSslRecoverableException()) {
1520 mLastSslUntrustedServerResult = result;
1521 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1522 }
1523 }
1524 }
1525
1526 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1527 dismissLoadingDialog();
1528 OCFile syncedFile = operation.getLocalFile();
1529 if (!result.isSuccess()) {
1530 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1531 Intent i = new Intent(this, ConflictsResolveActivity.class);
1532 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1533 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1534 startActivity(i);
1535
1536 }
1537
1538 } else {
1539 if (operation.transferWasRequested()) {
1540 onTransferStateChanged(syncedFile, true, true);
1541
1542 } else {
1543 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1544 Toast.LENGTH_LONG);
1545 msg.show();
1546 }
1547 }
1548 }
1549
1550 /**
1551 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1552 *
1553 * @param operation Creation operation performed.
1554 * @param result Result of the creation.
1555 */
1556 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1557 if (result.isSuccess()) {
1558 dismissLoadingDialog();
1559 refreshListOfFilesFragment();
1560 } else {
1561 dismissLoadingDialog();
1562 try {
1563 Toast msg = Toast.makeText(FileDisplayActivity.this,
1564 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1565 Toast.LENGTH_LONG);
1566 msg.show();
1567
1568 } catch (NotFoundException e) {
1569 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1570 }
1571 }
1572 }
1573
1574
1575 /**
1576 * {@inheritDoc}
1577 */
1578 @Override
1579 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1580 refreshListOfFilesFragment();
1581 FileFragment details = getSecondFragment();
1582 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1583 if (downloading || uploading) {
1584 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1585 } else {
1586 if (!file.fileExists()) {
1587 cleanSecondFragment();
1588 } else {
1589 ((FileDetailFragment)details).updateFileDetails(false, true);
1590 }
1591 }
1592 }
1593
1594 }
1595
1596
1597 private void requestForDownload() {
1598 Account account = getAccount();
1599 //if (!mWaitingToPreview.isDownloading()) {
1600 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1601 Intent i = new Intent(this, FileDownloader.class);
1602 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1603 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1604 startService(i);
1605 }
1606 }
1607
1608
1609 private OCFile getCurrentDir() {
1610 OCFile file = getFile();
1611 if (file != null) {
1612 if (file.isFolder()) {
1613 return file;
1614 } else if (getStorageManager() != null) {
1615 String parentPath = file.getRemotePath().substring(0,
1616 file.getRemotePath().lastIndexOf(file.getFileName()));
1617 return getStorageManager().getFileByPath(parentPath);
1618 }
1619 }
1620 return null;
1621 }
1622
1623 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1624 long currentSyncTime = System.currentTimeMillis();
1625
1626 mSyncInProgress = true;
1627
1628 // perform folder synchronization
1629 RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
1630 currentSyncTime,
1631 false,
1632 getFileOperationsHelper().isSharedSupported(),
1633 ignoreETag,
1634 getStorageManager(),
1635 getAccount(),
1636 getApplicationContext()
1637 );
1638 synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null);
1639
1640 setSupportProgressBarIndeterminateVisibility(true);
1641
1642 setBackgroundText();
1643 }
1644
1645 /**
1646 * Show untrusted cert dialog
1647 */
1648 public void showUntrustedCertDialog(RemoteOperationResult result) {
1649 // Show a dialog with the certificate info
1650 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
1651 (CertificateCombinedException)result.getException());
1652 FragmentManager fm = getSupportFragmentManager();
1653 FragmentTransaction ft = fm.beginTransaction();
1654 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1655 }
1656
1657 private void requestForDownload(OCFile file) {
1658 Account account = getAccount();
1659 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1660 Intent i = new Intent(this, FileDownloader.class);
1661 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1662 i.putExtra(FileDownloader.EXTRA_FILE, file);
1663 startService(i);
1664 }
1665 }
1666
1667 private void sendDownloadedFile(){
1668 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1669 mWaitingToSend = null;
1670 }
1671
1672
1673 /**
1674 * Requests the download of the received {@link OCFile} , updates the UI
1675 * to monitor the download progress and prepares the activity to send the file
1676 * when the download finishes.
1677 *
1678 * @param file {@link OCFile} to download and preview.
1679 */
1680 public void startDownloadForSending(OCFile file) {
1681 mWaitingToSend = file;
1682 requestForDownload(mWaitingToSend);
1683 boolean hasSecondFragment = (getSecondFragment()!= null);
1684 updateFragmentsVisibility(hasSecondFragment);
1685 }
1686
1687 /**
1688 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1689 *
1690 * @param file Image {@link OCFile} to show.
1691 */
1692 public void startImagePreview(OCFile file) {
1693 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1694 showDetailsIntent.putExtra(EXTRA_FILE, file);
1695 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1696 startActivity(showDetailsIntent);
1697
1698 }
1699
1700 /**
1701 * Stars the preview of an already down media {@link OCFile}.
1702 *
1703 * @param file Media {@link OCFile} to preview.
1704 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1705 * @param autoplay When 'true', the playback will start without user interactions.
1706 */
1707 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1708 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1709 setSecondFragment(mediaFragment);
1710 updateFragmentsVisibility(true);
1711 updateNavigationElementsInActionBar(file);
1712 setFile(file);
1713 }
1714
1715 /**
1716 * Requests the download of the received {@link OCFile} , updates the UI
1717 * to monitor the download progress and prepares the activity to preview
1718 * or open the file when the download finishes.
1719 *
1720 * @param file {@link OCFile} to download and preview.
1721 */
1722 public void startDownloadForPreview(OCFile file) {
1723 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1724 setSecondFragment(detailFragment);
1725 mWaitingToPreview = file;
1726 requestForDownload();
1727 updateFragmentsVisibility(true);
1728 updateNavigationElementsInActionBar(file);
1729 setFile(file);
1730 }
1731
1732
1733 public void cancelTransference(OCFile file) {
1734 getFileOperationsHelper().cancelTransference(file);
1735 if (mWaitingToPreview != null &&
1736 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1737 mWaitingToPreview = null;
1738 }
1739 if (mWaitingToSend != null &&
1740 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1741 mWaitingToSend = null;
1742 }
1743 onTransferStateChanged(file, false, false);
1744 }
1745
1746 @Override
1747 public void onRefresh(boolean ignoreETag) {
1748 refreshList(ignoreETag);
1749 }
1750
1751 @Override
1752 public void onRefresh() {
1753 refreshList(true);
1754 }
1755
1756 private void refreshList(boolean ignoreETag) {
1757 OCFileListFragment listOfFiles = getListOfFilesFragment();
1758 if (listOfFiles != null) {
1759 OCFile folder = listOfFiles.getCurrentFile();
1760 if (folder != null) {
1761 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1762 listDirectory(mFile);*/
1763 startSyncFolderOperation(folder, ignoreETag);
1764 }
1765 }
1766 }
1767
1768 private void sortByDate(boolean ascending){
1769 getListOfFilesFragment().sortByDate(ascending);
1770 }
1771
1772 private void sortBySize(boolean ascending){
1773 getListOfFilesFragment().sortBySize(ascending);
1774 }
1775
1776 private void sortByName(boolean ascending){
1777 getListOfFilesFragment().sortByName(ascending);
1778 }
1779
1780 }