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