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