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