OAuth clean-up and refactoring
[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-2013 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 as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.ui.activity;
21
22 import java.io.File;
23
24 import android.accounts.Account;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.SharedPreferences;
39 import android.content.SharedPreferences.Editor;
40 import android.content.pm.PackageInfo;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.res.Resources.NotFoundException;
43 import android.database.Cursor;
44 import android.graphics.Bitmap;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.os.IBinder;
50 import android.preference.PreferenceManager;
51 import android.provider.MediaStore;
52 import android.support.v4.app.FragmentTransaction;
53 import android.util.Log;
54 import android.view.View;
55 import android.view.ViewGroup;
56 import android.widget.ArrayAdapter;
57 import android.widget.EditText;
58 import android.widget.TextView;
59 import android.widget.Toast;
60
61 import com.actionbarsherlock.app.ActionBar;
62 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
63 import com.actionbarsherlock.app.SherlockFragmentActivity;
64 import com.actionbarsherlock.view.Menu;
65 import com.actionbarsherlock.view.MenuInflater;
66 import com.actionbarsherlock.view.MenuItem;
67 import com.actionbarsherlock.view.Window;
68 import com.owncloud.android.AccountUtils;
69 import com.owncloud.android.authentication.AccountAuthenticator;
70 import com.owncloud.android.datamodel.DataStorageManager;
71 import com.owncloud.android.datamodel.FileDataStorageManager;
72 import com.owncloud.android.datamodel.OCFile;
73 import com.owncloud.android.files.services.FileDownloader;
74 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
75 import com.owncloud.android.files.services.FileObserverService;
76 import com.owncloud.android.files.services.FileUploader;
77 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
78 import com.owncloud.android.operations.CreateFolderOperation;
79 import com.owncloud.android.operations.OnRemoteOperationListener;
80 import com.owncloud.android.operations.RemoteOperation;
81 import com.owncloud.android.operations.RemoteOperationResult;
82 import com.owncloud.android.operations.RemoveFileOperation;
83 import com.owncloud.android.operations.RenameFileOperation;
84 import com.owncloud.android.operations.SynchronizeFileOperation;
85 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
86 import com.owncloud.android.syncadapter.FileSyncService;
87 import com.owncloud.android.ui.dialog.ChangelogDialog;
88 import com.owncloud.android.ui.dialog.SslValidatorDialog;
89 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
90 import com.owncloud.android.ui.fragment.FileDetailFragment;
91 import com.owncloud.android.ui.fragment.OCFileListFragment;
92
93 import com.owncloud.android.R;
94
95 /**
96 * Displays, what files the user has available in his ownCloud.
97 *
98 * @author Bartek Przybylski
99 *
100 */
101
102 public class FileDisplayActivity extends SherlockFragmentActivity implements
103 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener {
104
105 private ArrayAdapter<String> mDirectories;
106 private OCFile mCurrentDir = null;
107 private OCFile mCurrentFile = null;
108
109 private DataStorageManager mStorageManager;
110 private SyncBroadcastReceiver mSyncBroadcastReceiver;
111 private UploadFinishReceiver mUploadFinishReceiver;
112 private DownloadFinishReceiver mDownloadFinishReceiver;
113 private FileDownloaderBinder mDownloaderBinder = null;
114 private FileUploaderBinder mUploaderBinder = null;
115 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
116 private RemoteOperationResult mLastSslUntrustedServerResult = null;
117
118 private OCFileListFragment mFileList;
119
120 private boolean mDualPane;
121 private Handler mHandler;
122
123 private static final int DIALOG_SETUP_ACCOUNT = 0;
124 private static final int DIALOG_CREATE_DIR = 1;
125 private static final int DIALOG_ABOUT_APP = 2;
126 public static final int DIALOG_SHORT_WAIT = 3;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
128 private static final int DIALOG_SSL_VALIDATOR = 5;
129 private static final int DIALOG_CERT_NOT_SAVED = 6;
130 private static final String DIALOG_CHANGELOG_TAG = "DIALOG_CHANGELOG";
131
132
133 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
134 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
135
136 private static final String TAG = "FileDisplayActivity";
137
138 private static int[] mMenuIdentifiersToPatch = {R.id.about_app};
139
140 @Override
141 public void onCreate(Bundle savedInstanceState) {
142 Log.d(getClass().toString(), "onCreate() start");
143 super.onCreate(savedInstanceState);
144
145 mHandler = new Handler();
146
147 /// Load of parameters from received intent
148 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
149 if (account != null && AccountUtils.setCurrentOwnCloudAccount(this, account.name)) {
150 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
151 }
152
153 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
154 if(savedInstanceState != null) {
155 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
156 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
157 }
158
159 if (!AccountUtils.accountsAreSetup(this)) {
160 /// no account available: FORCE ACCOUNT CREATION
161 mStorageManager = null;
162 createFirstAccount();
163
164 } else { /// at least an account is available
165
166 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
167
168 }
169
170 mUploadConnection = new ListServiceConnection();
171 mDownloadConnection = new ListServiceConnection();
172 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
173 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
174
175 // PIN CODE request ; best location is to decide, let's try this first
176 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
177 requestPinCode();
178 }
179
180 // file observer
181 Intent observer_intent = new Intent(this, FileObserverService.class);
182 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
183 startService(observer_intent);
184
185
186 /// USER INTERFACE
187 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
188
189 // Drop-down navigation
190 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
191 OCFile currFile = mCurrentDir;
192 while(mStorageManager != null && currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
193 mDirectories.add(currFile.getFileName());
194 currFile = mStorageManager.getFileById(currFile.getParentId());
195 }
196 mDirectories.add(OCFile.PATH_SEPARATOR);
197
198 // Inflate and set the layout view
199 setContentView(R.layout.files);
200 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
201 mDualPane = (findViewById(R.id.file_details_container) != null);
202 if (mDualPane) {
203 initFileDetailsInDualPane();
204 }
205
206 // Action bar setup
207 ActionBar actionBar = getSupportActionBar();
208 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
209 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
210 actionBar.setDisplayShowTitleEnabled(false);
211 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
212 actionBar.setListNavigationCallbacks(mDirectories, this);
213 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
214
215
216 // show changelog, if needed
217 //showChangeLog();
218
219 Log.d(getClass().toString(), "onCreate() end");
220 }
221
222
223 /**
224 * Shows a dialog with the change log of the current version after each app update
225 *
226 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
227 */
228 private void showChangeLog() {
229 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.JELLY_BEAN) {
230 final String KEY_VERSION = "version";
231 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
232 int currentVersionNumber = 0;
233 int savedVersionNumber = sharedPref.getInt(KEY_VERSION, 0);
234 try {
235 PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
236 currentVersionNumber = pi.versionCode;
237 } catch (Exception e) {}
238
239 if (currentVersionNumber > savedVersionNumber) {
240 ChangelogDialog.newInstance(true).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG);
241 Editor editor = sharedPref.edit();
242 editor.putInt(KEY_VERSION, currentVersionNumber);
243 editor.commit();
244 }
245 }
246 }
247
248
249 /**
250 * Launches the account creation activity. To use when no ownCloud account is available
251 */
252 private void createFirstAccount() {
253 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
254 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTHORITY });
255 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
256 }
257
258
259 /**
260 * Load of state dependent of the existence of an ownCloud account
261 */
262 private void initDataFromCurrentAccount() {
263 /// Storage manager initialization - access to local database
264 mStorageManager = new FileDataStorageManager(
265 AccountUtils.getCurrentOwnCloudAccount(this),
266 getContentResolver());
267
268 /// Check if mCurrentDir is a directory
269 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
270 mCurrentFile = mCurrentDir;
271 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
272 }
273
274 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
275 if (mCurrentDir != null) {
276 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
277 }
278 if (mCurrentFile != null) {
279 if (mCurrentFile.fileExists()) {
280 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
281 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
282 }
283
284 /// Default to root if mCurrentDir was not found
285 if (mCurrentDir == null) {
286 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
287 }
288 }
289
290
291 private void initFileDetailsInDualPane() {
292 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
293 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
294 if (mCurrentFile != null) {
295 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG); // empty FileDetailFragment
296 mCurrentFile = null;
297 } else {
298 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
299 }
300 transaction.commit();
301 }
302 }
303
304
305 @Override
306 public void onDestroy() {
307 super.onDestroy();
308 if (mDownloadConnection != null)
309 unbindService(mDownloadConnection);
310 if (mUploadConnection != null)
311 unbindService(mUploadConnection);
312 }
313
314
315 @Override
316 public boolean onCreateOptionsMenu(Menu menu) {
317 MenuInflater inflater = getSherlock().getMenuInflater();
318 inflater.inflate(R.menu.menu, menu);
319
320 patchHiddenAccents(menu);
321
322 return true;
323 }
324
325 /**
326 * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
327 *
328 * @param menu Menu to patch
329 */
330 private void patchHiddenAccents(Menu menu) {
331 for (int i = 0; i < mMenuIdentifiersToPatch.length ; i++) {
332 MenuItem aboutItem = menu.findItem(mMenuIdentifiersToPatch[i]);
333 if (aboutItem != null && aboutItem.getIcon() instanceof BitmapDrawable) {
334 // Clip off the bottom three (density independent) pixels of transparent padding
335 Bitmap original = ((BitmapDrawable) aboutItem.getIcon()).getBitmap();
336 float scale = getResources().getDisplayMetrics().density;
337 int clippedHeight = (int) (original.getHeight() - (3 * scale));
338 Bitmap scaled = Bitmap.createBitmap(original, 0, 0, original.getWidth(), clippedHeight);
339 aboutItem.setIcon(new BitmapDrawable(getResources(), scaled));
340 }
341 }
342 }
343
344
345 @Override
346 public boolean onOptionsItemSelected(MenuItem item) {
347 boolean retval = true;
348 switch (item.getItemId()) {
349 case R.id.createDirectoryItem: {
350 showDialog(DIALOG_CREATE_DIR);
351 break;
352 }
353 case R.id.startSync: {
354 startSynchronization();
355 break;
356 }
357 case R.id.action_upload: {
358 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
359 break;
360 }
361 case R.id.action_settings: {
362 Intent settingsIntent = new Intent(this, Preferences.class);
363 startActivity(settingsIntent);
364 break;
365 }
366 case R.id.about_app : {
367 showDialog(DIALOG_ABOUT_APP);
368 break;
369 }
370 case android.R.id.home: {
371 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
372 onBackPressed();
373 }
374 break;
375 }
376 default:
377 retval = super.onOptionsItemSelected(item);
378 }
379 return retval;
380 }
381
382 private void startSynchronization() {
383 ContentResolver.cancelSync(null, AccountAuthenticator.AUTHORITY); // cancel the current synchronizations of any ownCloud account
384 Bundle bundle = new Bundle();
385 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
386 ContentResolver.requestSync(
387 AccountUtils.getCurrentOwnCloudAccount(this),
388 AccountAuthenticator.AUTHORITY, bundle);
389 }
390
391
392 @Override
393 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
394 int i = itemPosition;
395 while (i-- != 0) {
396 onBackPressed();
397 }
398 // the next operation triggers a new call to this method, but it's necessary to
399 // ensure that the name exposed in the action bar is the current directory when the
400 // user selected it in the navigation list
401 if (itemPosition != 0)
402 getSupportActionBar().setSelectedNavigationItem(0);
403 return true;
404 }
405
406 /**
407 * Called, when the user selected something for uploading
408 */
409 public void onActivityResult(int requestCode, int resultCode, Intent data) {
410
411 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
412 requestSimpleUpload(data, resultCode);
413
414 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
415 requestMultipleUpload(data, resultCode);
416
417 }
418 }
419
420 private void requestMultipleUpload(Intent data, int resultCode) {
421 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
422 if (filePaths != null) {
423 String[] remotePaths = new String[filePaths.length];
424 String remotePathBase = "";
425 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
426 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
427 }
428 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
429 remotePathBase += OCFile.PATH_SEPARATOR;
430 for (int j = 0; j< remotePaths.length; j++) {
431 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
432 }
433
434 Intent i = new Intent(this, FileUploader.class);
435 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
436 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
437 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
438 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
439 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
440 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
441 startService(i);
442
443 } else {
444 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
445 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
446 t.show();
447 return;
448 }
449 }
450
451
452 private void requestSimpleUpload(Intent data, int resultCode) {
453 String filepath = null;
454 try {
455 Uri selectedImageUri = data.getData();
456
457 String filemanagerstring = selectedImageUri.getPath();
458 String selectedImagePath = getPath(selectedImageUri);
459
460 if (selectedImagePath != null)
461 filepath = selectedImagePath;
462 else
463 filepath = filemanagerstring;
464
465 } catch (Exception e) {
466 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
467 e.printStackTrace();
468
469 } finally {
470 if (filepath == null) {
471 Log.e("FileDisplay", "Couldnt resolve path to file");
472 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
473 t.show();
474 return;
475 }
476 }
477
478 Intent i = new Intent(this, FileUploader.class);
479 i.putExtra(FileUploader.KEY_ACCOUNT,
480 AccountUtils.getCurrentOwnCloudAccount(this));
481 String remotepath = new String();
482 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
483 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
484 }
485 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
486 remotepath += OCFile.PATH_SEPARATOR;
487 remotepath += new File(filepath).getName();
488
489 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
490 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
491 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
492 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
493 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
494 startService(i);
495 }
496
497
498 @Override
499 public void onBackPressed() {
500 if (mDirectories.getCount() <= 1) {
501 finish();
502 return;
503 }
504 popDirname();
505 mFileList.onNavigateUp();
506 mCurrentDir = mFileList.getCurrentFile();
507
508 if (mDualPane) {
509 // Resets the FileDetailsFragment on Tablets so that it always displays
510 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
511 if (fileDetails != null && !fileDetails.isEmpty()) {
512 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
513 transaction.remove(fileDetails);
514 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
515 transaction.commit();
516 }
517 }
518
519 if(mCurrentDir.getParentId() == 0){
520 ActionBar actionBar = getSupportActionBar();
521 actionBar.setDisplayHomeAsUpEnabled(false);
522 }
523 }
524
525 @Override
526 protected void onSaveInstanceState(Bundle outState) {
527 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
528 Log.d(getClass().toString(), "onSaveInstanceState() start");
529 super.onSaveInstanceState(outState);
530 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
531 if (mDualPane) {
532 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
533 if (fragment != null) {
534 OCFile file = fragment.getDisplayedFile();
535 if (file != null) {
536 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
537 }
538 }
539 }
540 Log.d(getClass().toString(), "onSaveInstanceState() end");
541 }
542
543 @Override
544 protected void onResume() {
545 Log.d(getClass().toString(), "onResume() start");
546 super.onResume();
547
548 if (AccountUtils.accountsAreSetup(this)) {
549
550 if (mStorageManager == null) {
551 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
552 initDataFromCurrentAccount();
553 if (mDualPane) {
554 initFileDetailsInDualPane();
555 }
556 }
557
558 // Listen for sync messages
559 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
560 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
561 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
562
563 // Listen for upload messages
564 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
565 mUploadFinishReceiver = new UploadFinishReceiver();
566 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
567
568 // Listen for download messages
569 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
570 mDownloadFinishReceiver = new DownloadFinishReceiver();
571 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
572
573 // List current directory
574 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
575
576 } else {
577
578 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
579 showDialog(DIALOG_SETUP_ACCOUNT);
580
581 }
582 Log.d(getClass().toString(), "onResume() end");
583 }
584
585
586 @Override
587 protected void onPause() {
588 Log.d(getClass().toString(), "onPause() start");
589 super.onPause();
590 if (mSyncBroadcastReceiver != null) {
591 unregisterReceiver(mSyncBroadcastReceiver);
592 mSyncBroadcastReceiver = null;
593 }
594 if (mUploadFinishReceiver != null) {
595 unregisterReceiver(mUploadFinishReceiver);
596 mUploadFinishReceiver = null;
597 }
598 if (mDownloadFinishReceiver != null) {
599 unregisterReceiver(mDownloadFinishReceiver);
600 mDownloadFinishReceiver = null;
601 }
602 if (!AccountUtils.accountsAreSetup(this)) {
603 dismissDialog(DIALOG_SETUP_ACCOUNT);
604 }
605
606 Log.d(getClass().toString(), "onPause() end");
607 }
608
609
610 @Override
611 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
612 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
613 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
614 }
615 }
616
617
618 @Override
619 protected Dialog onCreateDialog(int id) {
620 Dialog dialog = null;
621 AlertDialog.Builder builder;
622 switch (id) {
623 case DIALOG_SETUP_ACCOUNT: {
624 builder = new AlertDialog.Builder(this);
625 builder.setTitle(R.string.main_tit_accsetup);
626 builder.setMessage(R.string.main_wrn_accsetup);
627 builder.setCancelable(false);
628 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
629 public void onClick(DialogInterface dialog, int which) {
630 createFirstAccount();
631 dialog.dismiss();
632 }
633 });
634 String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
635 builder.setNegativeButton(message, new OnClickListener() {
636 public void onClick(DialogInterface dialog, int which) {
637 dialog.dismiss();
638 finish();
639 }
640 });
641 //builder.setNegativeButton(android.R.string.cancel, this);
642 dialog = builder.create();
643 break;
644 }
645 case DIALOG_ABOUT_APP: {
646 builder = new AlertDialog.Builder(this);
647 builder.setTitle(getString(R.string.about_title));
648 PackageInfo pkg;
649 try {
650 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
651 builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
652 builder.setIcon(android.R.drawable.ic_menu_info_details);
653 dialog = builder.create();
654 } catch (NameNotFoundException e) {
655 builder = null;
656 dialog = null;
657 Log.e(TAG, "Error while showing about dialog", e);
658 }
659 break;
660 }
661 case DIALOG_CREATE_DIR: {
662 builder = new Builder(this);
663 final EditText dirNameInput = new EditText(getBaseContext());
664 builder.setView(dirNameInput);
665 builder.setTitle(R.string.uploader_info_dirname);
666 int typed_color = getResources().getColor(R.color.setup_text_typed);
667 dirNameInput.setTextColor(typed_color);
668 builder.setPositiveButton(android.R.string.ok,
669 new OnClickListener() {
670 public void onClick(DialogInterface dialog, int which) {
671 String directoryName = dirNameInput.getText().toString();
672 if (directoryName.trim().length() == 0) {
673 dialog.cancel();
674 return;
675 }
676
677 // Figure out the path where the dir needs to be created
678 String path;
679 if (mCurrentDir == null) {
680 // this is just a patch; we should ensure that mCurrentDir never is null
681 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
682 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
683 mStorageManager.saveFile(file);
684 }
685 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
686 }
687 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
688
689 // Create directory
690 path += directoryName + OCFile.PATH_SEPARATOR;
691 RemoteOperation operation = new CreateFolderOperation(path, mCurrentDir.getFileId(), mStorageManager);
692 operation.execute( AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this),
693 FileDisplayActivity.this,
694 FileDisplayActivity.this,
695 mHandler,
696 FileDisplayActivity.this);
697
698 dialog.dismiss();
699
700 showDialog(DIALOG_SHORT_WAIT);
701 }
702 });
703 builder.setNegativeButton(R.string.common_cancel,
704 new OnClickListener() {
705 public void onClick(DialogInterface dialog, int which) {
706 dialog.cancel();
707 }
708 });
709 dialog = builder.create();
710 break;
711 }
712 case DIALOG_SHORT_WAIT: {
713 ProgressDialog working_dialog = new ProgressDialog(this);
714 working_dialog.setMessage(getResources().getString(
715 R.string.wait_a_moment));
716 working_dialog.setIndeterminate(true);
717 working_dialog.setCancelable(false);
718 dialog = working_dialog;
719 break;
720 }
721 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
722 final String [] items = { getString(R.string.actionbar_upload_files),
723 getString(R.string.actionbar_upload_from_apps) };
724 builder = new AlertDialog.Builder(this);
725 builder.setTitle(R.string.actionbar_upload);
726 builder.setItems(items, new DialogInterface.OnClickListener() {
727 public void onClick(DialogInterface dialog, int item) {
728 if (item == 0) {
729 //if (!mDualPane) {
730 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
731 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
732 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
733 //} else {
734 // TODO create and handle new fragment LocalFileListFragment
735 //}
736 } else if (item == 1) {
737 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
738 action = action.setType("*/*")
739 .addCategory(Intent.CATEGORY_OPENABLE);
740 startActivityForResult(
741 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
742 ACTION_SELECT_CONTENT_FROM_APPS);
743 }
744 }
745 });
746 dialog = builder.create();
747 break;
748 }
749 case DIALOG_SSL_VALIDATOR: {
750 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
751 break;
752 }
753 case DIALOG_CERT_NOT_SAVED: {
754 builder = new AlertDialog.Builder(this);
755 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
756 builder.setCancelable(false);
757 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
758 @Override
759 public void onClick(DialogInterface dialog, int which) {
760 dialog.dismiss();
761 };
762 });
763 dialog = builder.create();
764 break;
765 }
766 default:
767 dialog = null;
768 }
769
770 return dialog;
771 }
772
773
774 /**
775 * Translates a content URI of an image to a physical path
776 * on the disk
777 * @param uri The URI to resolve
778 * @return The path to the image or null if it could not be found
779 */
780 public String getPath(Uri uri) {
781 String[] projection = { MediaStore.Images.Media.DATA };
782 Cursor cursor = managedQuery(uri, projection, null, null, null);
783 if (cursor != null) {
784 int column_index = cursor
785 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
786 cursor.moveToFirst();
787 return cursor.getString(column_index);
788 }
789 return null;
790 }
791
792 /**
793 * Pushes a directory to the drop down list
794 * @param directory to push
795 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
796 */
797 public void pushDirname(OCFile directory) {
798 if(!directory.isDirectory()){
799 throw new IllegalArgumentException("Only directories may be pushed!");
800 }
801 mDirectories.insert(directory.getFileName(), 0);
802 mCurrentDir = directory;
803 }
804
805 /**
806 * Pops a directory name from the drop down list
807 * @return True, unless the stack is empty
808 */
809 public boolean popDirname() {
810 mDirectories.remove(mDirectories.getItem(0));
811 return !mDirectories.isEmpty();
812 }
813
814
815 // Custom array adapter to override text colors
816 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
817
818 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
819 super(ctx, view);
820 }
821
822 public View getView(int position, View convertView, ViewGroup parent) {
823 View v = super.getView(position, convertView, parent);
824
825 ((TextView) v).setTextColor(getResources().getColorStateList(
826 android.R.color.white));
827 return v;
828 }
829
830 public View getDropDownView(int position, View convertView,
831 ViewGroup parent) {
832 View v = super.getDropDownView(position, convertView, parent);
833
834 ((TextView) v).setTextColor(getResources().getColorStateList(
835 android.R.color.white));
836
837 return v;
838 }
839
840 }
841
842 private class SyncBroadcastReceiver extends BroadcastReceiver {
843
844 /**
845 * {@link BroadcastReceiver} to enable syncing feedback in UI
846 */
847 @Override
848 public void onReceive(Context context, Intent intent) {
849 boolean inProgress = intent.getBooleanExtra(
850 FileSyncService.IN_PROGRESS, false);
851 String accountName = intent
852 .getStringExtra(FileSyncService.ACCOUNT_NAME);
853
854 Log.d("FileDisplay", "sync of account " + accountName
855 + " is in_progress: " + inProgress);
856
857 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
858
859 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
860
861 boolean fillBlankRoot = false;
862 if (mCurrentDir == null) {
863 mCurrentDir = mStorageManager.getFileByPath("/");
864 fillBlankRoot = (mCurrentDir != null);
865 }
866
867 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
868 || fillBlankRoot ) {
869 if (!fillBlankRoot)
870 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
871 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
872 .findFragmentById(R.id.fileList);
873 if (fileListFragment != null) {
874 fileListFragment.listDirectory(mCurrentDir);
875 }
876 }
877
878 setSupportProgressBarIndeterminateVisibility(inProgress);
879 removeStickyBroadcast(intent);
880
881 }
882
883 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
884 if (synchResult != null) {
885 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
886 mLastSslUntrustedServerResult = synchResult;
887 showDialog(DIALOG_SSL_VALIDATOR);
888 }
889 }
890 }
891 }
892
893
894 private class UploadFinishReceiver extends BroadcastReceiver {
895 /**
896 * Once the file upload has finished -> update view
897 * @author David A. Velasco
898 * {@link BroadcastReceiver} to enable upload feedback in UI
899 */
900 @Override
901 public void onReceive(Context context, Intent intent) {
902 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
903 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
904 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
905 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
906 if (sameAccount && isDescendant) {
907 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
908 if (fileListFragment != null) {
909 fileListFragment.listDirectory();
910 }
911 }
912 }
913
914 }
915
916
917 /**
918 * Once the file download has finished -> update view
919 */
920 private class DownloadFinishReceiver extends BroadcastReceiver {
921 @Override
922 public void onReceive(Context context, Intent intent) {
923 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
924 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
925 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
926 boolean isDescendant = (mCurrentDir != null) && (downloadedRemotePath != null) && (downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
927 if (sameAccount && isDescendant) {
928 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
929 if (fileListFragment != null) {
930 fileListFragment.listDirectory();
931 }
932 }
933 }
934 }
935
936
937
938
939 /**
940 * {@inheritDoc}
941 */
942 @Override
943 public DataStorageManager getStorageManager() {
944 return mStorageManager;
945 }
946
947
948 /**
949 * {@inheritDoc}
950 */
951 @Override
952 public void onDirectoryClick(OCFile directory) {
953 pushDirname(directory);
954 ActionBar actionBar = getSupportActionBar();
955 actionBar.setDisplayHomeAsUpEnabled(true);
956
957 if (mDualPane) {
958 // Resets the FileDetailsFragment on Tablets so that it always displays
959 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
960 if (fileDetails != null && !fileDetails.isEmpty()) {
961 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
962 transaction.remove(fileDetails);
963 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
964 transaction.commit();
965 }
966 }
967 }
968
969
970 /**
971 * {@inheritDoc}
972 */
973 @Override
974 public void onFileClick(OCFile file) {
975
976 // If we are on a large device -> update fragment
977 if (mDualPane) {
978 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
979 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
980 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
981 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
982 transaction.commit();
983
984 } else { // small or medium screen device -> new Activity
985 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
986 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
987 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
988 startActivity(showDetailsIntent);
989 }
990 }
991
992
993 /**
994 * {@inheritDoc}
995 */
996 @Override
997 public OCFile getInitialDirectory() {
998 return mCurrentDir;
999 }
1000
1001
1002 /**
1003 * {@inheritDoc}
1004 */
1005 @Override
1006 public void onFileStateChanged() {
1007 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1008 if (fileListFragment != null) {
1009 fileListFragment.listDirectory();
1010 }
1011 }
1012
1013
1014 /**
1015 * {@inheritDoc}
1016 */
1017 @Override
1018 public FileDownloaderBinder getFileDownloaderBinder() {
1019 return mDownloaderBinder;
1020 }
1021
1022
1023 /**
1024 * {@inheritDoc}
1025 */
1026 @Override
1027 public FileUploaderBinder getFileUploaderBinder() {
1028 return mUploaderBinder;
1029 }
1030
1031
1032 /** Defines callbacks for service binding, passed to bindService() */
1033 private class ListServiceConnection implements ServiceConnection {
1034
1035 @Override
1036 public void onServiceConnected(ComponentName component, IBinder service) {
1037 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1038 Log.d(TAG, "Download service connected");
1039 mDownloaderBinder = (FileDownloaderBinder) service;
1040 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1041 Log.d(TAG, "Upload service connected");
1042 mUploaderBinder = (FileUploaderBinder) service;
1043 } else {
1044 return;
1045 }
1046 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1047 if (mFileList != null)
1048 mFileList.listDirectory();
1049 if (mDualPane) {
1050 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1051 if (fragment != null)
1052 fragment.updateFileDetails(false);
1053 }
1054 }
1055
1056 @Override
1057 public void onServiceDisconnected(ComponentName component) {
1058 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1059 Log.d(TAG, "Download service disconnected");
1060 mDownloaderBinder = null;
1061 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1062 Log.d(TAG, "Upload service disconnected");
1063 mUploaderBinder = null;
1064 }
1065 }
1066 };
1067
1068
1069
1070 /**
1071 * Launch an intent to request the PIN code to the user before letting him use the app
1072 */
1073 private void requestPinCode() {
1074 boolean pinStart = false;
1075 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1076 pinStart = appPrefs.getBoolean("set_pincode", false);
1077 if (pinStart) {
1078 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1079 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1080 startActivity(i);
1081 }
1082 }
1083
1084
1085 @Override
1086 public void onSavedCertificate() {
1087 startSynchronization();
1088 }
1089
1090
1091 @Override
1092 public void onFailedSavingCertificate() {
1093 showDialog(DIALOG_CERT_NOT_SAVED);
1094 }
1095
1096
1097 /**
1098 * Updates the view associated to the activity after the finish of some operation over files
1099 * in the current account.
1100 *
1101 * @param operation Removal operation performed.
1102 * @param result Result of the removal.
1103 */
1104 @Override
1105 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1106 if (operation instanceof RemoveFileOperation) {
1107 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1108
1109 } else if (operation instanceof RenameFileOperation) {
1110 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1111
1112 } else if (operation instanceof SynchronizeFileOperation) {
1113 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1114
1115 } else if (operation instanceof CreateFolderOperation) {
1116 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1117 }
1118 }
1119
1120 /**
1121 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1122 *
1123 * @param operation Creation operation performed.
1124 * @param result Result of the creation.
1125 */
1126 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1127 if (result.isSuccess()) {
1128 dismissDialog(DIALOG_SHORT_WAIT);
1129 mFileList.listDirectory();
1130
1131 } else {
1132 dismissDialog(DIALOG_SHORT_WAIT);
1133 try {
1134 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1135 msg.show();
1136
1137 } catch (NotFoundException e) {
1138 Log.e(TAG, "Error while trying to show fail message " , e);
1139 }
1140 }
1141 }
1142
1143
1144 /**
1145 * Updates the view associated to the activity after the finish of an operation trying to remove a
1146 * file.
1147 *
1148 * @param operation Removal operation performed.
1149 * @param result Result of the removal.
1150 */
1151 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1152 dismissDialog(DIALOG_SHORT_WAIT);
1153 if (result.isSuccess()) {
1154 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1155 msg.show();
1156 OCFile removedFile = operation.getFile();
1157 if (mDualPane) {
1158 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1159 if (details != null && removedFile.equals(details.getDisplayedFile()) ) {
1160 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1161 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1162 transaction.commit();
1163 }
1164 }
1165 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1166 mFileList.listDirectory();
1167 }
1168
1169 } else {
1170 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1171 msg.show();
1172 if (result.isSslRecoverableException()) {
1173 mLastSslUntrustedServerResult = result;
1174 showDialog(DIALOG_SSL_VALIDATOR);
1175 }
1176 }
1177 }
1178
1179 /**
1180 * Updates the view associated to the activity after the finish of an operation trying to rename a
1181 * file.
1182 *
1183 * @param operation Renaming operation performed.
1184 * @param result Result of the renaming.
1185 */
1186 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1187 dismissDialog(DIALOG_SHORT_WAIT);
1188 OCFile renamedFile = operation.getFile();
1189 if (result.isSuccess()) {
1190 if (mDualPane) {
1191 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1192 if (details != null && renamedFile.equals(details.getDisplayedFile()) ) {
1193 details.updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1194 }
1195 }
1196 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1197 mFileList.listDirectory();
1198 }
1199
1200 } else {
1201 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1202 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1203 msg.show();
1204 // TODO throw again the new rename dialog
1205 } else {
1206 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1207 msg.show();
1208 if (result.isSslRecoverableException()) {
1209 mLastSslUntrustedServerResult = result;
1210 showDialog(DIALOG_SSL_VALIDATOR);
1211 }
1212 }
1213 }
1214 }
1215
1216
1217 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1218 dismissDialog(DIALOG_SHORT_WAIT);
1219 OCFile syncedFile = operation.getLocalFile();
1220 if (!result.isSuccess()) {
1221 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1222 Intent i = new Intent(this, ConflictsResolveActivity.class);
1223 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1224 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1225 startActivity(i);
1226
1227 } else {
1228 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1229 msg.show();
1230 }
1231
1232 } else {
1233 if (operation.transferWasRequested()) {
1234 mFileList.listDirectory();
1235 onTransferStateChanged(syncedFile, true, true);
1236
1237 } else {
1238 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1239 msg.show();
1240 }
1241 }
1242 }
1243
1244
1245 /**
1246 * {@inheritDoc}
1247 */
1248 @Override
1249 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1250 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1251 if (fileListFragment != null) {
1252 fileListFragment.listDirectory();
1253 }*/
1254 if (mDualPane) {
1255 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1256 if (details != null && file.equals(details.getDisplayedFile()) ) {
1257 if (downloading || uploading) {
1258 details.updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1259 } else {
1260 details.updateFileDetails(downloading || uploading);
1261 }
1262 }
1263 }
1264 }
1265
1266
1267
1268
1269
1270 }