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