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