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