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