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