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