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