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