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