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