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