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