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