Skip to content
This repository has been archived by the owner on Oct 4, 2021. It is now read-only.

Commit

Permalink
replace moment as time/date lib
Browse files Browse the repository at this point in the history
  • Loading branch information
proddybot committed Feb 1, 2021
1 parent 30b67f2 commit dd79ab0
Show file tree
Hide file tree
Showing 8 changed files with 6,204 additions and 3,912 deletions.
9,897 changes: 6,080 additions & 3,817 deletions interface/package-lock.json

Large diffs are not rendered by default.

35 changes: 17 additions & 18 deletions interface/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,31 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@types/jwt-decode": "^3.1.0",
"@types/lodash": "^4.14.165",
"@types/node": "^12.12.32",
"@types/react": "^16.9.56",
"@types/react-dom": "^16.9.9",
"@material-ui/core": "^4.11.3",
"@material-ui/icons": "^4.11.2",
"@types/lodash": "^4.14.168",
"@types/node": "^12.19.15",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-material-ui-form-validator": "^2.1.0",
"@types/react-router": "^5.1.8",
"@types/react-router-dom": "^5.1.6",
"compression-webpack-plugin": "^4.0.0",
"jwt-decode": "^3.1.1",
"jwt-decode": "^3.1.2",
"lodash": "^4.17.20",
"mime-types": "^2.1.27",
"moment": "^2.29.1",
"notistack": "^1.0.1",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"mime-types": "^2.1.28",
"notistack": "^1.0.3",
"parse-ms": "^2.1.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-dropzone": "^11.2.4",
"react-form-validator-core": "^1.0.0",
"react-material-ui-form-validator": "^2.1.1",
"react-form-validator-core": "^1.0.1",
"react-material-ui-form-validator": "^2.1.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.4",
"react-scripts": "4.0.1",
"sockette": "^2.0.6",
"typescript": "^4.0.2",
"typescript": "4.0.5",
"zlib": "^1.0.5"
},
"scripts": {
Expand All @@ -52,6 +51,6 @@
]
},
"devDependencies": {
"react-app-rewired": "^2.1.6"
"react-app-rewired": "^2.1.8"
}
}
23 changes: 0 additions & 23 deletions interface/src/features/ApplicationContext.tsx

This file was deleted.

37 changes: 18 additions & 19 deletions interface/src/ntp/NTPStatusForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { Component, Fragment } from 'react';
import moment from 'moment';

import { WithTheme, withTheme } from '@material-ui/core/styles';
import { Avatar, Divider, List, ListItem, ListItemAvatar, ListItemText, Button } from '@material-ui/core';
Expand All @@ -14,7 +13,7 @@ import RefreshIcon from '@material-ui/icons/Refresh';

import { RestFormProps, FormButton, HighlightAvatar } from '../components';
import { isNtpActive, ntpStatusHighlight, ntpStatus } from './NTPStatus';
import { formatIsoDateTime, formatLocalDateTime } from './TimeFormat';
import { formatDuration, formatDateTime, formatLocalDateTime } from './TimeFormat';
import { NTPStatus, Time } from './types';
import { redirectingAuthorizedFetch, withAuthenticatedContext, AuthenticatedContextProps } from '../authentication';
import { TIME_ENDPOINT } from '../api';
Expand All @@ -39,34 +38,34 @@ class NTPStatusForm extends Component<NTPStatusFormProps, NTPStatusFormState> {
}

updateLocalTime = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ localTime: event.target.value });
this.setState({
localTime: event.target.value
});
}

openSetTime = () => {
this.setState({ localTime: formatLocalDateTime(moment()), settingTime: true, });
this.setState({
localTime: formatLocalDateTime(new Date()),
settingTime: true
});
}

closeSetTime = () => {
this.setState({ settingTime: false });
this.setState({
settingTime: false
});
}

createAdjustedTime = (): Time => {
const currentLocalTime = moment(this.props.data.time_local);
const newLocalTime = moment(this.state.localTime);
newLocalTime.subtract(currentLocalTime.utcOffset())
newLocalTime.milliseconds(0);
newLocalTime.utc();
return {
time_utc: newLocalTime.format()
}
}
createTime = (): Time => ({
local_time: formatLocalDateTime(new Date(this.state.localTime))
});

