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