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