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