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