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