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