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