configureTime = () => {
this.setState({ processing: true });
redirectingAuthorizedFetch(TIME_ENDPOINT,
{
method: 'POST',
body: JSON.stringify(this.createAdjustedTime()),
body: JSON.stringify(this.createTime()),
headers: {
'Content-Type': 'application/json'
}
Expand Down Expand Up @@ -153,7 +152,7 @@ class NTPStatusForm extends Component<NTPStatusFormProps, NTPStatusFormState> {
<AccessTimeIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Local Time" secondary={formatIsoDateTime(data.time_local)} />
<ListItemText primary="Local Time" secondary={formatDateTime(data.local_time)} />
</ListItem>
<Divider variant="inset" component="li" />
<ListItem>
Expand All @@ -162,7 +161,7 @@ class NTPStatusForm extends Component<NTPStatusFormProps, NTPStatusFormState> {
<SwapVerticalCircleIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary="UTC Time" secondary={formatIsoDateTime(data.time_utc)} />
<ListItemText primary="UTC Time" secondary={formatDateTime(data.utc_time)} />
</ListItem>
<Divider variant="inset" component="li" />
<ListItem>
Expand All @@ -171,7 +170,7 @@ class NTPStatusForm extends Component<NTPStatusFormProps, NTPStatusFormState> {
<AvTimerIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Uptime" secondary={moment.duration(data.uptime, 'seconds').humanize()} />
<ListItemText primary="Uptime" secondary={formatDuration(data.uptime)} />
</ListItem>
<Divider variant="inset" component="li" />
</List>
Expand Down
46 changes: 43 additions & 3 deletions interface/src/ntp/TimeFormat.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
import moment, { Moment } from 'moment';
import parseMilliseconds from 'parse-ms';

export const formatIsoDateTime = (isoDateString: string) => moment.parseZone(isoDateString).format('ll @ HH:mm:ss');
const LOCALE_FORMAT = new Intl.DateTimeFormat(
[...window.navigator.languages],
{
day: 'numeric',
month: 'short',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
}
);

export const formatLocalDateTime = (moment: Moment) => moment.format('YYYY-MM-DDTHH:mm');
export const formatDateTime = (dateTime: string) => {
return LOCALE_FORMAT.format(new Date(dateTime.substr(0, 19)));
}

export const formatLocalDateTime = (date: Date) => {
return new Date(date.getTime() - date.getTimezoneOffset() * 60000)
.toISOString()
.slice(0, -1)
.substr(0, 19);
}

export const formatDuration = (duration: number) => {
const { days, hours, minutes, seconds } = parseMilliseconds(duration * 1000);
var formatted = '';
if (days) {
formatted += pluralize(days, 'day');
}
if (formatted || hours) {
formatted += pluralize(hours, 'hour');
}
if (formatted || minutes) {
formatted += pluralize(minutes, 'minute');
}
if (formatted || seconds) {
formatted += pluralize(seconds, 'second');
}
return formatted;
}

const pluralize = (count: number, noun: string, suffix: string = 's') => ` ${count} ${noun}${count !== 1 ? suffix : ''} `;
8 changes: 4 additions & 4 deletions interface/src/ntp/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ export enum NTPSyncStatus {

export interface NTPStatus {
status: NTPSyncStatus;
time_utc: string;
time_local: string;
utc_time: string;
local_time: string;
server: string;
uptime: number;
}
Expand All @@ -19,5 +19,5 @@ export interface NTPSettings {
}

export interface Time {
time_utc: string;
}
local_time: string;
}
6 changes: 3 additions & 3 deletions lib/framework/NTPSettingsService.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ void NTPSettingsService::configureNTP() {

void NTPSettingsService::configureTime(AsyncWebServerRequest * request, JsonVariant & json) {
if (!sntp_enabled() && json.is<JsonObject>()) {
String timeUtc = json["time_utc"];
struct tm tm = {0};
char * s = strptime(timeUtc.c_str(), "%Y-%m-%dT%H:%M:%SZ", &tm);
struct tm tm = {0};
String timeLocal = json["local_time"];
char * s = strptime(timeLocal.c_str(), "%Y-%m-%dT%H:%M:%S", &tm);
if (s != nullptr) {
time_t time = mktime(&tm);
struct timeval now = {.tv_sec = time};
Expand Down
64 changes: 39 additions & 25 deletions lib/framework/NTPStatus.cpp
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
#include <NTPStatus.h>

NTPStatus::NTPStatus(AsyncWebServer * server, SecurityManager * securityManager) {
server->on(NTP_STATUS_SERVICE_PATH,
HTTP_GET,
securityManager->wrapRequest(std::bind(&NTPStatus::ntpStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED));
NTPStatus::NTPStatus(AsyncWebServer* server, SecurityManager* securityManager) {
server->on(NTP_STATUS_SERVICE_PATH,
HTTP_GET,
securityManager->wrapRequest(std::bind(&NTPStatus::ntpStatus, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
}

String toISOString(tm * time, bool incOffset) {
char time_string[25];
strftime(time_string, 25, incOffset ? "%FT%T%z" : "%FT%TZ", time);
return String(time_string);
/*
* Formats the time using the format provided.
*
* Uses a 25 byte buffer, large enough to fit an ISO time string with offset.
*/
String formatTime(tm* time, const char* format) {
char time_string[25];
strftime(time_string, 25, format, time);
return String(time_string);
}

void NTPStatus::ntpStatus(AsyncWebServerRequest * request) {
AsyncJsonResponse * response = new AsyncJsonResponse(false, MAX_NTP_STATUS_SIZE);
JsonObject root = response->getRoot();
String toUTCTimeString(tm* time) {
return formatTime(time, "%FT%TZ");
}

String toLocalTimeString(tm* time) {
return formatTime(time, "%FT%T");
}

void NTPStatus::ntpStatus(AsyncWebServerRequest* request) {
AsyncJsonResponse* response = new AsyncJsonResponse(false, MAX_NTP_STATUS_SIZE);
JsonObject root = response->getRoot();

// grab the current instant in unix seconds
time_t now = time(nullptr);
// grab the current instant in unix seconds
time_t now = time(nullptr);

// only provide enabled/disabled status for now
root["status"] = sntp_enabled() ? 1 : 0;
// only provide enabled/disabled status for now
root["status"] = sntp_enabled() ? 1 : 0;

// the current time in UTC
root["time_utc"] = toISOString(gmtime(&now), false);
// the current time in UTC
root["utc_time"] = toUTCTimeString(gmtime(&now));

// local time as ISO String with TZ
root["time_local"] = toISOString(localtime(&now), true);
// local time with offset
root["local_time"] = toLocalTimeString(localtime(&now));

// the sntp server name
root["server"] = sntp_getservername(0);
// the sntp server name
root["server"] = sntp_getservername(0);

// device uptime in seconds
root["uptime"] = uuid::get_uptime() / 1000;
// device uptime in seconds
root["uptime"] = millis() / 1000;

response->setLength();
request->send(response);
response->setLength();
request->send(response);
}

0 comments on commit dd79ab0

Please sign in to comment.