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