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