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