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