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