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