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