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