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