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