193d5d6825bc2bd2b67ffa503446e2b754ec19f9
[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 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
524 mDrawerLayout.closeDrawer(GravityCompat.START);
525 } else {
526 mDrawerLayout.openDrawer(GravityCompat.START);
527 }
528 break;
529 }
530 case R.id.action_sort: {
531 SharedPreferences appPreferences = PreferenceManager
532 .getDefaultSharedPreferences(this);
533
534 // Read sorting order, default to sort by name ascending
535 Integer sortOrder = appPreferences
536 .getInt("sortOrder", FileStorageUtils.SORT_NAME);
537
538 AlertDialog.Builder builder = new AlertDialog.Builder(this);
539 builder.setTitle(R.string.actionbar_sort_title)
540 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder ,
541 new DialogInterface.OnClickListener() {
542 public void onClick(DialogInterface dialog, int which) {
543 switch (which){
544 case 0:
545 sortByName(true);
546 break;
547 case 1:
548 sortByDate(false);
549 break;
550 }
551
552 dialog.dismiss();
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),
691 Toast.LENGTH_LONG);
692 t.show();
693 return;
694 }
695 }
696
697
698 private void requestSimpleUpload(Intent data, int resultCode) {
699 String filePath = null;
700 String mimeType = null;
701
702 Uri selectedImageUri = data.getData();
703
704 try {
705 mimeType = getContentResolver().getType(selectedImageUri);
706
707 String fileManagerString = selectedImageUri.getPath();
708 String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);
709
710 if (selectedImagePath != null)
711 filePath = selectedImagePath;
712 else
713 filePath = fileManagerString;
714
715 } catch (Exception e) {
716 Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
717 "Intent.ACTION_GET_CONTENT", e);
718
719 } finally {
720 if (filePath == null) {
721 Log_OC.e(TAG, "Couldn't resolve path to file");
722 Toast t = Toast.makeText(
723 this, getString(R.string.filedisplay_unexpected_bad_get_content),
724 Toast.LENGTH_LONG
725 );
726 t.show();
727 return;
728 }
729 }
730
731 Intent i = new Intent(this, FileUploader.class);
732 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
733 OCFile currentDir = getCurrentDir();
734 String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
735
736 if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
737 Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
738 try {
739 if (cursor != null && cursor.moveToFirst()) {
740 String displayName = cursor.getString(cursor.getColumnIndex(
741 OpenableColumns.DISPLAY_NAME));
742 Log_OC.v(TAG, "Display Name: " + displayName );
743
744 displayName.replace(File.separatorChar, '_');
745 displayName.replace(File.pathSeparatorChar, '_');
746 remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);
747
748 }
749 // and what happens in case of error?; wrong target name for the upload
750 } finally {
751 cursor.close();
752 }
753
754 } else {
755 remotePath += new File(filePath).getName();
756 }
757
758 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
759 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
760 i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
761 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
762 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
763 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
764 startService(i);
765 }
766
767 /**
768 * Request the operation for moving the file/folder from one path to another
769 *
770 * @param data Intent received
771 * @param resultCode Result code received
772 */
773 private void requestMoveOperation(Intent data, int resultCode) {
774 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
775 OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
776 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
777 }
778
779 @Override
780 public void onBackPressed() {
781 OCFileListFragment listOfFiles = getListOfFilesFragment();
782 if (mDualPane || getSecondFragment() == null) {
783 if (listOfFiles != null) { // should never be null, indeed
784 if (mDirectories.getCount() <= 1) {
785 finish();
786 return;
787 }
788 int levelsUp = listOfFiles.onBrowseUp();
789 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
790 popDirname();
791 }
792 }
793 }
794 if (listOfFiles != null) { // should never be null, indeed
795 setFile(listOfFiles.getCurrentFile());
796 }
797 cleanSecondFragment();
798
799 }
800
801 @Override
802 protected void onSaveInstanceState(Bundle outState) {
803 // responsibility of restore is preferred in onCreate() before than in
804 // onRestoreInstanceState when there are Fragments involved
805 Log_OC.v(TAG, "onSaveInstanceState() start");
806 super.onSaveInstanceState(outState);
807 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
808 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
809 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
810 // mRefreshSharesInProgress);
811 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
812
813 Log_OC.v(TAG, "onSaveInstanceState() end");
814 }
815
816
817
818 @Override
819 protected void onResume() {
820 Log_OC.v(TAG, "onResume() start");
821 super.onResume();
822
823 // refresh Navigation Drawer account list
824 mNavigationDrawerAdapter.updateAccountList();
825
826 // refresh list of files
827 refreshListOfFilesFragment();
828
829 // Listen for sync messages
830 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
831 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
832 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
833 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
834 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
835 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
836 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
837 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
838 // syncIntentFilter);
839
840 // Listen for upload messages
841 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
842 mUploadFinishReceiver = new UploadFinishReceiver();
843 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
844
845 // Listen for download messages
846 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
847 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
848 mDownloadFinishReceiver = new DownloadFinishReceiver();
849 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
850
851 Log_OC.v(TAG, "onResume() end");
852 }
853
854
855 @Override
856 protected void onPause() {
857 Log_OC.v(TAG, "onPause() start");
858 if (mSyncBroadcastReceiver != null) {
859 unregisterReceiver(mSyncBroadcastReceiver);
860 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
861 mSyncBroadcastReceiver = null;
862 }
863 if (mUploadFinishReceiver != null) {
864 unregisterReceiver(mUploadFinishReceiver);
865 mUploadFinishReceiver = null;
866 }
867 if (mDownloadFinishReceiver != null) {
868 unregisterReceiver(mDownloadFinishReceiver);
869 mDownloadFinishReceiver = null;
870 }
871
872 super.onPause();
873 Log_OC.v(TAG, "onPause() end");
874 }
875
876 /**
877 * Pushes a directory to the drop down list
878 * @param directory to push
879 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
880 */
881 public void pushDirname(OCFile directory) {
882 if(!directory.isFolder()){
883 throw new IllegalArgumentException("Only directories may be pushed!");
884 }
885 mDirectories.insert(directory.getFileName(), 0);
886 setFile(directory);
887 }
888
889 /**
890 * Pops a directory name from the drop down list
891 * @return True, unless the stack is empty
892 */
893 public boolean popDirname() {
894 mDirectories.remove(mDirectories.getItem(0));
895 return !mDirectories.isEmpty();
896 }
897
898 // Custom array adapter to override text colors
899 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
900
901 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
902 super(ctx, view);
903 }
904
905 public View getView(int position, View convertView, ViewGroup parent) {
906 View v = super.getView(position, convertView, parent);
907
908 ((TextView) v).setTextColor(getResources().getColorStateList(
909 android.R.color.white));
910
911 fixRoot((TextView) v );
912 return v;
913 }
914
915 public View getDropDownView(int position, View convertView,
916 ViewGroup parent) {
917 View v = super.getDropDownView(position, convertView, parent);
918
919 ((TextView) v).setTextColor(getResources().getColorStateList(
920 android.R.color.white));
921
922 fixRoot((TextView) v );
923 return v;
924 }
925
926 private void fixRoot(TextView v) {
927 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
928 v.setText(R.string.default_display_name_for_root_folder);
929 }
930 }
931
932 }
933
934 private class SyncBroadcastReceiver extends BroadcastReceiver {
935
936 /**
937 * {@link BroadcastReceiver} to enable syncing feedback in UI
938 */
939 @Override
940 public void onReceive(Context context, Intent intent) {
941 try {
942 String event = intent.getAction();
943 Log_OC.d(TAG, "Received broadcast " + event);
944 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
945 String synchFolderRemotePath =
946 intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
947 RemoteOperationResult synchResult =
948 (RemoteOperationResult)intent.getSerializableExtra(
949 FileSyncAdapter.EXTRA_RESULT);
950 boolean sameAccount = (getAccount() != null &&
951 accountName.equals(getAccount().name) && getStorageManager() != null);
952
953 if (sameAccount) {
954
955 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
956 mSyncInProgress = true;
957
958 } else {
959 OCFile currentFile = (getFile() == null) ? null :
960 getStorageManager().getFileByPath(getFile().getRemotePath());
961 OCFile currentDir = (getCurrentDir() == null) ? null :
962 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
963
964 if (currentDir == null) {
965 // current folder was removed from the server
966 Toast.makeText( FileDisplayActivity.this,
967 String.format(
968 getString(R.string.sync_current_folder_was_removed),
969 mDirectories.getItem(0)),
970 Toast.LENGTH_LONG)
971 .show();
972 browseToRoot();
973
974 } else {
975 if (currentFile == null && !getFile().isFolder()) {
976 // currently selected file was removed in the server, and now we
977 // know it
978 cleanSecondFragment();
979 currentFile = currentDir;
980 }
981
982 if (synchFolderRemotePath != null &&
983 currentDir.getRemotePath().equals(synchFolderRemotePath)) {
984 OCFileListFragment fileListFragment = getListOfFilesFragment();
985 if (fileListFragment != null) {
986 fileListFragment.listDirectory();
987 // TODO Enable when "On Device" is recovered ?
988 // fileListFragment.listDirectory(currentDir,
989 // MainApp.getOnlyOnDevice());
990 }
991 }
992 setFile(currentFile);
993 }
994
995 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
996 !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
997 .equals(event));
998
999 if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
1000 equals(event) &&
1001 /// TODO refactor and make common
1002 synchResult != null && !synchResult.isSuccess() &&
1003 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
1004 synchResult.isIdPRedirection() ||
1005 (synchResult.isException() && synchResult.getException()
1006 instanceof AuthenticatorException))) {
1007
1008
1009 try {
1010 OwnCloudClient client;
1011 OwnCloudAccount ocAccount =
1012 new OwnCloudAccount(getAccount(), context);
1013 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1014 removeClientFor(ocAccount));
1015
1016 if (client != null) {
1017 OwnCloudCredentials cred = client.getCredentials();
1018 if (cred != null) {
1019 AccountManager am = AccountManager.get(context);
1020 if (cred.authTokenExpires()) {
1021 am.invalidateAuthToken(
1022 getAccount().type,
1023 cred.getAuthToken()
1024 );
1025 } else {
1026 am.clearPassword(getAccount());
1027 }
1028 }
1029 }
1030 requestCredentialsUpdate();
1031
1032 } catch (AccountNotFoundException e) {
1033 Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
1034 }
1035
1036 }
1037 }
1038 removeStickyBroadcast(intent);
1039 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1040 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1041 /*|| mRefreshSharesInProgress*/);
1042
1043 setBackgroundText();
1044
1045 }
1046
1047 if (synchResult != null) {
1048 if (synchResult.getCode().equals(
1049 RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1050 mLastSslUntrustedServerResult = synchResult;
1051 }
1052 }
1053 } catch (RuntimeException e) {
1054 // avoid app crashes after changing the serial id of RemoteOperationResult
1055 // in owncloud library with broadcast notifications pending to process
1056 removeStickyBroadcast(intent);
1057 }
1058 }
1059 }
1060
1061 /**
1062 * Show a text message on screen view for notifying user if content is
1063 * loading or folder is empty
1064 */
1065 private void setBackgroundText() {
1066 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1067 if (ocFileListFragment != null) {
1068 int message = R.string.file_list_loading;
1069 if (!mSyncInProgress) {
1070 // In case file list is empty
1071 message = R.string.file_list_empty;
1072 }
1073 ocFileListFragment.setMessageForEmptyList(getString(message));
1074 } else {
1075 Log_OC.e(TAG, "OCFileListFragment is null");
1076 }
1077 }
1078
1079 /**
1080 * Once the file upload has finished -> update view
1081 */
1082 private class UploadFinishReceiver extends BroadcastReceiver {
1083 /**
1084 * Once the file upload has finished -> update view
1085 * @author David A. Velasco
1086 * {@link BroadcastReceiver} to enable upload feedback in UI
1087 */
1088 @Override
1089 public void onReceive(Context context, Intent intent) {
1090 try {
1091 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1092 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1093 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1094 OCFile currentDir = getCurrentDir();
1095 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1096 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1097
1098 if (sameAccount && isDescendant) {
1099 refreshListOfFilesFragment();
1100 }
1101
1102 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT,
1103 false);
1104 boolean renamedInUpload = getFile().getRemotePath().
1105 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1106 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1107 renamedInUpload;
1108 FileFragment details = getSecondFragment();
1109 boolean detailFragmentIsShown = (details != null &&
1110 details instanceof FileDetailFragment);
1111
1112 if (sameAccount && sameFile && detailFragmentIsShown) {
1113 if (uploadWasFine) {
1114 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1115 }
1116 if (renamedInUpload) {
1117 String newName = (new File(uploadedRemotePath)).getName();
1118 Toast msg = Toast.makeText(
1119 context,
1120 String.format(
1121 getString(R.string.filedetails_renamed_in_upload_msg),
1122 newName),
1123 Toast.LENGTH_LONG);
1124 msg.show();
1125 }
1126 if (uploadWasFine || getFile().fileExists()) {
1127 ((FileDetailFragment)details).updateFileDetails(false, true);
1128 } else {
1129 cleanSecondFragment();
1130 }
1131
1132 // Force the preview if the file is an image
1133 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1134 startImagePreview(getFile());
1135 } // TODO what about other kind of previews?
1136 }
1137
1138 } finally {
1139 if (intent != null) {
1140 removeStickyBroadcast(intent);
1141 }
1142 }
1143
1144 }
1145
1146 }
1147
1148
1149 /**
1150 * Class waiting for broadcast events from the {@link FileDownloader} service.
1151 *
1152 * Updates the UI when a download is started or finished, provided that it is relevant for the
1153 * current folder.
1154 */
1155 private class DownloadFinishReceiver extends BroadcastReceiver {
1156
1157 //int refreshCounter = 0;
1158 @Override
1159 public void onReceive(Context context, Intent intent) {
1160 try {
1161 boolean sameAccount = isSameAccount(context, intent);
1162 String downloadedRemotePath =
1163 intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1164 boolean isDescendant = isDescendant(downloadedRemotePath);
1165
1166 if (sameAccount && isDescendant) {
1167 String linkedToRemotePath =
1168 intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
1169 if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
1170 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1171 refreshListOfFilesFragment();
1172 }
1173 refreshSecondFragment(
1174 intent.getAction(),
1175 downloadedRemotePath,
1176 intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
1177 );
1178 }
1179
1180 if (mWaitingToSend != null) {
1181 mWaitingToSend =
1182 getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
1183 if (mWaitingToSend.isDown()) {
1184 sendDownloadedFile();
1185 }
1186 }
1187
1188 } finally {
1189 if (intent != null) {
1190 removeStickyBroadcast(intent);
1191 }
1192 }
1193 }
1194
1195 private boolean isDescendant(String downloadedRemotePath) {
1196 OCFile currentDir = getCurrentDir();
1197 return (
1198 currentDir != null &&
1199 downloadedRemotePath != null &&
1200 downloadedRemotePath.startsWith(currentDir.getRemotePath())
1201 );
1202 }
1203
1204 private boolean isAscendant(String linkedToRemotePath) {
1205 OCFile currentDir = getCurrentDir();
1206 return (
1207 currentDir != null &&
1208 currentDir.getRemotePath().startsWith(linkedToRemotePath)
1209 );
1210 }
1211
1212 private boolean isSameAccount(Context context, Intent intent) {
1213 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1214 return (accountName != null && getAccount() != null &&
1215 accountName.equals(getAccount().name));
1216 }
1217 }
1218
1219
1220 public void browseToRoot() {
1221 OCFileListFragment listOfFiles = getListOfFilesFragment();
1222 if (listOfFiles != null) { // should never be null, indeed
1223 while (mDirectories.getCount() > 1) {
1224 popDirname();
1225 }
1226 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1227 listOfFiles.listDirectory(root);
1228 // TODO Enable when "On Device" is recovered ?
1229 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1230 setFile(listOfFiles.getCurrentFile());
1231 startSyncFolderOperation(root, false);
1232 }
1233 cleanSecondFragment();
1234 }
1235
1236
1237 public void browseTo(OCFile folder) {
1238 if (folder == null || !folder.isFolder()) {
1239 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1240 }
1241 OCFileListFragment listOfFiles = getListOfFilesFragment();
1242 if (listOfFiles != null) {
1243 setNavigationListWithFolder(folder);
1244 listOfFiles.listDirectory(folder);
1245 // TODO Enable when "On Device" is recovered ?
1246 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1247 setFile(listOfFiles.getCurrentFile());
1248 startSyncFolderOperation(folder, false);
1249 } else {
1250 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1251 }
1252 cleanSecondFragment();
1253 }
1254
1255
1256 /**
1257 * {@inheritDoc}
1258 *
1259 * Updates action bar and second fragment, if in dual pane mode.
1260 */
1261 @Override
1262 public void onBrowsedDownTo(OCFile directory) {
1263 pushDirname(directory);
1264 cleanSecondFragment();
1265
1266 // Sync Folder
1267 startSyncFolderOperation(directory, false);
1268
1269 }
1270
1271 /**
1272 * Shows the information of the {@link OCFile} received as a
1273 * parameter in the second fragment.
1274 *
1275 * @param file {@link OCFile} whose details will be shown
1276 */
1277 @Override
1278 public void showDetails(OCFile file) {
1279 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1280 setSecondFragment(detailFragment);
1281 updateFragmentsVisibility(true);
1282 updateNavigationElementsInActionBar(file);
1283 setFile(file);
1284 }
1285
1286
1287 /**
1288 * TODO
1289 */
1290 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1291 ActionBar actionBar = getSupportActionBar();
1292
1293 // For adding content description tag to a title field in the action bar
1294 int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
1295
1296 if (chosenFile == null || mDualPane) {
1297 // only list of files - set for browsing through folders
1298 OCFile currentDir = getCurrentDir();
1299 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1300 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1301 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1302 actionBar.setDisplayHomeAsUpEnabled(true);
1303 actionBar.setDisplayShowTitleEnabled(true);
1304 if (!noRoot) {
1305 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1306 View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
1307 if (actionBarTitleView != null) { // it's null in Android 2.x
1308 actionBarTitleView.setContentDescription(
1309 getString(R.string.default_display_name_for_root_folder));
1310 }
1311 }
1312 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD :
1313 ActionBar.NAVIGATION_MODE_LIST);
1314 actionBar.setListNavigationCallbacks(mDirectories, this);
1315 // assuming mDirectories is updated
1316
1317 } else {
1318 actionBar.setDisplayHomeAsUpEnabled(true);
1319 actionBar.setDisplayShowTitleEnabled(true);
1320 actionBar.setTitle(chosenFile.getFileName());
1321 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1322 View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
1323 if (actionBarTitleView != null) { // it's null in Android 2.x
1324 getWindow().getDecorView().findViewById(actionBarTitleId).
1325 setContentDescription(chosenFile.getFileName());
1326 }
1327 }
1328 }
1329
1330
1331 @Override
1332 protected ServiceConnection newTransferenceServiceConnection() {
1333 return new ListServiceConnection();
1334 }
1335
1336 /** Defines callbacks for service binding, passed to bindService() */
1337 private class ListServiceConnection implements ServiceConnection {
1338
1339 @Override
1340 public void onServiceConnected(ComponentName component, IBinder service) {
1341 if (component.equals(new ComponentName(
1342 FileDisplayActivity.this, FileDownloader.class))) {
1343 Log_OC.d(TAG, "Download service connected");
1344 mDownloaderBinder = (FileDownloaderBinder) service;
1345 if (mWaitingToPreview != null)
1346 if (getStorageManager() != null) {
1347 // update the file
1348 mWaitingToPreview =
1349 getStorageManager().getFileById(mWaitingToPreview.getFileId());
1350 if (!mWaitingToPreview.isDown()) {
1351 requestForDownload();
1352 }
1353 }
1354
1355 } else if (component.equals(new ComponentName(FileDisplayActivity.this,
1356 FileUploader.class))) {
1357 Log_OC.d(TAG, "Upload service connected");
1358 mUploaderBinder = (FileUploaderBinder) service;
1359 } else {
1360 return;
1361 }
1362 // a new chance to get the mDownloadBinder through
1363 // getFileDownloadBinder() - THIS IS A MESS
1364 OCFileListFragment listOfFiles = getListOfFilesFragment();
1365 if (listOfFiles != null) {
1366 listOfFiles.listDirectory();
1367 // TODO Enable when "On Device" is recovered ?
1368 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1369 }
1370 FileFragment secondFragment = getSecondFragment();
1371 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1372 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1373 detailFragment.listenForTransferProgress();
1374 detailFragment.updateFileDetails(false, false);
1375 }
1376 }
1377
1378 @Override
1379 public void onServiceDisconnected(ComponentName component) {
1380 if (component.equals(new ComponentName(FileDisplayActivity.this,
1381 FileDownloader.class))) {
1382 Log_OC.d(TAG, "Download service disconnected");
1383 mDownloaderBinder = null;
1384 } else if (component.equals(new ComponentName(FileDisplayActivity.this,
1385 FileUploader.class))) {
1386 Log_OC.d(TAG, "Upload service disconnected");
1387 mUploaderBinder = null;
1388 }
1389 }
1390 };
1391
1392 @Override
1393 public void onSavedCertificate() {
1394 startSyncFolderOperation(getCurrentDir(), false);
1395 }
1396
1397
1398 @Override
1399 public void onFailedSavingCertificate() {
1400 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
1401 R.string.ssl_validator_not_saved, new String[]{}, R.string.common_ok, -1, -1
1402 );
1403 dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
1404 }
1405
1406 @Override
1407 public void onCancelCertificate() {
1408 // nothing to do
1409 }
1410
1411 /**
1412 * Updates the view associated to the activity after the finish of some operation over files
1413 * in the current account.
1414 *
1415 * @param operation Removal operation performed.
1416 * @param result Result of the removal.
1417 */
1418 @Override
1419 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1420 super.onRemoteOperationFinish(operation, result);
1421
1422 if (operation instanceof RemoveFileOperation) {
1423 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1424
1425 } else if (operation instanceof RenameFileOperation) {
1426 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1427
1428 } else if (operation instanceof SynchronizeFileOperation) {
1429 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1430
1431 } else if (operation instanceof CreateFolderOperation) {
1432 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1433
1434 } else if (operation instanceof CreateShareOperation) {
1435 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1436
1437 } else if (operation instanceof UnshareLinkOperation) {
1438 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1439
1440 } else if (operation instanceof MoveFileOperation) {
1441 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1442 }
1443
1444 }
1445
1446
1447 private void onCreateShareOperationFinish(CreateShareOperation operation,
1448 RemoteOperationResult result) {
1449 if (result.isSuccess()) {
1450 refreshShowDetails();
1451 refreshListOfFilesFragment();
1452 }
1453 }
1454
1455
1456 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
1457 RemoteOperationResult result) {
1458 if (result.isSuccess()) {
1459 refreshShowDetails();
1460 refreshListOfFilesFragment();
1461
1462 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1463 cleanSecondFragment();
1464 refreshListOfFilesFragment();
1465 }
1466 }
1467
1468 private void refreshShowDetails() {
1469 FileFragment details = getSecondFragment();
1470 if (details != null) {
1471 OCFile file = details.getFile();
1472 if (file != null) {
1473 file = getStorageManager().getFileByPath(file.getRemotePath());
1474 if (details instanceof PreviewMediaFragment) {
1475 // Refresh OCFile of the fragment
1476 ((PreviewMediaFragment) details).updateFile(file);
1477 } else {
1478 showDetails(file);
1479 }
1480 }
1481 invalidateOptionsMenu();
1482 }
1483 }
1484
1485 /**
1486 * Updates the view associated to the activity after the finish of an operation trying to
1487 * remove a file.
1488 *
1489 * @param operation Removal operation performed.
1490 * @param result Result of the removal.
1491 */
1492 private void onRemoveFileOperationFinish(RemoveFileOperation operation,
1493 RemoteOperationResult result) {
1494 dismissLoadingDialog();
1495
1496 Toast msg = Toast.makeText(this,
1497 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1498 Toast.LENGTH_LONG);
1499 msg.show();
1500
1501 if (result.isSuccess()) {
1502 OCFile removedFile = operation.getFile();
1503 FileFragment second = getSecondFragment();
1504 if (second != null && removedFile.equals(second.getFile())) {
1505 if (second instanceof PreviewMediaFragment) {
1506 ((PreviewMediaFragment)second).stopPreview(true);
1507 }
1508 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1509 cleanSecondFragment();
1510 }
1511 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1512 refreshListOfFilesFragment();
1513 }
1514 invalidateOptionsMenu();
1515 } else {
1516 if (result.isSslRecoverableException()) {
1517 mLastSslUntrustedServerResult = result;
1518 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1519 }
1520 }
1521 }
1522
1523
1524 /**
1525 * Updates the view associated to the activity after the finish of an operation trying to move a
1526 * file.
1527 *
1528 * @param operation Move operation performed.
1529 * @param result Result of the move operation.
1530 */
1531 private void onMoveFileOperationFinish(MoveFileOperation operation,
1532 RemoteOperationResult result) {
1533 if (result.isSuccess()) {
1534 dismissLoadingDialog();
1535 refreshListOfFilesFragment();
1536 } else {
1537 dismissLoadingDialog();
1538 try {
1539 Toast msg = Toast.makeText(FileDisplayActivity.this,
1540 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1541 Toast.LENGTH_LONG);
1542 msg.show();
1543
1544 } catch (NotFoundException e) {
1545 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1546 }
1547 }
1548 }
1549
1550
1551 /**
1552 * Updates the view associated to the activity after the finish of an operation trying to rename
1553 * a file.
1554 *
1555 * @param operation Renaming operation performed.
1556 * @param result Result of the renaming.
1557 */
1558 private void onRenameFileOperationFinish(RenameFileOperation operation,
1559 RemoteOperationResult result) {
1560 dismissLoadingDialog();
1561 OCFile renamedFile = operation.getFile();
1562 if (result.isSuccess()) {
1563 FileFragment details = getSecondFragment();
1564 if (details != null) {
1565 if (details instanceof FileDetailFragment &&
1566 renamedFile.equals(details.getFile()) ) {
1567 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1568 showDetails(renamedFile);
1569
1570 } else if (details instanceof PreviewMediaFragment &&
1571 renamedFile.equals(details.getFile())) {
1572 ((PreviewMediaFragment) details).updateFile(renamedFile);
1573 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1574 int position = ((PreviewMediaFragment)details).getPosition();
1575 startMediaPreview(renamedFile, position, true);
1576 } else {
1577 getFileOperationsHelper().openFile(renamedFile);
1578 }
1579 }
1580 }
1581
1582 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())){
1583 refreshListOfFilesFragment();
1584 }
1585
1586 } else {
1587 Toast msg = Toast.makeText(this,
1588 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1589 Toast.LENGTH_LONG);
1590 msg.show();
1591
1592 if (result.isSslRecoverableException()) {
1593 mLastSslUntrustedServerResult = result;
1594 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1595 }
1596 }
1597 }
1598
1599 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
1600 RemoteOperationResult result) {
1601 dismissLoadingDialog();
1602 OCFile syncedFile = operation.getLocalFile();
1603 if (!result.isSuccess()) {
1604 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1605 Intent i = new Intent(this, ConflictsResolveActivity.class);
1606 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1607 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1608 startActivity(i);
1609
1610 }
1611
1612 } else {
1613 if (operation.transferWasRequested()) {
1614 onTransferStateChanged(syncedFile, true, true);
1615
1616 } else {
1617 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
1618 operation, getResources()), Toast.LENGTH_LONG);
1619 msg.show();
1620 }
1621 }
1622 }
1623
1624 /**
1625 * Updates the view associated to the activity after the finish of an operation trying create a
1626 * new folder
1627 *
1628 * @param operation Creation operation performed.
1629 * @param result Result of the creation.
1630 */
1631 private void onCreateFolderOperationFinish(CreateFolderOperation operation,
1632 RemoteOperationResult result) {
1633 if (result.isSuccess()) {
1634 dismissLoadingDialog();
1635 refreshListOfFilesFragment();
1636 } else {
1637 dismissLoadingDialog();
1638 try {
1639 Toast msg = Toast.makeText(FileDisplayActivity.this,
1640 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1641 Toast.LENGTH_LONG);
1642 msg.show();
1643
1644 } catch (NotFoundException e) {
1645 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1646 }
1647 }
1648 }
1649
1650
1651 /**
1652 * {@inheritDoc}
1653 */
1654 @Override
1655 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1656 refreshListOfFilesFragment();
1657 FileFragment details = getSecondFragment();
1658 if (details != null && details instanceof FileDetailFragment &&
1659 file.equals(details.getFile()) ) {
1660 if (downloading || uploading) {
1661 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1662 } else {
1663 if (!file.fileExists()) {
1664 cleanSecondFragment();
1665 } else {
1666 ((FileDetailFragment)details).updateFileDetails(false, true);
1667 }
1668 }
1669 }
1670
1671 }
1672
1673
1674 private void requestForDownload() {
1675 Account account = getAccount();
1676 //if (!mWaitingToPreview.isDownloading()) {
1677 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1678 Intent i = new Intent(this, FileDownloader.class);
1679 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1680 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1681 startService(i);
1682 }
1683 }
1684
1685
1686 private OCFile getCurrentDir() {
1687 OCFile file = getFile();
1688 if (file != null) {
1689 if (file.isFolder()) {
1690 return file;
1691 } else if (getStorageManager() != null) {
1692 String parentPath = file.getRemotePath().substring(0,
1693 file.getRemotePath().lastIndexOf(file.getFileName()));
1694 return getStorageManager().getFileByPath(parentPath);
1695 }
1696 }
1697 return null;
1698 }
1699
1700 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1701 long currentSyncTime = System.currentTimeMillis();
1702
1703 mSyncInProgress = true;
1704
1705 // perform folder synchronization
1706 RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
1707 currentSyncTime,
1708 false,
1709 getFileOperationsHelper().isSharedSupported(),
1710 ignoreETag,
1711 getStorageManager(),
1712 getAccount(),
1713 getApplicationContext()
1714 );
1715 synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null);
1716
1717 setSupportProgressBarIndeterminateVisibility(true);
1718
1719 setBackgroundText();
1720 }
1721
1722 /**
1723 * Show untrusted cert dialog
1724 */
1725 public void showUntrustedCertDialog(RemoteOperationResult result) {
1726 // Show a dialog with the certificate info
1727 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
1728 (CertificateCombinedException) result.getException());
1729 FragmentManager fm = getSupportFragmentManager();
1730 FragmentTransaction ft = fm.beginTransaction();
1731 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1732 }
1733
1734 private void requestForDownload(OCFile file) {
1735 Account account = getAccount();
1736 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1737 Intent i = new Intent(this, FileDownloader.class);
1738 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1739 i.putExtra(FileDownloader.EXTRA_FILE, file);
1740 startService(i);
1741 }
1742 }
1743
1744 private void sendDownloadedFile(){
1745 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1746 mWaitingToSend = null;
1747 }
1748
1749
1750 /**
1751 * Requests the download of the received {@link OCFile} , updates the UI
1752 * to monitor the download progress and prepares the activity to send the file
1753 * when the download finishes.
1754 *
1755 * @param file {@link OCFile} to download and preview.
1756 */
1757 public void startDownloadForSending(OCFile file) {
1758 mWaitingToSend = file;
1759 requestForDownload(mWaitingToSend);
1760 boolean hasSecondFragment = (getSecondFragment()!= null);
1761 updateFragmentsVisibility(hasSecondFragment);
1762 }
1763
1764 /**
1765 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1766 *
1767 * @param file Image {@link OCFile} to show.
1768 */
1769 public void startImagePreview(OCFile file) {
1770 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1771 showDetailsIntent.putExtra(EXTRA_FILE, file);
1772 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1773 startActivity(showDetailsIntent);
1774
1775 }
1776
1777 /**
1778 * Stars the preview of an already down media {@link OCFile}.
1779 *
1780 * @param file Media {@link OCFile} to preview.
1781 * @param startPlaybackPosition Media position where the playback will be started,
1782 * in milliseconds.
1783 * @param autoplay When 'true', the playback will start without user
1784 * interactions.
1785 */
1786 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1787 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition,
1788 autoplay);
1789 setSecondFragment(mediaFragment);
1790 updateFragmentsVisibility(true);
1791 updateNavigationElementsInActionBar(file);
1792 setFile(file);
1793 }
1794
1795 /**
1796 * Requests the download of the received {@link OCFile} , updates the UI
1797 * to monitor the download progress and prepares the activity to preview
1798 * or open the file when the download finishes.
1799 *
1800 * @param file {@link OCFile} to download and preview.
1801 */
1802 public void startDownloadForPreview(OCFile file) {
1803 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1804 setSecondFragment(detailFragment);
1805 mWaitingToPreview = file;
1806 requestForDownload();
1807 updateFragmentsVisibility(true);
1808 updateNavigationElementsInActionBar(file);
1809 setFile(file);
1810 }
1811
1812
1813 public void cancelTransference(OCFile file) {
1814 getFileOperationsHelper().cancelTransference(file);
1815 if (mWaitingToPreview != null &&
1816 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1817 mWaitingToPreview = null;
1818 }
1819 if (mWaitingToSend != null &&
1820 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1821 mWaitingToSend = null;
1822 }
1823 onTransferStateChanged(file, false, false);
1824 }
1825
1826 @Override
1827 public void onRefresh(boolean ignoreETag) {
1828 refreshList(ignoreETag);
1829 }
1830
1831 @Override
1832 public void onRefresh() {
1833 refreshList(true);
1834 }
1835
1836 private void refreshList(boolean ignoreETag) {
1837 OCFileListFragment listOfFiles = getListOfFilesFragment();
1838 if (listOfFiles != null) {
1839 OCFile folder = listOfFiles.getCurrentFile();
1840 if (folder != null) {
1841 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1842 listDirectory(mFile);*/
1843 startSyncFolderOperation(folder, ignoreETag);
1844 }
1845 }
1846 }
1847
1848 private void sortByDate(boolean ascending){
1849 getListOfFilesFragment().sortByDate(ascending);
1850 }
1851
1852 private void sortBySize(boolean ascending){
1853 getListOfFilesFragment().sortBySize(ascending);
1854 }
1855
1856 private void sortByName(boolean ascending){
1857 getListOfFilesFragment().sortByName(ascending);
1858 }
1859
1860 public void allFilesOption() {
1861 browseToRoot();
1862 }
1863 }