Merge branch 'master' into develop
[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 if (synchResult != null) {
928 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
929 mLastSslUntrustedServerResult = synchResult;
930 }
931 }
932 } catch (RuntimeException e) {
933 // avoid app crashes after changing the serial id of RemoteOperationResult
934 // in owncloud library with broadcast notifications pending to process
935 removeStickyBroadcast(intent);
936 }
937 }
938 }
939
940
941 /**
942 * Once the file upload has finished -> update view
943 */
944 private class UploadFinishReceiver extends BroadcastReceiver {
945 /**
946 * Once the file upload has finished -> update view
947 * @author David A. Velasco
948 * {@link BroadcastReceiver} to enable upload feedback in UI
949 */
950 @Override
951 public void onReceive(Context context, Intent intent) {
952 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
953 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
954 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
955 OCFile currentDir = getCurrentDir();
956 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
957 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
958
959 if (sameAccount && isDescendant) {
960 refreshListOfFilesFragment();
961 }
962
963 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
964 boolean renamedInUpload = getFile().getRemotePath().
965 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
966 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
967 renamedInUpload;
968 FileFragment details = getSecondFragment();
969 boolean detailFragmentIsShown = (details != null &&
970 details instanceof FileDetailFragment);
971
972 if (sameAccount && sameFile && detailFragmentIsShown) {
973 if (uploadWasFine) {
974 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
975 }
976 if (renamedInUpload) {
977 String newName = (new File(uploadedRemotePath)).getName();
978 Toast msg = Toast.makeText(
979 context,
980 String.format(
981 getString(R.string.filedetails_renamed_in_upload_msg),
982 newName),
983 Toast.LENGTH_LONG);
984 msg.show();
985 }
986 if (uploadWasFine || getFile().fileExists()) {
987 ((FileDetailFragment)details).updateFileDetails(false, true);
988 } else {
989 cleanSecondFragment();
990 }
991
992 // Force the preview if the file is an image
993 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
994 startImagePreview(getFile());
995 } // TODO what about other kind of previews?
996 }
997
998 removeStickyBroadcast(intent);
999
1000 }
1001
1002 }
1003
1004
1005 /**
1006 * Class waiting for broadcast events from the {@link FielDownloader} service.
1007 *
1008 * Updates the UI when a download is started or finished, provided that it is relevant for the
1009 * current folder.
1010 */
1011 private class DownloadFinishReceiver extends BroadcastReceiver {
1012 @Override
1013 public void onReceive(Context context, Intent intent) {
1014 boolean sameAccount = isSameAccount(context, intent);
1015 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1016 boolean isDescendant = isDescendant(downloadedRemotePath);
1017
1018 if (sameAccount && isDescendant) {
1019 refreshListOfFilesFragment();
1020 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1021 }
1022
1023 if (mWaitingToSend != null) {
1024 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1025 if (mWaitingToSend.isDown()) {
1026 sendDownloadedFile();
1027 }
1028 }
1029
1030 removeStickyBroadcast(intent);
1031 }
1032
1033 private boolean isDescendant(String downloadedRemotePath) {
1034 OCFile currentDir = getCurrentDir();
1035 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1036 }
1037
1038 private boolean isSameAccount(Context context, Intent intent) {
1039 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1040 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1041 }
1042 }
1043
1044
1045 public void browseToRoot() {
1046 OCFileListFragment listOfFiles = getListOfFilesFragment();
1047 if (listOfFiles != null) { // should never be null, indeed
1048 while (mDirectories.getCount() > 1) {
1049 popDirname();
1050 }
1051 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1052 listOfFiles.listDirectory(root);
1053 setFile(listOfFiles.getCurrentFile());
1054 startSyncFolderOperation(root);
1055 }
1056 cleanSecondFragment();
1057 }
1058
1059
1060 public void browseTo(OCFile folder) {
1061 if (folder == null || !folder.isFolder()) {
1062 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1063 }
1064 OCFileListFragment listOfFiles = getListOfFilesFragment();
1065 if (listOfFiles != null) {
1066 setNavigationListWithFolder(folder);
1067 listOfFiles.listDirectory(folder);
1068 setFile(listOfFiles.getCurrentFile());
1069 startSyncFolderOperation(folder);
1070 } else {
1071 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1072 }
1073 cleanSecondFragment();
1074 }
1075
1076
1077 /**
1078 * {@inheritDoc}
1079 *
1080 * Updates action bar and second fragment, if in dual pane mode.
1081 */
1082 @Override
1083 public void onBrowsedDownTo(OCFile directory) {
1084 pushDirname(directory);
1085 cleanSecondFragment();
1086
1087 // Sync Folder
1088 startSyncFolderOperation(directory);
1089
1090 }
1091
1092 /**
1093 * Shows the information of the {@link OCFile} received as a
1094 * parameter in the second fragment.
1095 *
1096 * @param file {@link OCFile} whose details will be shown
1097 */
1098 @Override
1099 public void showDetails(OCFile file) {
1100 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1101 setSecondFragment(detailFragment);
1102 updateFragmentsVisibility(true);
1103 updateNavigationElementsInActionBar(file);
1104 setFile(file);
1105 }
1106
1107
1108 /**
1109 * TODO
1110 */
1111 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1112 ActionBar actionBar = getSupportActionBar();
1113 if (chosenFile == null || mDualPane) {
1114 // only list of files - set for browsing through folders
1115 OCFile currentDir = getCurrentDir();
1116 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1117 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1118 actionBar.setDisplayShowTitleEnabled(!noRoot);
1119 if (!noRoot) {
1120 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1121 }
1122 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1123 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1124
1125 } else {
1126 actionBar.setDisplayHomeAsUpEnabled(true);
1127 actionBar.setDisplayShowTitleEnabled(true);
1128 actionBar.setTitle(chosenFile.getFileName());
1129 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1130 }
1131 }
1132
1133
1134 @Override
1135 protected ServiceConnection newTransferenceServiceConnection() {
1136 return new ListServiceConnection();
1137 }
1138
1139 /** Defines callbacks for service binding, passed to bindService() */
1140 private class ListServiceConnection implements ServiceConnection {
1141
1142 @Override
1143 public void onServiceConnected(ComponentName component, IBinder service) {
1144 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1145 Log_OC.d(TAG, "Download service connected");
1146 mDownloaderBinder = (FileDownloaderBinder) service;
1147 if (mWaitingToPreview != null)
1148 if (getStorageManager() != null) {
1149 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1150 if (!mWaitingToPreview.isDown()) {
1151 requestForDownload();
1152 }
1153 }
1154
1155 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1156 Log_OC.d(TAG, "Upload service connected");
1157 mUploaderBinder = (FileUploaderBinder) service;
1158 } else {
1159 return;
1160 }
1161 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1162 OCFileListFragment listOfFiles = getListOfFilesFragment();
1163 if (listOfFiles != null) {
1164 listOfFiles.listDirectory();
1165 }
1166 FileFragment secondFragment = getSecondFragment();
1167 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1168 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1169 detailFragment.listenForTransferProgress();
1170 detailFragment.updateFileDetails(false, false);
1171 }
1172 }
1173
1174 @Override
1175 public void onServiceDisconnected(ComponentName component) {
1176 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1177 Log_OC.d(TAG, "Download service disconnected");
1178 mDownloaderBinder = null;
1179 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1180 Log_OC.d(TAG, "Upload service disconnected");
1181 mUploaderBinder = null;
1182 }
1183 }
1184 };
1185
1186
1187
1188 /**
1189 * Launch an intent to request the PIN code to the user before letting him use the app
1190 */
1191 private void requestPinCode() {
1192 boolean pinStart = false;
1193 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1194 pinStart = appPrefs.getBoolean("set_pincode", false);
1195 if (pinStart) {
1196 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1197 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1198 startActivity(i);
1199 }
1200 }
1201
1202
1203 @Override
1204 public void onSavedCertificate() {
1205 startSyncFolderOperation(getCurrentDir());
1206 }
1207
1208
1209 @Override
1210 public void onFailedSavingCertificate() {
1211 showDialog(DIALOG_CERT_NOT_SAVED);
1212 }
1213
1214 @Override
1215 public void onCancelCertificate() {
1216 // nothing to do
1217 }
1218
1219 /**
1220 * Updates the view associated to the activity after the finish of some operation over files
1221 * in the current account.
1222 *
1223 * @param operation Removal operation performed.
1224 * @param result Result of the removal.
1225 */
1226 @Override
1227 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1228 super.onRemoteOperationFinish(operation, result);
1229
1230 if (operation instanceof RemoveFileOperation) {
1231 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1232
1233 } else if (operation instanceof RenameFileOperation) {
1234 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1235
1236 } else if (operation instanceof SynchronizeFileOperation) {
1237 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1238
1239 } else if (operation instanceof CreateFolderOperation) {
1240 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1241
1242 } else if (operation instanceof CreateShareOperation) {
1243 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1244
1245 } else if (operation instanceof UnshareLinkOperation) {
1246 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1247
1248 }
1249
1250 }
1251
1252
1253 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1254 if (result.isSuccess()) {
1255 refreshShowDetails();
1256 refreshListOfFilesFragment();
1257 }
1258 }
1259
1260
1261 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1262 if (result.isSuccess()) {
1263 refreshShowDetails();
1264 refreshListOfFilesFragment();
1265
1266 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1267 cleanSecondFragment();
1268 refreshListOfFilesFragment();
1269 }
1270 }
1271
1272 private void refreshShowDetails() {
1273 FileFragment details = getSecondFragment();
1274 if (details != null) {
1275 OCFile file = details.getFile();
1276 if (file != null) {
1277 file = getStorageManager().getFileByPath(file.getRemotePath());
1278 if (details instanceof PreviewMediaFragment) {
1279 // Refresh OCFile of the fragment
1280 ((PreviewMediaFragment) details).updateFile(file);
1281 } else {
1282 showDetails(file);
1283 }
1284 }
1285 invalidateOptionsMenu();
1286 }
1287 }
1288
1289 /**
1290 * Updates the view associated to the activity after the finish of an operation trying to remove a
1291 * file.
1292 *
1293 * @param operation Removal operation performed.
1294 * @param result Result of the removal.
1295 */
1296 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1297 dismissLoadingDialog();
1298
1299 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1300 Toast.LENGTH_LONG);
1301 msg.show();
1302
1303 if (result.isSuccess()) {
1304 OCFile removedFile = operation.getFile();
1305 FileFragment second = getSecondFragment();
1306 if (second != null && removedFile.equals(second.getFile())) {
1307 if (second instanceof PreviewMediaFragment) {
1308 ((PreviewMediaFragment)second).stopPreview(true);
1309 }
1310 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1311 cleanSecondFragment();
1312 }
1313 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1314 refreshListOfFilesFragment();
1315 }
1316 invalidateOptionsMenu();
1317 } else {
1318 if (result.isSslRecoverableException()) {
1319 mLastSslUntrustedServerResult = result;
1320 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1321 }
1322 }
1323 }
1324
1325
1326 /**
1327 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1328 *
1329 * @param operation Creation operation performed.
1330 * @param result Result of the creation.
1331 */
1332 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1333 if (result.isSuccess()) {
1334 dismissLoadingDialog();
1335 refreshListOfFilesFragment();
1336 } else {
1337 dismissLoadingDialog();
1338 try {
1339 Toast msg = Toast.makeText(FileDisplayActivity.this,
1340 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1341 Toast.LENGTH_LONG);
1342 msg.show();
1343
1344 } catch (NotFoundException e) {
1345 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1346 }
1347 }
1348 }
1349
1350
1351 /**
1352 * Updates the view associated to the activity after the finish of an operation trying to rename a
1353 * file.
1354 *
1355 * @param operation Renaming operation performed.
1356 * @param result Result of the renaming.
1357 */
1358 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1359 dismissLoadingDialog();
1360 OCFile renamedFile = operation.getFile();
1361 if (result.isSuccess()) {
1362 FileFragment details = getSecondFragment();
1363 if (details != null) {
1364 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1365 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1366 showDetails(renamedFile);
1367
1368 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1369 ((PreviewMediaFragment) details).updateFile(renamedFile);
1370 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1371 int position = ((PreviewMediaFragment)details).getPosition();
1372 startMediaPreview(renamedFile, position, true);
1373 } else {
1374 getFileOperationsHelper().openFile(renamedFile);
1375 }
1376 }
1377 }
1378
1379 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1380 refreshListOfFilesFragment();
1381 }
1382
1383 } else {
1384 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1385 Toast.LENGTH_LONG);
1386 msg.show();
1387
1388 if (result.isSslRecoverableException()) {
1389 mLastSslUntrustedServerResult = result;
1390 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1391 }
1392 }
1393 }
1394
1395 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1396 dismissLoadingDialog();
1397 OCFile syncedFile = operation.getLocalFile();
1398 if (!result.isSuccess()) {
1399 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1400 Intent i = new Intent(this, ConflictsResolveActivity.class);
1401 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1402 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1403 startActivity(i);
1404
1405 }
1406
1407 } else {
1408 if (operation.transferWasRequested()) {
1409 onTransferStateChanged(syncedFile, true, true);
1410
1411 } else {
1412 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1413 Toast.LENGTH_LONG);
1414 msg.show();
1415 }
1416 }
1417 }
1418
1419
1420 /**
1421 * {@inheritDoc}
1422 */
1423 @Override
1424 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1425 refreshListOfFilesFragment();
1426 FileFragment details = getSecondFragment();
1427 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1428 if (downloading || uploading) {
1429 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1430 } else {
1431 if (!file.fileExists()) {
1432 cleanSecondFragment();
1433 } else {
1434 ((FileDetailFragment)details).updateFileDetails(false, true);
1435 }
1436 }
1437 }
1438
1439 }
1440
1441
1442 private void requestForDownload() {
1443 Account account = getAccount();
1444 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1445 Intent i = new Intent(this, FileDownloader.class);
1446 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1447 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1448 startService(i);
1449 }
1450 }
1451
1452
1453 private OCFile getCurrentDir() {
1454 OCFile file = getFile();
1455 if (file != null) {
1456 if (file.isFolder()) {
1457 return file;
1458 } else if (getStorageManager() != null) {
1459 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1460 return getStorageManager().getFileByPath(parentPath);
1461 }
1462 }
1463 return null;
1464 }
1465
1466 public void startSyncFolderOperation(OCFile folder) {
1467 long currentSyncTime = System.currentTimeMillis();
1468
1469 mSyncInProgress = true;
1470
1471 // perform folder synchronization
1472 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1473 currentSyncTime,
1474 false,
1475 getFileOperationsHelper().isSharedSupported(),
1476 getStorageManager(),
1477 getAccount(),
1478 getApplicationContext()
1479 );
1480 synchFolderOp.execute(getAccount(), this, null, null, this);
1481
1482 setSupportProgressBarIndeterminateVisibility(true);
1483 }
1484
1485 /**
1486 * Show untrusted cert dialog
1487 */
1488 public void showUntrustedCertDialog(RemoteOperationResult result) {
1489 // Show a dialog with the certificate info
1490 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1491 FragmentManager fm = getSupportFragmentManager();
1492 FragmentTransaction ft = fm.beginTransaction();
1493 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1494 }
1495
1496 private void requestForDownload(OCFile file) {
1497 Account account = getAccount();
1498 if (!mDownloaderBinder.isDownloading(account, file)) {
1499 Intent i = new Intent(this, FileDownloader.class);
1500 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1501 i.putExtra(FileDownloader.EXTRA_FILE, file);
1502 startService(i);
1503 }
1504 }
1505
1506 private void sendDownloadedFile(){
1507 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1508 mWaitingToSend = null;
1509 }
1510
1511
1512 /**
1513 * Requests the download of the received {@link OCFile} , updates the UI
1514 * to monitor the download progress and prepares the activity to send the file
1515 * when the download finishes.
1516 *
1517 * @param file {@link OCFile} to download and preview.
1518 */
1519 public void startDownloadForSending(OCFile file) {
1520 mWaitingToSend = file;
1521 requestForDownload(mWaitingToSend);
1522 boolean hasSecondFragment = (getSecondFragment()!= null);
1523 updateFragmentsVisibility(hasSecondFragment);
1524 }
1525
1526 /**
1527 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1528 *
1529 * @param file Image {@link OCFile} to show.
1530 */
1531 public void startImagePreview(OCFile file) {
1532 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1533 showDetailsIntent.putExtra(EXTRA_FILE, file);
1534 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1535 startActivity(showDetailsIntent);
1536
1537 }
1538
1539 /**
1540 * Stars the preview of an already down media {@link OCFile}.
1541 *
1542 * @param file Media {@link OCFile} to preview.
1543 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1544 * @param autoplay When 'true', the playback will start without user interactions.
1545 */
1546 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1547 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1548 setSecondFragment(mediaFragment);
1549 updateFragmentsVisibility(true);
1550 updateNavigationElementsInActionBar(file);
1551 setFile(file);
1552 }
1553
1554 /**
1555 * Requests the download of the received {@link OCFile} , updates the UI
1556 * to monitor the download progress and prepares the activity to preview
1557 * or open the file when the download finishes.
1558 *
1559 * @param file {@link OCFile} to download and preview.
1560 */
1561 public void startDownloadForPreview(OCFile file) {
1562 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1563 setSecondFragment(detailFragment);
1564 mWaitingToPreview = file;
1565 requestForDownload();
1566 updateFragmentsVisibility(true);
1567 updateNavigationElementsInActionBar(file);
1568 setFile(file);
1569 }
1570
1571
1572 public void cancelTransference(OCFile file) {
1573 getFileOperationsHelper().cancelTransference(file);
1574 if (mWaitingToPreview != null &&
1575 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1576 mWaitingToPreview = null;
1577 }
1578 if (mWaitingToSend != null &&
1579 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1580 mWaitingToSend = null;
1581 }
1582 onTransferStateChanged(file, false, false);
1583 }
1584
1585 }