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