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