4135ba3d2453410a0d416a645bbb1a529d4d940f
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.app.AlertDialog;
25 import android.app.Dialog;
26 import android.app.ProgressDialog;
27 import android.content.BroadcastReceiver;
28 import android.content.ComponentName;
29 import android.content.ContentResolver;
30 import android.content.Context;
31 import android.content.DialogInterface;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.ServiceConnection;
35 import android.content.SharedPreferences;
36 import android.content.SyncRequest;
37 import android.content.res.Resources.NotFoundException;
38 import android.database.Cursor;
39 import android.net.Uri;
40 import android.os.Bundle;
41 import android.os.Handler;
42 import android.os.IBinder;
43 import android.preference.PreferenceManager;
44 import android.provider.MediaStore;
45 import android.support.v4.app.Fragment;
46 import android.support.v4.app.FragmentManager;
47 import android.support.v4.app.FragmentTransaction;
48 import android.util.Log;
49 import android.view.View;
50 import android.view.ViewGroup;
51 import android.widget.ArrayAdapter;
52 import android.widget.TextView;
53 import android.widget.Toast;
54
55 import com.actionbarsherlock.app.ActionBar;
56 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
57 import com.actionbarsherlock.view.Menu;
58 import com.actionbarsherlock.view.MenuInflater;
59 import com.actionbarsherlock.view.MenuItem;
60 import com.actionbarsherlock.view.Window;
61 import com.owncloud.android.MainApp;
62 import com.owncloud.android.R;
63 import com.owncloud.android.datamodel.FileDataStorageManager;
64 import com.owncloud.android.datamodel.OCFile;
65 import com.owncloud.android.files.services.FileDownloader;
66 import com.owncloud.android.files.services.FileObserverService;
67 import com.owncloud.android.files.services.FileUploader;
68 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
69 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
70 import com.owncloud.android.operations.CreateFolderOperation;
71 import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener;
72 import com.owncloud.android.oc_framework.operations.RemoteOperation;
73 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
74 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
75 import com.owncloud.android.operations.GetSharedFilesOperation;
76 import com.owncloud.android.operations.RemoveFileOperation;
77 import com.owncloud.android.operations.RenameFileOperation;
78 import com.owncloud.android.operations.SynchronizeFileOperation;
79 import com.owncloud.android.operations.SynchronizeFolderOperation;
80 import com.owncloud.android.syncadapter.FileSyncService;
81 import com.owncloud.android.ui.dialog.EditNameDialog;
82 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
83 import com.owncloud.android.ui.dialog.LoadingDialog;
84 import com.owncloud.android.ui.dialog.SslValidatorDialog;
85 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
86 import com.owncloud.android.ui.fragment.FileDetailFragment;
87 import com.owncloud.android.ui.fragment.FileFragment;
88 import com.owncloud.android.ui.fragment.OCFileListFragment;
89 import com.owncloud.android.ui.preview.PreviewImageActivity;
90 import com.owncloud.android.ui.preview.PreviewMediaFragment;
91 import com.owncloud.android.ui.preview.PreviewVideoActivity;
92 import com.owncloud.android.utils.DisplayUtils;
93 import com.owncloud.android.utils.Log_OC;
94
95
96 /**
97 * Displays, what files the user has available in his ownCloud.
98 *
99 * @author Bartek Przybylski
100 * @author David A. Velasco
101 */
102
103 public class FileDisplayActivity extends FileActivity implements
104 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
105
106 private ArrayAdapter<String> mDirectories;
107
108 /** Access point to the cached database for the current ownCloud {@link Account} */
109 private FileDataStorageManager mStorageManager = null;
110
111 private SyncBroadcastReceiver mSyncBroadcastReceiver;
112 private UploadFinishReceiver mUploadFinishReceiver;
113 private DownloadFinishReceiver mDownloadFinishReceiver;
114 private FileDownloaderBinder mDownloaderBinder = null;
115 private FileUploaderBinder mUploaderBinder = null;
116 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
117 private RemoteOperationResult mLastSslUntrustedServerResult = null;
118
119 private boolean mDualPane;
120 private View mLeftFragmentContainer;
121 private View mRightFragmentContainer;
122
123 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
124 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
125
126 public static final int DIALOG_SHORT_WAIT = 0;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
128 private static final int DIALOG_SSL_VALIDATOR = 2;
129 private static final int DIALOG_CERT_NOT_SAVED = 3;
130
131 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
132
133 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
134
135 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
136 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
137
138 private static final String TAG = FileDisplayActivity.class.getSimpleName();
139
140 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
142
143 private OCFile mWaitingToPreview;
144 private Handler mHandler;
145
146 private boolean mSyncInProgress = false;
147
148 @Override
149 protected void onCreate(Bundle savedInstanceState) {
150 Log_OC.d(TAG, "onCreate() start");
151 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
152
153 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
154
155 mHandler = new Handler();
156
157 /// bindings to transference services
158 mUploadConnection = new ListServiceConnection();
159 mDownloadConnection = new ListServiceConnection();
160 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
161 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
162
163 // PIN CODE request ; best location is to decide, let's try this first
164 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
165 requestPinCode();
166 } else if (getIntent().getAction() == null && savedInstanceState == null) {
167 requestPinCode();
168 }
169
170 /// file observer
171 Intent observer_intent = new Intent(this, FileObserverService.class);
172 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
173 startService(observer_intent);
174
175 /// Load of saved instance state
176 if(savedInstanceState != null) {
177 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
178 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
179
180 } else {
181 mWaitingToPreview = null;
182 mSyncInProgress = false;
183 }
184
185 /// USER INTERFACE
186
187 // Inflate and set the layout view
188 setContentView(R.layout.files);
189 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
190 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
191 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
192 if (savedInstanceState == null) {
193 createMinFragments();
194 }
195
196 // Action bar setup
197 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
198 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress); // always AFTER setContentView(...) ; to work around bug in its implementation
200
201 Log_OC.d(TAG, "onCreate() end");
202 }
203
204 @Override
205 protected void onStart() {
206 super.onStart();
207 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
208 }
209
210 @Override
211 protected void onDestroy() {
212 super.onDestroy();
213 if (mDownloadConnection != null)
214 unbindService(mDownloadConnection);
215 if (mUploadConnection != null)
216 unbindService(mUploadConnection);
217 }
218
219
220 /**
221 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
222 */
223 @Override
224 protected void onAccountSet(boolean stateWasRecovered) {
225 if (getAccount() != null) {
226 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
227
228 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
229 OCFile file = getFile();
230 // get parent from path
231 String parentPath = "";
232 if (file != null) {
233 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
234 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
235 // get parent from path
236 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
237 if (mStorageManager.getFileByPath(parentPath) == null)
238 file = null; // not able to know the directory where the file is uploading
239 } else {
240 file = mStorageManager.getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
241 }
242 }
243 if (file == null) {
244 // fall back to root folder
245 file = mStorageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null
246 }
247 setFile(file);
248 setNavigationListWithFolder(file);
249
250 /// get the shared files
251 if (isSharedSupported()) {
252 startGetSharedFiles();
253 }
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 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
927
928 OCFile currentFile = (getFile() == null) ? null : mStorageManager.getFileByPath(getFile().getRemotePath());
929 OCFile currentDir = (getCurrentDir() == null) ? null : mStorageManager.getFileByPath(getCurrentDir().getRemotePath());
930
931 if (currentDir == null) {
932 // current folder was removed from the server
933 Toast.makeText( FileDisplayActivity.this,
934 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
935 Toast.LENGTH_LONG)
936 .show();
937 browseToRoot();
938
939 } else {
940 if (currentFile == null && !getFile().isFolder()) {
941 // currently selected file was removed in the server, and now we know it
942 cleanSecondFragment();
943 currentFile = currentDir;
944 }
945
946 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
947 OCFileListFragment fileListFragment = getListOfFilesFragment();
948 if (fileListFragment != null) {
949 fileListFragment.listDirectory(currentDir);
950 }
951 }
952 setFile(currentFile);
953 }
954
955 setSupportProgressBarIndeterminateVisibility(inProgress);
956 removeStickyBroadcast(intent);
957 mSyncInProgress = inProgress;
958
959 }
960
961 if (synchResult != null) {
962 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
963 mLastSslUntrustedServerResult = synchResult;
964 showDialog(DIALOG_SSL_VALIDATOR);
965 }
966 }
967 }
968 }
969
970
971 private class UploadFinishReceiver extends BroadcastReceiver {
972 /**
973 * Once the file upload has finished -> update view
974 * @author David A. Velasco
975 * {@link BroadcastReceiver} to enable upload feedback in UI
976 */
977 @Override
978 public void onReceive(Context context, Intent intent) {
979 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
980 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
981 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
982 OCFile currentDir = getCurrentDir();
983 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
984 if (sameAccount && isDescendant) {
985 refeshListOfFilesFragment();
986 }
987 }
988
989 }
990
991
992 /**
993 * Class waiting for broadcast events from the {@link FielDownloader} service.
994 *
995 * Updates the UI when a download is started or finished, provided that it is relevant for the
996 * current folder.
997 */
998 private class DownloadFinishReceiver extends BroadcastReceiver {
999 @Override
1000 public void onReceive(Context context, Intent intent) {
1001 boolean sameAccount = isSameAccount(context, intent);
1002 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1003 boolean isDescendant = isDescendant(downloadedRemotePath);
1004
1005 if (sameAccount && isDescendant) {
1006 refeshListOfFilesFragment();
1007 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1008 }
1009
1010 removeStickyBroadcast(intent);
1011 }
1012
1013 private boolean isDescendant(String downloadedRemotePath) {
1014 OCFile currentDir = getCurrentDir();
1015 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1016 }
1017
1018 private boolean isSameAccount(Context context, Intent intent) {
1019 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1020 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1021 }
1022 }
1023
1024
1025 /**
1026 * {@inheritDoc}
1027 */
1028 @Override
1029 public FileDataStorageManager getStorageManager() {
1030 return mStorageManager;
1031 }
1032
1033
1034 public void browseToRoot() {
1035 OCFileListFragment listOfFiles = getListOfFilesFragment();
1036 if (listOfFiles != null) { // should never be null, indeed
1037 while (mDirectories.getCount() > 1) {
1038 popDirname();
1039 }
1040 OCFile root = mStorageManager.getFileByPath(OCFile.ROOT_PATH);
1041 listOfFiles.listDirectory(root);
1042 setFile(listOfFiles.getCurrentFile());
1043 startSyncFolderOperation(root);
1044 }
1045 cleanSecondFragment();
1046 }
1047
1048
1049 public void browseTo(OCFile folder) {
1050 if (folder == null || !folder.isFolder()) {
1051 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1052 }
1053 OCFileListFragment listOfFiles = getListOfFilesFragment();
1054 if (listOfFiles != null) {
1055 setNavigationListWithFolder(folder);
1056 listOfFiles.listDirectory(folder);
1057 setFile(listOfFiles.getCurrentFile());
1058 startSyncFolderOperation(folder);
1059 } else {
1060 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1061 }
1062 cleanSecondFragment();
1063 }
1064
1065
1066 /**
1067 * {@inheritDoc}
1068 *
1069 * Updates action bar and second fragment, if in dual pane mode.
1070 */
1071 @Override
1072 public void onBrowsedDownTo(OCFile directory) {
1073 pushDirname(directory);
1074 cleanSecondFragment();
1075
1076 // Sync Folder
1077 startSyncFolderOperation(directory);
1078
1079 }
1080
1081 /**
1082 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1083 *
1084 * @param file Image {@link OCFile} to show.
1085 */
1086 @Override
1087 public void startImagePreview(OCFile file) {
1088 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1089 showDetailsIntent.putExtra(EXTRA_FILE, file);
1090 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1091 startActivity(showDetailsIntent);
1092 }
1093
1094 /**
1095 * Stars the preview of an already down media {@link OCFile}.
1096 *
1097 * @param file Media {@link OCFile} to preview.
1098 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1099 * @param autoplay When 'true', the playback will start without user interactions.
1100 */
1101 @Override
1102 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1103 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1104 setSecondFragment(mediaFragment);
1105 updateFragmentsVisibility(true);
1106 updateNavigationElementsInActionBar(file);
1107 setFile(file);
1108 }
1109
1110 /**
1111 * Requests the download of the received {@link OCFile} , updates the UI
1112 * to monitor the download progress and prepares the activity to preview
1113 * or open the file when the download finishes.
1114 *
1115 * @param file {@link OCFile} to download and preview.
1116 */
1117 @Override
1118 public void startDownloadForPreview(OCFile file) {
1119 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1120 setSecondFragment(detailFragment);
1121 mWaitingToPreview = file;
1122 requestForDownload();
1123 updateFragmentsVisibility(true);
1124 updateNavigationElementsInActionBar(file);
1125 setFile(file);
1126 }
1127
1128
1129 /**
1130 * Shows the information of the {@link OCFile} received as a
1131 * parameter in the second fragment.
1132 *
1133 * @param file {@link OCFile} whose details will be shown
1134 */
1135 @Override
1136 public void showDetails(OCFile file) {
1137 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1138 setSecondFragment(detailFragment);
1139 updateFragmentsVisibility(true);
1140 updateNavigationElementsInActionBar(file);
1141 setFile(file);
1142 }
1143
1144
1145 /**
1146 * TODO
1147 */
1148 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1149 ActionBar actionBar = getSupportActionBar();
1150 if (chosenFile == null || mDualPane) {
1151 // only list of files - set for browsing through folders
1152 OCFile currentDir = getCurrentDir();
1153 actionBar.setDisplayHomeAsUpEnabled(currentDir != null && currentDir.getParentId() != 0);
1154 actionBar.setDisplayShowTitleEnabled(false);
1155 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1156 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1157
1158 } else {
1159 actionBar.setDisplayHomeAsUpEnabled(true);
1160 actionBar.setDisplayShowTitleEnabled(true);
1161 actionBar.setTitle(chosenFile.getFileName());
1162 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1163 }
1164 }
1165
1166
1167 /**
1168 * {@inheritDoc}
1169 */
1170 @Override
1171 public void onFileStateChanged() {
1172 refeshListOfFilesFragment();
1173 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1174 }
1175
1176
1177 /**
1178 * {@inheritDoc}
1179 */
1180 @Override
1181 public FileDownloaderBinder getFileDownloaderBinder() {
1182 return mDownloaderBinder;
1183 }
1184
1185
1186 /**
1187 * {@inheritDoc}
1188 */
1189 @Override
1190 public FileUploaderBinder getFileUploaderBinder() {
1191 return mUploaderBinder;
1192 }
1193
1194
1195 /** Defines callbacks for service binding, passed to bindService() */
1196 private class ListServiceConnection implements ServiceConnection {
1197
1198 @Override
1199 public void onServiceConnected(ComponentName component, IBinder service) {
1200 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1201 Log_OC.d(TAG, "Download service connected");
1202 mDownloaderBinder = (FileDownloaderBinder) service;
1203 if (mWaitingToPreview != null) {
1204 requestForDownload();
1205 }
1206
1207 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1208 Log_OC.d(TAG, "Upload service connected");
1209 mUploaderBinder = (FileUploaderBinder) service;
1210 } else {
1211 return;
1212 }
1213 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1214 OCFileListFragment listOfFiles = getListOfFilesFragment();
1215 if (listOfFiles != null) {
1216 listOfFiles.listDirectory();
1217 }
1218 FileFragment secondFragment = getSecondFragment();
1219 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1220 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1221 detailFragment.listenForTransferProgress();
1222 detailFragment.updateFileDetails(false, false);
1223 }
1224 }
1225
1226 @Override
1227 public void onServiceDisconnected(ComponentName component) {
1228 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1229 Log_OC.d(TAG, "Download service disconnected");
1230 mDownloaderBinder = null;
1231 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1232 Log_OC.d(TAG, "Upload service disconnected");
1233 mUploaderBinder = null;
1234 }
1235 }
1236 };
1237
1238
1239
1240 /**
1241 * Launch an intent to request the PIN code to the user before letting him use the app
1242 */
1243 private void requestPinCode() {
1244 boolean pinStart = false;
1245 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1246 pinStart = appPrefs.getBoolean("set_pincode", false);
1247 if (pinStart) {
1248 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1249 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1250 startActivity(i);
1251 }
1252 }
1253
1254
1255 @Override
1256 public void onSavedCertificate() {
1257 startSyncFolderOperation(getCurrentDir());
1258 }
1259
1260
1261 @Override
1262 public void onFailedSavingCertificate() {
1263 showDialog(DIALOG_CERT_NOT_SAVED);
1264 }
1265
1266
1267 /**
1268 * Updates the view associated to the activity after the finish of some operation over files
1269 * in the current account.
1270 *
1271 * @param operation Removal operation performed.
1272 * @param result Result of the removal.
1273 */
1274 @Override
1275 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1276 if (operation instanceof RemoveFileOperation) {
1277 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1278
1279 } else if (operation instanceof RenameFileOperation) {
1280 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1281
1282 } else if (operation instanceof SynchronizeFileOperation) {
1283 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1284
1285 } else if (operation instanceof CreateFolderOperation) {
1286 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1287
1288 } else if (operation instanceof GetSharedFilesOperation) {
1289 onGetSharedFilesOperationFinish((GetSharedFilesOperation) operation, result);
1290 }
1291 }
1292
1293
1294 /** Updates the data about shared files
1295 *
1296 * @param operation Get Shared Files
1297 * @param result Result of the operation
1298 */
1299 private void onGetSharedFilesOperationFinish(GetSharedFilesOperation operation, RemoteOperationResult result) {
1300 // TODO
1301 // Refresh the filelist with the information
1302 refeshListOfFilesFragment();
1303
1304 }
1305
1306 /**
1307 * Updates the view associated to the activity after the finish of an operation trying to remove a
1308 * file.
1309 *
1310 * @param operation Removal operation performed.
1311 * @param result Result of the removal.
1312 */
1313 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1314 dismissLoadingDialog();
1315 if (result.isSuccess()) {
1316 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1317 msg.show();
1318 OCFile removedFile = operation.getFile();
1319 getSecondFragment();
1320 FileFragment second = getSecondFragment();
1321 if (second != null && removedFile.equals(second.getFile())) {
1322 cleanSecondFragment();
1323 }
1324 if (mStorageManager.getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1325 refeshListOfFilesFragment();
1326 }
1327
1328 } else {
1329 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1330 msg.show();
1331 if (result.isSslRecoverableException()) {
1332 mLastSslUntrustedServerResult = result;
1333 showDialog(DIALOG_SSL_VALIDATOR);
1334 }
1335 }
1336 }
1337
1338 /**
1339 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1340 *
1341 * @param operation Creation operation performed.
1342 * @param result Result of the creation.
1343 */
1344 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1345 if (result.isSuccess()) {
1346 dismissLoadingDialog();
1347 refeshListOfFilesFragment();
1348
1349 } else {
1350 dismissLoadingDialog();
1351 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1352 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1353 } else {
1354 try {
1355 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1356 msg.show();
1357
1358 } catch (NotFoundException e) {
1359 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1360 }
1361 }
1362 }
1363 }
1364
1365
1366 /**
1367 * Updates the view associated to the activity after the finish of an operation trying to rename a
1368 * file.
1369 *
1370 * @param operation Renaming operation performed.
1371 * @param result Result of the renaming.
1372 */
1373 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1374 dismissLoadingDialog();
1375 OCFile renamedFile = operation.getFile();
1376 if (result.isSuccess()) {
1377 if (mDualPane) {
1378 FileFragment details = getSecondFragment();
1379 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1380 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1381 }
1382 }
1383 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1384 refeshListOfFilesFragment();
1385 }
1386
1387 } else {
1388 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1389 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1390 msg.show();
1391 // TODO throw again the new rename dialog
1392 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1393 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1394 msg.show();
1395 } else {
1396 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1397 msg.show();
1398 if (result.isSslRecoverableException()) {
1399 mLastSslUntrustedServerResult = result;
1400 showDialog(DIALOG_SSL_VALIDATOR);
1401 }
1402 }
1403 }
1404 }
1405
1406
1407 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1408 dismissLoadingDialog();
1409 OCFile syncedFile = operation.getLocalFile();
1410 if (!result.isSuccess()) {
1411 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1412 Intent i = new Intent(this, ConflictsResolveActivity.class);
1413 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1414 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1415 startActivity(i);
1416
1417 }
1418
1419 } else {
1420 if (operation.transferWasRequested()) {
1421 refeshListOfFilesFragment();
1422 onTransferStateChanged(syncedFile, true, true);
1423
1424 } else {
1425 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1426 msg.show();
1427 }
1428 }
1429 }
1430
1431
1432 /**
1433 * {@inheritDoc}
1434 */
1435 @Override
1436 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1437 if (mDualPane) {
1438 FileFragment details = getSecondFragment();
1439 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1440 if (downloading || uploading) {
1441 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1442 } else {
1443 ((FileDetailFragment)details).updateFileDetails(false, true);
1444 }
1445 }
1446 }
1447 }
1448
1449
1450 public void onDismiss(EditNameDialog dialog) {
1451 if (dialog.getResult()) {
1452 String newDirectoryName = dialog.getNewFilename().trim();
1453 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1454 if (newDirectoryName.length() > 0) {
1455 String path = getCurrentDir().getRemotePath();
1456
1457 // Create directory
1458 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1459 RemoteOperation operation = new CreateFolderOperation(path, false, mStorageManager);
1460 operation.execute( getAccount(),
1461 FileDisplayActivity.this,
1462 FileDisplayActivity.this,
1463 mHandler,
1464 FileDisplayActivity.this);
1465
1466 showLoadingDialog();
1467 }
1468 }
1469 }
1470
1471
1472 private void requestForDownload() {
1473 Account account = getAccount();
1474 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1475 Intent i = new Intent(this, FileDownloader.class);
1476 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1477 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1478 startService(i);
1479 }
1480 }
1481
1482
1483 private OCFile getCurrentDir() {
1484 OCFile file = getFile();
1485 if (file != null) {
1486 if (file.isFolder()) {
1487 return file;
1488 } else if (mStorageManager != null) {
1489 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1490 return mStorageManager.getFileByPath(parentPath);
1491 }
1492 }
1493 return null;
1494 }
1495
1496 public void startSyncFolderOperation(OCFile folder) {
1497 long currentSyncTime = System.currentTimeMillis();
1498
1499 mSyncInProgress = true;
1500
1501 // perform folder synchronization
1502 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1503 currentSyncTime,
1504 false,
1505 getStorageManager(),
1506 getAccount(),
1507 getApplicationContext()
1508 );
1509 synchFolderOp.execute(getAccount(), this, null, null, this);
1510
1511 setSupportProgressBarIndeterminateVisibility(true);
1512 }
1513
1514
1515 private void startGetSharedFiles() {
1516 // Get shared files/folders
1517 RemoteOperation getSharedFiles = new GetSharedFilesOperation();
1518 getSharedFiles.execute(getAccount(), this, null, null, this);
1519
1520 }
1521
1522 // public void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
1523 // int childCount = viewGroup.getChildCount();
1524 // for (int i = 0; i < childCount; i++) {
1525 // View view = viewGroup.getChildAt(i);
1526 // view.setEnabled(enabled);
1527 // view.setClickable(!enabled);
1528 // if (view instanceof ViewGroup) {
1529 // enableDisableViewGroup((ViewGroup) view, enabled);
1530 // }
1531 // }
1532 // }
1533 }