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