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