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