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