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