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