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