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