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