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