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