OC-2834: Access to unshare link from PreviewMediaFragment
[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.PreviewMediaFragment;
90 import com.owncloud.android.ui.preview.PreviewVideoActivity;
91 import com.owncloud.android.utils.DisplayUtils;
92 import com.owncloud.android.utils.Log_OC;
93
94
95 /**
96 * Displays, what files the user has available in his ownCloud.
97 *
98 * @author Bartek Przybylski
99 * @author David A. Velasco
100 */
101
102 public class FileDisplayActivity extends FileActivity implements
103 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, EditNameDialogListener {
104
105 private ArrayAdapter<String> mDirectories;
106
107 private SyncBroadcastReceiver mSyncBroadcastReceiver;
108 private UploadFinishReceiver mUploadFinishReceiver;
109 private DownloadFinishReceiver mDownloadFinishReceiver;
110 private OperationsServiceReceiver mOperationsServiceReceiver;
111 private FileDownloaderBinder mDownloaderBinder = null;
112 private FileUploaderBinder mUploaderBinder = null;
113 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
114 private RemoteOperationResult mLastSslUntrustedServerResult = null;
115
116 private boolean mDualPane;
117 private View mLeftFragmentContainer;
118 private View mRightFragmentContainer;
119
120 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
121 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
122 private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
123
124 public static final int DIALOG_SHORT_WAIT = 0;
125 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
126 private static final int DIALOG_SSL_VALIDATOR = 2;
127 private static final int DIALOG_CERT_NOT_SAVED = 3;
128
129 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
130
131 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
132 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
133
134 private static final String TAG = FileDisplayActivity.class.getSimpleName();
135
136 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
137 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
138
139 private OCFile mWaitingToPreview;
140
141 private boolean mSyncInProgress = false;
142 private boolean mRefreshSharesInProgress = false;
143
144 @Override
145 protected void onCreate(Bundle savedInstanceState) {
146 Log_OC.d(TAG, "onCreate() start");
147 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
148
149 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
150
151 /// bindings to transference services
152 mUploadConnection = new ListServiceConnection();
153 mDownloadConnection = new ListServiceConnection();
154 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
155 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
156
157 // PIN CODE request ; best location is to decide, let's try this first
158 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
159 requestPinCode();
160 } else if (getIntent().getAction() == null && savedInstanceState == null) {
161 requestPinCode();
162 }
163
164 /// file observer
165 Intent observer_intent = new Intent(this, FileObserverService.class);
166 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
167 startService(observer_intent);
168
169 /// Load of saved instance state
170 if(savedInstanceState != null) {
171 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
172 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
173 mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
174
175 } else {
176 mWaitingToPreview = null;
177 mSyncInProgress = false;
178 mRefreshSharesInProgress = false;
179 }
180
181 /// USER INTERFACE
182
183 // Inflate and set the layout view
184 setContentView(R.layout.files);
185 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
186 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
187 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
188 if (savedInstanceState == null) {
189 createMinFragments();
190 }
191
192 // Action bar setup
193 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
194 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
195 setSupportProgressBarIndeterminateVisibility(mSyncInProgress || mRefreshSharesInProgress); // always AFTER setContentView(...) ; to work around bug in its implementation
196
197 Log_OC.d(TAG, "onCreate() end");
198 }
199
200 @Override
201 protected void onStart() {
202 super.onStart();
203 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
204 }
205
206 @Override
207 protected void onDestroy() {
208 super.onDestroy();
209 if (mDownloadConnection != null)
210 unbindService(mDownloadConnection);
211 if (mUploadConnection != null)
212 unbindService(mUploadConnection);
213 }
214
215
216 /**
217 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
218 */
219 @Override
220 protected void onAccountSet(boolean stateWasRecovered) {
221 super.onAccountSet(stateWasRecovered);
222 if (getAccount() != null) {
223 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
224 OCFile file = getFile();
225 // get parent from path
226 String parentPath = "";
227 if (file != null) {
228 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
229 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
230 // get parent from path
231 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
232 if (getStorageManager().getFileByPath(parentPath) == null)
233 file = null; // not able to know the directory where the file is uploading
234 } else {
235 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
236 }
237 }
238 if (file == null) {
239 // fall back to root folder
240 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
241 }
242 setFile(file);
243 setNavigationListWithFolder(file);
244
245 if (!stateWasRecovered) {
246 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
247 initFragmentsWithFile();
248 if (file.isFolder()) {
249 startSyncFolderOperation(file);
250 }
251
252 } else {
253 updateFragmentsVisibility(!file.isFolder());
254 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
255 }
256 }
257 }
258
259
260 private void setNavigationListWithFolder(OCFile file) {
261 mDirectories.clear();
262 OCFile fileIt = file;
263 String parentPath;
264 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
265 if (fileIt.isFolder()) {
266 mDirectories.add(fileIt.getFileName());
267 }
268 // get parent from path
269 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
270 fileIt = getStorageManager().getFileByPath(parentPath);
271 }
272 mDirectories.add(OCFile.PATH_SEPARATOR);
273 }
274
275
276 private void createMinFragments() {
277 OCFileListFragment listOfFiles = new OCFileListFragment();
278 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
279 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
280 transaction.commit();
281 }
282
283 private void initFragmentsWithFile() {
284 if (getAccount() != null && getFile() != null) {
285 /// First fragment
286 OCFileListFragment listOfFiles = getListOfFilesFragment();
287 if (listOfFiles != null) {
288 listOfFiles.listDirectory(getCurrentDir());
289 } else {
290 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
291 }
292
293 /// Second fragment
294 OCFile file = getFile();
295 Fragment secondFragment = chooseInitialSecondFragment(file);
296 if (secondFragment != null) {
297 setSecondFragment(secondFragment);
298 updateFragmentsVisibility(true);
299 updateNavigationElementsInActionBar(file);
300
301 } else {
302 cleanSecondFragment();
303 }
304
305 } else {
306 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
307 if (getAccount() == null) {
308 Log.wtf(TAG, "\t account is NULL");
309 }
310 if (getFile() == null) {
311 Log.wtf(TAG, "\t file is NULL");
312 }
313 }
314 }
315
316 private Fragment chooseInitialSecondFragment(OCFile file) {
317 Fragment secondFragment = null;
318 if (file != null && !file.isFolder()) {
319 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
320 && file.getLastSyncDateForProperties() > 0 // temporal fix
321 ) {
322 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
323 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
324 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
325
326 } else {
327 secondFragment = new FileDetailFragment(file, getAccount());
328 }
329 }
330 return secondFragment;
331 }
332
333
334 /**
335 * Replaces the second fragment managed by the activity with the received as
336 * a parameter.
337 *
338 * Assumes never will be more than two fragments managed at the same time.
339 *
340 * @param fragment New second Fragment to set.
341 */
342 private void setSecondFragment(Fragment fragment) {
343 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
344 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
345 transaction.commit();
346 }
347
348
349 private void updateFragmentsVisibility(boolean existsSecondFragment) {
350 if (mDualPane) {
351 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
352 mLeftFragmentContainer.setVisibility(View.VISIBLE);
353 }
354 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
355 mRightFragmentContainer.setVisibility(View.VISIBLE);
356 }
357
358 } else if (existsSecondFragment) {
359 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
360 mLeftFragmentContainer.setVisibility(View.GONE);
361 }
362 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
363 mRightFragmentContainer.setVisibility(View.VISIBLE);
364 }
365
366 } else {
367 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
368 mLeftFragmentContainer.setVisibility(View.VISIBLE);
369 }
370 if (mRightFragmentContainer.getVisibility() != View.GONE) {
371 mRightFragmentContainer.setVisibility(View.GONE);
372 }
373 }
374 }
375
376
377 private OCFileListFragment getListOfFilesFragment() {
378 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
379 if (listOfFiles != null) {
380 return (OCFileListFragment)listOfFiles;
381 }
382 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
383 return null;
384 }
385
386 protected FileFragment getSecondFragment() {
387 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
388 if (second != null) {
389 return (FileFragment)second;
390 }
391 return null;
392 }
393
394 public void cleanSecondFragment() {
395 Fragment second = getSecondFragment();
396 if (second != null) {
397 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
398 tr.remove(second);
399 tr.commit();
400 }
401 updateFragmentsVisibility(false);
402 updateNavigationElementsInActionBar(null);
403 }
404
405 protected void refeshListOfFilesFragment() {
406 OCFileListFragment fileListFragment = getListOfFilesFragment();
407 if (fileListFragment != null) {
408 fileListFragment.listDirectory();
409 }
410 }
411
412 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
413 FileFragment secondFragment = getSecondFragment();
414 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
415 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
416 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
417 OCFile fileInFragment = detailsFragment.getFile();
418 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
419 // the user browsed to other file ; forget the automatic preview
420 mWaitingToPreview = null;
421
422 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
423 // grant that the right panel updates the progress bar
424 detailsFragment.listenForTransferProgress();
425 detailsFragment.updateFileDetails(true, false);
426
427 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
428 // update the right panel
429 boolean detailsFragmentChanged = false;
430 if (waitedPreview) {
431 if (success) {
432 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
433 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
434 startMediaPreview(mWaitingToPreview, 0, true);
435 detailsFragmentChanged = true;
436 } else {
437 getFileOperationsHelper().openFile(mWaitingToPreview, this);
438 }
439 }
440 mWaitingToPreview = null;
441 }
442 if (!detailsFragmentChanged) {
443 detailsFragment.updateFileDetails(false, (success));
444 }
445 }
446 }
447 }
448
449 @Override
450 public boolean onCreateOptionsMenu(Menu menu) {
451 MenuInflater inflater = getSherlock().getMenuInflater();
452 inflater.inflate(R.menu.main_menu, menu);
453 return true;
454 }
455
456 @Override
457 public boolean onOptionsItemSelected(MenuItem item) {
458 boolean retval = true;
459 switch (item.getItemId()) {
460 case R.id.action_create_dir: {
461 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
462 dialog.show(getSupportFragmentManager(), "createdirdialog");
463 break;
464 }
465 case R.id.action_sync_account: {
466 startSynchronization();
467 break;
468 }
469 case R.id.action_upload: {
470 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
471 break;
472 }
473 case R.id.action_settings: {
474 Intent settingsIntent = new Intent(this, Preferences.class);
475 startActivity(settingsIntent);
476 break;
477 }
478 case android.R.id.home: {
479 FileFragment second = getSecondFragment();
480 OCFile currentDir = getCurrentDir();
481 if((currentDir != null && currentDir.getParentId() != 0) ||
482 (second != null && second.getFile() != null)) {
483 onBackPressed();
484
485 }
486 break;
487 }
488 default:
489 retval = super.onOptionsItemSelected(item);
490 }
491 return retval;
492 }
493
494 private void startSynchronization() {
495 Log_OC.e(TAG, "Got to start sync");
496 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
497 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
498 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
499 Bundle bundle = new Bundle();
500 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
501 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
502 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
503 ContentResolver.requestSync(
504 getAccount(),
505 MainApp.getAuthority(), bundle);
506 } else {
507 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
508 SyncRequest.Builder builder = new SyncRequest.Builder();
509 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
510 builder.setExpedited(true);
511 builder.setManual(true);
512 builder.syncOnce();
513 SyncRequest request = builder.build();
514 ContentResolver.requestSync(request);
515 }
516 }
517
518
519 @Override
520 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
521 if (itemPosition != 0) {
522 String targetPath = "";
523 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
524 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
525 }
526 targetPath = OCFile.PATH_SEPARATOR + targetPath;
527 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
528 if (targetFolder != null) {
529 browseTo(targetFolder);
530 }
531
532 // the next operation triggers a new call to this method, but it's necessary to
533 // ensure that the name exposed in the action bar is the current directory when the
534 // user selected it in the navigation list
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 return v;
873 }
874
875 public View getDropDownView(int position, View convertView,
876 ViewGroup parent) {
877 View v = super.getDropDownView(position, convertView, parent);
878
879 ((TextView) v).setTextColor(getResources().getColorStateList(
880 android.R.color.white));
881
882 return v;
883 }
884
885 }
886
887 private class SyncBroadcastReceiver extends BroadcastReceiver {
888
889 /**
890 * {@link BroadcastReceiver} to enable syncing feedback in UI
891 */
892 @Override
893 public void onReceive(Context context, Intent intent) {
894 String event = intent.getAction();
895 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
896 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
897 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
898 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
899
900 if (sameAccount) {
901
902 if (!FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
903 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
904 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
905
906 if (currentDir == null) {
907 // current folder was removed from the server
908 Toast.makeText( FileDisplayActivity.this,
909 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
910 Toast.LENGTH_LONG)
911 .show();
912 browseToRoot();
913
914 } else {
915 if (currentFile == null && !getFile().isFolder()) {
916 // currently selected file was removed in the server, and now we know it
917 cleanSecondFragment();
918 currentFile = currentDir;
919 }
920
921 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
922 OCFileListFragment fileListFragment = getListOfFilesFragment();
923 if (fileListFragment != null) {
924 fileListFragment.listDirectory(currentDir);
925 }
926 }
927 setFile(currentFile);
928 }
929
930 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
931 !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) &&
932 (synchResult == null || synchResult.isSuccess())) ;
933
934 if (synchResult != null &&
935 synchResult.isSuccess() &&
936 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
937 FileSyncAdapter.EVENT_FOLDER_CONTENTS_SYNCED.equals(event)
938 ) &&
939 !mRefreshSharesInProgress &&
940 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
941 ) {
942 startGetShares();
943 }
944
945 }
946 //removeStickyBroadcast(intent);
947 setSupportProgressBarIndeterminateVisibility(mSyncInProgress || mRefreshSharesInProgress);
948 }
949
950 if (synchResult != null) {
951 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
952 mLastSslUntrustedServerResult = synchResult;
953 showDialog(DIALOG_SSL_VALIDATOR);
954 }
955 }
956 }
957 }
958
959
960 private class UploadFinishReceiver extends BroadcastReceiver {
961 /**
962 * Once the file upload has finished -> update view
963 * @author David A. Velasco
964 * {@link BroadcastReceiver} to enable upload feedback in UI
965 */
966 @Override
967 public void onReceive(Context context, Intent intent) {
968 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
969 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
970 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
971 OCFile currentDir = getCurrentDir();
972 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
973 if (sameAccount && isDescendant) {
974 refeshListOfFilesFragment();
975 }
976 }
977
978 }
979
980
981 /**
982 * Class waiting for broadcast events from the {@link FielDownloader} service.
983 *
984 * Updates the UI when a download is started or finished, provided that it is relevant for the
985 * current folder.
986 */
987 private class DownloadFinishReceiver extends BroadcastReceiver {
988 @Override
989 public void onReceive(Context context, Intent intent) {
990 boolean sameAccount = isSameAccount(context, intent);
991 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
992 boolean isDescendant = isDescendant(downloadedRemotePath);
993
994 if (sameAccount && isDescendant) {
995 refeshListOfFilesFragment();
996 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
997 }
998
999 removeStickyBroadcast(intent);
1000 }
1001
1002 private boolean isDescendant(String downloadedRemotePath) {
1003 OCFile currentDir = getCurrentDir();
1004 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1005 }
1006
1007 private boolean isSameAccount(Context context, Intent intent) {
1008 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1009 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1010 }
1011 }
1012
1013
1014 /**
1015 * Class waiting for broadcast events from the {@link OperationsService}.
1016 *
1017 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1018 * operation performed in {@link OperationsService}.
1019 *
1020 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1021 * probably all the operations associated to the app model.
1022 */
1023 private class OperationsServiceReceiver extends BroadcastReceiver {
1024
1025 @Override
1026 public void onReceive(Context context, Intent intent) {
1027 if (OperationsService.ACTION_OPERATION_ADDED.equals(intent.getAction())) {
1028
1029 } else if (OperationsService.ACTION_OPERATION_FINISHED.equals(intent.getAction())) {
1030 mRefreshSharesInProgress = false;
1031
1032 Account account = intent.getParcelableExtra(OperationsService.EXTRA_ACCOUNT);
1033 RemoteOperationResult getSharesResult = (RemoteOperationResult)intent.getSerializableExtra(OperationsService.EXTRA_RESULT);
1034 if (getAccount() != null && account.name.equals(getAccount().name)
1035 && getStorageManager() != null
1036 ) {
1037 refeshListOfFilesFragment();
1038 }
1039 if ((getSharesResult != null) &&
1040 RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(getSharesResult.getCode())) {
1041 mLastSslUntrustedServerResult = getSharesResult;
1042 showDialog(DIALOG_SSL_VALIDATOR);
1043 }
1044
1045 setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1046 }
1047
1048 }
1049
1050 }
1051
1052 public void browseToRoot() {
1053 OCFileListFragment listOfFiles = getListOfFilesFragment();
1054 if (listOfFiles != null) { // should never be null, indeed
1055 while (mDirectories.getCount() > 1) {
1056 popDirname();
1057 }
1058 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1059 listOfFiles.listDirectory(root);
1060 setFile(listOfFiles.getCurrentFile());
1061 startSyncFolderOperation(root);
1062 }
1063 cleanSecondFragment();
1064 }
1065
1066
1067 public void browseTo(OCFile folder) {
1068 if (folder == null || !folder.isFolder()) {
1069 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1070 }
1071 OCFileListFragment listOfFiles = getListOfFilesFragment();
1072 if (listOfFiles != null) {
1073 setNavigationListWithFolder(folder);
1074 listOfFiles.listDirectory(folder);
1075 setFile(listOfFiles.getCurrentFile());
1076 startSyncFolderOperation(folder);
1077 } else {
1078 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1079 }
1080 cleanSecondFragment();
1081 }
1082
1083
1084 /**
1085 * {@inheritDoc}
1086 *
1087 * Updates action bar and second fragment, if in dual pane mode.
1088 */
1089 @Override
1090 public void onBrowsedDownTo(OCFile directory) {
1091 pushDirname(directory);
1092 cleanSecondFragment();
1093
1094 // Sync Folder
1095 startSyncFolderOperation(directory);
1096
1097 }
1098
1099 /**
1100 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1101 *
1102 * @param file Image {@link OCFile} to show.
1103 */
1104 @Override
1105 public void startImagePreview(OCFile file) {
1106 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1107 showDetailsIntent.putExtra(EXTRA_FILE, file);
1108 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1109 startActivity(showDetailsIntent);
1110 }
1111
1112 /**
1113 * Stars the preview of an already down media {@link OCFile}.
1114 *
1115 * @param file Media {@link OCFile} to preview.
1116 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1117 * @param autoplay When 'true', the playback will start without user interactions.
1118 */
1119 @Override
1120 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1121 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1122 setSecondFragment(mediaFragment);
1123 updateFragmentsVisibility(true);
1124 updateNavigationElementsInActionBar(file);
1125 setFile(file);
1126 }
1127
1128 /**
1129 * Requests the download of the received {@link OCFile} , updates the UI
1130 * to monitor the download progress and prepares the activity to preview
1131 * or open the file when the download finishes.
1132 *
1133 * @param file {@link OCFile} to download and preview.
1134 */
1135 @Override
1136 public void startDownloadForPreview(OCFile file) {
1137 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1138 setSecondFragment(detailFragment);
1139 mWaitingToPreview = file;
1140 requestForDownload();
1141 updateFragmentsVisibility(true);
1142 updateNavigationElementsInActionBar(file);
1143 setFile(file);
1144 }
1145
1146
1147 /**
1148 * Shows the information of the {@link OCFile} received as a
1149 * parameter in the second fragment.
1150 *
1151 * @param file {@link OCFile} whose details will be shown
1152 */
1153 @Override
1154 public void showDetails(OCFile file) {
1155 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1156 setSecondFragment(detailFragment);
1157 updateFragmentsVisibility(true);
1158 updateNavigationElementsInActionBar(file);
1159 setFile(file);
1160 }
1161
1162
1163 /**
1164 * TODO
1165 */
1166 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1167 ActionBar actionBar = getSupportActionBar();
1168 if (chosenFile == null || mDualPane) {
1169 // only list of files - set for browsing through folders
1170 OCFile currentDir = getCurrentDir();
1171 actionBar.setDisplayHomeAsUpEnabled(currentDir != null && currentDir.getParentId() != 0);
1172 actionBar.setDisplayShowTitleEnabled(false);
1173 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1174 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1175
1176 } else {
1177 actionBar.setDisplayHomeAsUpEnabled(true);
1178 actionBar.setDisplayShowTitleEnabled(true);
1179 actionBar.setTitle(chosenFile.getFileName());
1180 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1181 }
1182 }
1183
1184
1185 /**
1186 * {@inheritDoc}
1187 */
1188 @Override
1189 public void onFileStateChanged() {
1190 refeshListOfFilesFragment();
1191 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1192 }
1193
1194
1195 /**
1196 * {@inheritDoc}
1197 */
1198 @Override
1199 public FileDownloaderBinder getFileDownloaderBinder() {
1200 return mDownloaderBinder;
1201 }
1202
1203
1204 /**
1205 * {@inheritDoc}
1206 */
1207 @Override
1208 public FileUploaderBinder getFileUploaderBinder() {
1209 return mUploaderBinder;
1210 }
1211
1212
1213 /** Defines callbacks for service binding, passed to bindService() */
1214 private class ListServiceConnection implements ServiceConnection {
1215
1216 @Override
1217 public void onServiceConnected(ComponentName component, IBinder service) {
1218 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1219 Log_OC.d(TAG, "Download service connected");
1220 mDownloaderBinder = (FileDownloaderBinder) service;
1221 if (mWaitingToPreview != null) {
1222 requestForDownload();
1223 }
1224
1225 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1226 Log_OC.d(TAG, "Upload service connected");
1227 mUploaderBinder = (FileUploaderBinder) service;
1228 } else {
1229 return;
1230 }
1231 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1232 OCFileListFragment listOfFiles = getListOfFilesFragment();
1233 if (listOfFiles != null) {
1234 listOfFiles.listDirectory();
1235 }
1236 FileFragment secondFragment = getSecondFragment();
1237 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1238 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1239 detailFragment.listenForTransferProgress();
1240 detailFragment.updateFileDetails(false, false);
1241 }
1242 }
1243
1244 @Override
1245 public void onServiceDisconnected(ComponentName component) {
1246 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1247 Log_OC.d(TAG, "Download service disconnected");
1248 mDownloaderBinder = null;
1249 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1250 Log_OC.d(TAG, "Upload service disconnected");
1251 mUploaderBinder = null;
1252 }
1253 }
1254 };
1255
1256
1257
1258 /**
1259 * Launch an intent to request the PIN code to the user before letting him use the app
1260 */
1261 private void requestPinCode() {
1262 boolean pinStart = false;
1263 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1264 pinStart = appPrefs.getBoolean("set_pincode", false);
1265 if (pinStart) {
1266 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1267 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1268 startActivity(i);
1269 }
1270 }
1271
1272
1273 @Override
1274 public void onSavedCertificate() {
1275 startSyncFolderOperation(getCurrentDir());
1276 }
1277
1278
1279 @Override
1280 public void onFailedSavingCertificate() {
1281 showDialog(DIALOG_CERT_NOT_SAVED);
1282 }
1283
1284
1285 /**
1286 * Updates the view associated to the activity after the finish of some operation over files
1287 * in the current account.
1288 *
1289 * @param operation Removal operation performed.
1290 * @param result Result of the removal.
1291 */
1292 @Override
1293 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1294 super.onRemoteOperationFinish(operation, result);
1295
1296 if (operation instanceof RemoveFileOperation) {
1297 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1298
1299 } else if (operation instanceof RenameFileOperation) {
1300 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1301
1302 } else if (operation instanceof SynchronizeFileOperation) {
1303 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1304
1305 } else if (operation instanceof CreateFolderOperation) {
1306 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1307
1308 } else if (operation instanceof CreateShareOperation) {
1309 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1310
1311 } else if (operation instanceof UnshareLinkOperation) {
1312 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1313
1314 }
1315
1316 }
1317
1318
1319 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1320 if (result.isSuccess()) {
1321 refeshListOfFilesFragment();
1322 }
1323 }
1324
1325
1326 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1327 if (result.isSuccess()) {
1328 refeshListOfFilesFragment();
1329 }
1330 }
1331
1332
1333 /**
1334 * Updates the view associated to the activity after the finish of an operation trying to remove a
1335 * file.
1336 *
1337 * @param operation Removal operation performed.
1338 * @param result Result of the removal.
1339 */
1340 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1341 dismissLoadingDialog();
1342 if (result.isSuccess()) {
1343 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1344 msg.show();
1345 OCFile removedFile = operation.getFile();
1346 getSecondFragment();
1347 FileFragment second = getSecondFragment();
1348 if (second != null && removedFile.equals(second.getFile())) {
1349 cleanSecondFragment();
1350 }
1351 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1352 refeshListOfFilesFragment();
1353 }
1354
1355 } else {
1356 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1357 msg.show();
1358 if (result.isSslRecoverableException()) {
1359 mLastSslUntrustedServerResult = result;
1360 showDialog(DIALOG_SSL_VALIDATOR);
1361 }
1362 }
1363 }
1364
1365 /**
1366 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1367 *
1368 * @param operation Creation operation performed.
1369 * @param result Result of the creation.
1370 */
1371 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1372 if (result.isSuccess()) {
1373 dismissLoadingDialog();
1374 refeshListOfFilesFragment();
1375
1376 } else {
1377 dismissLoadingDialog();
1378 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1379 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1380 } else {
1381 try {
1382 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1383 msg.show();
1384
1385 } catch (NotFoundException e) {
1386 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1387 }
1388 }
1389 }
1390 }
1391
1392
1393 /**
1394 * Updates the view associated to the activity after the finish of an operation trying to rename a
1395 * file.
1396 *
1397 * @param operation Renaming operation performed.
1398 * @param result Result of the renaming.
1399 */
1400 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1401 dismissLoadingDialog();
1402 OCFile renamedFile = operation.getFile();
1403 if (result.isSuccess()) {
1404 if (mDualPane) {
1405 FileFragment details = getSecondFragment();
1406 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1407 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1408 }
1409 }
1410 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1411 refeshListOfFilesFragment();
1412 }
1413
1414 } else {
1415 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1416 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1417 msg.show();
1418 // TODO throw again the new rename dialog
1419 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1420 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1421 msg.show();
1422 } else {
1423 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1424 msg.show();
1425 if (result.isSslRecoverableException()) {
1426 mLastSslUntrustedServerResult = result;
1427 showDialog(DIALOG_SSL_VALIDATOR);
1428 }
1429 }
1430 }
1431 }
1432
1433
1434 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1435 dismissLoadingDialog();
1436 OCFile syncedFile = operation.getLocalFile();
1437 if (!result.isSuccess()) {
1438 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1439 Intent i = new Intent(this, ConflictsResolveActivity.class);
1440 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1441 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1442 startActivity(i);
1443
1444 }
1445
1446 } else {
1447 if (operation.transferWasRequested()) {
1448 refeshListOfFilesFragment();
1449 onTransferStateChanged(syncedFile, true, true);
1450
1451 } else {
1452 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1453 msg.show();
1454 }
1455 }
1456 }
1457
1458
1459 /**
1460 * {@inheritDoc}
1461 */
1462 @Override
1463 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1464 if (mDualPane) {
1465 FileFragment details = getSecondFragment();
1466 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1467 if (downloading || uploading) {
1468 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1469 } else {
1470 ((FileDetailFragment)details).updateFileDetails(false, true);
1471 }
1472 }
1473 }
1474 }
1475
1476
1477 public void onDismiss(EditNameDialog dialog) {
1478 if (dialog.getResult()) {
1479 String newDirectoryName = dialog.getNewFilename().trim();
1480 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1481 if (newDirectoryName.length() > 0) {
1482 String path = getCurrentDir().getRemotePath();
1483
1484 // Create directory
1485 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1486 RemoteOperation operation = new CreateFolderOperation(path, false, getStorageManager());
1487 operation.execute( getAccount(),
1488 FileDisplayActivity.this,
1489 FileDisplayActivity.this,
1490 getHandler(),
1491 FileDisplayActivity.this);
1492
1493 showLoadingDialog();
1494 }
1495 }
1496 }
1497
1498
1499 private void requestForDownload() {
1500 Account account = getAccount();
1501 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1502 Intent i = new Intent(this, FileDownloader.class);
1503 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1504 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1505 startService(i);
1506 }
1507 }
1508
1509
1510 private OCFile getCurrentDir() {
1511 OCFile file = getFile();
1512 if (file != null) {
1513 if (file.isFolder()) {
1514 return file;
1515 } else if (getStorageManager() != null) {
1516 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1517 return getStorageManager().getFileByPath(parentPath);
1518 }
1519 }
1520 return null;
1521 }
1522
1523 public void startSyncFolderOperation(OCFile folder) {
1524 long currentSyncTime = System.currentTimeMillis();
1525
1526 mSyncInProgress = true;
1527
1528 // perform folder synchronization
1529 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1530 currentSyncTime,
1531 false,
1532 getStorageManager(),
1533 getAccount(),
1534 getApplicationContext()
1535 );
1536 synchFolderOp.execute(getAccount(), this, null, null, this);
1537
1538 setSupportProgressBarIndeterminateVisibility(true);
1539 }
1540
1541
1542 private void startGetShares() {
1543 // Get shared files/folders
1544 Intent intent = new Intent(this, OperationsService.class);
1545 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1546 startService(intent);
1547
1548 mRefreshSharesInProgress = true;
1549 }
1550
1551
1552
1553
1554 }