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