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