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