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