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