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