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