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