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