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