UpdateService.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package in.ocsf.these.days.app.service;/* kpmy 19.02.2017 */
  2. import com.pengrad.telegrambot.model.Update;
  3. import in.ocsf.these.days.app.messaging.UpdateHelper;
  4. import in.ocsf.these.days.app.object.Chat;
  5. import in.ocsf.these.days.app.object.User;
  6. import in.ocsf.these.days.app.repo.ChatRepository;
  7. import in.ocsf.these.days.app.repo.UserRepository;
  8. import in.ocsf.these.days.app.state.IChat;
  9. import in.ocsf.these.days.app.state.StateService;
  10. import in.ocsf.these.days.app.state.account.Accounted;
  11. import org.apache.log4j.Logger;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.context.ApplicationContext;
  14. import org.springframework.statemachine.StateMachine;
  15. import org.springframework.stereotype.Service;
  16. import java.util.Optional;
  17. @Service
  18. public class UpdateService {
  19. private final Logger log = Logger.getLogger(getClass());
  20. @Autowired
  21. private ApplicationContext context;
  22. @Autowired
  23. private UserRepository userRepo;
  24. @Autowired
  25. private StateService stateService;
  26. @Autowired
  27. private ChatRepository chatRepo;
  28. @Autowired
  29. private CommandService commandService;
  30. @Autowired
  31. private Accounted accounted;
  32. private void handleUpdate(UpdateHelper upd) {
  33. if (!upd.hasText()) throw new RuntimeException();
  34. User user = User.fromUser(upd.getUser());
  35. user = Optional.ofNullable(userRepo.findOne(user.getId())).orElse(user);
  36. StateMachine<Accounted.State, Accounted.Event> state = stateService.getStateFor(user);
  37. stateService.put(state, IChat.USER, user.getId());
  38. stateService.put(state, upd);
  39. if (state.getState() == null) {
  40. userRepo.save(user);
  41. chatRepo.findByUserIdAndThenClose(user.getId());
  42. state.start();
  43. stateService.setStateFor(user, state);
  44. userRepo.save(user);
  45. }
  46. if (upd.isCommand())
  47. commandService.handle(state);
  48. else {
  49. Optional<Chat> chat0 = chatRepo.findByUserIdAndStateThenActualize(user.getId());
  50. chat0.ifPresent(c -> {
  51. StateMachine chatState = stateService.getChatStateFor(c);
  52. stateService.put(chatState, upd);
  53. stateService.put(chatState, IChat.CHAT, c.getId());
  54. IChat chat = context.getBean(c.getType().getBean());
  55. chat.handle(chatState);
  56. });
  57. if (!chat0.isPresent())
  58. accounted.handle(state);
  59. }
  60. }
  61. public void handleUpdate(Update upd) {
  62. UpdateHelper helper = UpdateHelper.from(upd);
  63. if (!helper.isEdit()) handleUpdate(helper);
  64. }
  65. }