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