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