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