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