| 1 | import { createStore } from "/js/AlpineStore.js"; |
| 2 | import * as api from "/js/api.js"; |
| 3 | import { |
| 4 | store as notificationStore, |
| 5 | defaultPriority, |
| 6 | } from "/components/notifications/notification-store.js"; |
| 7 | import { formatDateTime } from "/js/time-utils.js"; |
| 8 | |
| 9 | const model = { |
| 10 | pluginName: "", |
| 11 | pluginDisplayName: "", |
| 12 | output: "", |
| 13 | running: false, |
| 14 | exitCode: null, |
| 15 | lastExecution: null, |
| 16 | |
| 17 | async open(plugin) { |
| 18 | if (!plugin?.name) return; |
| 19 | this.pluginName = plugin.name; |
| 20 | this.pluginDisplayName = plugin.display_name || plugin.name; |
| 21 | this.output = ""; |
| 22 | this.exitCode = null; |
| 23 | this.lastExecution = null; |
| 24 | window.openModal?.("components/plugins/list/plugin-execute-modal.html"); |
| 25 | await this.fetchLastExecution(); |
| 26 | }, |
| 27 | |
| 28 | async fetchLastExecution() { |
| 29 | try { |
| 30 | const response = await api.callJsonApi("plugins", { |
| 31 | action: "get_execute_record", |
| 32 | plugin_name: this.pluginName, |
| 33 | }); |
| 34 | this.lastExecution = response.data || null; |
| 35 | } catch (e) { |
| 36 | this.lastExecution = null; |
| 37 | } |
| 38 | }, |
| 39 | |
| 40 | async run() { |
| 41 | if (!this.pluginName) return; |
| 42 | this.output = ""; |
| 43 | this.exitCode = null; |
| 44 | this.running = true; |
| 45 | try { |
| 46 | const response = await api.callJsonApi("plugins", { |
| 47 | action: "run_execute_script", |
| 48 | plugin_name: this.pluginName, |
| 49 | }); |
| 50 | this.output = response.output || ""; |
| 51 | this.exitCode = response.exit_code ?? null; |
| 52 | if (response.executed_at) { |
| 53 | this.lastExecution = { |
| 54 | executed_at: response.executed_at, |
| 55 | exit_code: response.exit_code ?? null, |
| 56 | }; |
| 57 | } |
| 58 | } catch (e) { |
| 59 | this.output = e.message || String(e); |
| 60 | this.exitCode = -1; |
| 61 | notificationStore.frontendError( |
| 62 | e.message || String(e), |
| 63 | "Failed to run execute script", |
| 64 | 3, |
| 65 | "pluginExecute", |
| 66 | defaultPriority, |
| 67 | true, |
| 68 | ); |
| 69 | } finally { |
| 70 | this.running = false; |
| 71 | } |
| 72 | }, |
| 73 | |
| 74 | cleanup() { |
| 75 | this.pluginName = ""; |
| 76 | this.pluginDisplayName = ""; |
| 77 | this.output = ""; |
| 78 | this.running = false; |
| 79 | this.exitCode = null; |
| 80 | this.lastExecution = null; |
| 81 | }, |
| 82 | |
| 83 | formatTimestamp(value) { |
| 84 | if (!value) return ""; |
| 85 | return formatDateTime(value, "full"); |
| 86 | }, |
| 87 | }; |
| 88 | |
| 89 | export const store = createStore("pluginExecuteStore", model); |