Refactored handle of user response in confirmation dialog for file removal to avoid...
[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-2013 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.EditNameDialog;
83 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
84 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
85 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
86 import com.owncloud.android.ui.fragment.FileDetailFragment;
87 import com.owncloud.android.ui.fragment.FileFragment;
88 import com.owncloud.android.ui.fragment.OCFileListFragment;
89 import com.owncloud.android.ui.preview.PreviewImageActivity;
90 import com.owncloud.android.ui.preview.PreviewImageFragment;
91 import com.owncloud.android.ui.preview.PreviewMediaFragment;
92 import com.owncloud.android.ui.preview.PreviewVideoActivity;
93 import com.owncloud.android.utils.DisplayUtils;
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,
106 OnSslUntrustedCertListener, EditNameDialogListener {
107
108 private ArrayAdapter<String> mDirectories;
109
110 private SyncBroadcastReceiver mSyncBroadcastReceiver;
111 private UploadFinishReceiver mUploadFinishReceiver;
112 private DownloadFinishReceiver mDownloadFinishReceiver;
113 private RemoteOperationResult mLastSslUntrustedServerResult = null;
114
115 private boolean mDualPane;
116 private View mLeftFragmentContainer;
117 private View mRightFragmentContainer;
118
119 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
120 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
121 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
122
123 public static final int DIALOG_SHORT_WAIT = 0;
124 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
125 private static final int DIALOG_CERT_NOT_SAVED = 2;
126
127 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
128
129 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
130 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
131
132 private static final String TAG = FileDisplayActivity.class.getSimpleName();
133
134 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
135 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
136
137 private OCFile mWaitingToPreview;
138
139 private boolean mSyncInProgress = false;
140
141 private String DIALOG_UNTRUSTED_CERT;
142
143 private OCFile mWaitingToSend;
144
145 @Override
146 protected void onCreate(Bundle savedInstanceState) {
147 Log_OC.d(TAG, "onCreate() start");
148 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
149
150 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
151
152 // PIN CODE request ; best location is to decide, let's try this first
153 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
154 requestPinCode();
155 } else if (getIntent().getAction() == null && savedInstanceState == null) {
156 requestPinCode();
157 }
158
159 /// file observer
160 Intent observer_intent = new Intent(this, FileObserverService.class);
161 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
162 startService(observer_intent);
163
164 /// Load of saved instance state
165 if(savedInstanceState != null) {
166 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
167 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
168 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
169
170 } else {
171 mWaitingToPreview = null;
172 mSyncInProgress = false;
173 mWaitingToSend = null;
174 }
175
176 /// USER INTERFACE
177
178 // Inflate and set the layout view
179 setContentView(R.layout.files);
180 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
181 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
182 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
183 if (savedInstanceState == null) {
184 createMinFragments();
185 } else {
186 Log_OC.d(TAG, "Init the secondFragment again");
187 if (mDualPane) {
188 initFragmentsWithFile();
189 }
190 }
191
192 // Action bar setup
193 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
194 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
195 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
196
197 Log_OC.d(TAG, "onCreate() end");
198 }
199
200 @Override
201 protected void onStart() {
202 super.onStart();
203 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
204 }
205
206 @Override
207 protected void onDestroy() {
208 super.onDestroy();
209 }
210
211 /**
212 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
213 */
214 @Override
215 protected void onAccountSet(boolean stateWasRecovered) {
216 super.onAccountSet(stateWasRecovered);
217 if (getAccount() != null) {
218 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
219 OCFile file = getFile();
220 // get parent from path
221 String parentPath = "";
222 if (file != null) {
223 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
224 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
225 // get parent from path
226 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
227 if (getStorageManager().getFileByPath(parentPath) == null)
228 file = null; // not able to know the directory where the file is uploading
229 } else {
230 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
231 }
232 }
233 if (file == null) {
234 // fall back to root folder
235 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
236 }
237 setFile(file);
238 setNavigationListWithFolder(file);
239
240 if (!stateWasRecovered) {
241 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
242 initFragmentsWithFile();
243 if (file.isFolder()) {
244 startSyncFolderOperation(file);
245 }
246
247 } else {
248 updateFragmentsVisibility(!file.isFolder());
249 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
250 }
251 }
252 }
253
254
255 private void setNavigationListWithFolder(OCFile file) {
256 mDirectories.clear();
257 OCFile fileIt = file;
258 String parentPath;
259 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
260 if (fileIt.isFolder()) {
261 mDirectories.add(fileIt.getFileName());
262 }
263 // get parent from path
264 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
265 fileIt = getStorageManager().getFileByPath(parentPath);
266 }
267 mDirectories.add(OCFile.PATH_SEPARATOR);
268 }
269
270
271 private void createMinFragments() {
272 OCFileListFragment listOfFiles = new OCFileListFragment();
273 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
274 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
275 transaction.commit();
276 }
277
278 private void initFragmentsWithFile() {
279 if (getAccount() != null && getFile() != null) {
280 /// First fragment
281 OCFileListFragment listOfFiles = getListOfFilesFragment();
282 if (listOfFiles != null) {
283 listOfFiles.listDirectory(getCurrentDir());
284 } else {
285 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
286 }
287
288 /// Second fragment
289 OCFile file = getFile();
290 Fragment secondFragment = chooseInitialSecondFragment(file);
291 if (secondFragment != null) {
292 setSecondFragment(secondFragment);
293 updateFragmentsVisibility(true);
294 updateNavigationElementsInActionBar(file);
295
296 } else {
297 cleanSecondFragment();
298 }
299
300 } else {
301 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
302 if (getAccount() == null) {
303 Log.wtf(TAG, "\t account is NULL");
304 }
305 if (getFile() == null) {
306 Log.wtf(TAG, "\t file is NULL");
307 }
308 }
309 }
310
311 private Fragment chooseInitialSecondFragment(OCFile file) {
312 Fragment secondFragment = null;
313 if (file != null && !file.isFolder()) {
314 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
315 && file.getLastSyncDateForProperties() > 0 // temporal fix
316 ) {
317 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
318 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
319 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
320
321 } else {
322 secondFragment = new FileDetailFragment(file, getAccount());
323 }
324 }
325 return secondFragment;
326 }
327
328
329 /**
330 * Replaces the second fragment managed by the activity with the received as
331 * a parameter.
332 *
333 * Assumes never will be more than two fragments managed at the same time.
334 *
335 * @param fragment New second Fragment to set.
336 */
337 private void setSecondFragment(Fragment fragment) {
338 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
339 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
340 transaction.commit();
341 }
342
343
344 private void updateFragmentsVisibility(boolean existsSecondFragment) {
345 if (mDualPane) {
346 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
347 mLeftFragmentContainer.setVisibility(View.VISIBLE);
348 }
349 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
350 mRightFragmentContainer.setVisibility(View.VISIBLE);
351 }
352
353 } else if (existsSecondFragment) {
354 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
355 mLeftFragmentContainer.setVisibility(View.GONE);
356 }
357 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
358 mRightFragmentContainer.setVisibility(View.VISIBLE);
359 }
360
361 } else {
362 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
363 mLeftFragmentContainer.setVisibility(View.VISIBLE);
364 }
365 if (mRightFragmentContainer.getVisibility() != View.GONE) {
366 mRightFragmentContainer.setVisibility(View.GONE);
367 }
368 }
369 }
370
371
372 private OCFileListFragment getListOfFilesFragment() {
373 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
374 if (listOfFiles != null) {
375 return (OCFileListFragment)listOfFiles;
376 }
377 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
378 return null;
379 }
380
381 public FileFragment getSecondFragment() {
382 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
383 if (second != null) {
384 return (FileFragment)second;
385 }
386 return null;
387 }
388
389 protected void cleanSecondFragment() {
390 Fragment second = getSecondFragment();
391 if (second != null) {
392 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
393 tr.remove(second);
394 tr.commit();
395 }
396 updateFragmentsVisibility(false);
397 updateNavigationElementsInActionBar(null);
398 }
399
400 protected void refreshListOfFilesFragment() {
401 OCFileListFragment fileListFragment = getListOfFilesFragment();
402 if (fileListFragment != null) {
403 fileListFragment.listDirectory();
404 }
405 }
406
407 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
408 FileFragment secondFragment = getSecondFragment();
409 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
410 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
411 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
412 OCFile fileInFragment = detailsFragment.getFile();
413 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
414 // the user browsed to other file ; forget the automatic preview
415 mWaitingToPreview = null;
416
417 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
418 // grant that the right panel updates the progress bar
419 detailsFragment.listenForTransferProgress();
420 detailsFragment.updateFileDetails(true, false);
421
422 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
423 // update the right panel
424 boolean detailsFragmentChanged = false;
425 if (waitedPreview) {
426 if (success) {
427 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
428 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
429 startMediaPreview(mWaitingToPreview, 0, true);
430 detailsFragmentChanged = true;
431 } else {
432 getFileOperationsHelper().openFile(mWaitingToPreview);
433 }
434 }
435 mWaitingToPreview = null;
436 }
437 if (!detailsFragmentChanged) {
438 detailsFragment.updateFileDetails(false, (success));
439 }
440 }
441 }
442 }
443
444 @Override
445 public boolean onCreateOptionsMenu(Menu menu) {
446 MenuInflater inflater = getSherlock().getMenuInflater();
447 inflater.inflate(R.menu.main_menu, menu);
448 return true;
449 }
450
451 @Override
452 public boolean onOptionsItemSelected(MenuItem item) {
453 boolean retval = true;
454 switch (item.getItemId()) {
455 case R.id.action_create_dir: {
456 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
457 dialog.show(getSupportFragmentManager(), "createdirdialog");
458 break;
459 }
460 case R.id.action_sync_account: {
461 startSynchronization();
462 break;
463 }
464 case R.id.action_upload: {
465 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
466 break;
467 }
468 case R.id.action_settings: {
469 Intent settingsIntent = new Intent(this, Preferences.class);
470 startActivity(settingsIntent);
471 break;
472 }
473 case android.R.id.home: {
474 FileFragment second = getSecondFragment();
475 OCFile currentDir = getCurrentDir();
476 if((currentDir != null && currentDir.getParentId() != 0) ||
477 (second != null && second.getFile() != null)) {
478 onBackPressed();
479
480 }
481 break;
482 }
483 default:
484 retval = super.onOptionsItemSelected(item);
485 }
486 return retval;
487 }
488
489 private void startSynchronization() {
490 Log_OC.e(TAG, "Got to start sync");
491 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
492 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
493 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
494 Bundle bundle = new Bundle();
495 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
496 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
497 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
498 ContentResolver.requestSync(
499 getAccount(),
500 MainApp.getAuthority(), bundle);
501 } else {
502 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
503 SyncRequest.Builder builder = new SyncRequest.Builder();
504 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
505 builder.setExpedited(true);
506 builder.setManual(true);
507 builder.syncOnce();
508 SyncRequest request = builder.build();
509 ContentResolver.requestSync(request);
510 }
511 }
512
513
514 @Override
515 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
516 if (itemPosition != 0) {
517 String targetPath = "";
518 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
519 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
520 }
521 targetPath = OCFile.PATH_SEPARATOR + targetPath;
522 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
523 if (targetFolder != null) {
524 browseTo(targetFolder);
525 }
526
527 // the next operation triggers a new call to this method, but it's necessary to
528 // ensure that the name exposed in the action bar is the current directory when the
529 // user selected it in the navigation list
530 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
531 getSupportActionBar().setSelectedNavigationItem(0);
532 }
533 return true;
534 }
535
536 /**
537 * Called, when the user selected something for uploading
538 */
539 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
540 super.onActivityResult(requestCode, resultCode, data);
541
542 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
543 requestSimpleUpload(data, resultCode);
544
545 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
546 requestMultipleUpload(data, resultCode);
547
548 }
549 }
550
551 private void requestMultipleUpload(Intent data, int resultCode) {
552 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
553 if (filePaths != null) {
554 String[] remotePaths = new String[filePaths.length];
555 String remotePathBase = "";
556 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
557 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
558 }
559 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
560 remotePathBase += OCFile.PATH_SEPARATOR;
561 for (int j = 0; j< remotePaths.length; j++) {
562 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
563 }
564
565 Intent i = new Intent(this, FileUploader.class);
566 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
567 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
568 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
569 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
570 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
571 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
572 startService(i);
573
574 } else {
575 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
576 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
577 t.show();
578 return;
579 }
580 }
581
582
583 private void requestSimpleUpload(Intent data, int resultCode) {
584 String filepath = null;
585 try {
586 Uri selectedImageUri = data.getData();
587
588 String filemanagerstring = selectedImageUri.getPath();
589 String selectedImagePath = getPath(selectedImageUri);
590
591 if (selectedImagePath != null)
592 filepath = selectedImagePath;
593 else
594 filepath = filemanagerstring;
595
596 } catch (Exception e) {
597 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
598 e.printStackTrace();
599
600 } finally {
601 if (filepath == null) {
602 Log_OC.e(TAG, "Couldnt resolve path to file");
603 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
604 t.show();
605 return;
606 }
607 }
608
609 Intent i = new Intent(this, FileUploader.class);
610 i.putExtra(FileUploader.KEY_ACCOUNT,
611 getAccount());
612 String remotepath = new String();
613 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
614 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
615 }
616 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
617 remotepath += OCFile.PATH_SEPARATOR;
618 remotepath += new File(filepath).getName();
619
620 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
621 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
622 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
623 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
624 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
625 startService(i);
626 }
627
628 @Override
629 public void onBackPressed() {
630 OCFileListFragment listOfFiles = getListOfFilesFragment();
631 if (mDualPane || getSecondFragment() == null) {
632 if (listOfFiles != null) { // should never be null, indeed
633 if (mDirectories.getCount() <= 1) {
634 finish();
635 return;
636 }
637 int levelsUp = listOfFiles.onBrowseUp();
638 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
639 popDirname();
640 }
641 }
642 }
643 if (listOfFiles != null) { // should never be null, indeed
644 setFile(listOfFiles.getCurrentFile());
645 }
646 cleanSecondFragment();
647
648 }
649
650 @Override
651 protected void onSaveInstanceState(Bundle outState) {
652 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
653 Log_OC.e(TAG, "onSaveInstanceState() start");
654 super.onSaveInstanceState(outState);
655 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
656 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
657 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
658 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
659
660 Log_OC.d(TAG, "onSaveInstanceState() end");
661 }
662
663
664
665 @Override
666 protected void onResume() {
667 super.onResume();
668 Log_OC.e(TAG, "onResume() start");
669
670 // Listen for sync messages
671 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
672 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
673 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
674 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
675 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
676 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
677 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
678 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
679
680 // Listen for upload messages
681 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
682 mUploadFinishReceiver = new UploadFinishReceiver();
683 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
684
685 // Listen for download messages
686 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
687 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
688 mDownloadFinishReceiver = new DownloadFinishReceiver();
689 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
690
691 Log_OC.d(TAG, "onResume() end");
692 }
693
694
695 @Override
696 protected void onPause() {
697 super.onPause();
698 Log_OC.e(TAG, "onPause() start");
699 if (mSyncBroadcastReceiver != null) {
700 unregisterReceiver(mSyncBroadcastReceiver);
701 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
702 mSyncBroadcastReceiver = null;
703 }
704 if (mUploadFinishReceiver != null) {
705 unregisterReceiver(mUploadFinishReceiver);
706 mUploadFinishReceiver = null;
707 }
708 if (mDownloadFinishReceiver != null) {
709 unregisterReceiver(mDownloadFinishReceiver);
710 mDownloadFinishReceiver = null;
711 }
712 Log_OC.d(TAG, "onPause() end");
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 ((FileDetailFragment)details).updateFileDetails(false, false);
987
988 // Force the preview if the file is an image
989 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
990 startImagePreview(getFile());
991 } // TODO what about other kind of previews?
992 }
993
994 removeStickyBroadcast(intent);
995
996 }
997
998 }
999
1000
1001 /**
1002 * Class waiting for broadcast events from the {@link FielDownloader} service.
1003 *
1004 * Updates the UI when a download is started or finished, provided that it is relevant for the
1005 * current folder.
1006 */
1007 private class DownloadFinishReceiver extends BroadcastReceiver {
1008 @Override
1009 public void onReceive(Context context, Intent intent) {
1010 boolean sameAccount = isSameAccount(context, intent);
1011 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1012 boolean isDescendant = isDescendant(downloadedRemotePath);
1013
1014 if (sameAccount && isDescendant) {
1015 refreshListOfFilesFragment();
1016 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1017 }
1018
1019 if (mWaitingToSend != null) {
1020 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1021 if (mWaitingToSend.isDown()) {
1022 sendDownloadedFile();
1023 }
1024 }
1025
1026 removeStickyBroadcast(intent);
1027 }
1028
1029 private boolean isDescendant(String downloadedRemotePath) {
1030 OCFile currentDir = getCurrentDir();
1031 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1032 }
1033
1034 private boolean isSameAccount(Context context, Intent intent) {
1035 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1036 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1037 }
1038 }
1039
1040
1041 public void browseToRoot() {
1042 OCFileListFragment listOfFiles = getListOfFilesFragment();
1043 if (listOfFiles != null) { // should never be null, indeed
1044 while (mDirectories.getCount() > 1) {
1045 popDirname();
1046 }
1047 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1048 listOfFiles.listDirectory(root);
1049 setFile(listOfFiles.getCurrentFile());
1050 startSyncFolderOperation(root);
1051 }
1052 cleanSecondFragment();
1053 }
1054
1055
1056 public void browseTo(OCFile folder) {
1057 if (folder == null || !folder.isFolder()) {
1058 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1059 }
1060 OCFileListFragment listOfFiles = getListOfFilesFragment();
1061 if (listOfFiles != null) {
1062 setNavigationListWithFolder(folder);
1063 listOfFiles.listDirectory(folder);
1064 setFile(listOfFiles.getCurrentFile());
1065 startSyncFolderOperation(folder);
1066 } else {
1067 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1068 }
1069 cleanSecondFragment();
1070 }
1071
1072
1073 /**
1074 * {@inheritDoc}
1075 *
1076 * Updates action bar and second fragment, if in dual pane mode.
1077 */
1078 @Override
1079 public void onBrowsedDownTo(OCFile directory) {
1080 pushDirname(directory);
1081 cleanSecondFragment();
1082
1083 // Sync Folder
1084 startSyncFolderOperation(directory);
1085
1086 }
1087
1088 /**
1089 * Shows the information of the {@link OCFile} received as a
1090 * parameter in the second fragment.
1091 *
1092 * @param file {@link OCFile} whose details will be shown
1093 */
1094 @Override
1095 public void showDetails(OCFile file) {
1096 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1097 setSecondFragment(detailFragment);
1098 updateFragmentsVisibility(true);
1099 updateNavigationElementsInActionBar(file);
1100 setFile(file);
1101 }
1102
1103
1104 /**
1105 * TODO
1106 */
1107 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1108 ActionBar actionBar = getSupportActionBar();
1109 if (chosenFile == null || mDualPane) {
1110 // only list of files - set for browsing through folders
1111 OCFile currentDir = getCurrentDir();
1112 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1113 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1114 actionBar.setDisplayShowTitleEnabled(!noRoot);
1115 if (!noRoot) {
1116 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1117 }
1118 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1119 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1120
1121 } else {
1122 actionBar.setDisplayHomeAsUpEnabled(true);
1123 actionBar.setDisplayShowTitleEnabled(true);
1124 actionBar.setTitle(chosenFile.getFileName());
1125 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1126 }
1127 }
1128
1129
1130 @Override
1131 protected ServiceConnection newTransferenceServiceConnection() {
1132 return new ListServiceConnection();
1133 }
1134
1135 /** Defines callbacks for service binding, passed to bindService() */
1136 private class ListServiceConnection implements ServiceConnection {
1137
1138 @Override
1139 public void onServiceConnected(ComponentName component, IBinder service) {
1140 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1141 Log_OC.d(TAG, "Download service connected");
1142 mDownloaderBinder = (FileDownloaderBinder) service;
1143 if (mWaitingToPreview != null) {
1144 requestForDownload();
1145 }
1146
1147 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1148 Log_OC.d(TAG, "Upload service connected");
1149 mUploaderBinder = (FileUploaderBinder) service;
1150 } else {
1151 return;
1152 }
1153 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1154 OCFileListFragment listOfFiles = getListOfFilesFragment();
1155 if (listOfFiles != null) {
1156 listOfFiles.listDirectory();
1157 }
1158 FileFragment secondFragment = getSecondFragment();
1159 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1160 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1161 detailFragment.listenForTransferProgress();
1162 detailFragment.updateFileDetails(false, false);
1163 }
1164 }
1165
1166 @Override
1167 public void onServiceDisconnected(ComponentName component) {
1168 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1169 Log_OC.d(TAG, "Download service disconnected");
1170 mDownloaderBinder = null;
1171 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1172 Log_OC.d(TAG, "Upload service disconnected");
1173 mUploaderBinder = null;
1174 }
1175 }
1176 };
1177
1178
1179
1180 /**
1181 * Launch an intent to request the PIN code to the user before letting him use the app
1182 */
1183 private void requestPinCode() {
1184 boolean pinStart = false;
1185 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1186 pinStart = appPrefs.getBoolean("set_pincode", false);
1187 if (pinStart) {
1188 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1189 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1190 startActivity(i);
1191 }
1192 }
1193
1194
1195 @Override
1196 public void onSavedCertificate() {
1197 startSyncFolderOperation(getCurrentDir());
1198 }
1199
1200
1201 @Override
1202 public void onFailedSavingCertificate() {
1203 showDialog(DIALOG_CERT_NOT_SAVED);
1204 }
1205
1206 @Override
1207 public void onCancelCertificate() {
1208 // nothing to do
1209 }
1210
1211 /**
1212 * Updates the view associated to the activity after the finish of some operation over files
1213 * in the current account.
1214 *
1215 * @param operation Removal operation performed.
1216 * @param result Result of the removal.
1217 */
1218 @Override
1219 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1220 super.onRemoteOperationFinish(operation, result);
1221
1222 if (operation instanceof RemoveFileOperation) {
1223 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1224
1225 } else if (operation instanceof RenameFileOperation) {
1226 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1227
1228 } else if (operation instanceof SynchronizeFileOperation) {
1229 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1230
1231 } else if (operation instanceof CreateFolderOperation) {
1232 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1233
1234 } else if (operation instanceof CreateShareOperation) {
1235 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1236
1237 } else if (operation instanceof UnshareLinkOperation) {
1238 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1239
1240 }
1241
1242 }
1243
1244
1245 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1246 if (result.isSuccess()) {
1247 refreshShowDetails();
1248 refreshListOfFilesFragment();
1249 }
1250 }
1251
1252
1253 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1254 if (result.isSuccess()) {
1255 refreshShowDetails();
1256 refreshListOfFilesFragment();
1257
1258 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1259 cleanSecondFragment();
1260 refreshListOfFilesFragment();
1261 }
1262 }
1263
1264 private void refreshShowDetails() {
1265 FileFragment details = getSecondFragment();
1266 if (details != null) {
1267 OCFile file = details.getFile();
1268 if (file != null) {
1269 file = getStorageManager().getFileByPath(file.getRemotePath());
1270 if (details instanceof PreviewMediaFragment) {
1271 // Refresh OCFile of the fragment
1272 ((PreviewMediaFragment) details).updateFile(file);
1273 } else {
1274 showDetails(file);
1275 }
1276 }
1277 invalidateOptionsMenu();
1278 }
1279 }
1280
1281 /**
1282 * Updates the view associated to the activity after the finish of an operation trying to remove a
1283 * file.
1284 *
1285 * @param operation Removal operation performed.
1286 * @param result Result of the removal.
1287 */
1288 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1289 dismissLoadingDialog();
1290 if (result.isSuccess()) {
1291 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1292 msg.show();
1293 OCFile removedFile = operation.getFile();
1294 FileFragment second = getSecondFragment();
1295 if (second != null && removedFile.equals(second.getFile())) {
1296 if (second instanceof PreviewMediaFragment) {
1297 ((PreviewMediaFragment)second).stopPreview(true);
1298 }
1299 cleanSecondFragment();
1300 }
1301 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1302 refreshListOfFilesFragment();
1303 }
1304
1305 } else {
1306 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1307 msg.show();
1308 if (result.isSslRecoverableException()) {
1309 mLastSslUntrustedServerResult = result;
1310 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1311 }
1312 }
1313 }
1314
1315
1316 /**
1317 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1318 *
1319 * @param operation Creation operation performed.
1320 * @param result Result of the creation.
1321 */
1322 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1323 if (result.isSuccess()) {
1324 dismissLoadingDialog();
1325 refreshListOfFilesFragment();
1326 } else {
1327 dismissLoadingDialog();
1328 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1329 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1330 } else {
1331 try {
1332 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1333 msg.show();
1334
1335 } catch (NotFoundException e) {
1336 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1337 }
1338 }
1339 }
1340 }
1341
1342
1343 /**
1344 * Updates the view associated to the activity after the finish of an operation trying to rename a
1345 * file.
1346 *
1347 * @param operation Renaming operation performed.
1348 * @param result Result of the renaming.
1349 */
1350 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1351 dismissLoadingDialog();
1352 OCFile renamedFile = operation.getFile();
1353 if (result.isSuccess()) {
1354 FileFragment details = getSecondFragment();
1355 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1356 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1357 }
1358 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1359 refreshListOfFilesFragment();
1360 }
1361
1362 } else {
1363 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1364 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1365 msg.show();
1366 // TODO throw again the new rename dialog
1367 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1368 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1369 msg.show();
1370 } else {
1371 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1372 msg.show();
1373 if (result.isSslRecoverableException()) {
1374 mLastSslUntrustedServerResult = result;
1375 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1376 }
1377 }
1378 }
1379 }
1380
1381 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1382 dismissLoadingDialog();
1383 OCFile syncedFile = operation.getLocalFile();
1384 if (!result.isSuccess()) {
1385 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1386 Intent i = new Intent(this, ConflictsResolveActivity.class);
1387 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1388 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1389 startActivity(i);
1390
1391 }
1392
1393 } else {
1394 if (operation.transferWasRequested()) {
1395 onTransferStateChanged(syncedFile, true, true);
1396
1397 } else {
1398 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1399 msg.show();
1400 }
1401 }
1402 }
1403
1404
1405 /**
1406 * {@inheritDoc}
1407 */
1408 @Override
1409 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1410 FileFragment details = getSecondFragment();
1411 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1412 if (downloading || uploading) {
1413 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1414 } else {
1415 ((FileDetailFragment)details).updateFileDetails(false, true);
1416 }
1417 }
1418 }
1419
1420
1421 public void onDismiss(EditNameDialog dialog) {
1422 if (dialog.getResult()) {
1423 String newDirectoryName = dialog.getNewFilename().trim();
1424 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1425 if (newDirectoryName.length() > 0) {
1426 String path = getCurrentDir().getRemotePath();
1427
1428 // Create directory
1429 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1430 getFileOperationsHelper().createFolder(path, false);
1431 }
1432 }
1433 }
1434
1435
1436 private void requestForDownload() {
1437 Account account = getAccount();
1438 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1439 Intent i = new Intent(this, FileDownloader.class);
1440 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1441 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1442 startService(i);
1443 }
1444 }
1445
1446
1447 private OCFile getCurrentDir() {
1448 OCFile file = getFile();
1449 if (file != null) {
1450 if (file.isFolder()) {
1451 return file;
1452 } else if (getStorageManager() != null) {
1453 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1454 return getStorageManager().getFileByPath(parentPath);
1455 }
1456 }
1457 return null;
1458 }
1459
1460 public void startSyncFolderOperation(OCFile folder) {
1461 long currentSyncTime = System.currentTimeMillis();
1462
1463 mSyncInProgress = true;
1464
1465 // perform folder synchronization
1466 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1467 currentSyncTime,
1468 false,
1469 getFileOperationsHelper().isSharedSupported(),
1470 getStorageManager(),
1471 getAccount(),
1472 getApplicationContext()
1473 );
1474 synchFolderOp.execute(getAccount(), this, null, null, this);
1475
1476 setSupportProgressBarIndeterminateVisibility(true);
1477 }
1478
1479 /**
1480 * Show untrusted cert dialog
1481 */
1482 public void showUntrustedCertDialog(RemoteOperationResult result) {
1483 // Show a dialog with the certificate info
1484 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1485 FragmentManager fm = getSupportFragmentManager();
1486 FragmentTransaction ft = fm.beginTransaction();
1487 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1488 }
1489
1490 private void requestForDownload(OCFile file) {
1491 Account account = getAccount();
1492 if (!mDownloaderBinder.isDownloading(account, file)) {
1493 Intent i = new Intent(this, FileDownloader.class);
1494 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1495 i.putExtra(FileDownloader.EXTRA_FILE, file);
1496 startService(i);
1497 }
1498 }
1499
1500 private void sendDownloadedFile(){
1501 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1502 mWaitingToSend = null;
1503 }
1504
1505
1506 /**
1507 * Requests the download of the received {@link OCFile} , updates the UI
1508 * to monitor the download progress and prepares the activity to send the file
1509 * when the download finishes.
1510 *
1511 * @param file {@link OCFile} to download and preview.
1512 */
1513 public void startDownloadForSending(OCFile file) {
1514 mWaitingToSend = file;
1515 requestForDownload(mWaitingToSend);
1516 boolean hasSecondFragment = (getSecondFragment()!= null);
1517 updateFragmentsVisibility(hasSecondFragment);
1518 }
1519
1520 /**
1521 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1522 *
1523 * @param file Image {@link OCFile} to show.
1524 */
1525 public void startImagePreview(OCFile file) {
1526 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1527 showDetailsIntent.putExtra(EXTRA_FILE, file);
1528 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1529 startActivity(showDetailsIntent);
1530 }
1531
1532 /**
1533 * Stars the preview of an already down media {@link OCFile}.
1534 *
1535 * @param file Media {@link OCFile} to preview.
1536 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1537 * @param autoplay When 'true', the playback will start without user interactions.
1538 */
1539 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1540 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1541 setSecondFragment(mediaFragment);
1542 updateFragmentsVisibility(true);
1543 updateNavigationElementsInActionBar(file);
1544 setFile(file);
1545 }
1546
1547 /**
1548 * Requests the download of the received {@link OCFile} , updates the UI
1549 * to monitor the download progress and prepares the activity to preview
1550 * or open the file when the download finishes.
1551 *
1552 * @param file {@link OCFile} to download and preview.
1553 */
1554 public void startDownloadForPreview(OCFile file) {
1555 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1556 setSecondFragment(detailFragment);
1557 mWaitingToPreview = file;
1558 requestForDownload();
1559 updateFragmentsVisibility(true);
1560 updateNavigationElementsInActionBar(file);
1561 setFile(file);
1562 }
1563
1564
1565 public void cancelTransference(OCFile file) {
1566 Account account = getAccount();
1567 if (mDownloaderBinder != null && mDownloaderBinder.isDownloading(account, file)) {
1568 mDownloaderBinder.cancel(account, file);
1569 refreshListOfFilesFragment();
1570 onTransferStateChanged(file, false, false);
1571
1572 } else if (mUploaderBinder != null && mUploaderBinder.isUploading(account, file)) {
1573 mUploaderBinder.cancel(account, file);
1574 refreshListOfFilesFragment();
1575 if (!file.fileExists()) {
1576 cleanSecondFragment();
1577
1578 } else {
1579 onTransferStateChanged(file, false, false);
1580 }
1581 }
1582 }
1583
1584 }