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