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