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