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