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