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