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