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