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