Handle error when site not returned

This commit is contained in:
abias 2023-05-14 19:49:55 -04:00
parent 025daaa582
commit 3996cdaae3
9 changed files with 190 additions and 157 deletions

View file

@ -16,7 +16,7 @@ import { getHttpBase, getHttpBaseInternal } from "../shared/env";
import { import {
ILemmyConfig, ILemmyConfig,
InitialFetchRequest, InitialFetchRequest,
IsoData, IsoDataOptionalSite,
} from "../shared/interfaces"; } from "../shared/interfaces";
import { routes } from "../shared/routes"; import { routes } from "../shared/routes";
import { import {
@ -78,6 +78,7 @@ server.get("/css/themes/:name", async (req, res) => {
res.contentType("text/css"); res.contentType("text/css");
const theme = req.params.name; const theme = req.params.name;
if (!theme.endsWith(".css")) { if (!theme.endsWith(".css")) {
res.statusCode = 400;
res.send("Theme must be a css file"); res.send("Theme must be a css file");
} }
@ -121,8 +122,6 @@ server.get("/*", async (req, res) => {
const getSiteForm: GetSite = { auth }; const getSiteForm: GetSite = { auth };
const promises: Promise<any>[] = [];
const headers = setForwardedHeaders(req.headers); const headers = setForwardedHeaders(req.headers);
const client = new LemmyHttp(getHttpBaseInternal(), headers); const client = new LemmyHttp(getHttpBaseInternal(), headers);
@ -131,6 +130,9 @@ server.get("/*", async (req, res) => {
// Get site data first // Get site data first
// This bypasses errors, so that the client can hit the error on its own, // This bypasses errors, so that the client can hit the error on its own,
// in order to remove the jwt on the browser. Necessary for wrong jwts // in order to remove the jwt on the browser. Necessary for wrong jwts
let site: GetSiteResponse | undefined = undefined;
let routeData: any[] = [];
try {
let try_site: any = await client.getSite(getSiteForm); let try_site: any = await client.getSite(getSiteForm);
if (try_site.error == "not_logged_in") { if (try_site.error == "not_logged_in") {
console.error( console.error(
@ -146,9 +148,10 @@ server.get("/*", async (req, res) => {
return; return;
} }
const site: GetSiteResponse = try_site; site = try_site;
initializeSite(site); initializeSite(site);
if (site) {
const initialFetchReq: InitialFetchRequest = { const initialFetchReq: InitialFetchRequest = {
client, client,
auth, auth,
@ -158,11 +161,14 @@ server.get("/*", async (req, res) => {
}; };
if (activeRoute?.fetchInitialData) { if (activeRoute?.fetchInitialData) {
promises.push(...activeRoute.fetchInitialData(initialFetchReq)); routeData = await Promise.all([
...activeRoute.fetchInitialData(initialFetchReq),
]);
}
}
} catch (error) {
routeData = [getErrorRouteData(error)];
} }
let routeData = await Promise.all(promises);
// let routeData = [{ error: "I am an error, hear me roar!" } as any];
// Redirect to the 404 if there's an API error // Redirect to the 404 if there's an API error
if (routeData[0] && routeData[0].error) { if (routeData[0] && routeData[0].error) {
@ -171,28 +177,14 @@ server.get("/*", async (req, res) => {
if (error === "instance_is_private") { if (error === "instance_is_private") {
return res.redirect(`/signup`); return res.redirect(`/signup`);
} else { } else {
const errorPageData: ErrorPageData = { type: "error" }; routeData = [getErrorRouteData(error, site)];
// Exact error should only be seen in a development environment. Users
// in production will get a more generic message.
if (NODE_ENV === "development") {
errorPageData.error = error;
}
const adminMatrixIds = site.admins
.map(({ person: { matrix_user_id } }) => matrix_user_id)
.filter(id => id) as string[];
if (adminMatrixIds.length > 0) {
errorPageData.adminMatrixIds = adminMatrixIds;
}
routeData = [errorPageData];
} }
} }
console.log("Route Data");
console.log(routeData); console.log(routeData);
const isoData: IsoData = { const isoData: IsoDataOptionalSite = {
path, path,
site_res: site, site_res: site,
routeData, routeData,
@ -204,91 +196,11 @@ server.get("/*", async (req, res) => {
</StaticRouter> </StaticRouter>
); );
const eruda = (
<>
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>
</>
);
const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
const root = renderToString(wrapper); const root = renderToString(wrapper);
const helmet = Helmet.renderStatic();
const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST }; res.send(await createSsrHtml(root, isoData));
const appleTouchIcon = site.site_view.site.icon
? `data:image/png;base64,${sharp(
await fetchIconPng(site.site_view.site.icon)
)
.resize(180, 180)
.extend({
bottom: 20,
top: 20,
left: 20,
right: 20,
background: "#222222",
})
.png()
.toBuffer()
.then(buf => buf.toString("base64"))}`
: favIconPngUrl;
res.send(`
<!DOCTYPE html>
<html ${helmet.htmlAttributes.toString()} lang="en">
<head>
<script>window.isoData = ${JSON.stringify(isoData)}</script>
<script>window.lemmyConfig = ${serialize(config)}</script>
<!-- A remote debugging utility for mobile -->
${erudaStr}
<!-- Custom injected script -->
${customHtmlHeader}
${helmet.title.toString()}
${helmet.meta.toString()}
<!-- Required meta tags -->
<meta name="Description" content="Lemmy">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link
id="favicon"
rel="shortcut icon"
type="image/x-icon"
href=${site.site_view.site.icon ?? favIconUrl}
/>
<!-- Web app manifest -->
<link rel="manifest" href="data:application/manifest+json;base64,${await generateManifestBase64(
site.site_view.site
)}">
<link rel="apple-touch-icon" href=${appleTouchIcon} />
<link rel="apple-touch-startup-image" href=${appleTouchIcon} />
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
<!-- Current theme and more -->
${helmet.link.toString()}
</head>
<body ${helmet.bodyAttributes.toString()}>
<noscript>
<div class="alert alert-danger rounded-0" role="alert">
<b>Javascript is disabled. Actions will not work.</b>
</div>
</noscript>
<div id='root'>${root}</div>
<script defer src='/static/js/client.js'></script>
</body>
</html>
`);
} catch (err) { } catch (err) {
// If an error is caught here, the error page couldn't even be rendered
console.error(err); console.error(err);
res.statusCode = 500; res.statusCode = 500;
return res.send(NODE_ENV === "development" ? err.message : "Server error"); return res.send(NODE_ENV === "development" ? err.message : "Server error");
@ -382,3 +294,116 @@ async function fetchIconPng(iconUrl: string) {
.then(res => res.blob()) .then(res => res.blob())
.then(blob => blob.arrayBuffer()); .then(blob => blob.arrayBuffer());
} }
function getErrorRouteData(error: string, site?: GetSiteResponse) {
const errorPageData: ErrorPageData = { type: "error" };
// Exact error should only be seen in a development environment. Users
// in production will get a more generic message.
if (NODE_ENV === "development") {
errorPageData.error = error;
}
const adminMatrixIds = site?.admins
.map(({ person: { matrix_user_id } }) => matrix_user_id)
.filter(id => id) as string[] | undefined;
if (adminMatrixIds && adminMatrixIds.length > 0) {
errorPageData.adminMatrixIds = adminMatrixIds;
}
return [errorPageData];
}
async function createSsrHtml(root: string, isoData: IsoDataOptionalSite) {
const site = isoData.site_res;
const appleTouchIcon = site?.site_view.site.icon
? `data:image/png;base64,${sharp(
await fetchIconPng(site.site_view.site.icon)
)
.resize(180, 180)
.extend({
bottom: 20,
top: 20,
left: 20,
right: 20,
background: "#222222",
})
.png()
.toBuffer()
.then(buf => buf.toString("base64"))}`
: favIconPngUrl;
const eruda = (
<>
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>
</>
);
const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
const helmet = Helmet.renderStatic();
const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
return `
<!DOCTYPE html>
<html ${helmet.htmlAttributes.toString()} lang="en">
<head>
<script>window.isoData = ${JSON.stringify(isoData)}</script>
<script>window.lemmyConfig = ${serialize(config)}</script>
<!-- A remote debugging utility for mobile -->
${erudaStr}
<!-- Custom injected script -->
${customHtmlHeader}
${helmet.title.toString()}
${helmet.meta.toString()}
<!-- Required meta tags -->
<meta name="Description" content="Lemmy">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link
id="favicon"
rel="shortcut icon"
type="image/x-icon"
href=${site?.site_view.site.icon ?? favIconUrl}
/>
<!-- Web app manifest -->
${
site &&
`<link
rel="manifest"
href={${`data:application/manifest+json;base64,${await generateManifestBase64(
site.site_view.site
)}`}}
/>`
}
<link rel="apple-touch-icon" href=${appleTouchIcon} />
<link rel="apple-touch-startup-image" href=${appleTouchIcon} />
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
<!-- Current theme and more -->
${helmet.link.toString()}
</head>
<body ${helmet.bodyAttributes.toString()}>
<noscript>
<div class="alert alert-danger rounded-0" role="alert">
<b>Javascript is disabled. Actions will not work.</b>
</div>
</noscript>
<div id='root'>${root}</div>
<script defer src='/static/js/client.js'></script>
</body>
</html>
`;
}

View file

@ -1,6 +1,7 @@
import { Component } from "inferno"; import { Component } from "inferno";
import { Provider } from "inferno-i18next-dess"; import { Provider } from "inferno-i18next-dess";
import { Route, Switch } from "inferno-router"; import { Route, Switch } from "inferno-router";
import { IsoDataOptionalSite } from "shared/interfaces";
import { i18n } from "../../i18next"; import { i18n } from "../../i18next";
import { routes } from "../../routes"; import { routes } from "../../routes";
import { isAuthPath, setIsoData } from "../../utils"; import { isAuthPath, setIsoData } from "../../utils";
@ -13,19 +14,22 @@ import "./styles.scss";
import { Theme } from "./theme"; import { Theme } from "./theme";
export class App extends Component<any, any> { export class App extends Component<any, any> {
private isoData = setIsoData(this.context); private isoData: IsoDataOptionalSite = setIsoData(this.context);
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
} }
render() { render() {
const siteRes = this.isoData.site_res; const siteRes = this.isoData.site_res;
const siteView = siteRes.site_view; const siteView = siteRes?.site_view;
console.log(`Path: ${this.isoData.path}`);
return ( return (
<> <>
<Provider i18next={i18n}> <Provider i18next={i18n}>
<div id="app"> <div id="app">
{siteView && (
<Theme defaultTheme={siteView.local_site.default_theme} /> <Theme defaultTheme={siteView.local_site.default_theme} />
)}
<Navbar siteRes={siteRes} /> <Navbar siteRes={siteRes} />
<div className="mt-4 p-0 fl-1"> <div className="mt-4 p-0 fl-1">
<Switch> <Switch>

View file

@ -1,9 +1,10 @@
import { Component } from "inferno"; import { Component } from "inferno";
import { Link } from "inferno-router"; import { Link } from "inferno-router";
import { IsoDataOptionalSite } from "shared/interfaces";
import { ErrorPageData, setIsoData } from "../../utils"; import { ErrorPageData, setIsoData } from "../../utils";
export class ErrorPage extends Component<any, any> { export class ErrorPage extends Component<any, any> {
private isoData = setIsoData(this.context); private isoData: IsoDataOptionalSite = setIsoData(this.context);
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
@ -28,8 +29,8 @@ export class ErrorPage extends Component<any, any> {
<div> <div>
<div> <div>
If you would like to reach out to one of{" "} If you would like to reach out to one of{" "}
{this.isoData.site_res.site_view.site.name}&apos;s admins for {this.isoData.site_res?.site_view.site.name ?? "this instance"}
support, try the following Matrix addresses: &apos;s admins for support, try the following Matrix addresses:
</div> </div>
<ul> <ul>
{errorPageData.adminMatrixIds.map(matrixId => ( {errorPageData.adminMatrixIds.map(matrixId => (

View file

@ -6,7 +6,7 @@ import { docsUrl, joinLemmyUrl, repoUrl } from "../../utils";
import { VERSION } from "../../version"; import { VERSION } from "../../version";
interface FooterProps { interface FooterProps {
site: GetSiteResponse; site?: GetSiteResponse;
} }
export class Footer extends Component<FooterProps, any> { export class Footer extends Component<FooterProps, any> {
@ -19,27 +19,27 @@ export class Footer extends Component<FooterProps, any> {
<nav className="container-lg navbar navbar-expand-md navbar-light navbar-bg p-3"> <nav className="container-lg navbar navbar-expand-md navbar-light navbar-bg p-3">
<div className="navbar-collapse"> <div className="navbar-collapse">
<ul className="navbar-nav ml-auto"> <ul className="navbar-nav ml-auto">
{this.props.site.version !== VERSION && ( {this.props.site?.version !== VERSION && (
<li className="nav-item"> <li className="nav-item">
<span className="nav-link">UI: {VERSION}</span> <span className="nav-link">UI: {VERSION}</span>
</li> </li>
)} )}
<li className="nav-item"> <li className="nav-item">
<span className="nav-link">BE: {this.props.site.version}</span> <span className="nav-link">BE: {this.props.site?.version}</span>
</li> </li>
<li className="nav-item"> <li className="nav-item">
<NavLink className="nav-link" to="/modlog"> <NavLink className="nav-link" to="/modlog">
{i18n.t("modlog")} {i18n.t("modlog")}
</NavLink> </NavLink>
</li> </li>
{this.props.site.site_view.local_site.legal_information && ( {this.props.site?.site_view.local_site.legal_information && (
<li className="nav-item"> <li className="nav-item">
<NavLink className="nav-link" to="/legal"> <NavLink className="nav-link" to="/legal">
{i18n.t("legal_information")} {i18n.t("legal_information")}
</NavLink> </NavLink>
</li> </li>
)} )}
{this.props.site.site_view.local_site.federation_enabled && ( {this.props.site?.site_view.local_site.federation_enabled && (
<li className="nav-item"> <li className="nav-item">
<NavLink className="nav-link" to="/instances"> <NavLink className="nav-link" to="/instances">
{i18n.t("instances")} {i18n.t("instances")}

View file

@ -35,7 +35,7 @@ import { Icon } from "../common/icon";
import { PictrsImage } from "../common/pictrs-image"; import { PictrsImage } from "../common/pictrs-image";
interface NavbarProps { interface NavbarProps {
siteRes: GetSiteResponse; siteRes?: GetSiteResponse;
} }
interface NavbarState { interface NavbarState {
@ -119,7 +119,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
// TODO class active corresponding to current page // TODO class active corresponding to current page
navbar() { navbar() {
let siteView = this.props.siteRes.site_view; let siteView = this.props.siteRes?.site_view;
let person = UserService.Instance.myUserInfo?.local_user_view.person; let person = UserService.Instance.myUserInfo?.local_user_view.person;
return ( return (
<nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3"> <nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3">
@ -127,13 +127,13 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
<NavLink <NavLink
to="/" to="/"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)} onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={siteView.site.description ?? siteView.site.name} title={siteView?.site.description ?? siteView?.site.name ?? "Lemmy"}
className="d-flex align-items-center navbar-brand mr-md-3" className="d-flex align-items-center navbar-brand mr-md-3"
> >
{siteView.site.icon && showAvatars() && ( {siteView?.site.icon && showAvatars() && (
<PictrsImage src={siteView.site.icon} icon /> <PictrsImage src={siteView.site.icon} icon />
)} )}
{siteView.site.name} {siteView?.site.name ?? "Lemmy"}
</NavLink> </NavLink>
{UserService.Instance.myUserInfo && ( {UserService.Instance.myUserInfo && (
<> <>
@ -245,7 +245,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
{i18n.t("create_post")} {i18n.t("create_post")}
</NavLink> </NavLink>
</li> </li>
{canCreateCommunity(this.props.siteRes) && ( {this.props.siteRes && canCreateCommunity(this.props.siteRes) && (
<li className="nav-item"> <li className="nav-item">
<NavLink <NavLink
to="/create_community" to="/create_community"

View file

@ -13,8 +13,9 @@ class ErrorGuard extends Component<any, any> {
const errorPageData = this.isoData.routeData[0] as const errorPageData = this.isoData.routeData[0] as
| ErrorPageData | ErrorPageData
| undefined; | undefined;
const siteRes = this.isoData.site_res;
if (errorPageData?.type === "error") { if (errorPageData?.type === "error" || !siteRes) {
return <ErrorPage />; return <ErrorPage />;
} else { } else {
return this.props.children; return this.props.children;

View file

@ -1231,9 +1231,6 @@ export class Settings extends Component<any, SettingsState> {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
return; return;
} else if (op == UserOperation.SaveUserSettings) { } else if (op == UserOperation.SaveUserSettings) {
let data = wsJsonToRes<LoginResponse>(msg);
UserService.Instance.login(data);
location.reload();
this.setState({ saveUserSettingsLoading: false }); this.setState({ saveUserSettingsLoading: false });
toast(i18n.t("saved")); toast(i18n.t("saved"));
window.scrollTo(0, 0); window.scrollTo(0, 0);

View file

@ -10,6 +10,9 @@ export interface IsoData {
site_res: GetSiteResponse; site_res: GetSiteResponse;
} }
export type IsoDataOptionalSite = Partial<IsoData> &
Pick<IsoData, Exclude<keyof IsoData, "site_res">>;
export interface ILemmyConfig { export interface ILemmyConfig {
wsHost?: string; wsHost?: string;
} }

View file

@ -1399,10 +1399,12 @@ export function personSelectName({
return local ? pName : `${hostname(actor_id)}/${pName}`; return local ? pName : `${hostname(actor_id)}/${pName}`;
} }
export function initializeSite(site: GetSiteResponse) { export function initializeSite(site?: GetSiteResponse) {
UserService.Instance.myUserInfo = site.my_user; UserService.Instance.myUserInfo = site?.my_user;
i18n.changeLanguage(getLanguages()[0]); i18n.changeLanguage(getLanguages()[0]);
if (site) {
setupEmojiDataModel(site.custom_emojis); setupEmojiDataModel(site.custom_emojis);
}
setupMarkdown(); setupMarkdown();
} }