Merge pull request #1024 from SleeplessOne1917/nicer-error-hnadling

Nicer error handling
This commit is contained in:
SleeplessOne1917 2023-05-23 23:09:41 +00:00 committed by GitHub
commit a3c37d37a8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 623 additions and 465 deletions

View file

@ -2,6 +2,6 @@ generate_translations.js
webpack.config.js
src/api_tests
**/*.png
**/*.svg
**/*.css
**/*.scss
**/*.svg

View file

@ -61,6 +61,7 @@
"isomorphic-cookie": "^1.2.4",
"jwt-decode": "^3.1.2",
"lemmy-js-client": "0.17.2-rc.17",
"lodash": "^4.17.21",
"markdown-it": "^13.0.1",
"markdown-it-container": "^3.0.0",
"markdown-it-emoji": "^2.0.2",
@ -77,6 +78,7 @@
"sass": "^1.62.1",
"sass-loader": "^13.2.2",
"serialize-javascript": "^6.0.1",
"service-worker-webpack": "^1.0.0",
"sharp": "^0.32.1",
"tippy.js": "^6.3.7",
"toastify-js": "^1.12.0",
@ -112,7 +114,6 @@
"prettier-plugin-organize-imports": "^3.2.2",
"prettier-plugin-packagejson": "^2.4.3",
"rimraf": "^5.0.0",
"service-worker-webpack": "^1.0.0",
"sortpack": "^2.3.4",
"style-loader": "^3.3.2",
"terser": "^5.17.3",

View file

@ -16,10 +16,16 @@ import { getHttpBase, getHttpBaseInternal } from "../shared/env";
import {
ILemmyConfig,
InitialFetchRequest,
IsoData,
IsoDataOptionalSite,
} from "../shared/interfaces";
import { routes } from "../shared/routes";
import { favIconPngUrl, favIconUrl, initializeSite } from "../shared/utils";
import {
ErrorPageData,
favIconPngUrl,
favIconUrl,
initializeSite,
isAuthPath,
} from "../shared/utils";
const server = express();
const [hostname, port] = process.env["LEMMY_UI_HOST"]
@ -70,6 +76,7 @@ server.get("/css/themes/:name", async (req, res) => {
res.contentType("text/css");
const theme = req.params.name;
if (!theme.endsWith(".css")) {
res.statusCode = 400;
res.send("Theme must be a css file");
}
@ -109,19 +116,22 @@ server.get("/css/themelist", async (_req, res) => {
server.get("/*", async (req, res) => {
try {
const activeRoute = routes.find(route => matchPath(req.path, route));
const context = {} as any;
let auth: string | undefined = IsomorphicCookie.load("jwt", req);
const getSiteForm: GetSite = { auth };
const promises: Promise<any>[] = [];
const headers = setForwardedHeaders(req.headers);
const client = new LemmyHttp(getHttpBaseInternal(), headers);
const { path, url, query } = req;
// Get site data first
// 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
let site: GetSiteResponse | undefined = undefined;
let routeData: any[] = [];
let errorPageData: ErrorPageData | undefined;
try {
let try_site: any = await client.getSite(getSiteForm);
if (try_site.error == "not_logged_in") {
console.error(
@ -131,22 +141,33 @@ server.get("/*", async (req, res) => {
auth = undefined;
try_site = await client.getSite(getSiteForm);
}
const site: GetSiteResponse = try_site;
if (!auth && isAuthPath(path)) {
res.redirect("/login");
return;
}
site = try_site;
initializeSite(site);
if (site) {
const initialFetchReq: InitialFetchRequest = {
client,
auth,
path: req.path,
query: req.query,
path,
query,
site,
};
if (activeRoute?.fetchInitialData) {
promises.push(...activeRoute.fetchInitialData(initialFetchReq));
routeData = await Promise.all([
...activeRoute.fetchInitialData(initialFetchReq),
]);
}
}
} catch (error) {
errorPageData = getErrorPageData(error, site);
}
const routeData = await Promise.all(promises);
// Redirect to the 404 if there's an API error
if (routeData[0] && routeData[0].error) {
@ -155,112 +176,33 @@ server.get("/*", async (req, res) => {
if (error === "instance_is_private") {
return res.redirect(`/signup`);
} else {
return res.send(`404: ${removeAuthParam(error)}`);
errorPageData = getErrorPageData(error, site);
}
}
const isoData: IsoData = {
path: req.path,
const isoData: IsoDataOptionalSite = {
path,
site_res: site,
routeData,
errorPageData,
};
const wrapper = (
<StaticRouter location={req.url} context={isoData}>
<StaticRouter location={url} context={isoData}>
<App />
</StaticRouter>
);
if (context.url) {
return res.redirect(context.url);
}
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 helmet = Helmet.renderStatic();
const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
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>
`);
res.send(await createSsrHtml(root, isoData));
} catch (err) {
// If an error is caught here, the error page couldn't even be rendered
console.error(err);
return res.send(`404: ${removeAuthParam(err)}`);
res.statusCode = 500;
return res.send(
process.env.NODE_ENV === "development" ? err.message : "Server error"
);
}
});
@ -292,16 +234,6 @@ process.on("SIGINT", () => {
process.exit(0);
});
function removeAuthParam(err: any): string {
return removeParam(err.toString(), "auth");
}
function removeParam(url: string, parameter: string): string {
return url
.replace(new RegExp("[?&]" + parameter + "=[^&#]*(#.*)?$"), "$1")
.replace(new RegExp("([?&])" + parameter + "=[^&]*&"), "$1");
}
const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
const defaultLogoPathDirectory = path.join(
process.cwd(),
@ -361,3 +293,114 @@ async function fetchIconPng(iconUrl: string) {
.then(res => res.blob())
.then(blob => blob.arrayBuffer());
}
function getErrorPageData(error: Error, site?: GetSiteResponse) {
const errorPageData: ErrorPageData = {};
if (site) {
errorPageData.error = error.message;
}
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,36 +1,57 @@
import { Component } from "inferno";
import { Provider } from "inferno-i18next-dess";
import { Route, Switch } from "inferno-router";
import { IsoDataOptionalSite } from "shared/interfaces";
import { i18n } from "../../i18next";
import { routes } from "../../routes";
import { setIsoData } from "../../utils";
import { isAuthPath, setIsoData } from "../../utils";
import AuthGuard from "../common/auth-guard";
import ErrorGuard from "../common/error-guard";
import { ErrorPage } from "./error-page";
import { Footer } from "./footer";
import { Navbar } from "./navbar";
import { NoMatch } from "./no-match";
import "./styles.scss";
import { Theme } from "./theme";
export class App extends Component<any, any> {
private isoData = setIsoData(this.context);
private isoData: IsoDataOptionalSite = setIsoData(this.context);
constructor(props: any, context: any) {
super(props, context);
}
render() {
let siteRes = this.isoData.site_res;
let siteView = siteRes.site_view;
const siteRes = this.isoData.site_res;
const siteView = siteRes?.site_view;
return (
<>
<Provider i18next={i18n}>
<div id="app">
{siteView && (
<Theme defaultTheme={siteView.local_site.default_theme} />
)}
<Navbar siteRes={siteRes} />
<div className="mt-4 p-0 fl-1">
<Switch>
{routes.map(({ path, component }) => (
<Route key={path} path={path} exact component={component} />
{routes.map(({ path, component: RouteComponent }) => (
<Route
key={path}
path={path}
exact
component={routeProps => (
<ErrorGuard>
{RouteComponent &&
(isAuthPath(path ?? "") ? (
<AuthGuard>
<RouteComponent {...routeProps} />
</AuthGuard>
) : (
<RouteComponent {...routeProps} />
))}
<Route component={NoMatch} />
</ErrorGuard>
)}
/>
))}
<Route component={ErrorPage} />
</Switch>
</div>
<Footer site={siteRes} />

View file

@ -0,0 +1,69 @@
import { Component } from "inferno";
import { T } from "inferno-i18next-dess";
import { Link } from "inferno-router";
import { i18n } from "../../i18next";
import { IsoDataOptionalSite } from "../../interfaces";
import { setIsoData } from "../../utils";
export class ErrorPage extends Component<any, any> {
private isoData: IsoDataOptionalSite = setIsoData(this.context);
constructor(props: any, context: any) {
super(props, context);
}
render() {
const { errorPageData } = this.isoData;
return (
<div className="container-lg text-center">
<h1>
{errorPageData
? i18n.t("error_page_title")
: i18n.t("not_found_page_title")}
</h1>
{errorPageData ? (
<T i18nKey="error_page_paragraph" className="p-4" parent="p">
#<a href="https://lemmy.ml/c/lemmy_support">#</a>#
<a href="https://matrix.to/#/#lemmy-space:matrix.org">#</a>#
</T>
) : (
<p>{i18n.t("not_found_page_message")}</p>
)}
{!errorPageData && (
<Link to="/" replace>
{i18n.t("not_found_return_home_button")}
</Link>
)}
{errorPageData?.adminMatrixIds &&
errorPageData.adminMatrixIds.length > 0 && (
<>
<div>
{i18n.t("error_page_admin_matrix", {
instance:
this.isoData.site_res?.site_view.site.name ??
"this instance",
})}
</div>
<ul className="mx-auto mt-2" style={{ width: "fit-content" }}>
{errorPageData.adminMatrixIds.map(matrixId => (
<li key={matrixId} className="text-info">
{matrixId}
</li>
))}
</ul>
</>
)}
{errorPageData?.error && (
<T
i18nKey="error_code_message"
parent="p"
interpolation={{ error: errorPageData.error }}
>
#<strong className="text-danger">#</strong>#
</T>
)}
</div>
);
}
}

View file

@ -6,7 +6,7 @@ import { docsUrl, joinLemmyUrl, repoUrl } from "../../utils";
import { VERSION } from "../../version";
interface FooterProps {
site: GetSiteResponse;
site?: GetSiteResponse;
}
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">
<div className="navbar-collapse">
<ul className="navbar-nav ml-auto">
{this.props.site.version !== VERSION && (
{this.props.site?.version !== VERSION && (
<li className="nav-item">
<span className="nav-link">UI: {VERSION}</span>
</li>
)}
<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 className="nav-item">
<NavLink className="nav-link" to="/modlog">
{i18n.t("modlog")}
</NavLink>
</li>
{this.props.site.site_view.local_site.legal_information && (
{this.props.site?.site_view.local_site.legal_information && (
<li className="nav-item">
<NavLink className="nav-link" to="/legal">
{i18n.t("legal_information")}
</NavLink>
</li>
)}
{this.props.site.site_view.local_site.federation_enabled && (
{this.props.site?.site_view.local_site.federation_enabled && (
<li className="nav-item">
<NavLink className="nav-link" to="/instances">
{i18n.t("instances")}

View file

@ -1,4 +1,4 @@
import { Component, createRef, linkEvent } from "inferno";
import { Component, linkEvent } from "inferno";
import { NavLink } from "inferno-router";
import {
CommentResponse,
@ -35,26 +35,18 @@ import { Icon } from "../common/icon";
import { PictrsImage } from "../common/pictrs-image";
interface NavbarProps {
siteRes: GetSiteResponse;
siteRes?: GetSiteResponse;
}
interface NavbarState {
expanded: boolean;
unreadInboxCount: number;
unreadReportCount: number;
unreadApplicationCount: number;
showDropdown: boolean;
onSiteBanner?(url: string): any;
}
function handleCollapseClick(i: Navbar) {
if (i.collapseButtonRef.current?.ariaExpanded === "true") {
i.collapseButtonRef.current?.click();
}
}
function handleLogOut() {
UserService.Instance.logout();
}
export class Navbar extends Component<NavbarProps, NavbarState> {
private wsSub: Subscription;
private userSub: Subscription;
@ -65,9 +57,10 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
unreadInboxCount: 0,
unreadReportCount: 0,
unreadApplicationCount: 0,
expanded: false,
showDropdown: false,
};
subscription: any;
collapseButtonRef = createRef<HTMLButtonElement>();
constructor(props: any, context: any) {
super(props, context);
@ -120,34 +113,40 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
this.unreadApplicationCountSub.unsubscribe();
}
// TODO class active corresponding to current page
render() {
const siteView = this.props.siteRes.site_view;
const person = UserService.Instance.myUserInfo?.local_user_view.person;
return this.navbar();
}
// TODO class active corresponding to current page
navbar() {
let siteView = this.props.siteRes?.site_view;
let person = UserService.Instance.myUserInfo?.local_user_view.person;
return (
<nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3 container-lg">
<nav className="navbar navbar-expand-md navbar-light shadow-sm p-0 px-3">
<div className="container-lg">
<NavLink
to="/"
title={siteView.site.description ?? siteView.site.name}
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={siteView?.site.description ?? siteView?.site.name ?? "Lemmy"}
className="d-flex align-items-center navbar-brand mr-md-3"
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{siteView.site.icon && showAvatars() && (
{siteView?.site.icon && showAvatars() && (
<PictrsImage src={siteView.site.icon} icon />
)}
{siteView.site.name}
{siteView?.site.name ?? "Lemmy"}
</NavLink>
{person && (
<ul className="navbar-nav d-flex flex-row ml-auto d-md-none">
{UserService.Instance.myUserInfo && (
<>
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<NavLink
to="/inbox"
className="p-1 nav-link border-0"
className="p-1 navbar-toggler nav-link border-0"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_messages", {
count: Number(this.state.unreadInboxCount),
formattedCount: numToSI(this.state.unreadInboxCount),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="bell" />
{this.state.unreadInboxCount > 0 && (
@ -157,16 +156,18 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
</ul>
{this.moderatesSomething && (
<ul className="navbar-nav ml-1">
<li className="nav-item">
<NavLink
to="/reports"
className="p-1 nav-link border-0"
className="p-1 navbar-toggler nav-link border-0"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_reports", {
count: Number(this.state.unreadReportCount),
formattedCount: numToSI(this.state.unreadReportCount),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="shield" />
{this.state.unreadReportCount > 0 && (
@ -176,17 +177,21 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
</ul>
)}
{amAdmin() && (
<ul className="navbar-nav ml-1">
<li className="nav-item">
<NavLink
to="/registration_applications"
className="p-1 nav-link border-0"
className="p-1 navbar-toggler nav-link border-0"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_registration_applications", {
count: Number(this.state.unreadApplicationCount),
formattedCount: numToSI(this.state.unreadApplicationCount),
formattedCount: numToSI(
this.state.unreadApplicationCount
),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="clipboard" />
{this.state.unreadApplicationCount > 0 && (
@ -196,30 +201,29 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
)}
</ul>
)}
</>
)}
<button
className="navbar-toggler border-0 p-1"
type="button"
aria-label="menu"
onClick={linkEvent(this, this.handleToggleExpandNavbar)}
data-tippy-content={i18n.t("expand_here")}
data-bs-toggle="collapse"
data-bs-target="#navbarDropdown"
aria-controls="navbarDropdown"
aria-expanded="false"
ref={this.collapseButtonRef}
>
<Icon icon="menu" />
</button>
<div className="collapse navbar-collapse my-2" id="navbarDropdown">
<ul className="mr-auto navbar-nav">
<div
className={`${!this.state.expanded && "collapse"} navbar-collapse`}
>
<ul className="navbar-nav my-2 mr-auto">
<li className="nav-item">
<NavLink
to="/communities"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("communities")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{i18n.t("communities")}
</NavLink>
@ -235,19 +239,19 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
state: { prevPath: this.currentLocation },
}}
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("create_post")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{i18n.t("create_post")}
</NavLink>
</li>
{canCreateCommunity(this.props.siteRes) && (
{this.props.siteRes && canCreateCommunity(this.props.siteRes) && (
<li className="nav-item">
<NavLink
to="/create_community"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("create_community")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{i18n.t("create_community")}
</NavLink>
@ -263,44 +267,47 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
</a>
</li>
</ul>
<ul className="navbar-nav">
{!this.context.router.history.location.pathname.match(
/^\/search/
) && (
<li className="nav-item">
<NavLink
to="/search"
className="nav-link"
title={i18n.t("search")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="search" />
</NavLink>
</li>
)}
<ul className="navbar-nav my-2">
{amAdmin() && (
<li className="nav-item">
<NavLink
to="/admin"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("admin_settings")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="settings" />
</NavLink>
</li>
)}
{person ? (
</ul>
{!this.context.router.history.location.pathname.match(
/^\/search/
) && (
<ul className="navbar-nav">
<li className="nav-item">
<NavLink
to="/search"
className="nav-link"
title={i18n.t("search")}
>
<Icon icon="search" />
</NavLink>
</li>
</ul>
)}
{UserService.Instance.myUserInfo ? (
<>
<ul className="navbar-nav my-2">
<li className="nav-item">
<NavLink
className="nav-link"
to="/inbox"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_messages", {
count: Number(this.state.unreadInboxCount),
formattedCount: numToSI(this.state.unreadInboxCount),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="bell" />
{this.state.unreadInboxCount > 0 && (
@ -310,16 +317,18 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
</ul>
{this.moderatesSomething && (
<ul className="navbar-nav my-2">
<li className="nav-item">
<NavLink
className="nav-link"
to="/reports"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_reports", {
count: Number(this.state.unreadReportCount),
formattedCount: numToSI(this.state.unreadReportCount),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="shield" />
{this.state.unreadReportCount > 0 && (
@ -329,19 +338,21 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
</ul>
)}
{amAdmin() && (
<ul className="navbar-nav my-2">
<li className="nav-item">
<NavLink
to="/registration_applications"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("unread_registration_applications", {
count: Number(this.state.unreadApplicationCount),
formattedCount: numToSI(
this.state.unreadApplicationCount
),
})}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="clipboard" />
{this.state.unreadApplicationCount > 0 && (
@ -351,41 +362,48 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
)}
</NavLink>
</li>
</ul>
)}
{person && (
<div className="dropdown">
<ul className="navbar-nav">
<li className="nav-item dropdown">
<button
className="btn dropdown-toggle"
className="nav-link btn btn-link dropdown-toggle"
onClick={linkEvent(this, this.handleToggleDropdown)}
id="navbarDropdown"
role="button"
aria-expanded="false"
data-bs-toggle="dropdown"
>
<span>
{showAvatars() && person.avatar && (
<PictrsImage src={person.avatar} icon />
)}
{person.display_name ?? person.name}
</span>
</button>
<ul
className="dropdown-menu"
style={{ "min-width": "fit-content" }}
{this.state.showDropdown && (
<div
className="dropdown-content"
onMouseLeave={linkEvent(
this,
this.handleToggleDropdown
)}
>
<li>
<li className="nav-item">
<NavLink
to={`/u/${person.name}`}
className="dropdown-item px-2"
className="nav-link"
title={i18n.t("profile")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="user" classes="mr-1" />
{i18n.t("profile")}
</NavLink>
</li>
<li>
<li className="nav-item">
<NavLink
to="/settings"
className="dropdown-item px-2"
className="nav-link"
title={i18n.t("settings")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
<Icon icon="settings" classes="mr-1" />
{i18n.t("settings")}
@ -394,27 +412,30 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
<li>
<hr className="dropdown-divider" />
</li>
<li>
<li className="nav-item">
<button
className="dropdown-item btn btn-link px-2"
onClick={handleLogOut}
className="nav-link btn btn-link"
onClick={linkEvent(this, this.handleLogoutClick)}
title="test"
>
<Icon icon="log-out" classes="mr-1" />
{i18n.t("logout")}
</button>
</li>
</ul>
</div>
)}
</li>
</ul>
)}
</>
) : (
<>
<ul className="navbar-nav my-2">
<li className="nav-item">
<NavLink
to="/login"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("login")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{i18n.t("login")}
</NavLink>
@ -423,15 +444,15 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
<NavLink
to="/signup"
className="nav-link"
onMouseUp={linkEvent(this, this.handleHideExpandNavbar)}
title={i18n.t("sign_up")}
onMouseUp={linkEvent(this, handleCollapseClick)}
>
{i18n.t("sign_up")}
</NavLink>
</li>
</>
)}
</ul>
)}
</div>
</div>
</nav>
);
@ -443,6 +464,23 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
return amAdmin() || moderatesS;
}
handleToggleExpandNavbar(i: Navbar) {
i.setState({ expanded: !i.state.expanded });
}
handleHideExpandNavbar(i: Navbar) {
i.setState({ expanded: false, showDropdown: false });
}
handleLogoutClick(i: Navbar) {
i.setState({ showDropdown: false, expanded: false });
UserService.Instance.logout();
}
handleToggleDropdown(i: Navbar) {
i.setState({ showDropdown: !i.state.showDropdown });
}
parseMessage(msg: any) {
let op = wsUserOp(msg);
console.log(msg);

View file

@ -1,26 +0,0 @@
import { NoOptionI18nKeys } from "i18next";
import { Component } from "inferno";
import { i18n } from "../../i18next";
export class NoMatch extends Component<any, any> {
private errCode = new URLSearchParams(this.props.location.search).get(
"err"
) as NoOptionI18nKeys;
constructor(props: any, context: any) {
super(props, context);
}
render() {
return (
<div className="container-lg">
<h1>404</h1>
{this.errCode && (
<h3>
{i18n.t("code")}: {i18n.t(this.errCode)}
</h3>
)}
</div>
);
}
}

View file

@ -0,0 +1,13 @@
import { InfernoNode } from "inferno";
import { Redirect } from "inferno-router";
import { UserService } from "../../services";
function AuthGuard(props: { children?: InfernoNode }) {
if (!UserService.Instance.myUserInfo) {
return <Redirect to="/login" />;
} else {
return props.children;
}
}
export default AuthGuard;

View file

@ -0,0 +1,24 @@
import { Component } from "inferno";
import { setIsoData } from "../../utils";
import { ErrorPage } from "../app/error-page";
class ErrorGuard extends Component<any, any> {
private isoData = setIsoData(this.context);
constructor(props: any, context: any) {
super(props, context);
}
render() {
const errorPageData = this.isoData.errorPageData;
const siteRes = this.isoData.site_res;
if (errorPageData || !siteRes) {
return <ErrorPage />;
} else {
return this.props.children;
}
}
}
export default ErrorGuard;

View file

@ -1,9 +1,7 @@
import { Component } from "inferno";
import { Redirect } from "inferno-router";
import { CommunityView, GetSiteResponse } from "lemmy-js-client";
import { Subscription } from "rxjs";
import { i18n } from "../../i18next";
import { UserService } from "../../services/UserService";
import {
enableNsfw,
isBrowser,
@ -50,7 +48,6 @@ export class CreateCommunity extends Component<any, CreateCommunityState> {
render() {
return (
<div className="container-lg">
{!UserService.Instance.myUserInfo && <Redirect to="/login" />}
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}

View file

@ -111,11 +111,6 @@ export class Inbox extends Component<any, InboxState> {
this.handleSortChange = this.handleSortChange.bind(this);
this.handlePageChange = this.handlePageChange.bind(this);
if (!UserService.Instance.myUserInfo && isBrowser()) {
toast(i18n.t("not_logged_in"), "danger");
this.context.router.history.push(`/login`);
}
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);

View file

@ -59,11 +59,6 @@ export class RegistrationApplications extends Component<
this.handlePageChange = this.handlePageChange.bind(this);
if (!UserService.Instance.myUserInfo && isBrowser()) {
toast(i18n.t("not_logged_in"), "danger");
this.context.router.history.push(`/login`);
}
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);

View file

@ -96,11 +96,6 @@ export class Reports extends Component<any, ReportsState> {
this.handlePageChange = this.handlePageChange.bind(this);
if (!UserService.Instance.myUserInfo && isBrowser()) {
toast(i18n.t("not_logged_in"), "danger");
this.context.router.history.push(`/login`);
}
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);

View file

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

View file

@ -1,5 +1,4 @@
import { Component } from "inferno";
import { Redirect } from "inferno-router";
import { RouteComponentProps } from "inferno-router/dist/Route";
import {
GetCommunity,
@ -13,7 +12,7 @@ import {
import { Subscription } from "rxjs";
import { InitialFetchRequest, PostFormParams } from "shared/interfaces";
import { i18n } from "../../i18next";
import { UserService, WebSocketService } from "../../services";
import { WebSocketService } from "../../services";
import {
Choice,
QueryParams,
@ -145,7 +144,6 @@ export class CreatePost extends Component<
return (
<div className="container-lg">
{!UserService.Instance.myUserInfo && <Redirect to="/login" />}
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}

View file

@ -10,7 +10,7 @@ import {
import { Subscription } from "rxjs";
import { i18n } from "../../i18next";
import { InitialFetchRequest } from "../../interfaces";
import { UserService, WebSocketService } from "../../services";
import { WebSocketService } from "../../services";
import {
getRecipientIdFromProps,
isBrowser,
@ -51,11 +51,6 @@ export class CreatePrivateMessage extends Component<
this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage);
if (!UserService.Instance.myUserInfo && isBrowser()) {
toast(i18n.t("not_logged_in"), "danger");
this.context.router.history.push(`/login`);
}
// Only fetch the data if coming from another route
if (this.isoData.path == this.context.router.route.match.url) {
this.state = {

View file

@ -1,5 +1,6 @@
import { CommentView, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
import type { ParsedQs } from "qs";
import { ErrorPageData } from "./utils";
/**
* This contains serialized data, it needs to be deserialized before use.
@ -8,8 +9,12 @@ export interface IsoData {
path: string;
routeData: any[];
site_res: GetSiteResponse;
errorPageData?: ErrorPageData;
}
export type IsoDataOptionalSite = Partial<IsoData> &
Pick<IsoData, Exclude<keyof IsoData, "site_res">>;
export interface ILemmyConfig {
wsHost?: string;
}

View file

@ -105,6 +105,11 @@ export type ThemeColor =
| "gray"
| "gray-dark";
export interface ErrorPageData {
error?: string;
adminMatrixIds?: string[];
}
let customEmojis: EmojiMartCategory[] = [];
export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
string,
@ -1260,16 +1265,7 @@ export function isBrowser() {
export function setIsoData(context: any): IsoData {
// If its the browser, you need to deserialize the data from the window
if (isBrowser()) {
let json = window.isoData;
let routeData = json.routeData;
let site_res = json.site_res;
let isoData: IsoData = {
path: json.path,
site_res,
routeData,
};
return isoData;
return window.isoData;
} else return context.router.staticContext;
}
@ -1391,10 +1387,12 @@ export function personSelectName({
return local ? pName : `${hostname(actor_id)}/${pName}`;
}
export function initializeSite(site: GetSiteResponse) {
UserService.Instance.myUserInfo = site.my_user;
export function initializeSite(site?: GetSiteResponse) {
UserService.Instance.myUserInfo = site?.my_user;
i18n.changeLanguage(getLanguages()[0]);
if (site) {
setupEmojiDataModel(site.custom_emojis);
}
setupMarkdown();
}

View file

@ -5553,7 +5553,7 @@ lodash@^3.10.1:
resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6"
integrity sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==
lodash@^4.17.20:
lodash@^4.17.20, lodash@^4.17.21:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==