Merge branch 'develop' into sorting_files_2
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22 import java.io.IOException;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AuthenticatorException;
27 import android.accounts.OperationCanceledException;
28 import android.app.AlertDialog;
29 import android.app.Dialog;
30 import android.app.ProgressDialog;
31 import android.content.BroadcastReceiver;
32 import android.content.ComponentName;
33 import android.content.ContentResolver;
34 import android.content.Context;
35 import android.content.DialogInterface;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.ServiceConnection;
39 import android.content.SharedPreferences;
40 import android.content.SyncRequest;
41 import android.content.res.Resources.NotFoundException;
42 import android.database.Cursor;
43 import android.net.Uri;
44 import android.os.Bundle;
45 import android.os.IBinder;
46 import android.preference.PreferenceManager;
47 import android.provider.MediaStore;
48 import android.support.v4.app.Fragment;
49 import android.support.v4.app.FragmentManager;
50 import android.support.v4.app.FragmentTransaction;
51 import android.view.View;
52 import android.view.ViewGroup;
53 import android.widget.ArrayAdapter;
54 import android.widget.TextView;
55 import android.widget.Toast;
56
57 import com.actionbarsherlock.app.ActionBar;
58 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
59 import com.actionbarsherlock.view.Menu;
60 import com.actionbarsherlock.view.MenuInflater;
61 import com.actionbarsherlock.view.MenuItem;
62 import com.actionbarsherlock.view.Window;
63 import com.owncloud.android.BuildConfig;
64 import com.owncloud.android.MainApp;
65 import com.owncloud.android.R;
66 import com.owncloud.android.datamodel.OCFile;
67 import com.owncloud.android.files.services.FileDownloader;
68 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
69 import com.owncloud.android.files.services.FileUploader;
70 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
71 import com.owncloud.android.lib.common.OwnCloudAccount;
72 import com.owncloud.android.lib.common.OwnCloudClient;
73 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
74 import com.owncloud.android.lib.common.OwnCloudCredentials;
75 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
76 import com.owncloud.android.lib.common.network.CertificateCombinedException;
77 import com.owncloud.android.lib.common.operations.RemoteOperation;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
79 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
80 import com.owncloud.android.lib.common.utils.Log_OC;
81 import com.owncloud.android.operations.CreateFolderOperation;
82 import com.owncloud.android.operations.CreateShareOperation;
83 import com.owncloud.android.operations.MoveFileOperation;
84 import com.owncloud.android.operations.RemoveFileOperation;
85 import com.owncloud.android.operations.RenameFileOperation;
86 import com.owncloud.android.operations.SynchronizeFileOperation;
87 import com.owncloud.android.operations.SynchronizeFolderOperation;
88 import com.owncloud.android.operations.UnshareLinkOperation;
89 import com.owncloud.android.services.observer.FileObserverService;
90 import com.owncloud.android.syncadapter.FileSyncAdapter;
91 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
92 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
93 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
94 import com.owncloud.android.ui.fragment.FileDetailFragment;
95 import com.owncloud.android.ui.fragment.FileFragment;
96 import com.owncloud.android.ui.fragment.OCFileListFragment;
97 import com.owncloud.android.ui.preview.PreviewImageActivity;
98 import com.owncloud.android.ui.preview.PreviewImageFragment;
99 import com.owncloud.android.ui.preview.PreviewMediaFragment;
100 import com.owncloud.android.ui.preview.PreviewVideoActivity;
101 import com.owncloud.android.utils.DisplayUtils;
102 import com.owncloud.android.utils.ErrorMessageAdapter;
103
104
105 /**
106 * Displays, what files the user has available in his ownCloud.
107 *
108 * @author Bartek Przybylski
109 * @author David A. Velasco
110 */
111
112 public class FileDisplayActivity extends HookActivity implements
113 FileFragment.ContainerActivity, OnNavigationListener,
114 OnSslUntrustedCertListener, OnEnforceableRefreshListener {
115
116 private ArrayAdapter<String> mDirectories;
117
118 private SyncBroadcastReceiver mSyncBroadcastReceiver;
119 private UploadFinishReceiver mUploadFinishReceiver;
120 private DownloadFinishReceiver mDownloadFinishReceiver;
121 private RemoteOperationResult mLastSslUntrustedServerResult = null;
122
123 private boolean mDualPane;
124 private View mLeftFragmentContainer;
125 private View mRightFragmentContainer;
126
127 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
130
131 public static final int DIALOG_SHORT_WAIT = 0;
132 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
133 private static final int DIALOG_CERT_NOT_SAVED = 2;
134
135 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
136
137 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
138 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
139 public static final int ACTION_MOVE_FILES = 3;
140
141 private static final String TAG = FileDisplayActivity.class.getSimpleName();
142
143 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
145
146 private OCFile mWaitingToPreview;
147
148 private boolean mSyncInProgress = false;
149
150 private String DIALOG_UNTRUSTED_CERT;
151
152 private OCFile mWaitingToSend;
153
154 @Override
155 protected void onCreate(Bundle savedInstanceState) {
156 Log_OC.d(TAG, "onCreate() start");
157 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
158
159 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
160
161 // PIN CODE request ; best location is to decide, let's try this first
162 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
163 requestPinCode();
164 } else if (getIntent().getAction() == null && savedInstanceState == null) {
165 requestPinCode();
166 }
167
168 /// grant that FileObserverService is watching favourite files
169 if (savedInstanceState == null) {
170 Intent initObserversIntent = FileObserverService.makeInitIntent(this);
171 startService(initObserversIntent);
172 }
173
174 /// Load of saved instance state
175 if(savedInstanceState != null) {
176 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
177 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
178 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
179
180 } else {
181 mWaitingToPreview = null;
182 mSyncInProgress = false;
183 mWaitingToSend = null;
184 }
185
186 /// USER INTERFACE
187
188 // Inflate and set the layout view
189 setContentView(R.layout.files);
190 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
191 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
192 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
193 if (savedInstanceState == null) {
194 createMinFragments();
195 }
196
197 // Action bar setup
198 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
199 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
200 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
201
202 setBackgroundText();
203
204 Log_OC.d(TAG, "onCreate() end");
205 }
206
207 @Override
208 protected void onStart() {
209 super.onStart();
210 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
211 }
212
213 @Override
214 protected void onDestroy() {
215 super.onDestroy();
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.e(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 =
474 CreateFolderDialogFragment.newInstance(getCurrentDir());
475 dialog.show(getSupportFragmentManager(), "createdirdialog");
476 break;
477 }
478 case R.id.action_sync_account: {
479 startSynchronization();
480 break;
481 }
482 case R.id.action_upload: {
483 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
484 break;
485 }
486 case R.id.action_settings: {
487 Intent settingsIntent = new Intent(this, Preferences.class);
488 startActivity(settingsIntent);
489 break;
490 }
491 case R.id.action_logger: {
492 Intent loggerIntent = new Intent(getApplicationContext(),LogHistoryActivity.class);
493 startActivity(loggerIntent);
494 break;
495 }
496 case android.R.id.home: {
497 FileFragment second = getSecondFragment();
498 OCFile currentDir = getCurrentDir();
499 if((currentDir != null && currentDir.getParentId() != 0) ||
500 (second != null && second.getFile() != null)) {
501 onBackPressed();
502
503 }
504 break;
505 }
506 case R.id.action_sort: {
507 SharedPreferences appPreferences = PreferenceManager
508 .getDefaultSharedPreferences(getApplicationContext());
509
510 // Read sorting order, default to sort by name ascending
511 Integer sortOrder = appPreferences
512 .getInt("sortOrder", 0);
513
514 AlertDialog.Builder builder = new AlertDialog.Builder(this);
515 builder.setTitle(R.string.actionbar_sort_title)
516 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder , new DialogInterface.OnClickListener() {
517 public void onClick(DialogInterface dialog, int which) {
518
519 switch (which){
520 case 0:
521 sortByName(true);
522 break;
523 case 1:
524 sortByDate(false);
525 break;
526 case 2:
527 sortBySize(false);
528 break;
529 }
530
531 dialog.dismiss();
532
533 }
534 });
535 builder.create().show();
536 break;
537 }
538 default:
539 retval = super.onOptionsItemSelected(item);
540 }
541 return retval;
542 }
543
544 private void startSynchronization() {
545 Log_OC.e(TAG, "Got to start sync");
546 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
547 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
548 ContentResolver.cancelSync(null, MainApp.getAuthority()); // 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.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
553 ContentResolver.requestSync(
554 getAccount(),
555 MainApp.getAuthority(), bundle);
556 } else {
557 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
558 SyncRequest.Builder builder = new SyncRequest.Builder();
559 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
560 builder.setExpedited(true);
561 builder.setManual(true);
562 builder.syncOnce();
563 SyncRequest request = builder.build();
564 ContentResolver.requestSync(request);
565 }
566 }
567
568
569 @Override
570 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
571 if (itemPosition != 0) {
572 String targetPath = "";
573 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
574 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
575 }
576 targetPath = OCFile.PATH_SEPARATOR + targetPath;
577 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
578 if (targetFolder != null) {
579 browseTo(targetFolder);
580 }
581
582 // the next operation triggers a new call to this method, but it's necessary to
583 // ensure that the name exposed in the action bar is the current directory when the
584 // user selected it in the navigation list
585 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
586 getSupportActionBar().setSelectedNavigationItem(0);
587 }
588 return true;
589 }
590
591 /**
592 * Called, when the user selected something for uploading
593 */
594 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
595 super.onActivityResult(requestCode, resultCode, data);
596
597 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
598 requestSimpleUpload(data, resultCode);
599
600 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
601 requestMultipleUpload(data, resultCode);
602
603 } else if (requestCode == ACTION_MOVE_FILES && (resultCode == RESULT_OK ||
604 resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
605
606 final Intent fData = data;
607 final int fResultCode = resultCode;
608 getHandler().postDelayed(
609 new Runnable() {
610 @Override
611 public void run() {
612 requestMoveOperation(fData, fResultCode);
613 }
614 },
615 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
616 );
617 }
618 }
619
620 private void requestMultipleUpload(Intent data, int resultCode) {
621 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
622 if (filePaths != null) {
623 String[] remotePaths = new String[filePaths.length];
624 String remotePathBase = "";
625 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
626 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
627 }
628 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
629 remotePathBase += OCFile.PATH_SEPARATOR;
630 for (int j = 0; j< remotePaths.length; j++) {
631 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
632 }
633
634 Intent i = new Intent(this, FileUploader.class);
635 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
636 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
637 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
638 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
639 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
640 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
641 startService(i);
642
643 } else {
644 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
645 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
646 t.show();
647 return;
648 }
649 }
650
651
652 private void requestSimpleUpload(Intent data, int resultCode) {
653 String filepath = null;
654 try {
655 Uri selectedImageUri = data.getData();
656
657 String filemanagerstring = selectedImageUri.getPath();
658 String selectedImagePath = getPath(selectedImageUri);
659
660 if (selectedImagePath != null)
661 filepath = selectedImagePath;
662 else
663 filepath = filemanagerstring;
664
665 } catch (Exception e) {
666 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
667 e.printStackTrace();
668
669 } finally {
670 if (filepath == null) {
671 Log_OC.e(TAG, "Couldnt resolve path to file");
672 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
673 t.show();
674 return;
675 }
676 }
677
678 Intent i = new Intent(this, FileUploader.class);
679 i.putExtra(FileUploader.KEY_ACCOUNT,
680 getAccount());
681 String remotepath = new String();
682 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
683 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
684 }
685 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
686 remotepath += OCFile.PATH_SEPARATOR;
687 remotepath += new File(filepath).getName();
688
689 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
690 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
691 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
692 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
693 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
694 startService(i);
695 }
696
697 /**
698 * Request the operation for moving the file/folder from one path to another
699 *
700 * @param data Intent received
701 * @param resultCode Result code received
702 */
703 private void requestMoveOperation(Intent data, int resultCode) {
704 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
705 OCFile targetFile = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_TARGET_FILE);
706 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
707 }
708
709 @Override
710 public void onBackPressed() {
711 OCFileListFragment listOfFiles = getListOfFilesFragment();
712 if (mDualPane || getSecondFragment() == null) {
713 if (listOfFiles != null) { // should never be null, indeed
714 if (mDirectories.getCount() <= 1) {
715 finish();
716 return;
717 }
718 int levelsUp = listOfFiles.onBrowseUp();
719 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
720 popDirname();
721 }
722 }
723 }
724 if (listOfFiles != null) { // should never be null, indeed
725 setFile(listOfFiles.getCurrentFile());
726 }
727 cleanSecondFragment();
728
729 }
730
731 @Override
732 protected void onSaveInstanceState(Bundle outState) {
733 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
734 Log_OC.e(TAG, "onSaveInstanceState() start");
735 super.onSaveInstanceState(outState);
736 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
737 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
738 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
739 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
740
741 Log_OC.d(TAG, "onSaveInstanceState() end");
742 }
743
744
745
746 @Override
747 protected void onResume() {
748 super.onResume();
749 Log_OC.e(TAG, "onResume() start");
750
751 // refresh list of files
752 refreshListOfFilesFragment();
753
754 // Listen for sync messages
755 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
756 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
757 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
758 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
759 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
760 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
761 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
762 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
763
764 // Listen for upload messages
765 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
766 mUploadFinishReceiver = new UploadFinishReceiver();
767 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
768
769 // Listen for download messages
770 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
771 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
772 mDownloadFinishReceiver = new DownloadFinishReceiver();
773 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
774
775 Log_OC.d(TAG, "onResume() end");
776 }
777
778
779 @Override
780 protected void onPause() {
781 Log_OC.e(TAG, "onPause() start");
782 if (mSyncBroadcastReceiver != null) {
783 unregisterReceiver(mSyncBroadcastReceiver);
784 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
785 mSyncBroadcastReceiver = null;
786 }
787 if (mUploadFinishReceiver != null) {
788 unregisterReceiver(mUploadFinishReceiver);
789 mUploadFinishReceiver = null;
790 }
791 if (mDownloadFinishReceiver != null) {
792 unregisterReceiver(mDownloadFinishReceiver);
793 mDownloadFinishReceiver = null;
794 }
795
796
797 Log_OC.d(TAG, "onPause() end");
798 super.onPause();
799 }
800
801
802 @Override
803 protected Dialog onCreateDialog(int id) {
804 Dialog dialog = null;
805 AlertDialog.Builder builder;
806 switch (id) {
807 case DIALOG_SHORT_WAIT: {
808 ProgressDialog working_dialog = new ProgressDialog(this);
809 working_dialog.setMessage(getResources().getString(
810 R.string.wait_a_moment));
811 working_dialog.setIndeterminate(true);
812 working_dialog.setCancelable(false);
813 dialog = working_dialog;
814 break;
815 }
816 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
817
818
819 String[] allTheItems = { getString(R.string.actionbar_upload_files),
820 getString(R.string.actionbar_upload_from_apps) };
821
822 builder = new AlertDialog.Builder(this);
823 builder.setTitle(R.string.actionbar_upload);
824 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
825 public void onClick(DialogInterface dialog, int item) {
826 if (item == 0) {
827 // if (!mDualPane) {
828 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
829 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
830 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
831 // } else {
832 // TODO create and handle new fragment
833 // LocalFileListFragment
834 // }
835 } else if (item == 1) {
836 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
837 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
838 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
839 ACTION_SELECT_CONTENT_FROM_APPS);
840 }
841 }
842 });
843 dialog = builder.create();
844 break;
845 }
846 case DIALOG_CERT_NOT_SAVED: {
847 builder = new AlertDialog.Builder(this);
848 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
849 builder.setCancelable(false);
850 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
851 @Override
852 public void onClick(DialogInterface dialog, int which) {
853 dialog.dismiss();
854 };
855 });
856 dialog = builder.create();
857 break;
858 }
859 default:
860 dialog = null;
861 }
862
863 return dialog;
864 }
865
866
867 /**
868 * Translates a content URI of an image to a physical path
869 * on the disk
870 * @param uri The URI to resolve
871 * @return The path to the image or null if it could not be found
872 */
873 public String getPath(Uri uri) {
874 String[] projection = { MediaStore.Images.Media.DATA };
875 Cursor cursor = managedQuery(uri, projection, null, null, null);
876 if (cursor != null) {
877 int column_index = cursor
878 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
879 cursor.moveToFirst();
880 return cursor.getString(column_index);
881 }
882 return null;
883 }
884
885 /**
886 * Pushes a directory to the drop down list
887 * @param directory to push
888 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
889 */
890 public void pushDirname(OCFile directory) {
891 if(!directory.isFolder()){
892 throw new IllegalArgumentException("Only directories may be pushed!");
893 }
894 mDirectories.insert(directory.getFileName(), 0);
895 setFile(directory);
896 }
897
898 /**
899 * Pops a directory name from the drop down list
900 * @return True, unless the stack is empty
901 */
902 public boolean popDirname() {
903 mDirectories.remove(mDirectories.getItem(0));
904 return !mDirectories.isEmpty();
905 }
906
907 // Custom array adapter to override text colors
908 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
909
910 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
911 super(ctx, view);
912 }
913
914 public View getView(int position, View convertView, ViewGroup parent) {
915 View v = super.getView(position, convertView, parent);
916
917 ((TextView) v).setTextColor(getResources().getColorStateList(
918 android.R.color.white));
919
920 fixRoot((TextView) v );
921 return v;
922 }
923
924 public View getDropDownView(int position, View convertView,
925 ViewGroup parent) {
926 View v = super.getDropDownView(position, convertView, parent);
927
928 ((TextView) v).setTextColor(getResources().getColorStateList(
929 android.R.color.white));
930
931 fixRoot((TextView) v );
932 return v;
933 }
934
935 private void fixRoot(TextView v) {
936 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
937 v.setText(R.string.default_display_name_for_root_folder);
938 }
939 }
940
941 }
942
943 private class SyncBroadcastReceiver extends BroadcastReceiver {
944
945 /**
946 * {@link BroadcastReceiver} to enable syncing feedback in UI
947 */
948 @Override
949 public void onReceive(Context context, Intent intent) {
950 try {
951 String event = intent.getAction();
952 Log_OC.d(TAG, "Received broadcast " + event);
953 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
954 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
955 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
956 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
957
958 if (sameAccount) {
959
960 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
961 mSyncInProgress = true;
962
963 } else {
964 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
965 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
966
967 if (currentDir == null) {
968 // current folder was removed from the server
969 Toast.makeText( FileDisplayActivity.this,
970 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
971 Toast.LENGTH_LONG)
972 .show();
973 browseToRoot();
974
975 } else {
976 if (currentFile == null && !getFile().isFolder()) {
977 // currently selected file was removed in the server, and now we know it
978 cleanSecondFragment();
979 currentFile = currentDir;
980 }
981
982 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
983 OCFileListFragment fileListFragment = getListOfFilesFragment();
984 if (fileListFragment != null) {
985 fileListFragment.listDirectory(currentDir);
986 }
987 }
988 setFile(currentFile);
989 }
990
991 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
992
993 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
994 equals(event) &&
995 /// TODO refactor and make common
996 synchResult != null && !synchResult.isSuccess() &&
997 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
998 synchResult.isIdPRedirection() ||
999 (synchResult.isException() && synchResult.getException()
1000 instanceof AuthenticatorException))) {
1001
1002 OwnCloudClient client = null;
1003 try {
1004 OwnCloudAccount ocAccount =
1005 new OwnCloudAccount(getAccount(), context);
1006 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1007 removeClientFor(ocAccount));
1008 // TODO get rid of these exceptions
1009 } catch (AccountNotFoundException e) {
1010 e.printStackTrace();
1011 } catch (AuthenticatorException e) {
1012 e.printStackTrace();
1013 } catch (OperationCanceledException e) {
1014 e.printStackTrace();
1015 } catch (IOException e) {
1016 e.printStackTrace();
1017 }
1018
1019 if (client != null) {
1020 OwnCloudCredentials cred = client.getCredentials();
1021 if (cred != null) {
1022 AccountManager am = AccountManager.get(context);
1023 if (cred.authTokenExpires()) {
1024 am.invalidateAuthToken(
1025 getAccount().type,
1026 cred.getAuthToken()
1027 );
1028 } else {
1029 am.clearPassword(getAccount());
1030 }
1031 }
1032 }
1033
1034 requestCredentialsUpdate();
1035
1036 }
1037 }
1038 removeStickyBroadcast(intent);
1039 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1040 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1041
1042 setBackgroundText();
1043
1044 }
1045
1046 if (synchResult != null) {
1047 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1048 mLastSslUntrustedServerResult = synchResult;
1049 }
1050 }
1051 } catch (RuntimeException e) {
1052 // avoid app crashes after changing the serial id of RemoteOperationResult
1053 // in owncloud library with broadcast notifications pending to process
1054 removeStickyBroadcast(intent);
1055 }
1056 }
1057 }
1058
1059 /**
1060 * Show a text message on screen view for notifying user if content is
1061 * loading or folder is empty
1062 */
1063 private void setBackgroundText() {
1064 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1065 if (ocFileListFragment != null) {
1066 int message = R.string.file_list_loading;
1067 if (!mSyncInProgress) {
1068 // In case file list is empty
1069 message = R.string.file_list_empty;
1070 }
1071 ocFileListFragment.setMessageForEmptyList(getString(message));
1072 } else {
1073 Log_OC.e(TAG, "OCFileListFragment is null");
1074 }
1075 }
1076
1077 /**
1078 * Once the file upload has finished -> update view
1079 */
1080 private class UploadFinishReceiver extends BroadcastReceiver {
1081 /**
1082 * Once the file upload has finished -> update view
1083 * @author David A. Velasco
1084 * {@link BroadcastReceiver} to enable upload feedback in UI
1085 */
1086 @Override
1087 public void onReceive(Context context, Intent intent) {
1088 try {
1089 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1090 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1091 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1092 OCFile currentDir = getCurrentDir();
1093 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1094 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1095
1096 if (sameAccount && isDescendant) {
1097 refreshListOfFilesFragment();
1098 }
1099
1100 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1101 boolean renamedInUpload = getFile().getRemotePath().
1102 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1103 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1104 renamedInUpload;
1105 FileFragment details = getSecondFragment();
1106 boolean detailFragmentIsShown = (details != null &&
1107 details instanceof FileDetailFragment);
1108
1109 if (sameAccount && sameFile && detailFragmentIsShown) {
1110 if (uploadWasFine) {
1111 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1112 }
1113 if (renamedInUpload) {
1114 String newName = (new File(uploadedRemotePath)).getName();
1115 Toast msg = Toast.makeText(
1116 context,
1117 String.format(
1118 getString(R.string.filedetails_renamed_in_upload_msg),
1119 newName),
1120 Toast.LENGTH_LONG);
1121 msg.show();
1122 }
1123 if (uploadWasFine || getFile().fileExists()) {
1124 ((FileDetailFragment)details).updateFileDetails(false, true);
1125 } else {
1126 cleanSecondFragment();
1127 }
1128
1129 // Force the preview if the file is an image
1130 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1131 startImagePreview(getFile());
1132 } // TODO what about other kind of previews?
1133 }
1134
1135 } finally {
1136 if (intent != null) {
1137 removeStickyBroadcast(intent);
1138 }
1139 }
1140
1141 }
1142
1143 }
1144
1145
1146 /**
1147 * Class waiting for broadcast events from the {@link FielDownloader} service.
1148 *
1149 * Updates the UI when a download is started or finished, provided that it is relevant for the
1150 * current folder.
1151 */
1152 private class DownloadFinishReceiver extends BroadcastReceiver {
1153 @Override
1154 public void onReceive(Context context, Intent intent) {
1155 try {
1156 boolean sameAccount = isSameAccount(context, intent);
1157 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1158 boolean isDescendant = isDescendant(downloadedRemotePath);
1159
1160 if (sameAccount && isDescendant) {
1161 refreshListOfFilesFragment();
1162 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1163 }
1164
1165 if (mWaitingToSend != null) {
1166 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1167 if (mWaitingToSend.isDown()) {
1168 sendDownloadedFile();
1169 }
1170 }
1171
1172 } finally {
1173 if (intent != null) {
1174 removeStickyBroadcast(intent);
1175 }
1176 }
1177 }
1178
1179 private boolean isDescendant(String downloadedRemotePath) {
1180 OCFile currentDir = getCurrentDir();
1181 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1182 }
1183
1184 private boolean isSameAccount(Context context, Intent intent) {
1185 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1186 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1187 }
1188 }
1189
1190
1191 public void browseToRoot() {
1192 OCFileListFragment listOfFiles = getListOfFilesFragment();
1193 if (listOfFiles != null) { // should never be null, indeed
1194 while (mDirectories.getCount() > 1) {
1195 popDirname();
1196 }
1197 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1198 listOfFiles.listDirectory(root);
1199 setFile(listOfFiles.getCurrentFile());
1200 startSyncFolderOperation(root, false);
1201 }
1202 cleanSecondFragment();
1203 }
1204
1205
1206 public void browseTo(OCFile folder) {
1207 if (folder == null || !folder.isFolder()) {
1208 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1209 }
1210 OCFileListFragment listOfFiles = getListOfFilesFragment();
1211 if (listOfFiles != null) {
1212 setNavigationListWithFolder(folder);
1213 listOfFiles.listDirectory(folder);
1214 setFile(listOfFiles.getCurrentFile());
1215 startSyncFolderOperation(folder, false);
1216 } else {
1217 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1218 }
1219 cleanSecondFragment();
1220 }
1221
1222
1223 /**
1224 * {@inheritDoc}
1225 *
1226 * Updates action bar and second fragment, if in dual pane mode.
1227 */
1228 @Override
1229 public void onBrowsedDownTo(OCFile directory) {
1230 pushDirname(directory);
1231 cleanSecondFragment();
1232
1233 // Sync Folder
1234 startSyncFolderOperation(directory, false);
1235
1236 }
1237
1238 /**
1239 * Shows the information of the {@link OCFile} received as a
1240 * parameter in the second fragment.
1241 *
1242 * @param file {@link OCFile} whose details will be shown
1243 */
1244 @Override
1245 public void showDetails(OCFile file) {
1246 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1247 setSecondFragment(detailFragment);
1248 updateFragmentsVisibility(true);
1249 updateNavigationElementsInActionBar(file);
1250 setFile(file);
1251 }
1252
1253
1254 /**
1255 * TODO
1256 */
1257 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1258 ActionBar actionBar = getSupportActionBar();
1259 if (chosenFile == null || mDualPane) {
1260 // only list of files - set for browsing through folders
1261 OCFile currentDir = getCurrentDir();
1262 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1263 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1264 actionBar.setDisplayShowTitleEnabled(!noRoot);
1265 if (!noRoot) {
1266 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1267 }
1268 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1269 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1270
1271 } else {
1272 actionBar.setDisplayHomeAsUpEnabled(true);
1273 actionBar.setDisplayShowTitleEnabled(true);
1274 actionBar.setTitle(chosenFile.getFileName());
1275 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1276 }
1277 }
1278
1279
1280 @Override
1281 protected ServiceConnection newTransferenceServiceConnection() {
1282 return new ListServiceConnection();
1283 }
1284
1285 /** Defines callbacks for service binding, passed to bindService() */
1286 private class ListServiceConnection implements ServiceConnection {
1287
1288 @Override
1289 public void onServiceConnected(ComponentName component, IBinder service) {
1290 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1291 Log_OC.d(TAG, "Download service connected");
1292 mDownloaderBinder = (FileDownloaderBinder) service;
1293 if (mWaitingToPreview != null)
1294 if (getStorageManager() != null) {
1295 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1296 if (!mWaitingToPreview.isDown()) {
1297 requestForDownload();
1298 }
1299 }
1300
1301 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1302 Log_OC.d(TAG, "Upload service connected");
1303 mUploaderBinder = (FileUploaderBinder) service;
1304 } else {
1305 return;
1306 }
1307 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1308 OCFileListFragment listOfFiles = getListOfFilesFragment();
1309 if (listOfFiles != null) {
1310 listOfFiles.listDirectory();
1311 }
1312 FileFragment secondFragment = getSecondFragment();
1313 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1314 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1315 detailFragment.listenForTransferProgress();
1316 detailFragment.updateFileDetails(false, false);
1317 }
1318 }
1319
1320 @Override
1321 public void onServiceDisconnected(ComponentName component) {
1322 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1323 Log_OC.d(TAG, "Download service disconnected");
1324 mDownloaderBinder = null;
1325 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1326 Log_OC.d(TAG, "Upload service disconnected");
1327 mUploaderBinder = null;
1328 }
1329 }
1330 };
1331
1332
1333
1334 /**
1335 * Launch an intent to request the PIN code to the user before letting him use the app
1336 */
1337 private void requestPinCode() {
1338 boolean pinStart = false;
1339 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1340 pinStart = appPrefs.getBoolean("set_pincode", false);
1341 if (pinStart) {
1342 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1343 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1344 startActivity(i);
1345 }
1346 }
1347
1348
1349 @Override
1350 public void onSavedCertificate() {
1351 startSyncFolderOperation(getCurrentDir(), false);
1352 }
1353
1354
1355 @Override
1356 public void onFailedSavingCertificate() {
1357 showDialog(DIALOG_CERT_NOT_SAVED);
1358 }
1359
1360 @Override
1361 public void onCancelCertificate() {
1362 // nothing to do
1363 }
1364
1365 /**
1366 * Updates the view associated to the activity after the finish of some operation over files
1367 * in the current account.
1368 *
1369 * @param operation Removal operation performed.
1370 * @param result Result of the removal.
1371 */
1372 @Override
1373 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1374 super.onRemoteOperationFinish(operation, result);
1375
1376 if (operation instanceof RemoveFileOperation) {
1377 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1378
1379 } else if (operation instanceof RenameFileOperation) {
1380 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1381
1382 } else if (operation instanceof SynchronizeFileOperation) {
1383 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1384
1385 } else if (operation instanceof CreateFolderOperation) {
1386 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1387
1388 } else if (operation instanceof CreateShareOperation) {
1389 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1390
1391 } else if (operation instanceof UnshareLinkOperation) {
1392 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1393
1394 } else if (operation instanceof MoveFileOperation) {
1395 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1396 }
1397
1398 }
1399
1400
1401 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1402 if (result.isSuccess()) {
1403 refreshShowDetails();
1404 refreshListOfFilesFragment();
1405 }
1406 }
1407
1408
1409 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1410 if (result.isSuccess()) {
1411 refreshShowDetails();
1412 refreshListOfFilesFragment();
1413
1414 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1415 cleanSecondFragment();
1416 refreshListOfFilesFragment();
1417 }
1418 }
1419
1420 private void refreshShowDetails() {
1421 FileFragment details = getSecondFragment();
1422 if (details != null) {
1423 OCFile file = details.getFile();
1424 if (file != null) {
1425 file = getStorageManager().getFileByPath(file.getRemotePath());
1426 if (details instanceof PreviewMediaFragment) {
1427 // Refresh OCFile of the fragment
1428 ((PreviewMediaFragment) details).updateFile(file);
1429 } else {
1430 showDetails(file);
1431 }
1432 }
1433 invalidateOptionsMenu();
1434 }
1435 }
1436
1437 /**
1438 * Updates the view associated to the activity after the finish of an operation trying to remove a
1439 * file.
1440 *
1441 * @param operation Removal operation performed.
1442 * @param result Result of the removal.
1443 */
1444 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1445 dismissLoadingDialog();
1446
1447 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1448 Toast.LENGTH_LONG);
1449 msg.show();
1450
1451 if (result.isSuccess()) {
1452 OCFile removedFile = operation.getFile();
1453 FileFragment second = getSecondFragment();
1454 if (second != null && removedFile.equals(second.getFile())) {
1455 if (second instanceof PreviewMediaFragment) {
1456 ((PreviewMediaFragment)second).stopPreview(true);
1457 }
1458 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1459 cleanSecondFragment();
1460 }
1461 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1462 refreshListOfFilesFragment();
1463 }
1464 invalidateOptionsMenu();
1465 } else {
1466 if (result.isSslRecoverableException()) {
1467 mLastSslUntrustedServerResult = result;
1468 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1469 }
1470 }
1471 }
1472
1473
1474 /**
1475 * Updates the view associated to the activity after the finish of an operation trying to move a
1476 * file.
1477 *
1478 * @param operation Move operation performed.
1479 * @param result Result of the move operation.
1480 */
1481 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1482 if (result.isSuccess()) {
1483 dismissLoadingDialog();
1484 refreshListOfFilesFragment();
1485 } else {
1486 dismissLoadingDialog();
1487 try {
1488 Toast msg = Toast.makeText(FileDisplayActivity.this,
1489 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1490 Toast.LENGTH_LONG);
1491 msg.show();
1492
1493 } catch (NotFoundException e) {
1494 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1495 }
1496 }
1497 }
1498
1499
1500 /**
1501 * Updates the view associated to the activity after the finish of an operation trying to rename a
1502 * file.
1503 *
1504 * @param operation Renaming operation performed.
1505 * @param result Result of the renaming.
1506 */
1507 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1508 dismissLoadingDialog();
1509 OCFile renamedFile = operation.getFile();
1510 if (result.isSuccess()) {
1511 FileFragment details = getSecondFragment();
1512 if (details != null) {
1513 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1514 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1515 showDetails(renamedFile);
1516
1517 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1518 ((PreviewMediaFragment) details).updateFile(renamedFile);
1519 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1520 int position = ((PreviewMediaFragment)details).getPosition();
1521 startMediaPreview(renamedFile, position, true);
1522 } else {
1523 getFileOperationsHelper().openFile(renamedFile);
1524 }
1525 }
1526 }
1527
1528 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1529 refreshListOfFilesFragment();
1530 }
1531
1532 } else {
1533 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1534 Toast.LENGTH_LONG);
1535 msg.show();
1536
1537 if (result.isSslRecoverableException()) {
1538 mLastSslUntrustedServerResult = result;
1539 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1540 }
1541 }
1542 }
1543
1544 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1545 dismissLoadingDialog();
1546 OCFile syncedFile = operation.getLocalFile();
1547 if (!result.isSuccess()) {
1548 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1549 Intent i = new Intent(this, ConflictsResolveActivity.class);
1550 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1551 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1552 startActivity(i);
1553
1554 }
1555
1556 } else {
1557 if (operation.transferWasRequested()) {
1558 onTransferStateChanged(syncedFile, true, true);
1559
1560 } else {
1561 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1562 Toast.LENGTH_LONG);
1563 msg.show();
1564 }
1565 }
1566 }
1567
1568 /**
1569 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1570 *
1571 * @param operation Creation operation performed.
1572 * @param result Result of the creation.
1573 */
1574 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1575 if (result.isSuccess()) {
1576 dismissLoadingDialog();
1577 refreshListOfFilesFragment();
1578 } else {
1579 dismissLoadingDialog();
1580 try {
1581 Toast msg = Toast.makeText(FileDisplayActivity.this,
1582 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1583 Toast.LENGTH_LONG);
1584 msg.show();
1585
1586 } catch (NotFoundException e) {
1587 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1588 }
1589 }
1590 }
1591
1592
1593 /**
1594 * {@inheritDoc}
1595 */
1596 @Override
1597 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1598 refreshListOfFilesFragment();
1599 FileFragment details = getSecondFragment();
1600 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1601 if (downloading || uploading) {
1602 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1603 } else {
1604 if (!file.fileExists()) {
1605 cleanSecondFragment();
1606 } else {
1607 ((FileDetailFragment)details).updateFileDetails(false, true);
1608 }
1609 }
1610 }
1611
1612 }
1613
1614
1615 private void requestForDownload() {
1616 Account account = getAccount();
1617 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1618 Intent i = new Intent(this, FileDownloader.class);
1619 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1620 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1621 startService(i);
1622 }
1623 }
1624
1625
1626 private OCFile getCurrentDir() {
1627 OCFile file = getFile();
1628 if (file != null) {
1629 if (file.isFolder()) {
1630 return file;
1631 } else if (getStorageManager() != null) {
1632 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1633 return getStorageManager().getFileByPath(parentPath);
1634 }
1635 }
1636 return null;
1637 }
1638
1639 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1640 long currentSyncTime = System.currentTimeMillis();
1641
1642 mSyncInProgress = true;
1643
1644 // perform folder synchronization
1645 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1646 currentSyncTime,
1647 false,
1648 getFileOperationsHelper().isSharedSupported(),
1649 ignoreETag,
1650 getStorageManager(),
1651 getAccount(),
1652 getApplicationContext()
1653 );
1654 synchFolderOp.execute(getAccount(), this, null, null);
1655
1656 setSupportProgressBarIndeterminateVisibility(true);
1657
1658 setBackgroundText();
1659 }
1660
1661 /**
1662 * Show untrusted cert dialog
1663 */
1664 public void showUntrustedCertDialog(RemoteOperationResult result) {
1665 // Show a dialog with the certificate info
1666 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1667 FragmentManager fm = getSupportFragmentManager();
1668 FragmentTransaction ft = fm.beginTransaction();
1669 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1670 }
1671
1672 private void requestForDownload(OCFile file) {
1673 Account account = getAccount();
1674 if (!mDownloaderBinder.isDownloading(account, file)) {
1675 Intent i = new Intent(this, FileDownloader.class);
1676 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1677 i.putExtra(FileDownloader.EXTRA_FILE, file);
1678 startService(i);
1679 }
1680 }
1681
1682 private void sendDownloadedFile(){
1683 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1684 mWaitingToSend = null;
1685 }
1686
1687
1688 /**
1689 * Requests the download of the received {@link OCFile} , updates the UI
1690 * to monitor the download progress and prepares the activity to send the file
1691 * when the download finishes.
1692 *
1693 * @param file {@link OCFile} to download and preview.
1694 */
1695 public void startDownloadForSending(OCFile file) {
1696 mWaitingToSend = file;
1697 requestForDownload(mWaitingToSend);
1698 boolean hasSecondFragment = (getSecondFragment()!= null);
1699 updateFragmentsVisibility(hasSecondFragment);
1700 }
1701
1702 /**
1703 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1704 *
1705 * @param file Image {@link OCFile} to show.
1706 */
1707 public void startImagePreview(OCFile file) {
1708 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1709 showDetailsIntent.putExtra(EXTRA_FILE, file);
1710 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1711 startActivity(showDetailsIntent);
1712
1713 }
1714
1715 /**
1716 * Stars the preview of an already down media {@link OCFile}.
1717 *
1718 * @param file Media {@link OCFile} to preview.
1719 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1720 * @param autoplay When 'true', the playback will start without user interactions.
1721 */
1722 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1723 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1724 setSecondFragment(mediaFragment);
1725 updateFragmentsVisibility(true);
1726 updateNavigationElementsInActionBar(file);
1727 setFile(file);
1728 }
1729
1730 /**
1731 * Requests the download of the received {@link OCFile} , updates the UI
1732 * to monitor the download progress and prepares the activity to preview
1733 * or open the file when the download finishes.
1734 *
1735 * @param file {@link OCFile} to download and preview.
1736 */
1737 public void startDownloadForPreview(OCFile file) {
1738 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1739 setSecondFragment(detailFragment);
1740 mWaitingToPreview = file;
1741 requestForDownload();
1742 updateFragmentsVisibility(true);
1743 updateNavigationElementsInActionBar(file);
1744 setFile(file);
1745 }
1746
1747
1748 public void cancelTransference(OCFile file) {
1749 getFileOperationsHelper().cancelTransference(file);
1750 if (mWaitingToPreview != null &&
1751 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1752 mWaitingToPreview = null;
1753 }
1754 if (mWaitingToSend != null &&
1755 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1756 mWaitingToSend = null;
1757 }
1758 onTransferStateChanged(file, false, false);
1759 }
1760
1761 @Override
1762 public void onRefresh(boolean ignoreETag) {
1763 refreshList(ignoreETag);
1764 }
1765
1766 @Override
1767 public void onRefresh() {
1768 refreshList(true);
1769 }
1770
1771 private void refreshList(boolean ignoreETag) {
1772 OCFileListFragment listOfFiles = getListOfFilesFragment();
1773 if (listOfFiles != null) {
1774 OCFile folder = listOfFiles.getCurrentFile();
1775 if (folder != null) {
1776 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1777 listDirectory(mFile);*/
1778 startSyncFolderOperation(folder, ignoreETag);
1779 }
1780 }
1781 }
1782
1783 private void sortByDate(boolean ascending){
1784 getListOfFilesFragment().sortByDate(ascending);
1785 }
1786
1787 private void sortBySize(boolean ascending){
1788 getListOfFilesFragment().sortBySize(ascending);
1789 }
1790
1791 private void sortByName(boolean ascending){
1792 getListOfFilesFragment().sortByName(ascending);
1793 }
1794 }