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