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