You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1538 lines
47 KiB

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import {
UserOperation,
CommunityUser,
SortType,
ListingType,
UserView,
UserSettingsForm,
LoginResponse,
DeleteAccountForm,
WebSocketJsonResponse,
Site,
UserDetailsView,
UserDetailsResponse,
GetSiteModeratorsResponse,
CommunityModsState,
BanUserForm,
UserTagResponse,
Post,
Comment,
} from '../interfaces';
import { WebSocketService, UserService } from '../services';
import {
wsJsonToRes,
fetchLimit,
routeSortTypeToEnum,
capitalizeFirstLetter,
languages,
toast,
setupTippy,
mapSiteModeratorsResponse,
canMod,
getAllUserModeratedCommunities,
api,
} from '../utils';
import { UserListing } from './user-listing';
import { SortSelect } from './sort-select';
import { ListingTypeSelect } from './listing-type-select';
import { MomentTime } from './moment-time';
import { i18n } from '../i18next';
import moment from 'moment';
import { UserDetails } from './user-details';
import { Icon } from './icon';
import { linkEvent } from '../linkEvent';
import { changeTheme } from '../theme';
import Button, { ResponsiveButton } from './elements/Button';
import { Box, Checkbox, Heading, Input, Label, Select } from 'theme-ui';
import Block, { Flex } from './elements/Block';
import Card from './elements/Card';
import StyledLink from '../StyledLink';
import Header, { Separator } from './Header';
import { Menu, MenuList, MenuButton, MenuItem } from './MenuButton';
import { BanDialog, BanDialogActions } from './Dialog';
import PurgeUserForm from './PurgeUserForm';
import { ThemeSelector } from './ThemeSystemProvider';
import { siteSubject } from '../services/SiteService';
import { AxiosError } from 'axios';
interface UserState {
user: UserView;
user_id: number;
username: string;
follows: Array<CommunityUser>;
moderates: Array<CommunityUser>;
posts: Array<Post>;
comments: Array<Comment>;
view: UserDetailsView;
sort: SortType;
page: number;
loading: boolean;
avatarLoading: boolean;
userSettingsForm: UserSettingsForm;
userSettingsLoading: boolean;
deleteAccountLoading: boolean;
deleteAccountShowConfirm: boolean;
deleteAccountForm: DeleteAccountForm;
site: Site;
communityMods: CommunityModsState | null;
admins: Array<UserView>;
sitemods: Array<UserView>;
banUserShow: boolean;
siteBanUserShow: boolean;
userSettingsShow: boolean;
banReason: string;
pronouns: string | null;
additionalPronouns: string | null;
}
interface UserProps {
view: UserDetailsView;
sort: SortType;
page: number;
user_id: number | null;
username: string;
}
interface UrlParams {
view?: string;
sort?: string;
page?: number;
}
function getViewFromProps(view: any): UserDetailsView {
return view
? UserDetailsView[capitalizeFirstLetter(view)]
: UserDetailsView.Overview;
}
function getSortTypeFromProps(sort: any): SortType {
return sort ? routeSortTypeToEnum(sort) : SortType.New;
}
function getPageFromProps(page: any): number {
return page ? Number(page) : 1;
}
class BaseUser extends Component<any, UserState> {
private subscription: Subscription;
private siteSub: Subscription;
private emptyState: UserState = {
user: {
id: null,
name: null,
published: null,
number_of_posts: null,
post_score: null,
number_of_comments: null,
comment_score: null,
banned: null,
avatar: null,
show_avatars: null,
send_notifications_to_email: null,
has_2fa: null,
actor_id: null,
local: null,
inbox_disabled: null,
},
user_id: null,
username: null,
follows: [],
moderates: [],
posts: [],
comments: [],
loading: true,
avatarLoading: false,
view: getViewFromProps(this.props.match.view),
sort: getSortTypeFromProps(this.props.match.sort),
page: getPageFromProps(this.props.match.page),
userSettingsForm: {
show_nsfw: null,
theme: null,
default_sort_type: null,
default_listing_type: null,
lang: null,
show_avatars: null,
send_notifications_to_email: null,
has_2fa: null,
auth: null,
inbox_disabled: null,
},
userSettingsLoading: null,
deleteAccountLoading: null,
deleteAccountShowConfirm: false,
deleteAccountForm: {
password: null,
},
site: {
id: undefined,
name: undefined,
creator_id: undefined,
published: undefined,
creator_name: undefined,
number_of_users: undefined,
number_of_posts: undefined,
number_of_comments: undefined,
number_of_communities: undefined,
enable_create_communities: undefined,
enable_downvotes: undefined,
open_registration: undefined,
enable_nsfw: undefined,
},
communityMods: null,
admins: [],
sitemods: [],
banUserShow: false,
siteBanUserShow: false,
banReason: null,
userSettingsShow: false,
pronouns: 'none',
additionalPronouns: 'none',
};
state = this.emptyState;
constructor(props: any, context: any) {
super(props, context);
this.handleSortChange = this.handleSortChange.bind(this);
this.handleUserSettingsSortTypeChange = this.handleUserSettingsSortTypeChange.bind(
this
);
this.handleUserSettingsListingTypeChange = this.handleUserSettingsListingTypeChange.bind(
this
);
this.handlePageChange = this.handlePageChange.bind(this);
this.isModerator = this.isModerator.bind(this);
this.handlePronounsChange = this.handlePronounsChange.bind(this);
this.handleAdditionalPronounsChange = this.handleAdditionalPronounsChange.bind(
this
);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
}
componentDidMount() {
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
this.siteSub = siteSubject.subscribe(res => {
this.setState({
site: res.site,
admins: res.admins,
sitemods: res.sitemods,
});
});
this.fetchUserData();
}
fetchUserData = async (): Promise<void> => {
let params;
if (this.isCurrentUser) {
params = new URLSearchParams({
user_id: UserService.Instance.user.id,
sort: SortType[this.state.sort],
saved_only: this.state.view === UserDetailsView.Saved,
page: this.state.page,
limit: fetchLimit,
auth: UserService.Instance.auth,
} as any);
} else {
params = new URLSearchParams({
username: this.state.username,
sort: SortType[this.state.sort],
saved_only: this.state.view === UserDetailsView.Saved,
page: this.state.page,
limit: fetchLimit,
} as any);
}
api
.get<UserDetailsResponse>(`user?${params.toString()}`)
.then(res => {
const data = res.data;
this.setState(
{
user: data.user,
follows: data.follows,
moderates: data.moderates,
posts: data.posts,
comments: data.comments,
loading: false,
},
() => {
WebSocketService.Instance.getUserTags({ user: data.user.id });
if (this.isCurrentUser) {
const userSettingsForm = {
show_nsfw: UserService.Instance.user.show_nsfw,
theme: UserService.Instance.user.theme
? UserService.Instance.user.theme
: 'chapo',
default_sort_type: UserService.Instance.user.default_sort_type,
default_listing_type:
UserService.Instance.user.default_listing_type,
lang: UserService.Instance.user.lang,
avatar: UserService.Instance.user.avatar,
email: data.user.email,
send_notifications_to_email:
data.user.send_notifications_to_email,
has_2fa: data.user.has_2fa,
show_avatars: data.user.show_avatars,
matrix_user_id: data.user.matrix_user_id,
inbox_disabled: data.user.inbox_disabled,
} as UserSettingsForm;
this.setState({ userSettingsForm: userSettingsForm });
}
}
);
})
.catch((err: Error | AxiosError) => {
const res = (err as AxiosError).response;
if (res) {
const data = res.data as { error: string };
toast(i18n.t(data.error), 'danger');
} else {
console.log(err);
}
});
};
get isCurrentUser() {
return (
UserService.Instance.user &&
UserService.Instance.user.name === this.state.username
);
}
componentWillUnmount() {
this.subscription.unsubscribe();
this.siteSub.unsubscribe();
}
static getDerivedStateFromProps(props: any): UserProps {
return {
view: getViewFromProps(props.match.params.view),
sort: getSortTypeFromProps(props.match.params.sort),
page: getPageFromProps(props.match.params.page),
user_id: Number(props.match.params.id) || null,
username: props.match.params.username,
};
}
componentDidUpdate(lastProps: any, _lastState: UserState, _snapshot: any) {
// Necessary if you are on a post and you click another post (same route)
if (
lastProps.location.pathname.split('/')[2] !==
lastProps.history.location.pathname.split('/')[2]
) {
// Couldnt get a refresh working. This does for now.
location.reload();
}
const prev = lastProps.location.pathname.split('/')[4];
const next = lastProps.history.location.pathname.split('/')[4];
if (prev && next && prev !== next) {
if (
// eslint-disable-next-line prettier/prettier
UserDetailsView[capitalizeFirstLetter(prev)] === UserDetailsView.Saved ||
UserDetailsView[capitalizeFirstLetter(next)] === UserDetailsView.Saved
) {
this.fetchUserData();
}
}
document.title = `/u/${this.state.username} - ${this.state.site.name}`;
setupTippy();
}
render() {
const { user } = this.state;
return (
<div className="container">
<Header
title={this.state.username}
subtitle={`(${this.state.pronouns} / ${this.state.additionalPronouns})`}
details={{
[i18n.t('post_count_label', {
count: user.number_of_posts,
})]: user.number_of_posts,
[i18n.t('comment_count_label', {
count: user.number_of_comments,
})]: user.number_of_comments,
}}
>
{!this.state.loading && (
<Flex>
<Separator />
{this.isCurrentUser ? (
<Button
css={{ width: '100%' }}
mt={2}
onClick={this.handleLogoutClick}
>
{i18n.t('logout')}
</Button>
) : (
<ResponsiveButton
as={StyledLink}
to={`/create_private_message?recipient_id=${this.state.user.id}`}
mr={2}
mobileText={<Icon name="mail" />}
>
{i18n.t('send_message')}
</ResponsiveButton>
)}
{(this.canAdmin || this.canSitemod || this.isModerator()) &&
!this.isCurrentUser && (
<Menu>
<MenuButton title="view more actions" variant="outline">
<Icon name="more" />
</MenuButton>
<MenuList>
{(this.canAdmin || this.canSitemod) &&
this.state.user.banned && (
<MenuItem
onClick={linkEvent(
this,
this.handleSiteBanUserShow
)}
>
Unban From Site
</MenuItem>
)}
{(this.canAdmin || this.canSitemod) &&
!this.state.user.banned && (
<MenuItem
onClick={linkEvent(
this,
this.handleSiteBanUserShow
)}
>
Ban From Site
</MenuItem>
)}
{this.isModerator() && (
<MenuItem
onClick={linkEvent(this, this.handleBanUserShow)}
>
{i18n.t('ban_from_my_communities')}
</MenuItem>
)}
{this.isModerator() && (
<MenuItem onClick={linkEvent(this, this.handleUnban)}>
Unban from my communities
</MenuItem>
)}
</MenuList>
</Menu>
)}
{this.isCurrentUser && (
<Button
onClick={() =>
this.setState({
userSettingsShow: !this.state.userSettingsShow,
})
}
variant="outline"
css={{
borderWidth: 0,
}}
>
<Icon name="settings" />
</Button>
)}
</Flex>
)}
</Header>
{this.isCurrentUser &&
this.state.userSettingsShow &&
this.userSettings()}
{this.state.loading && (
<Heading as="h5">
<svg className="icon icon-spinner spin">
<use xlinkHref="#icon-spinner" />
</svg>
</Heading>
)}
<div className="row user-settings-container">
<main className="col-12 col-md-8" role="main">
{!this.state.loading && this.selects()}
<UserDetails
user_id={this.state.user_id}
username={this.state.username}
sort={SortType[this.state.sort]}
page={this.state.page}
limit={fetchLimit}
enableDownvotes={this.state.site.enable_downvotes}
enableNsfw={this.state.site.enable_nsfw}
view={this.state.view}
onPageChange={this.handlePageChange}
posts={this.state.posts}
comments={this.state.comments}
admins={this.state.admins}
siteMods={this.state.sitemods}
/>
</main>
{!this.state.loading && (
<aside className="col-12 col-md-4 sidebar">
{(this.canAdmin || this.canSitemod || this.isModerator()) &&
!this.isCurrentUser &&
this.modActions()}
{this.userInfo()}
{this.moderates()}
{this.follows()}
</aside>
)}
</div>
</div>
);
}
viewRadios() {
return (
<div className="btn-group btn-group-toggle">
<Button
as="label"
variant={
this.state.view == UserDetailsView.Overview ? 'primary' : 'muted'
}
>
<input
type="radio"
className="visually-hidden"
value={UserDetailsView.Overview}
checked={this.state.view === UserDetailsView.Overview}
onChange={linkEvent(this, this.handleViewChange)}
/>
{i18n.t('overview')}
</Button>
<Button
as="label"
variant={
this.state.view == UserDetailsView.Comments ? 'primary' : 'muted'
}
>
<input
type="radio"
className="visually-hidden"
value={UserDetailsView.Comments}
checked={this.state.view == UserDetailsView.Comments}
onChange={linkEvent(this, this.handleViewChange)}
/>
{i18n.t('comments')}
</Button>
<Button
as="label"
variant={
this.state.view == UserDetailsView.Posts ? 'primary' : 'muted'
}
>
<input
type="radio"
className="visually-hidden"
value={UserDetailsView.Posts}
checked={this.state.view == UserDetailsView.Posts}
onChange={linkEvent(this, this.handleViewChange)}
/>
{i18n.t('posts')}
</Button>
<Button
as="label"
variant={
this.state.view == UserDetailsView.Saved ? 'primary' : 'muted'
}
>
<input
className="visually-hidden"
type="radio"
value={UserDetailsView.Saved}
checked={this.state.view == UserDetailsView.Saved}
onChange={linkEvent(this, this.handleViewChange)}
/>
{i18n.t('saved')}
</Button>
</div>
);
}
selects() {
return (
<div className="mb-2">
<Block my={3}>
<div className="mr-3 mb-2 user-view-toggle">{this.viewRadios()}</div>
</Block>
<SortSelect
sort={this.state.sort}
onChange={this.handleSortChange}
hideHot
/>
<a
href={`/feeds/u/${this.state.username}.xml?sort=${
SortType[this.state.sort]
}`}
target="_blank"
rel="noopener"
title="RSS"
>
<Icon name="rss" className="icon mx-2 text-muted small" />
</a>
</div>
);
}
userInfo() {
let user = this.state.user;
return (
<div>
<Card mb={3}>
<Heading as="h5">
<ul className="list-inline mb-0">
<li className="list-inline-item">
<UserListing user={user} realLink />
</li>
{user.banned && (
<li
className="list-inline-item badge badge-danger"
key={user.id}
>
{i18n.t('banned')}
</li>
)}
</ul>
</Heading>
<div className="d-flex align-items-center mb-2">
<svg className="icon">
<use xlinkHref="#icon-cake" />
</svg>
<span className="ml-2">
{i18n.t('cake_day_title')}{' '}
{moment.utc(user.published).local().format('MMM DD, YYYY')}
</span>
</div>
<div>
{i18n.t('joined')} <MomentTime data={user} showAgo />
</div>
</Card>
</div>
);
}
userSettings() {
return (
<div>
<Box mb={3} css={{ maxWidth: '800px' }}>
<Heading as="h5">{i18n.t('settings')}</Heading>
<form onSubmit={linkEvent(this, this.handleUserSettingsSubmit)}>
<div className="form-group row">
<label
className="col-lg-5 col-form-label"
htmlFor="user-pronouns"
>
{i18n.t('pronouns')}
</label>
<div className="col-lg-7">
<Select
id="user-pronouns"
value={this.state.pronouns}
onChange={this.handlePronounsChange}
>
<option value="none/use name">none/use name</option>
<option value="any">any</option>
<option value="comrade/them">comrade/them</option>
<option value="des/pair">des/pair</option>
<option value="doe/deer">doe/deer</option>
<option value="e/em/eir">e/em/eir</option>
<option value="ey/em">ey/em</option>
<option value="fae/faer">fae/faer</option>
<option value="he/him">he/him</option>
<option value="hy/hym">hy/hym</option>
<option value="it/its">it/its</option>
<option value="love/loves">love/loves</option>
<option value="she/her">she/her</option>
<option value="they/them">they/them</option>
<option value="undecided">undecided</option>
<option value="xe/xem">xe/xem</option>
<option value="xey/xem">xey/xem</option>
<option value="ze/hir">ze/hir</option>
</Select>
</div>
</div>
{!(
this.state.pronouns === '' || this.state.pronouns === 'none'
) && (
<div className="form-group row">
<label
className="col-lg-5 col-form-label"
htmlFor="user-secondary-pronouns"
>
{i18n.t('additional_pronouns')}
</label>
<div className="col-lg-7">
<Select
id="user-secondary-pronouns"
value={this.state.additionalPronouns}
onChange={this.handleAdditionalPronounsChange}
>
<option value="none/use name">none/use name</option>
<option value="any">any</option>
<option value="comrade/them">comrade/them</option>
<option value="des/pair">des/pair</option>
<option value="doe/deer">doe/deer</option>
<option value="e/em/eir">e/em/eir</option>
<option value="ey/em">ey/em</option>
<option value="fae/faer">fae/faer</option>
<option value="he/him">he/him</option>
<option value="hy/hym">hy/hym</option>
<option value="it/its">it/its</option>
<option value="love/loves">love/loves</option>
<option value="she/her">she/her</option>
<option value="they/them">they/them</option>
<option value="undecided">undecided</option>
<option value="xe/xem">xe/xem</option>
<option value="xey/xem">xey/xem</option>
<option value="ze/hir">ze/hir</option>
</Select>
</div>
</div>
)}
<div className="form-group">
<label>{i18n.t('language')}</label>
<Select
value={this.state.userSettingsForm.lang}
onChange={linkEvent(this, this.handleUserSettingsLangChange)}
>
<option disabled>{i18n.t('language')}</option>
<option value="browser">{i18n.t('browser_default')}</option>
<option disabled></option>
{languages.map(lang => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</Select>
</div>
<div className="form-group">
<label>{i18n.t('theme')}</label>
<ThemeSelector
value={this.state.userSettingsForm.theme}
onChange={this.handleUserSettingsThemeChange}
/>
</div>
<form className="form-group">
<label>
<div className="mr-2">{i18n.t('sort_type')}</div>
</label>
<ListingTypeSelect
type_={this.state.userSettingsForm.default_listing_type}
onChange={this.handleUserSettingsListingTypeChange}
/>
</form>
<form className="form-group">
<label>
<div className="mr-2">{i18n.t('type')}</div>
</label>
<SortSelect
sort={parseInt(
// @ts-ignore
this.state.userSettingsForm.default_sort_type,
10
)}
onChange={this.handleUserSettingsSortTypeChange}
/>
</form>
<div className="form-group row">
<label className="col-lg-3 col-form-label" htmlFor="user-email">
{i18n.t('email')}
</label>
<div className="col-lg-9">
<Input
type="email"
id="user-email"
placeholder={i18n.t('optional')}
value={this.state.userSettingsForm.email}
onInput={linkEvent(this, this.handleUserSettingsEmailChange)}
minLength={3}
/>
</div>
</div>
<div className="form-group">
<Label>
<Checkbox
id="user-enable-2fa"
type="checkbox"
checked={this.state.userSettingsForm.has_2fa}
onChange={linkEvent(
this,
this.handleUserSettingsEnable2faChange
)}
/>
Enable two-factor authentication
</Label>
</div>
<div className="form-group row">
<label className="col-lg-5 col-form-label">
<a href="https://about.riot.im/" target="_blank" rel="noopener">
{i18n.t('matrix_user_id')}
</a>
</label>
<div className="col-lg-7">
<Input
type="text"
placeholder="@user:example.com"
value={this.state.userSettingsForm.matrix_user_id}
onInput={linkEvent(
this,
this.handleUserSettingsMatrixUserIdChange
)}
minLength={3}
/>
</div>
</div>
<div className="form-group row">
<label
className="col-lg-5 col-form-label"
htmlFor="user-password"
>
{i18n.t('new_password')}
</label>
<div className="col-lg-7">
<Input
type="password"
id="user-password"
value={this.state.userSettingsForm.new_password}
autoComplete="new-password"
onInput={linkEvent(
this,
this.handleUserSettingsNewPasswordChange
)}
/>
</div>
</div>
<div className="form-group row">
<label
className="col-lg-5 col-form-label"
htmlFor="user-verify-password"
>
{i18n.t('verify_password')}
</label>
<div className="col-lg-7">
<Input
type="password"
id="user-verify-password"
value={this.state.userSettingsForm.new_password_verify}
autoComplete="new-password"
onInput={linkEvent(
this,
this.handleUserSettingsNewPasswordVerifyChange
)}
/>
</div>
</div>
<div className="form-group row">
<label
className="col-lg-5 col-form-label"
htmlFor="user-old-password"
>
{i18n.t('old_password')}
</label>
<div className="col-lg-7">
<Input
type="password"
id="user-old-password"
value={this.state.userSettingsForm.old_password}
autoComplete="new-password"
onInput={linkEvent(
this,
this.handleUserSettingsOldPasswordChange
)}
/>
</div>
</div>
{this.state.site.enable_nsfw && (
<div className="form-group">
<Label>
<Checkbox
id="user-show-nsfw"
type="checkbox"
checked={this.state.userSettingsForm.show_nsfw}
onChange={linkEvent(
this,
this.handleUserSettingsShowNsfwChange
)}
/>
{i18n.t('show_nsfw')}
</Label>
</div>
)}
<div className="form-group">
<Label>
<Checkbox
id="user-show-avatars"
type="checkbox"
checked={this.state.userSettingsForm.show_avatars}
onChange={linkEvent(
this,
this.handleUserSettingsShowAvatarsChange
)}
/>
{i18n.t('show_avatars')}
</Label>
</div>
<div className="form-group">
<Label>
<Checkbox
id="user-send-notifications-to-email"
type="checkbox"
disabled={!this.state.user.email}
checked={
this.state.userSettingsForm.send_notifications_to_email
}
onChange={linkEvent(
this,
this.handleUserSettingsSendNotificationsToEmailChange
)}
/>
{i18n.t('send_notifications_to_email')}
</Label>
</div>
<div className="form-group">
<Label>
<Checkbox
id="user-inbox-disabled"
type="checkbox"
checked={this.state.userSettingsForm.inbox_disabled}
onChange={linkEvent(this, this.handleUserSettingsInboxChange)}
/>
{i18n.t('disable_inbox')}
</Label>
</div>
<div className="form-group">
<Button
type="submit"
mr={4}
loading={this.state.userSettingsLoading}
block
>
{capitalizeFirstLetter(i18n.t('save'))}
</Button>
</div>
<hr />
<div className="form-group mb-0">
<Button
variant="danger"
block
onClick={linkEvent(
this,
this.handleDeleteAccountShowConfirmToggle
)}
>
{i18n.t('delete_account')}
</Button>
{this.state.deleteAccountShowConfirm && (
<>
<div className="my-2 alert alert-danger" role="alert">
{i18n.t('delete_account_confirm')}
</div>
<Input
type="password"
value={this.state.deleteAccountForm.password}
autoComplete="new-password"
onInput={linkEvent(
this,
this.handleDeleteAccountPasswordChange
)}
className="my-2"
/>
<Button
variant="danger"
mr={4}
disabled={!this.state.deleteAccountForm.password}
onClick={linkEvent(this, this.handleDeleteAccount)}
>
{this.state.deleteAccountLoading ? (
<svg className="icon icon-spinner spin">
<use xlinkHref="#icon-spinner" />
</svg>
) : (
capitalizeFirstLetter(i18n.t('delete'))
)}
</Button>
<Button
className="btn btn-secondary"
onClick={linkEvent(
this,
this.handleDeleteAccountShowConfirmToggle
)}
>
{i18n.t('cancel')}
</Button>
</>
)}
</div>
</form>
</Box>
</div>
);
}
modActions() {
return (
<div>
<Card mb={3}>
<Heading as="h5">Mod Actions</Heading>
<Flex flexDirection="column" alignItems="flex-start">
{(this.canAdmin || this.canSitemod) && (
<PurgeUserForm user_id={this.state.user.id} />
)}
{(this.canAdmin || this.canSitemod) && this.state.user.banned && (
<Button
my={1}
onClick={linkEvent(this, this.handleSiteBanUserShow)}
>
Unban from site
</Button>
)}
{(this.canAdmin || this.canSitemod) && !this.state.user.banned && (
<Button
my={1}
onClick={linkEvent(this, this.handleSiteBanUserShow)}
>
Ban from site
</Button>
)}
{this.isModerator() && (
<Button my={1} onClick={linkEvent(this, this.handleBanUserShow)}>
{i18n.t('ban_from_my_communities')}
</Button>
)}
{this.isModerator() && (
<Button my={1} onClick={linkEvent(this, this.handleUnban)}>
Unban from my communities
</Button>
)}
<BanDialog
isOpen={this.state.banUserShow}
onSubmit={this.handleBan}
onClose={this.handleCloseBanDialog}
action={BanDialogActions.Ban}
/>
<BanDialog
isOpen={this.state.siteBanUserShow}
onSubmit={banReason =>
this.state.user.banned
? this.handleSiteUnban(banReason)
: this.handleSiteBan(banReason)
}
onClose={this.handleCloseBanDialog}
action={
this.state.user.banned
? BanDialogActions.Unban
: BanDialogActions.Ban
}
/>
</Flex>
</Card>
</div>
);
}
moderates() {
return (
<div>
{this.state.moderates.length > 0 && (
<Card mb={3}>
<Heading as="h5">{i18n.t('moderates')}</Heading>
<ul className="list-unstyled mb-0">
{this.state.moderates.map(community => (
<li key={community.id}>
<StyledLink to={`/c/${community.community_name}`}>
{community.community_name}
</StyledLink>
</li>
))}
</ul>
</Card>
)}
</div>
);
}
follows() {
return (
<div>
{this.state.follows.length > 0 && (
<Card mb={3}>
<Heading as="h5">{i18n.t('subscribed')}</Heading>
<ul className="list-unstyled mb-0">
{this.state.follows.map(community => (
<li key={community.id}>
<StyledLink to={`/c/${community.community_name}`}>
{community.community_name}
</StyledLink>
</li>
))}
</ul>
</Card>
)}
</div>
);
}
get canAdmin(): boolean {
return (
this.state.admins &&
canMod(
UserService.Instance.user,
this.state.admins.map(a => a.id),
this.state.user_id
)
);
}
get canSitemod(): boolean {
return (
this.state.sitemods &&
canMod(
UserService.Instance.user,
this.state.sitemods.map(a => a.id),
this.state.user_id
)
);
}
isModerator() {
return (
getAllUserModeratedCommunities({
siteModerators: this.state.communityMods || {},
moderatorId: UserService.Instance.user?.id,
}).length > 0
);
}
updateUrl(paramUpdates: UrlParams) {
const page = paramUpdates.page || this.state.page;
const viewStr =
paramUpdates.view || UserDetailsView[this.state.view].toLowerCase();
const sortStr =
paramUpdates.sort || SortType[this.state.sort].toLowerCase();
this.props.history.push(
`/u/${this.state.username}/view/${viewStr}/sort/${sortStr}/page/${page}`
);
}
handlePageChange(page: number) {
this.updateUrl({ page });
}
handleSortChange(val: SortType) {
this.updateUrl({ sort: SortType[val].toLowerCase(), page: 1 });
}
handleViewChange(i: BaseUser, event: any) {
i.updateUrl({
view: UserDetailsView[Number(event.target.value)].toLowerCase(),
page: 1,
});
}
handleUserSettingsEnable2faChange(i: BaseUser, event: any) {
if (event.target.checked && !i.state.userSettingsForm.email) {
(document.getElementById(
'user-enable-2fa'
) as HTMLInputElement).setCustomValidity(
'Email needed for two-factor authenticaion'
);
} else {
(document.getElementById(
'user-enable-2fa'
) as HTMLInputElement).setCustomValidity('');
}
i.state.userSettingsForm.has_2fa = event.target.checked;
i.setState(i.state);
}
handleUserSettingsShowNsfwChange(i: BaseUser, event: any) {
i.state.userSettingsForm.show_nsfw = event.target.checked;
i.setState(i.state);
}
handleUserSettingsShowAvatarsChange(i: BaseUser, event: any) {
i.state.userSettingsForm.show_avatars = event.target.checked;
UserService.Instance.user.show_avatars = event.target.checked; // Just for instant updates
i.setState(i.state);
}
handleUserSettingsSendNotificationsToEmailChange(i: BaseUser, event: any) {
i.state.userSettingsForm.send_notifications_to_email = event.target.checked;
i.setState(i.state);
}
handleUserSettingsInboxChange(i: BaseUser, event: any) {
i.setState({
userSettingsForm: {
...i.state.userSettingsForm,
inbox_disabled: event.target.checked,
},
});
}
handleUserSettingsThemeChange = (value: string) => {
changeTheme(value);
this.setState({
userSettingsForm: { ...this.state.userSettingsForm, theme: value },
});
};
handleUserSettingsLangChange(i: BaseUser, event: any) {
i.state.userSettingsForm.lang = event.target.value;
i18n.changeLanguage(i.state.userSettingsForm.lang);
i.setState(i.state);
}
handleUserSettingsSortTypeChange(val: SortType) {
// @ts-ignore
this.state.userSettingsForm.default_sort_type = parseInt(val, 10);
this.setState(this.state);
}
handleUserSettingsListingTypeChange(val: ListingType) {
this.state.userSettingsForm.default_listing_type = val;
this.setState(this.state);
}
handleUserSettingsEmailChange(i: BaseUser, event: any) {
if (event.target.value == '') {
(document.getElementById(
'user-enable-2fa'
) as HTMLInputElement).setCustomValidity(
'Email needed for two-factor authenticaion'
);
} else
(document.getElementById(
'user-enable-2fa'
) as HTMLInputElement).setCustomValidity('');
i.state.userSettingsForm.email = event.target.value;
if (i.state.userSettingsForm.email == '' && !i.state.user.email) {
i.state.userSettingsForm.email = undefined;
}
i.setState(i.state);
}
handleUserSettingsMatrixUserIdChange(i: BaseUser, event: any) {
i.state.userSettingsForm.matrix_user_id = event.target.value;
if (
i.state.userSettingsForm.matrix_user_id == '' &&
!i.state.user.matrix_user_id
) {
i.state.userSettingsForm.matrix_user_id = undefined;
}
i.setState(i.state);
}
handleUserSettingsNewPasswordChange(i: BaseUser, event: any) {
i.state.userSettingsForm.new_password = event.target.value;
if (i.state.userSettingsForm.new_password == '') {
i.state.userSettingsForm.new_password = undefined;
}
i.setState(i.state);
}
handleUserSettingsNewPasswordVerifyChange(i: BaseUser, event: any) {
i.state.userSettingsForm.new_password_verify = event.target.value;
if (i.state.userSettingsForm.new_password_verify == '') {
i.state.userSettingsForm.new_password_verify = undefined;
}
i.setState(i.state);
}
handleUserSettingsOldPasswordChange(i: BaseUser, event: any) {
i.state.userSettingsForm.old_password = event.target.value;
if (i.state.userSettingsForm.old_password == '') {
i.state.userSettingsForm.old_password = undefined;
}
i.setState(i.state);
}
handleImageUpload(i: BaseUser, event: any) {
event.preventDefault();
let file = event.target.files[0];
const imageUploadUrl = `/pictrs/image`;
const formData = new FormData();
formData.append('images[]', file);
i.state.avatarLoading = true;
i.setState(i.state);
fetch(imageUploadUrl, {
method: 'POST',
body: formData,
})
.then(res => res.json())
.then(res => {
console.log('pictrs upload:');
console.log(res);
if (res.msg == 'ok') {
let hash = res.files[0].file;
let url = `${window.location.origin}/pictrs/image/${hash}`;
i.state.userSettingsForm.avatar = url;
i.state.avatarLoading = false;
i.setState(i.state);
} else {
i.state.avatarLoading = false;
i.setState(i.state);
toast(JSON.stringify(res), 'danger');
}
})
.catch(error => {
i.state.avatarLoading = false;
i.setState(i.state);
toast(error, 'danger');
});
}
removeAvatar(i: BaseUser, event: any) {
event.preventDefault();
i.state.userSettingsLoading = true;
i.state.userSettingsForm.avatar = '';
i.setState(i.state);
WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
}
get checkSettingsAvatar(): boolean {
return (
this.state.userSettingsForm.avatar &&
this.state.userSettingsForm.avatar != ''
);
}
handleUserSettingsSubmit(i: BaseUser, event: any) {
event.preventDefault();
if (!i.state.userSettingsForm.email && i.state.userSettingsForm.has_2fa) {
return;
}
i.state.userSettingsLoading = true;
i.setState(i.state);
WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
let pronounsValue = null;
if (i.state.pronouns !== 'none' && i.state.pronouns !== '') {
pronounsValue = i.state.pronouns;
if (
i.state.additionalPronouns !== 'none' &&
i.state.additionalPronouns !== '' &&
i.state.additionalPronouns !== i.state.pronouns
) {
pronounsValue += `,${i.state.additionalPronouns}`;
}
}
WebSocketService.Instance.setUserTags({
tag: 'pronouns',
value: pronounsValue,
});
}
handlePronounsChange(e: any) {
this.setState({ pronouns: e.target.value });
}
handleAdditionalPronounsChange(e: any) {
this.setState({ additionalPronouns: e.target.value });
}
handleDeleteAccountShowConfirmToggle(i: BaseUser, event: any) {
event.preventDefault();
i.state.deleteAccountShowConfirm = !i.state.deleteAccountShowConfirm;
i.setState(i.state);
}
handleDeleteAccountPasswordChange(i: BaseUser, event: any) {
i.state.deleteAccountForm.password = event.target.value;
i.setState(i.state);
}
handleLogoutClick() {
UserService.Instance.logout();
this.props.history.push('/');
}
handleDeleteAccount(i: BaseUser, event: any) {
event.preventDefault();
i.state.deleteAccountLoading = true;
i.setState(i.state);
WebSocketService.Instance.deleteAccount(i.state.deleteAccountForm);
}
handleBanUserShow(i: BaseUser) {
i.state.banUserShow = !i.state.banUserShow;
i.setState(i.state);
}
handleSiteBanUserShow(i: BaseUser) {
i.state.siteBanUserShow = !i.state.siteBanUserShow;
i.setState(i.state);
}
handleCloseBanDialog = () => {
this.setState({ siteBanUserShow: false, banUserShow: false });
};
handleBanReasonChange = (event: any) => {
this.setState({ banReason: event.target.value });
};
handleSiteUnban = banReason => {
event.preventDefault();
if (this.canAdmin || this.canSitemod) {
const form: BanUserForm = {
user_id: this.state.user.id,
ban: false,
reason: banReason,
};
WebSocketService.Instance.banUser(form);
}
this.setState({
banReason: null,
siteBanUserShow: false,
user: {
...this.state.user,
banned: false,
},
});
};
handleSiteBan = banReason => {
event.preventDefault();
if (this.canAdmin || this.canSitemod) {
const form: BanUserForm = {
user_id: this.state.user.id,
ban: true,
reason: banReason,
};
WebSocketService.Instance.banUser(form);
}
this.setState({
banReason: null,
siteBanUserShow: false,
user: {
...this.state.user,
banned: true,
},
});
};
handleBan = banReason => {
if (this.isModerator()) {
const communityIds = getAllUserModeratedCommunities({
siteModerators: this.state.communityMods,
moderatorId: UserService.Instance.user.id,
});
communityIds.forEach(communityId => {
WebSocketService.Instance.banFromCommunity({
community_id: communityId,
user_id: this.state.user.id,
ban: true,
reason: banReason,
});
});
}
this.setState({
banReason: null,
banUserShow: false,
});
};
handleUnban(i: BaseUser, event: any) {
event.preventDefault();
if (i.isModerator()) {
const communityIds = getAllUserModeratedCommunities({
siteModerators: i.state.communityMods,
moderatorId: UserService.Instance.user.id,
});
communityIds.forEach(communityId => {
WebSocketService.Instance.banFromCommunity({
community_id: communityId,
user_id: i.state.user.id,
ban: false,
reason: i.state.banReason,
});
});
}
i.state.banReason = null;
i.state.banUserShow = false;
i.setState(i.state);
}
parseMessage(msg: WebSocketJsonResponse) {
const res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
if (msg.error == 'couldnt_find_that_username_or_email') {
this.props.history.push('/');
}
this.setState({
deleteAccountLoading: false,
avatarLoading: false,
userSettingsLoading: false,
});
return;
} else if (res.op == UserOperation.SaveUserSettings) {
const data = res.data as LoginResponse;
UserService.Instance.login(data);
this.setState({
userSettingsLoading: false,
});
window.scrollTo(0, 0);
} else if (res.op == UserOperation.DeleteAccount) {
this.setState({
deleteAccountLoading: false,
deleteAccountShowConfirm: false,
});
this.props.history.push('/');
} else if (res.op == UserOperation.GetSiteModerators) {
const data = res.data as GetSiteModeratorsResponse;
this.setState({
communityMods: mapSiteModeratorsResponse(data),
});
} else if (res.op == UserOperation.GetUserTag) {
const data = res.data as UserTagResponse;
const pronouns = data.tags.pronouns == null ? '' : data.tags.pronouns;
const pronounsArray = pronouns.split(',');
this.setState({
pronouns: pronounsArray[0] || 'none',
additionalPronouns: pronounsArray[1] || 'none',
});
}
}
}
export const User = withRouter(BaseUser);