ActionsProvider.kt 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) Milan Jurkulák 2024.
  3. * Contact:
  4. * e: mimoccc@gmail.com
  5. * e: mj@mjdev.org
  6. * w: https://mjdev.org
  7. */
  8. package eu.mjdev.desktop.managers.artificialintelligence.actions
  9. import eu.mjdev.desktop.managers.artificialintelligence.actions.base.Action
  10. import eu.mjdev.desktop.managers.artificialintelligence.actions.base.ActionException
  11. import eu.mjdev.desktop.managers.artificialintelligence.actions.base.ActionException.ActionFail
  12. import eu.mjdev.desktop.managers.artificialintelligence.actions.base.ActionException.ActionSuccess
  13. import eu.mjdev.desktop.managers.artificialintelligence.actions.base.ActionProviderScope
  14. import eu.mjdev.desktop.provider.DesktopProvider
  15. import kotlinx.coroutines.CoroutineScope
  16. import kotlinx.coroutines.Dispatchers
  17. import kotlinx.coroutines.runBlocking
  18. @Suppress("unused")
  19. class ActionsProvider(
  20. val api: DesktopProvider,
  21. ) : ArrayList<Action>() {
  22. val scope: CoroutineScope = api.scope
  23. constructor(
  24. api: DesktopProvider,
  25. block: ActionsProvider.() -> Unit = {}
  26. ) : this(api) {
  27. block.invoke(this)
  28. }
  29. constructor(
  30. api: DesktopProvider,
  31. vararg actions: Action
  32. ) : this(api) {
  33. addAll(actions)
  34. }
  35. fun action(
  36. command: String,
  37. action: suspend ActionProviderScope.() -> ActionException,
  38. ) {
  39. add(
  40. Action(
  41. name = command,
  42. text = command,
  43. action = action
  44. )
  45. )
  46. }
  47. // todo regexp & fuzzy
  48. fun tryAction(
  49. text: String
  50. ): ActionException {
  51. return text.trim().let { t ->
  52. firstOrNull { a ->
  53. a.text.contentEquals(t, true) || a.text.contains(t, true)
  54. }?.let { a ->
  55. a.lastSeen = System.currentTimeMillis()
  56. runBlocking(Dispatchers.IO) {
  57. a.action.invoke(ActionProviderScope(api)).let { r ->
  58. if(r is ActionFail) r else ActionSuccess(a.responseSuccess, r)
  59. }
  60. }
  61. } ?: ActionException.ActionNone
  62. }
  63. }
  64. }