Show the layout to hsare with user in phone and tablet
[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.ShareFileDialogFragment;
94 import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
95 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
96 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
97 import com.owncloud.android.ui.dialog.UploadSourceDialogFragment;
98 import com.owncloud.android.ui.fragment.FileDetailFragment;
99 import com.owncloud.android.ui.fragment.FileFragment;
100 import com.owncloud.android.ui.fragment.OCFileListFragment;
101 import com.owncloud.android.ui.preview.PreviewImageActivity;
102 import com.owncloud.android.ui.preview.PreviewImageFragment;
103 import com.owncloud.android.ui.preview.PreviewMediaFragment;
104 import com.owncloud.android.ui.preview.PreviewTextFragment;
105 import com.owncloud.android.ui.preview.PreviewVideoActivity;
106 import com.owncloud.android.utils.DisplayUtils;
107 import com.owncloud.android.utils.ErrorMessageAdapter;
108 import com.owncloud.android.utils.FileStorageUtils;
109 import com.owncloud.android.utils.UriUtils;
110
111 import java.io.File;
112
113 /**
114 * Displays, what files the user has available in his ownCloud.
115 */
116
117 public class FileDisplayActivity extends HookActivity
118 implements FileFragment.ContainerActivity,
119 OnSslUntrustedCertListener, OnEnforceableRefreshListener {
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 /**
1233 * Shows the share view for sharing {@link OCFile} received as a
1234 * parameter in the second fragment.
1235 *
1236 * @param file {@link OCFile} File to share with
1237 */
1238 @Override
1239 public void showShareFile(OCFile file) {
1240 ShareFileDialogFragment dialog =
1241 ShareFileDialogFragment.newInstance(file, getAccount());
1242 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_FILE);
1243 }
1244
1245 @Override
1246 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
1247 if (mDualPane) {
1248 // in dual pane mode, keep the focus of title an action bar in the current folder
1249 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1250
1251 } else {
1252 super.updateActionBarTitleAndHomeButton(chosenFile);
1253 }
1254
1255 }
1256
1257 @Override
1258 protected ServiceConnection newTransferenceServiceConnection() {
1259 return new ListServiceConnection();
1260 }
1261
1262 /**
1263 * Defines callbacks for service binding, passed to bindService()
1264 */
1265 private class ListServiceConnection implements ServiceConnection {
1266
1267 @Override
1268 public void onServiceConnected(ComponentName component, IBinder service) {
1269 if (component.equals(new ComponentName(
1270 FileDisplayActivity.this, FileDownloader.class))) {
1271 Log_OC.d(TAG, "Download service connected");
1272 mDownloaderBinder = (FileDownloaderBinder) service;
1273 if (mWaitingToPreview != null)
1274 if (getStorageManager() != null) {
1275 // update the file
1276 mWaitingToPreview =
1277 getStorageManager().getFileById(mWaitingToPreview.getFileId());
1278 if (!mWaitingToPreview.isDown()) {
1279 requestForDownload();
1280 }
1281 }
1282
1283 } else if (component.equals(new ComponentName(FileDisplayActivity.this,
1284 FileUploader.class))) {
1285 Log_OC.d(TAG, "Upload service connected");
1286 mUploaderBinder = (FileUploaderBinder) service;
1287 } else {
1288 return;
1289 }
1290 // a new chance to get the mDownloadBinder through
1291 // getFileDownloadBinder() - THIS IS A MESS
1292 OCFileListFragment listOfFiles = getListOfFilesFragment();
1293 if (listOfFiles != null) {
1294 listOfFiles.listDirectory();
1295 // TODO Enable when "On Device" is recovered ?
1296 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1297 }
1298 FileFragment secondFragment = getSecondFragment();
1299 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1300 FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
1301 detailFragment.listenForTransferProgress();
1302 detailFragment.updateFileDetails(false, false);
1303 }
1304 }
1305
1306 @Override
1307 public void onServiceDisconnected(ComponentName component) {
1308 if (component.equals(new ComponentName(FileDisplayActivity.this,
1309 FileDownloader.class))) {
1310 Log_OC.d(TAG, "Download service disconnected");
1311 mDownloaderBinder = null;
1312 } else if (component.equals(new ComponentName(FileDisplayActivity.this,
1313 FileUploader.class))) {
1314 Log_OC.d(TAG, "Upload service disconnected");
1315 mUploaderBinder = null;
1316 }
1317 }
1318 }
1319
1320 @Override
1321 public void onSavedCertificate() {
1322 startSyncFolderOperation(getCurrentDir(), false);
1323 }
1324
1325
1326 @Override
1327 public void onFailedSavingCertificate() {
1328 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
1329 R.string.ssl_validator_not_saved, new String[]{}, R.string.common_ok, -1, -1
1330 );
1331 dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
1332 }
1333
1334 @Override
1335 public void onCancelCertificate() {
1336 // nothing to do
1337 }
1338
1339 /**
1340 * Updates the view associated to the activity after the finish of some operation over files
1341 * in the current account.
1342 *
1343 * @param operation Removal operation performed.
1344 * @param result Result of the removal.
1345 */
1346 @Override
1347 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1348 super.onRemoteOperationFinish(operation, result);
1349
1350 if (operation instanceof RemoveFileOperation) {
1351 onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
1352
1353 } else if (operation instanceof RenameFileOperation) {
1354 onRenameFileOperationFinish((RenameFileOperation) operation, result);
1355
1356 } else if (operation instanceof SynchronizeFileOperation) {
1357 onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
1358
1359 } else if (operation instanceof CreateFolderOperation) {
1360 onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
1361
1362 } else if (operation instanceof CreateShareOperation) {
1363 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1364
1365 } else if (operation instanceof UnshareLinkOperation) {
1366 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
1367
1368 } else if (operation instanceof MoveFileOperation) {
1369 onMoveFileOperationFinish((MoveFileOperation) operation, result);
1370
1371 } else if (operation instanceof CopyFileOperation) {
1372 onCopyFileOperationFinish((CopyFileOperation) operation, result);
1373 }
1374
1375 }
1376 private void onCreateShareOperationFinish(CreateShareOperation operation,
1377 RemoteOperationResult result) {
1378 if (result.isSuccess()) {
1379 refreshShowDetails();
1380 refreshListOfFilesFragment();
1381 }
1382 }
1383
1384 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
1385 RemoteOperationResult result) {
1386 if (result.isSuccess()) {
1387 refreshShowDetails();
1388 refreshListOfFilesFragment();
1389
1390 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1391 cleanSecondFragment();
1392 refreshListOfFilesFragment();
1393 }
1394 }
1395
1396 private void refreshShowDetails() {
1397 FileFragment details = getSecondFragment();
1398 if (details != null) {
1399 OCFile file = details.getFile();
1400 if (file != null) {
1401 file = getStorageManager().getFileByPath(file.getRemotePath());
1402 if (details instanceof PreviewMediaFragment) {
1403 // Refresh OCFile of the fragment
1404 ((PreviewMediaFragment) details).updateFile(file);
1405 } else if (details instanceof PreviewTextFragment) {
1406 // Refresh OCFile of the fragment
1407 ((PreviewTextFragment) details).updateFile(file);
1408 } else {
1409 showDetails(file);
1410 }
1411 }
1412 invalidateOptionsMenu();
1413 }
1414 }
1415
1416 /**
1417 * Updates the view associated to the activity after the finish of an operation trying to
1418 * remove a file.
1419 *
1420 * @param operation Removal operation performed.
1421 * @param result Result of the removal.
1422 */
1423 private void onRemoveFileOperationFinish(RemoveFileOperation operation,
1424 RemoteOperationResult result) {
1425 dismissLoadingDialog();
1426
1427 Toast msg = Toast.makeText(this,
1428 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1429 Toast.LENGTH_LONG);
1430 msg.show();
1431
1432 if (result.isSuccess()) {
1433 OCFile removedFile = operation.getFile();
1434 FileFragment second = getSecondFragment();
1435 if (second != null && removedFile.equals(second.getFile())) {
1436 if (second instanceof PreviewMediaFragment) {
1437 ((PreviewMediaFragment) second).stopPreview(true);
1438 }
1439 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1440 cleanSecondFragment();
1441 }
1442 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())){
1443 refreshListOfFilesFragment();
1444 }
1445 invalidateOptionsMenu();
1446 } else {
1447 if (result.isSslRecoverableException()) {
1448 mLastSslUntrustedServerResult = result;
1449 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1450 }
1451 }
1452 }
1453
1454
1455 /**
1456 * Updates the view associated to the activity after the finish of an operation trying to move a
1457 * file.
1458 *
1459 * @param operation Move operation performed.
1460 * @param result Result of the move operation.
1461 */
1462 private void onMoveFileOperationFinish(MoveFileOperation operation,
1463 RemoteOperationResult result) {
1464 if (result.isSuccess()) {
1465 dismissLoadingDialog();
1466 refreshListOfFilesFragment();
1467 } else {
1468 dismissLoadingDialog();
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 dismissLoadingDialog();
1491 refreshListOfFilesFragment();
1492 } else {
1493 dismissLoadingDialog();
1494 try {
1495 Toast msg = Toast.makeText(FileDisplayActivity.this,
1496 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1497 Toast.LENGTH_LONG);
1498 msg.show();
1499
1500 } catch (NotFoundException e) {
1501 Log_OC.e(TAG, "Error while trying to show fail message ", e);
1502 }
1503 }
1504 }
1505
1506 /**
1507 * Updates the view associated to the activity after the finish of an operation trying to rename
1508 * a file.
1509 *
1510 * @param operation Renaming operation performed.
1511 * @param result Result of the renaming.
1512 */
1513 private void onRenameFileOperationFinish(RenameFileOperation operation,
1514 RemoteOperationResult result) {
1515 dismissLoadingDialog();
1516 OCFile renamedFile = operation.getFile();
1517 if (result.isSuccess()) {
1518 FileFragment details = getSecondFragment();
1519 if (details != null) {
1520 if (details instanceof FileDetailFragment &&
1521 renamedFile.equals(details.getFile()) ) {
1522 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1523 showDetails(renamedFile);
1524
1525 } else if (details instanceof PreviewMediaFragment &&
1526 renamedFile.equals(details.getFile())) {
1527 ((PreviewMediaFragment) details).updateFile(renamedFile);
1528 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1529 int position = ((PreviewMediaFragment) details).getPosition();
1530 startMediaPreview(renamedFile, position, true);
1531 } else {
1532 getFileOperationsHelper().openFile(renamedFile);
1533 }
1534 } else if (details instanceof PreviewTextFragment &&
1535 renamedFile.equals(details.getFile())) {
1536 ((PreviewTextFragment) details).updateFile(renamedFile);
1537 if (PreviewTextFragment.canBePreviewed(renamedFile)) {
1538 startTextPreview(renamedFile);
1539 } else {
1540 getFileOperationsHelper().openFile(renamedFile);
1541 }
1542 }
1543 }
1544
1545 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())){
1546 refreshListOfFilesFragment();
1547 }
1548
1549 } else {
1550 Toast msg = Toast.makeText(this,
1551 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1552 Toast.LENGTH_LONG);
1553 msg.show();
1554
1555 if (result.isSslRecoverableException()) {
1556 mLastSslUntrustedServerResult = result;
1557 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1558 }
1559 }
1560 }
1561
1562 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
1563 RemoteOperationResult result) {
1564 if (result.isSuccess()) {
1565 if (operation.transferWasRequested()) {
1566 OCFile syncedFile = operation.getLocalFile();
1567 onTransferStateChanged(syncedFile, true, true);
1568 invalidateOptionsMenu();
1569 refreshShowDetails();
1570 }
1571 }
1572 }
1573
1574 /**
1575 * Updates the view associated to the activity after the finish of an operation trying create a
1576 * new folder
1577 *
1578 * @param operation Creation operation performed.
1579 * @param result Result of the creation.
1580 */
1581 private void onCreateFolderOperationFinish(CreateFolderOperation operation,
1582 RemoteOperationResult result) {
1583 if (result.isSuccess()) {
1584 dismissLoadingDialog();
1585 refreshListOfFilesFragment();
1586 } else {
1587 dismissLoadingDialog();
1588 try {
1589 Toast msg = Toast.makeText(FileDisplayActivity.this,
1590 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1591 Toast.LENGTH_LONG);
1592 msg.show();
1593
1594 } catch (NotFoundException e) {
1595 Log_OC.e(TAG, "Error while trying to show fail message ", e);
1596 }
1597 }
1598 }
1599
1600
1601 /**
1602 * {@inheritDoc}
1603 */
1604 @Override
1605 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1606 refreshListOfFilesFragment();
1607 FileFragment details = getSecondFragment();
1608 if (details != null && details instanceof FileDetailFragment &&
1609 file.equals(details.getFile()) ) {
1610 if (downloading || uploading) {
1611 ((FileDetailFragment) details).updateFileDetails(file, getAccount());
1612 } else {
1613 if (!file.fileExists()) {
1614 cleanSecondFragment();
1615 } else {
1616 ((FileDetailFragment) details).updateFileDetails(false, true);
1617 }
1618 }
1619 }
1620
1621 }
1622
1623
1624 private void requestForDownload() {
1625 Account account = getAccount();
1626 //if (!mWaitingToPreview.isDownloading()) {
1627 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1628 Intent i = new Intent(this, FileDownloader.class);
1629 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1630 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1631 startService(i);
1632 }
1633 }
1634
1635
1636 private OCFile getCurrentDir() {
1637 OCFile file = getFile();
1638 if (file != null) {
1639 if (file.isFolder()) {
1640 return file;
1641 } else if (getStorageManager() != null) {
1642 String parentPath = file.getRemotePath().substring(0,
1643 file.getRemotePath().lastIndexOf(file.getFileName()));
1644 return getStorageManager().getFileByPath(parentPath);
1645 }
1646 }
1647 return null;
1648 }
1649
1650 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1651 long currentSyncTime = System.currentTimeMillis();
1652
1653 mSyncInProgress = true;
1654
1655 // perform folder synchronization
1656 RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
1657 currentSyncTime,
1658 false,
1659 getFileOperationsHelper().isSharedSupported(),
1660 ignoreETag,
1661 getStorageManager(),
1662 getAccount(),
1663 getApplicationContext()
1664 );
1665 synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null);
1666
1667 mProgressBar.setIndeterminate(true);
1668
1669 setBackgroundText();
1670 }
1671
1672 /**
1673 * Show untrusted cert dialog
1674 */
1675 public void showUntrustedCertDialog(RemoteOperationResult result) {
1676 // Show a dialog with the certificate info
1677 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
1678 (CertificateCombinedException) result.getException());
1679 FragmentManager fm = getSupportFragmentManager();
1680 FragmentTransaction ft = fm.beginTransaction();
1681 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1682 }
1683
1684 private void requestForDownload(OCFile file) {
1685 Account account = getAccount();
1686 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1687 Intent i = new Intent(this, FileDownloader.class);
1688 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1689 i.putExtra(FileDownloader.EXTRA_FILE, file);
1690 startService(i);
1691 }
1692 }
1693
1694 private void sendDownloadedFile() {
1695 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1696 mWaitingToSend = null;
1697 }
1698
1699
1700 /**
1701 * Requests the download of the received {@link OCFile} , updates the UI
1702 * to monitor the download progress and prepares the activity to send the file
1703 * when the download finishes.
1704 *
1705 * @param file {@link OCFile} to download and preview.
1706 */
1707 public void startDownloadForSending(OCFile file) {
1708 mWaitingToSend = file;
1709 requestForDownload(mWaitingToSend);
1710 boolean hasSecondFragment = (getSecondFragment() != null);
1711 updateFragmentsVisibility(hasSecondFragment);
1712 }
1713
1714 /**
1715 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1716 *
1717 * @param file Image {@link OCFile} to show.
1718 */
1719 public void startImagePreview(OCFile file) {
1720 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1721 showDetailsIntent.putExtra(EXTRA_FILE, file);
1722 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1723 startActivity(showDetailsIntent);
1724 }
1725
1726 /**
1727 * Stars the preview of an already down media {@link OCFile}.
1728 *
1729 * @param file Media {@link OCFile} to preview.
1730 * @param startPlaybackPosition Media position where the playback will be started,
1731 * in milliseconds.
1732 * @param autoplay When 'true', the playback will start without user
1733 * interactions.
1734 */
1735 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1736 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition,
1737 autoplay);
1738 setSecondFragment(mediaFragment);
1739 updateFragmentsVisibility(true);
1740 updateActionBarTitleAndHomeButton(file);
1741 setFile(file);
1742 }
1743
1744 /**
1745 * Stars the preview of a text file {@link OCFile}.
1746 *
1747 * @param file Text {@link OCFile} to preview.
1748 */
1749 public void startTextPreview(OCFile file) {
1750 Bundle args = new Bundle();
1751 args.putParcelable(EXTRA_FILE, file);
1752 args.putParcelable(EXTRA_ACCOUNT, getAccount());
1753 Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
1754 PreviewTextFragment.class.getName(), args);
1755 setSecondFragment(textPreviewFragment);
1756 updateFragmentsVisibility(true);
1757 //updateNavigationElementsInActionBar(file);
1758 setFile(file);
1759 }
1760
1761 /**
1762 * Requests the download of the received {@link OCFile} , updates the UI
1763 * to monitor the download progress and prepares the activity to preview
1764 * or open the file when the download finishes.
1765 *
1766 * @param file {@link OCFile} to download and preview.
1767 */
1768 public void startDownloadForPreview(OCFile file) {
1769 Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
1770 setSecondFragment(detailFragment);
1771 mWaitingToPreview = file;
1772 requestForDownload();
1773 updateFragmentsVisibility(true);
1774 updateActionBarTitleAndHomeButton(file);
1775 setFile(file);
1776 }
1777
1778
1779 public void cancelTransference(OCFile file) {
1780 getFileOperationsHelper().cancelTransference(file);
1781 if (mWaitingToPreview != null &&
1782 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1783 mWaitingToPreview = null;
1784 }
1785 if (mWaitingToSend != null &&
1786 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1787 mWaitingToSend = null;
1788 }
1789 onTransferStateChanged(file, false, false);
1790 }
1791
1792 @Override
1793 public void onRefresh(boolean ignoreETag) {
1794 refreshList(ignoreETag);
1795 }
1796
1797 @Override
1798 public void onRefresh() {
1799 refreshList(true);
1800 }
1801
1802 private void refreshList(boolean ignoreETag) {
1803 OCFileListFragment listOfFiles = getListOfFilesFragment();
1804 if (listOfFiles != null) {
1805 OCFile folder = listOfFiles.getCurrentFile();
1806 if (folder != null) {
1807 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1808 listDirectory(mFile);*/
1809 startSyncFolderOperation(folder, ignoreETag);
1810 }
1811 }
1812 }
1813
1814 private void sortByDate(boolean ascending) {
1815 getListOfFilesFragment().sortByDate(ascending);
1816 }
1817
1818 private void sortBySize(boolean ascending) {
1819 getListOfFilesFragment().sortBySize(ascending);
1820 }
1821
1822 private void sortByName(boolean ascending) {
1823 getListOfFilesFragment().sortByName(ascending);
1824 }
1825
1826 public void allFilesOption() {
1827 browseToRoot();
1828 }
1829 }