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