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