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