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