a7a25382b74f9dc2929e0baf8a348262704a1c7f
[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.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.FileDownloader.FileDownloaderBinder;
69 import com.owncloud.android.files.services.FileUploader;
70 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
71 import com.owncloud.android.lib.common.OwnCloudAccount;
72 import com.owncloud.android.lib.common.OwnCloudClient;
73 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
74 import com.owncloud.android.lib.common.OwnCloudCredentials;
75 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
76 import com.owncloud.android.lib.common.network.CertificateCombinedException;
77 import com.owncloud.android.lib.common.operations.RemoteOperation;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
79 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
80 import com.owncloud.android.operations.CreateFolderOperation;
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.services.observer.FileObserverService;
88 import com.owncloud.android.syncadapter.FileSyncAdapter;
89 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
90 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
91 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
92 import com.owncloud.android.ui.fragment.FileDetailFragment;
93 import com.owncloud.android.ui.fragment.FileFragment;
94 import com.owncloud.android.ui.fragment.OCFileListFragment;
95 import com.owncloud.android.ui.preview.PreviewImageActivity;
96 import com.owncloud.android.ui.preview.PreviewImageFragment;
97 import com.owncloud.android.ui.preview.PreviewMediaFragment;
98 import com.owncloud.android.ui.preview.PreviewVideoActivity;
99 import com.owncloud.android.utils.DisplayUtils;
100 import com.owncloud.android.utils.ErrorMessageAdapter;
101 import com.owncloud.android.utils.Log_OC;
102
103
104 /**
105 * Displays, what files the user has available in his ownCloud.
106 *
107 * @author Bartek Przybylski
108 * @author David A. Velasco
109 */
110
111 public class FileDisplayActivity extends HookActivity implements
112 FileFragment.ContainerActivity, OnNavigationListener, OnSslUntrustedCertListener {
113
114 private ArrayAdapter<String> mDirectories;
115
116 private SyncBroadcastReceiver mSyncBroadcastReceiver;
117 private UploadFinishReceiver mUploadFinishReceiver;
118 private DownloadFinishReceiver mDownloadFinishReceiver;
119 private RemoteOperationResult mLastSslUntrustedServerResult = null;
120
121 private boolean mDualPane;
122 private View mLeftFragmentContainer;
123 private View mRightFragmentContainer;
124
125 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
126 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
127 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
128
129 public static final int DIALOG_SHORT_WAIT = 0;
130 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
131 private static final int DIALOG_CERT_NOT_SAVED = 2;
132
133 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
134
135 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
136 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
137
138 private static final String TAG = FileDisplayActivity.class.getSimpleName();
139
140 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
142
143 private OCFile mWaitingToPreview;
144
145 private boolean mSyncInProgress = false;
146
147 private String DIALOG_UNTRUSTED_CERT;
148
149 private OCFile mWaitingToSend;
150
151 @Override
152 protected void onCreate(Bundle savedInstanceState) {
153 Log_OC.d(TAG, "onCreate() start");
154 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
155
156 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
157
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
160 requestPinCode();
161 } else if (getIntent().getAction() == null && savedInstanceState == null) {
162 requestPinCode();
163 }
164
165 /// grant that FileObserverService is watching favourite files
166 if (savedInstanceState == null) {
167 Intent initObserversIntent = FileObserverService.makeInitIntent(this);
168 startService(initObserversIntent);
169 }
170
171 /// Load of saved instance state
172 if(savedInstanceState != null) {
173 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
174 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
175 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
176
177 } else {
178 mWaitingToPreview = null;
179 mSyncInProgress = false;
180 mWaitingToSend = null;
181 }
182
183 /// USER INTERFACE
184
185 // Inflate and set the layout view
186 setContentView(R.layout.files);
187 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
188 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
189 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
190 if (savedInstanceState == null) {
191 createMinFragments();
192 }
193
194 // Action bar setup
195 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
196 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
198
199 setBackgroundText();
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
743 String[] allTheItems = { getString(R.string.actionbar_upload_files),
744 getString(R.string.actionbar_upload_from_apps) };
745
746 builder = new AlertDialog.Builder(this);
747 builder.setTitle(R.string.actionbar_upload);
748 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
749 public void onClick(DialogInterface dialog, int item) {
750 if (item == 0) {
751 // if (!mDualPane) {
752 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
753 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
754 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
755 // } else {
756 // TODO create and handle new fragment
757 // LocalFileListFragment
758 // }
759 } else if (item == 1) {
760 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
761 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
762 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
763 ACTION_SELECT_CONTENT_FROM_APPS);
764 }
765 }
766 });
767 dialog = builder.create();
768 break;
769 }
770 case DIALOG_CERT_NOT_SAVED: {
771 builder = new AlertDialog.Builder(this);
772 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
773 builder.setCancelable(false);
774 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
775 @Override
776 public void onClick(DialogInterface dialog, int which) {
777 dialog.dismiss();
778 };
779 });
780 dialog = builder.create();
781 break;
782 }
783 default:
784 dialog = null;
785 }
786
787 return dialog;
788 }
789
790
791 /**
792 * Translates a content URI of an image to a physical path
793 * on the disk
794 * @param uri The URI to resolve
795 * @return The path to the image or null if it could not be found
796 */
797 public String getPath(Uri uri) {
798 String[] projection = { MediaStore.Images.Media.DATA };
799 Cursor cursor = managedQuery(uri, projection, null, null, null);
800 if (cursor != null) {
801 int column_index = cursor
802 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
803 cursor.moveToFirst();
804 return cursor.getString(column_index);
805 }
806 return null;
807 }
808
809 /**
810 * Pushes a directory to the drop down list
811 * @param directory to push
812 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
813 */
814 public void pushDirname(OCFile directory) {
815 if(!directory.isFolder()){
816 throw new IllegalArgumentException("Only directories may be pushed!");
817 }
818 mDirectories.insert(directory.getFileName(), 0);
819 setFile(directory);
820 }
821
822 /**
823 * Pops a directory name from the drop down list
824 * @return True, unless the stack is empty
825 */
826 public boolean popDirname() {
827 mDirectories.remove(mDirectories.getItem(0));
828 return !mDirectories.isEmpty();
829 }
830
831 // Custom array adapter to override text colors
832 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
833
834 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
835 super(ctx, view);
836 }
837
838 public View getView(int position, View convertView, ViewGroup parent) {
839 View v = super.getView(position, convertView, parent);
840
841 ((TextView) v).setTextColor(getResources().getColorStateList(
842 android.R.color.white));
843
844 fixRoot((TextView) v );
845 return v;
846 }
847
848 public View getDropDownView(int position, View convertView,
849 ViewGroup parent) {
850 View v = super.getDropDownView(position, convertView, parent);
851
852 ((TextView) v).setTextColor(getResources().getColorStateList(
853 android.R.color.white));
854
855 fixRoot((TextView) v );
856 return v;
857 }
858
859 private void fixRoot(TextView v) {
860 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
861 v.setText(R.string.default_display_name_for_root_folder);
862 }
863 }
864
865 }
866
867 private class SyncBroadcastReceiver extends BroadcastReceiver {
868
869 /**
870 * {@link BroadcastReceiver} to enable syncing feedback in UI
871 */
872 @Override
873 public void onReceive(Context context, Intent intent) {
874 try {
875 String event = intent.getAction();
876 Log_OC.d(TAG, "Received broadcast " + event);
877 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
878 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
879 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
880 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
881
882 if (sameAccount) {
883
884 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
885 mSyncInProgress = true;
886
887 } else {
888 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
889 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
890
891 if (currentDir == null) {
892 // current folder was removed from the server
893 Toast.makeText( FileDisplayActivity.this,
894 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
895 Toast.LENGTH_LONG)
896 .show();
897 browseToRoot();
898
899 } else {
900 if (currentFile == null && !getFile().isFolder()) {
901 // currently selected file was removed in the server, and now we know it
902 cleanSecondFragment();
903 currentFile = currentDir;
904 }
905
906 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
907 OCFileListFragment fileListFragment = getListOfFilesFragment();
908 if (fileListFragment != null) {
909 fileListFragment.listDirectory(currentDir);
910 }
911 }
912 setFile(currentFile);
913 }
914
915 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
916
917 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
918 equals(event) &&
919 /// TODO refactor and make common
920 synchResult != null && !synchResult.isSuccess() &&
921 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
922 synchResult.isIdPRedirection() ||
923 (synchResult.isException() && synchResult.getException()
924 instanceof AuthenticatorException))) {
925
926 OwnCloudClient client = null;
927 try {
928 OwnCloudAccount ocAccount =
929 new OwnCloudAccount(getAccount(), context);
930 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
931 removeClientFor(ocAccount));
932 // TODO get rid of these exceptions
933 } catch (AccountNotFoundException e) {
934 e.printStackTrace();
935 } catch (AuthenticatorException e) {
936 e.printStackTrace();
937 } catch (OperationCanceledException e) {
938 e.printStackTrace();
939 } catch (IOException e) {
940 e.printStackTrace();
941 }
942
943 if (client != null) {
944 OwnCloudCredentials cred = client.getCredentials();
945 if (cred != null) {
946 AccountManager am = AccountManager.get(context);
947 if (cred.authTokenExpires()) {
948 am.invalidateAuthToken(
949 getAccount().type,
950 cred.getAuthToken()
951 );
952 } else {
953 am.clearPassword(getAccount());
954 }
955 }
956 }
957
958 requestCredentialsUpdate();
959
960 }
961 }
962 removeStickyBroadcast(intent);
963 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
964 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
965
966 setBackgroundText();
967
968 }
969
970 if (synchResult != null) {
971 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
972 mLastSslUntrustedServerResult = synchResult;
973 }
974 }
975 } catch (RuntimeException e) {
976 // avoid app crashes after changing the serial id of RemoteOperationResult
977 // in owncloud library with broadcast notifications pending to process
978 removeStickyBroadcast(intent);
979 }
980 }
981 }
982
983 /**
984 * Show a text message on screen view for notifying user if content is
985 * loading or folder is empty
986 */
987 private void setBackgroundText() {
988 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
989 if (ocFileListFragment != null) {
990 int message = R.string.file_list_loading;
991 if (!mSyncInProgress) {
992 // In case file list is empty
993 message = R.string.file_list_empty;
994 }
995 ocFileListFragment.setMessageForEmptyList(getString(message));
996 } else {
997 Log.e(TAG, "OCFileListFragment is null");
998 }
999 }
1000
1001 /**
1002 * Once the file upload has finished -> update view
1003 */
1004 private class UploadFinishReceiver extends BroadcastReceiver {
1005 /**
1006 * Once the file upload has finished -> update view
1007 * @author David A. Velasco
1008 * {@link BroadcastReceiver} to enable upload feedback in UI
1009 */
1010 @Override
1011 public void onReceive(Context context, Intent intent) {
1012 try {
1013 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1014 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1015 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1016 OCFile currentDir = getCurrentDir();
1017 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1018 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1019
1020 if (sameAccount && isDescendant) {
1021 refreshListOfFilesFragment();
1022 }
1023
1024 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1025 boolean renamedInUpload = getFile().getRemotePath().
1026 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1027 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1028 renamedInUpload;
1029 FileFragment details = getSecondFragment();
1030 boolean detailFragmentIsShown = (details != null &&
1031 details instanceof FileDetailFragment);
1032
1033 if (sameAccount && sameFile && detailFragmentIsShown) {
1034 if (uploadWasFine) {
1035 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1036 }
1037 if (renamedInUpload) {
1038 String newName = (new File(uploadedRemotePath)).getName();
1039 Toast msg = Toast.makeText(
1040 context,
1041 String.format(
1042 getString(R.string.filedetails_renamed_in_upload_msg),
1043 newName),
1044 Toast.LENGTH_LONG);
1045 msg.show();
1046 }
1047 if (uploadWasFine || getFile().fileExists()) {
1048 ((FileDetailFragment)details).updateFileDetails(false, true);
1049 } else {
1050 cleanSecondFragment();
1051 }
1052
1053 // Force the preview if the file is an image
1054 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1055 startImagePreview(getFile());
1056 } // TODO what about other kind of previews?
1057 }
1058
1059 } finally {
1060 if (intent != null) {
1061 removeStickyBroadcast(intent);
1062 }
1063 }
1064
1065 }
1066
1067 }
1068
1069
1070 /**
1071 * Class waiting for broadcast events from the {@link FielDownloader} service.
1072 *
1073 * Updates the UI when a download is started or finished, provided that it is relevant for the
1074 * current folder.
1075 */
1076 private class DownloadFinishReceiver extends BroadcastReceiver {
1077 @Override
1078 public void onReceive(Context context, Intent intent) {
1079 try {
1080 boolean sameAccount = isSameAccount(context, intent);
1081 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1082 boolean isDescendant = isDescendant(downloadedRemotePath);
1083
1084 if (sameAccount && isDescendant) {
1085 refreshListOfFilesFragment();
1086 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1087 }
1088
1089 if (mWaitingToSend != null) {
1090 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1091 if (mWaitingToSend.isDown()) {
1092 sendDownloadedFile();
1093 }
1094 }
1095
1096 } finally {
1097 if (intent != null) {
1098 removeStickyBroadcast(intent);
1099 }
1100 }
1101 }
1102
1103 private boolean isDescendant(String downloadedRemotePath) {
1104 OCFile currentDir = getCurrentDir();
1105 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1106 }
1107
1108 private boolean isSameAccount(Context context, Intent intent) {
1109 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1110 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1111 }
1112 }
1113
1114
1115 public void browseToRoot() {
1116 OCFileListFragment listOfFiles = getListOfFilesFragment();
1117 if (listOfFiles != null) { // should never be null, indeed
1118 while (mDirectories.getCount() > 1) {
1119 popDirname();
1120 }
1121 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1122 listOfFiles.listDirectory(root);
1123 setFile(listOfFiles.getCurrentFile());
1124 startSyncFolderOperation(root);
1125 }
1126 cleanSecondFragment();
1127 }
1128
1129
1130 public void browseTo(OCFile folder) {
1131 if (folder == null || !folder.isFolder()) {
1132 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1133 }
1134 OCFileListFragment listOfFiles = getListOfFilesFragment();
1135 if (listOfFiles != null) {
1136 setNavigationListWithFolder(folder);
1137 listOfFiles.listDirectory(folder);
1138 setFile(listOfFiles.getCurrentFile());
1139 startSyncFolderOperation(folder);
1140 } else {
1141 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1142 }
1143 cleanSecondFragment();
1144 }
1145
1146
1147 /**
1148 * {@inheritDoc}
1149 *
1150 * Updates action bar and second fragment, if in dual pane mode.
1151 */
1152 @Override
1153 public void onBrowsedDownTo(OCFile directory) {
1154 pushDirname(directory);
1155 cleanSecondFragment();
1156
1157 // Sync Folder
1158 startSyncFolderOperation(directory);
1159
1160 }
1161
1162 /**
1163 * Shows the information of the {@link OCFile} received as a
1164 * parameter in the second fragment.
1165 *
1166 * @param file {@link OCFile} whose details will be shown
1167 */
1168 @Override
1169 public void showDetails(OCFile file) {
1170 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1171 setSecondFragment(detailFragment);
1172 updateFragmentsVisibility(true);
1173 updateNavigationElementsInActionBar(file);
1174 setFile(file);
1175 }
1176
1177
1178 /**
1179 * TODO
1180 */
1181 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1182 ActionBar actionBar = getSupportActionBar();
1183 if (chosenFile == null || mDualPane) {
1184 // only list of files - set for browsing through folders
1185 OCFile currentDir = getCurrentDir();
1186 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1187 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1188 actionBar.setDisplayShowTitleEnabled(!noRoot);
1189 if (!noRoot) {
1190 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1191 }
1192 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1193 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1194
1195 } else {
1196 actionBar.setDisplayHomeAsUpEnabled(true);
1197 actionBar.setDisplayShowTitleEnabled(true);
1198 actionBar.setTitle(chosenFile.getFileName());
1199 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1200 }
1201 }
1202
1203
1204 @Override
1205 protected ServiceConnection newTransferenceServiceConnection() {
1206 return new ListServiceConnection();
1207 }
1208
1209 /** Defines callbacks for service binding, passed to bindService() */
1210 private class ListServiceConnection implements ServiceConnection {
1211
1212 @Override
1213 public void onServiceConnected(ComponentName component, IBinder service) {
1214 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1215 Log_OC.d(TAG, "Download service connected");
1216 mDownloaderBinder = (FileDownloaderBinder) service;
1217 if (mWaitingToPreview != null)
1218 if (getStorageManager() != null) {
1219 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1220 if (!mWaitingToPreview.isDown()) {
1221 requestForDownload();
1222 }
1223 }
1224
1225 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1226 Log_OC.d(TAG, "Upload service connected");
1227 mUploaderBinder = (FileUploaderBinder) service;
1228 } else {
1229 return;
1230 }
1231 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1232 OCFileListFragment listOfFiles = getListOfFilesFragment();
1233 if (listOfFiles != null) {
1234 listOfFiles.listDirectory();
1235 }
1236 FileFragment secondFragment = getSecondFragment();
1237 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1238 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1239 detailFragment.listenForTransferProgress();
1240 detailFragment.updateFileDetails(false, false);
1241 }
1242 }
1243
1244 @Override
1245 public void onServiceDisconnected(ComponentName component) {
1246 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1247 Log_OC.d(TAG, "Download service disconnected");
1248 mDownloaderBinder = null;
1249 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1250 Log_OC.d(TAG, "Upload service disconnected");
1251 mUploaderBinder = null;
1252 }
1253 }
1254 };
1255
1256
1257
1258 /**
1259 * Launch an intent to request the PIN code to the user before letting him use the app
1260 */
1261 private void requestPinCode() {
1262 boolean pinStart = false;
1263 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1264 pinStart = appPrefs.getBoolean("set_pincode", false);
1265 if (pinStart) {
1266 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1267 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1268 startActivity(i);
1269 }
1270 }
1271
1272
1273 @Override
1274 public void onSavedCertificate() {
1275 startSyncFolderOperation(getCurrentDir());
1276 }
1277
1278
1279 @Override
1280 public void onFailedSavingCertificate() {
1281 showDialog(DIALOG_CERT_NOT_SAVED);
1282 }
1283
1284 @Override
1285 public void onCancelCertificate() {
1286 // nothing to do
1287 }
1288
1289 /**
1290 * Updates the view associated to the activity after the finish of some operation over files
1291 * in the current account.
1292 *
1293 * @param operation Removal operation performed.
1294 * @param result Result of the removal.
1295 */
1296 @Override
1297 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1298 super.onRemoteOperationFinish(operation, result);
1299
1300 if (operation instanceof RemoveFileOperation) {
1301 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1302
1303 } else if (operation instanceof RenameFileOperation) {
1304 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1305
1306 } else if (operation instanceof SynchronizeFileOperation) {
1307 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1308
1309 } else if (operation instanceof CreateFolderOperation) {
1310 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1311
1312 } else if (operation instanceof CreateShareOperation) {
1313 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1314
1315 } else if (operation instanceof UnshareLinkOperation) {
1316 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1317
1318 }
1319
1320 }
1321
1322
1323 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1324 if (result.isSuccess()) {
1325 refreshShowDetails();
1326 refreshListOfFilesFragment();
1327 }
1328 }
1329
1330
1331 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1332 if (result.isSuccess()) {
1333 refreshShowDetails();
1334 refreshListOfFilesFragment();
1335
1336 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1337 cleanSecondFragment();
1338 refreshListOfFilesFragment();
1339 }
1340 }
1341
1342 private void refreshShowDetails() {
1343 FileFragment details = getSecondFragment();
1344 if (details != null) {
1345 OCFile file = details.getFile();
1346 if (file != null) {
1347 file = getStorageManager().getFileByPath(file.getRemotePath());
1348 if (details instanceof PreviewMediaFragment) {
1349 // Refresh OCFile of the fragment
1350 ((PreviewMediaFragment) details).updateFile(file);
1351 } else {
1352 showDetails(file);
1353 }
1354 }
1355 invalidateOptionsMenu();
1356 }
1357 }
1358
1359 /**
1360 * Updates the view associated to the activity after the finish of an operation trying to remove a
1361 * file.
1362 *
1363 * @param operation Removal operation performed.
1364 * @param result Result of the removal.
1365 */
1366 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1367 dismissLoadingDialog();
1368
1369 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1370 Toast.LENGTH_LONG);
1371 msg.show();
1372
1373 if (result.isSuccess()) {
1374 OCFile removedFile = operation.getFile();
1375 FileFragment second = getSecondFragment();
1376 if (second != null && removedFile.equals(second.getFile())) {
1377 if (second instanceof PreviewMediaFragment) {
1378 ((PreviewMediaFragment)second).stopPreview(true);
1379 }
1380 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1381 cleanSecondFragment();
1382 }
1383 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1384 refreshListOfFilesFragment();
1385 }
1386 invalidateOptionsMenu();
1387 } else {
1388 if (result.isSslRecoverableException()) {
1389 mLastSslUntrustedServerResult = result;
1390 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1391 }
1392 }
1393 }
1394
1395
1396 /**
1397 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1398 *
1399 * @param operation Creation operation performed.
1400 * @param result Result of the creation.
1401 */
1402 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1403 if (result.isSuccess()) {
1404 dismissLoadingDialog();
1405 refreshListOfFilesFragment();
1406 } else {
1407 dismissLoadingDialog();
1408 try {
1409 Toast msg = Toast.makeText(FileDisplayActivity.this,
1410 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1411 Toast.LENGTH_LONG);
1412 msg.show();
1413
1414 } catch (NotFoundException e) {
1415 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1416 }
1417 }
1418 }
1419
1420
1421 /**
1422 * Updates the view associated to the activity after the finish of an operation trying to rename a
1423 * file.
1424 *
1425 * @param operation Renaming operation performed.
1426 * @param result Result of the renaming.
1427 */
1428 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1429 dismissLoadingDialog();
1430 OCFile renamedFile = operation.getFile();
1431 if (result.isSuccess()) {
1432 FileFragment details = getSecondFragment();
1433 if (details != null) {
1434 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1435 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1436 showDetails(renamedFile);
1437
1438 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1439 ((PreviewMediaFragment) details).updateFile(renamedFile);
1440 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1441 int position = ((PreviewMediaFragment)details).getPosition();
1442 startMediaPreview(renamedFile, position, true);
1443 } else {
1444 getFileOperationsHelper().openFile(renamedFile);
1445 }
1446 }
1447 }
1448
1449 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1450 refreshListOfFilesFragment();
1451 }
1452
1453 } else {
1454 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1455 Toast.LENGTH_LONG);
1456 msg.show();
1457
1458 if (result.isSslRecoverableException()) {
1459 mLastSslUntrustedServerResult = result;
1460 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1461 }
1462 }
1463 }
1464
1465 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1466 dismissLoadingDialog();
1467 OCFile syncedFile = operation.getLocalFile();
1468 if (!result.isSuccess()) {
1469 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1470 Intent i = new Intent(this, ConflictsResolveActivity.class);
1471 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1472 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1473 startActivity(i);
1474
1475 }
1476
1477 } else {
1478 if (operation.transferWasRequested()) {
1479 onTransferStateChanged(syncedFile, true, true);
1480
1481 } else {
1482 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1483 Toast.LENGTH_LONG);
1484 msg.show();
1485 }
1486 }
1487 }
1488
1489
1490 /**
1491 * {@inheritDoc}
1492 */
1493 @Override
1494 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1495 refreshListOfFilesFragment();
1496 FileFragment details = getSecondFragment();
1497 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1498 if (downloading || uploading) {
1499 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1500 } else {
1501 if (!file.fileExists()) {
1502 cleanSecondFragment();
1503 } else {
1504 ((FileDetailFragment)details).updateFileDetails(false, true);
1505 }
1506 }
1507 }
1508
1509 }
1510
1511
1512 private void requestForDownload() {
1513 Account account = getAccount();
1514 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1515 Intent i = new Intent(this, FileDownloader.class);
1516 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1517 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1518 startService(i);
1519 }
1520 }
1521
1522
1523 private OCFile getCurrentDir() {
1524 OCFile file = getFile();
1525 if (file != null) {
1526 if (file.isFolder()) {
1527 return file;
1528 } else if (getStorageManager() != null) {
1529 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1530 return getStorageManager().getFileByPath(parentPath);
1531 }
1532 }
1533 return null;
1534 }
1535
1536 public void startSyncFolderOperation(OCFile folder) {
1537 long currentSyncTime = System.currentTimeMillis();
1538
1539 mSyncInProgress = true;
1540
1541 // perform folder synchronization
1542 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1543 currentSyncTime,
1544 false,
1545 getFileOperationsHelper().isSharedSupported(),
1546 getStorageManager(),
1547 getAccount(),
1548 getApplicationContext()
1549 );
1550 synchFolderOp.execute(getAccount(), this, null, null);
1551
1552 setSupportProgressBarIndeterminateVisibility(true);
1553
1554 setBackgroundText();
1555 }
1556
1557 /**
1558 * Show untrusted cert dialog
1559 */
1560 public void showUntrustedCertDialog(RemoteOperationResult result) {
1561 // Show a dialog with the certificate info
1562 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1563 FragmentManager fm = getSupportFragmentManager();
1564 FragmentTransaction ft = fm.beginTransaction();
1565 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1566 }
1567
1568 private void requestForDownload(OCFile file) {
1569 Account account = getAccount();
1570 if (!mDownloaderBinder.isDownloading(account, file)) {
1571 Intent i = new Intent(this, FileDownloader.class);
1572 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1573 i.putExtra(FileDownloader.EXTRA_FILE, file);
1574 startService(i);
1575 }
1576 }
1577
1578 private void sendDownloadedFile(){
1579 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1580 mWaitingToSend = null;
1581 }
1582
1583
1584 /**
1585 * Requests the download of the received {@link OCFile} , updates the UI
1586 * to monitor the download progress and prepares the activity to send the file
1587 * when the download finishes.
1588 *
1589 * @param file {@link OCFile} to download and preview.
1590 */
1591 public void startDownloadForSending(OCFile file) {
1592 mWaitingToSend = file;
1593 requestForDownload(mWaitingToSend);
1594 boolean hasSecondFragment = (getSecondFragment()!= null);
1595 updateFragmentsVisibility(hasSecondFragment);
1596 }
1597
1598 /**
1599 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1600 *
1601 * @param file Image {@link OCFile} to show.
1602 */
1603 public void startImagePreview(OCFile file) {
1604 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1605 showDetailsIntent.putExtra(EXTRA_FILE, file);
1606 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1607 startActivity(showDetailsIntent);
1608
1609 }
1610
1611 /**
1612 * Stars the preview of an already down media {@link OCFile}.
1613 *
1614 * @param file Media {@link OCFile} to preview.
1615 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1616 * @param autoplay When 'true', the playback will start without user interactions.
1617 */
1618 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1619 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1620 setSecondFragment(mediaFragment);
1621 updateFragmentsVisibility(true);
1622 updateNavigationElementsInActionBar(file);
1623 setFile(file);
1624 }
1625
1626 /**
1627 * Requests the download of the received {@link OCFile} , updates the UI
1628 * to monitor the download progress and prepares the activity to preview
1629 * or open the file when the download finishes.
1630 *
1631 * @param file {@link OCFile} to download and preview.
1632 */
1633 public void startDownloadForPreview(OCFile file) {
1634 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1635 setSecondFragment(detailFragment);
1636 mWaitingToPreview = file;
1637 requestForDownload();
1638 updateFragmentsVisibility(true);
1639 updateNavigationElementsInActionBar(file);
1640 setFile(file);
1641 }
1642
1643
1644 public void cancelTransference(OCFile file) {
1645 getFileOperationsHelper().cancelTransference(file);
1646 if (mWaitingToPreview != null &&
1647 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1648 mWaitingToPreview = null;
1649 }
1650 if (mWaitingToSend != null &&
1651 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1652 mWaitingToSend = null;
1653 }
1654 onTransferStateChanged(file, false, false);
1655 }
1656
1657 }