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