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