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