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