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