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