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