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