Debian Codegraph @

pkg/lib/cockpit-components-shutdown.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React from 'react';
8 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
9 import {
10 Modal, ModalBody, ModalFooter, ModalHeader
11 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
12 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
13 import { Flex } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
14 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
15 import { TextArea } from "@patternfly/react-core/dist/esm/components/TextArea/index.js";
16 import { DatePicker } from "@patternfly/react-core/dist/esm/components/DatePicker/index.js";
17 import { TimePicker } from "@patternfly/react-core/dist/esm/components/TimePicker/index.js";
18
19 import { ServerTime } from 'serverTime.js';
20 import * as timeformat from "timeformat";
21 import { DialogsContext } from "dialogs.jsx";
22 import { FormHelper } from "cockpit-components-form-helper";
23
24 import { SimpleSelect } from "cockpit-components-simple-select";
25
26 import "cockpit-components-shutdown.scss";
27
28 const _ = cockpit.gettext;
29
30 export class ShutdownModal extends React.Component {
31 static contextType = DialogsContext;
32
33 constructor(props) {
34 super(props);
35 this.date_spawn = null;
36 this.state = {
37 error: "",
38 dateError: "",
39 message: "",
40 isOpen: false,
41 selected: "1",
42 dateObject: undefined,
43 startDate: undefined,
44 date: "",
45 time: "",
46 when: "+1",
47 formFilled: false,
48 };
49 this.onSubmit = this.onSubmit.bind(this);
50 this.updateDate = this.updateDate.bind(this);
51 this.updateTime = this.updateTime.bind(this);
52 this.calculate = this.calculate.bind(this);
53 this.dateRangeValidator = this.dateRangeValidator.bind(this);
54
55 this.server_time = new ServerTime();
56 }
57
58 componentDidMount() {
59 this.server_time.wait()
60 .then(() => {
61 const dateObject = this.server_time.utc_fake_now;
62 const date = dateObject.toISOString().split("T")[0];
63 const hour = dateObject.getUTCHours();
64 const minute = dateObject.getUTCMinutes();
65 this.setState({
66 dateObject,
67 date,
68 startDate: new Date(dateObject.toDateString()),
69 time: hour.toString().padStart(2, "0") + ":" + minute.toString().padStart(2, "0"),
70 });
71 })
72 .always(() => this.setState({ formFilled: true }));
73 }
74
75 updateDate(value, dateObject) {
76 this.setState({ date: value, dateObject }, this.calculate);
77 }
78
79 updateTime(value, hour, minute) {
80 this.setState({ time: value, hour, minute }, this.calculate);
81 }
82
83 calculate() {
84 if (this.date_spawn)
85 this.date_spawn.close("cancelled");
86
87 if (this.state.selected != "x") {
88 this.setState(prevState => ({
89 when: "+" + prevState.selected,
90 error: "",
91 dateError: "",
92 }));
93 return;
94 }
95
96 const time_error = this.state.hour === null || this.state.minute === null;
97 const date_error = !this.state.dateObject;
98
99 if (time_error && date_error) {
100 this.setState({ dateError: _("Invalid date format and invalid time format") });
101 return;
102 } else if (time_error) {
103 this.setState({ dateError: _("Invalid time format") });
104 return;
105 } else if (date_error) {
106 this.setState({ dateError: _("Invalid date format") });
107 return;
108 }
109
110 const cmd = ["date", "--date=" + (new Intl.DateTimeFormat('en-us').format(this.state.dateObject)) + " " + this.state.time, "+%s"];
111 this.date_spawn = cockpit.spawn(cmd, { err: "message" });
112 this.date_spawn.then(data => {
113 const input_timestamp = parseInt(data, 10);
114 const server_timestamp = parseInt(this.server_time.now.getTime() / 1000, 10);
115 let offset = Math.ceil((input_timestamp - server_timestamp) / 60);
116
117 /* If the time in minutes just changed, make it happen now */
118 if (offset === -1) {
119 offset = 0;
120 } else if (offset < 0) { // Otherwise it is a failure
121 this.setState({ dateError: _("Cannot schedule event in the past") });
122 return;
123 }
124
125 this.setState({
126 when: "+" + offset,
127 error: "",
128 dateError: "",
129 });
130 });
131 this.date_spawn.catch(e => {
132 if (e.problem == "cancelled")
133 return;
134 this.setState({ error: e.toString() });
135 });
136 this.date_spawn.finally(() => { this.date_spawn = null });
137 }
138
139 onSubmit(event) {
140 const Dialogs = this.context;
141 const arg = this.props.shutdown ? "--poweroff" : "--reboot";
142 if (!this.props.shutdown)
143 cockpit.hint("restart");
144
145 cockpit.spawn(["shutdown", arg, this.state.when, this.state.message], { superuser: "require", err: "message" })
146 .then(this.props.onClose || Dialogs.close)
147 .catch(e => this.setState({ error: e.toString() }));
148
149 event.preventDefault();
150 return false;
151 }
152
153 dateRangeValidator(date) {
154 if (this.state.startDate && date < this.state.startDate) {
155 return _("Cannot schedule event in the past");
156 }
157 return '';
158 }
159
160 render() {
161 const Dialogs = this.context;
162 const options = [
163 { value: "0", content: _("No delay") },
164 { decorator: "divider", key: "divider" },
165 { value: "1", content: _("1 minute") },
166 { value: "5", content: _("5 minutes") },
167 { value: "20", content: _("20 minutes") },
168 { value: "40", content: _("40 minutes") },
169 { value: "60", content: _("60 minutes") },
170 { decorator: "divider", key: "divider-2" },
171 { value: "x", content: _("Specific time") },
172 ];
173
174 return (
175 <Modal isOpen position="top" variant="medium"
176 onClose={this.props.onClose || Dialogs.close}
177 id="shutdown-dialog"
178 >
179 <ModalHeader title={this.props.shutdown ? _("Shut down") : _("Reboot")} />
180 <ModalBody>
181 <Form isHorizontal onSubmit={this.onSubmit}>
182 <FormGroup fieldId="message" label={_("Message to logged in users")}>
183 <TextArea id="message" resizeOrientation="vertical" value={this.state.message} onChange={(_, v) => this.setState({ message: v })} />
184 </FormGroup>
185 <FormGroup fieldId="delay" label={_("Delay")}>
186 <Flex className="shutdown-delay-group" alignItems={{ default: 'alignItemsCenter' }}>
187 <SimpleSelect
188 toggleProps={{ id: "delay", className: 'shutdown-select-delay' }}
189 options={options}
190 selected={this.state.selected}
191 isDisabled={!this.state.formFilled}
192 onSelect={s => this.setState({ selected: s }, this.calculate)} />
193 {this.state.selected === "x" && <>
194 <DatePicker aria-label={_("Pick date")}
195 buttonAriaLabel={_("Toggle date picker")}
196 className='shutdown-date-picker'
197 invalidFormatText=""
198 isDisabled={!this.state.formFilled}
199 locale={timeformat.dateFormatLang()}
200 weekStart={timeformat.firstDayOfWeek()}
201 onBlur={this.calculate}
202 onChange={(_, d, ds) => this.updateDate(d, ds)}
203 validators={[this.dateRangeValidator]}
204 value={this.state.date}
205 appendTo={() => document.body} />
206 <TimePicker time={this.state.time} is24Hour
207 className='shutdown-time-picker'
208 id="shutdown-time"
209 isDisabled={!this.state.formFilled}
210 invalidFormatErrorMessage=""
211 menuAppendTo={() => document.body}
212 onBlur={this.calculate}
213 onChange={(_, time, h, m) => this.updateTime(time, h, m) } />
214 </>}
215 </Flex>
216 <FormHelper fieldId="delay" helperTextInvalid={this.state.dateError} />
217 </FormGroup>
218 </Form>
219 {this.state.error && <Alert isInline variant='danger' title={this.state.error} />}
220 </ModalBody>
221 <ModalFooter>
222 <Button variant='danger' isDisabled={this.state.error || this.state.dateError} onClick={this.onSubmit}>{this.props.shutdown ? _("Shut down") : _("Reboot")}</Button>
223 <Button variant='link' onClick={this.props.onClose || Dialogs.close}>{_("Cancel")}</Button>
224 </ModalFooter>
225 </Modal>
226 );
227 }
228 }