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