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