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