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