1 import { None, Option, Some } from "@sniptt/monads";
2 import { Component, linkEvent } from "inferno";
3 import { Link } from "inferno-router";
12 GetPersonDetailsResponse,
21 } from "lemmy-js-client";
22 import moment from "moment";
23 import { Subscription } from "rxjs";
24 import { i18n } from "../../i18next";
25 import { InitialFetchRequest, PersonDetailsView } from "../../interfaces";
26 import { UserService, WebSocketService } from "../../services";
30 capitalizeFirstLetter,
32 createPostLikeFindRes,
45 restoreScrollPosition,
56 import { BannerIconHeader } from "../common/banner-icon-header";
57 import { HtmlTags } from "../common/html-tags";
58 import { Icon, Spinner } from "../common/icon";
59 import { MomentTime } from "../common/moment-time";
60 import { SortSelect } from "../common/sort-select";
61 import { CommunityLink } from "../community/community-link";
62 import { PersonDetails } from "./person-details";
63 import { PersonListing } from "./person-listing";
65 interface ProfileState {
66 personRes: Option<GetPersonDetailsResponse>;
68 view: PersonDetailsView;
72 personBlocked: boolean;
73 banReason: Option<string>;
74 banExpireDays: Option<number>;
75 showBanDialog: boolean;
77 siteRes: GetSiteResponse;
80 interface ProfileProps {
81 view: PersonDetailsView;
84 person_id: number | null;
94 export class Profile extends Component<any, ProfileState> {
95 private isoData = setIsoData(this.context, GetPersonDetailsResponse);
96 private subscription: Subscription;
97 private emptyState: ProfileState = {
99 userName: getUsernameFromProps(this.props),
101 view: Profile.getViewFromProps(this.props.match.view),
102 sort: Profile.getSortTypeFromProps(this.props.match.sort),
103 page: Profile.getPageFromProps(this.props.match.page),
104 personBlocked: false,
105 siteRes: this.isoData.site_res,
106 showBanDialog: false,
112 constructor(props: any, context: any) {
113 super(props, context);
115 this.state = this.emptyState;
116 this.handleSortChange = this.handleSortChange.bind(this);
117 this.handlePageChange = this.handlePageChange.bind(this);
119 this.parseMessage = this.parseMessage.bind(this);
120 this.subscription = wsSubscribe(this.parseMessage);
122 // Only fetch the data if coming from another route
123 if (this.isoData.path == this.context.router.route.match.url) {
126 personRes: Some(this.isoData.routeData[0] as GetPersonDetailsResponse),
130 this.fetchUserData();
133 this.setPersonBlock();
137 let form = new GetPersonDetails({
138 username: Some(this.state.userName),
141 sort: Some(this.state.sort),
142 saved_only: Some(this.state.view === PersonDetailsView.Saved),
143 page: Some(this.state.page),
144 limit: Some(fetchLimit),
145 auth: auth(false).ok(),
147 WebSocketService.Instance.send(wsClient.getPersonDetails(form));
150 get amCurrentUser() {
151 return UserService.Instance.myUserInfo.match({
153 this.state.personRes.match({
155 mui.local_user_view.person.id == res.person_view.person.id,
163 UserService.Instance.myUserInfo.match({
165 this.state.personRes.match({
168 personBlocked: mui.person_blocks
169 .map(a => a.target.id)
170 .includes(res.person_view.person.id),
178 static getViewFromProps(view: string): PersonDetailsView {
179 return view ? PersonDetailsView[view] : PersonDetailsView.Overview;
182 static getSortTypeFromProps(sort: string): SortType {
183 return sort ? routeSortTypeToEnum(sort) : SortType.New;
186 static getPageFromProps(page: number): number {
187 return page ? Number(page) : 1;
190 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
191 let pathSplit = req.path.split("/");
193 let username = pathSplit[2];
194 let view = this.getViewFromProps(pathSplit[4]);
195 let sort = Some(this.getSortTypeFromProps(pathSplit[6]));
196 let page = Some(this.getPageFromProps(Number(pathSplit[8])));
198 let form = new GetPersonDetails({
199 username: Some(username),
203 saved_only: Some(view === PersonDetailsView.Saved),
205 limit: Some(fetchLimit),
208 return [req.client.getPersonDetails(form)];
211 componentDidMount() {
215 componentWillUnmount() {
216 this.subscription.unsubscribe();
217 saveScrollPosition(this.context);
220 static getDerivedStateFromProps(props: any): ProfileProps {
222 view: this.getViewFromProps(props.match.params.view),
223 sort: this.getSortTypeFromProps(props.match.params.sort),
224 page: this.getPageFromProps(props.match.params.page),
225 person_id: Number(props.match.params.id) || null,
226 username: props.match.params.username,
230 componentDidUpdate(lastProps: any) {
231 // Necessary if you are on a post and you click another post (same route)
233 lastProps.location.pathname.split("/")[2] !==
234 lastProps.history.location.pathname.split("/")[2]
236 // Couldnt get a refresh working. This does for now.
241 get documentTitle(): string {
242 return this.state.siteRes.site_view.match({
244 this.state.personRes.match({
246 `@${res.person_view.person.name} - ${siteView.site.name}`,
255 <div className="container">
256 {this.state.loading ? (
261 this.state.personRes.match({
263 <div className="row">
264 <div className="col-12 col-md-8">
267 title={this.documentTitle}
268 path={this.context.router.route.match.url}
269 description={res.person_view.person.bio}
270 image={res.person_view.person.avatar}
275 {!this.state.loading && this.selects()}
278 admins={this.state.siteRes.admins}
279 sort={this.state.sort}
280 page={this.state.page}
282 enableDownvotes={enableDownvotes(this.state.siteRes)}
283 enableNsfw={enableNsfw(this.state.siteRes)}
284 view={this.state.view}
285 onPageChange={this.handlePageChange}
289 {!this.state.loading && (
290 <div className="col-12 col-md-4">
292 {this.amCurrentUser && this.follows()}
306 <div className="btn-group btn-group-toggle flex-wrap mb-2">
308 className={`btn btn-outline-secondary pointer
309 ${this.state.view == PersonDetailsView.Overview && "active"}
314 value={PersonDetailsView.Overview}
315 checked={this.state.view === PersonDetailsView.Overview}
316 onChange={linkEvent(this, this.handleViewChange)}
321 className={`btn btn-outline-secondary pointer
322 ${this.state.view == PersonDetailsView.Comments && "active"}
327 value={PersonDetailsView.Comments}
328 checked={this.state.view == PersonDetailsView.Comments}
329 onChange={linkEvent(this, this.handleViewChange)}
334 className={`btn btn-outline-secondary pointer
335 ${this.state.view == PersonDetailsView.Posts && "active"}
340 value={PersonDetailsView.Posts}
341 checked={this.state.view == PersonDetailsView.Posts}
342 onChange={linkEvent(this, this.handleViewChange)}
347 className={`btn btn-outline-secondary pointer
348 ${this.state.view == PersonDetailsView.Saved && "active"}
353 value={PersonDetailsView.Saved}
354 checked={this.state.view == PersonDetailsView.Saved}
355 onChange={linkEvent(this, this.handleViewChange)}
364 let profileRss = `/feeds/u/${this.state.userName}.xml?sort=${this.state.sort}`;
367 <div className="mb-2">
368 <span className="mr-3">{this.viewRadios()}</span>
370 sort={this.state.sort}
371 onChange={this.handleSortChange}
375 <a href={profileRss} rel={relTags} title="RSS">
376 <Icon icon="rss" classes="text-muted small mx-2" />
378 <link rel="alternate" type="application/atom+xml" href={profileRss} />
382 handleBlockPerson(personId: number) {
384 let blockUserForm = new BlockPerson({
387 auth: auth().unwrap(),
389 WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
392 handleUnblockPerson(recipientId: number) {
393 let blockUserForm = new BlockPerson({
394 person_id: recipientId,
396 auth: auth().unwrap(),
398 WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
402 return this.state.personRes
403 .map(r => r.person_view)
408 banner={pv.person.banner}
409 icon={pv.person.avatar}
411 <div className="mb-3">
413 <div className="mb-0 d-flex flex-wrap">
415 {pv.person.display_name && (
416 <h5 className="mb-0">{pv.person.display_name}</h5>
418 <ul className="list-inline mb-2">
419 <li className="list-inline-item">
428 {isBanned(pv.person) && (
429 <li className="list-inline-item badge badge-danger">
433 {pv.person.admin && (
434 <li className="list-inline-item badge badge-light">
438 {pv.person.bot_account && (
439 <li className="list-inline-item badge badge-light">
440 {i18n.t("bot_account").toLowerCase()}
446 <div className="flex-grow-1 unselectable pointer mx-2"></div>
447 {!this.amCurrentUser &&
448 UserService.Instance.myUserInfo.isSome() && (
451 className={`d-flex align-self-start btn btn-secondary mr-2 ${
452 !pv.person.matrix_user_id && "invisible"
455 href={`https://matrix.to/#/${pv.person.matrix_user_id}`}
457 {i18n.t("send_secure_message")}
461 "d-flex align-self-start btn btn-secondary mr-2"
463 to={`/create_private_message/recipient/${pv.person.id}`}
465 {i18n.t("send_message")}
467 {this.state.personBlocked ? (
470 "d-flex align-self-start btn btn-secondary mr-2"
474 this.handleUnblockPerson
477 {i18n.t("unblock_user")}
482 "d-flex align-self-start btn btn-secondary mr-2"
486 this.handleBlockPerson
489 {i18n.t("block_user")}
497 Some(this.state.siteRes.admins),
500 !isAdmin(Some(this.state.siteRes.admins), pv.person.id) &&
501 !this.state.showBanDialog &&
502 (!isBanned(pv.person) ? (
505 "d-flex align-self-start btn btn-secondary mr-2"
507 onClick={linkEvent(this, this.handleModBanShow)}
508 aria-label={i18n.t("ban")}
510 {capitalizeFirstLetter(i18n.t("ban"))}
515 "d-flex align-self-start btn btn-secondary mr-2"
517 onClick={linkEvent(this, this.handleModBanSubmit)}
518 aria-label={i18n.t("unban")}
520 {capitalizeFirstLetter(i18n.t("unban"))}
524 {pv.person.bio.match({
526 <div className="d-flex align-items-center mb-2">
529 dangerouslySetInnerHTML={mdToHtml(bio)}
536 <ul className="list-inline mb-2">
537 <li className="list-inline-item badge badge-light">
538 {i18n.t("number_of_posts", {
539 count: pv.counts.post_count,
540 formattedCount: numToSI(pv.counts.post_count),
543 <li className="list-inline-item badge badge-light">
544 {i18n.t("number_of_comments", {
545 count: pv.counts.comment_count,
546 formattedCount: numToSI(pv.counts.comment_count),
551 <div className="text-muted">
552 {i18n.t("joined")}{" "}
554 published={pv.person.published}
560 <div className="d-flex align-items-center text-muted mb-2">
562 <span className="ml-2">
563 {i18n.t("cake_day_title")}{" "}
565 .utc(pv.person.published)
567 .format("MMM DD, YYYY")}
579 return this.state.personRes
580 .map(r => r.person_view)
584 {this.state.showBanDialog && (
585 <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
586 <div className="form-group row col-12">
588 className="col-form-label"
589 htmlFor="profile-ban-reason"
595 id="profile-ban-reason"
596 className="form-control mr-2"
597 placeholder={i18n.t("reason")}
598 value={toUndefined(this.state.banReason)}
599 onInput={linkEvent(this, this.handleModBanReasonChange)}
601 <label className="col-form-label" htmlFor={`mod-ban-expires`}>
606 id={`mod-ban-expires`}
607 className="form-control mr-2"
608 placeholder={i18n.t("number_of_days")}
609 value={toUndefined(this.state.banExpireDays)}
610 onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
612 <div className="form-group">
613 <div className="form-check">
615 className="form-check-input"
616 id="mod-ban-remove-data"
618 checked={this.state.removeData}
621 this.handleModRemoveDataChange
625 className="form-check-label"
626 htmlFor="mod-ban-remove-data"
627 title={i18n.t("remove_content_more")}
629 {i18n.t("remove_content")}
634 {/* TODO hold off on expires until later */}
635 {/* <div class="form-group row"> */}
636 {/* <label class="col-form-label">Expires</label> */}
637 {/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
639 <div className="form-group row">
642 className="btn btn-secondary mr-2"
643 aria-label={i18n.t("cancel")}
644 onClick={linkEvent(this, this.handleModBanSubmitCancel)}
650 className="btn btn-secondary"
651 aria-label={i18n.t("ban")}
653 {i18n.t("ban")} {pv.person.name}
664 // TODO test this, make sure its good
666 return this.state.personRes
667 .map(r => r.moderates)
670 if (moderates.length > 0) {
671 <div className="card border-secondary mb-3">
672 <div className="card-body">
673 <h5>{i18n.t("moderates")}</h5>
674 <ul className="list-unstyled mb-0">
675 {moderates.map(cmv => (
676 <li key={cmv.community.id}>
677 <CommunityLink community={cmv.community} />
690 return UserService.Instance.myUserInfo
694 if (follows.length > 0) {
695 <div className="card border-secondary mb-3">
696 <div className="card-body">
697 <h5>{i18n.t("subscribed")}</h5>
698 <ul className="list-unstyled mb-0">
699 {follows.map(cfv => (
700 <li key={cfv.community.id}>
701 <CommunityLink community={cfv.community} />
713 updateUrl(paramUpdates: UrlParams) {
714 const page = paramUpdates.page || this.state.page;
715 const viewStr = paramUpdates.view || PersonDetailsView[this.state.view];
716 const sortStr = paramUpdates.sort || this.state.sort;
718 let typeView = `/u/${this.state.userName}`;
720 this.props.history.push(
721 `${typeView}/view/${viewStr}/sort/${sortStr}/page/${page}`
723 this.setState({ loading: true });
724 this.fetchUserData();
727 handlePageChange(page: number) {
728 this.updateUrl({ page: page });
731 handleSortChange(val: SortType) {
732 this.updateUrl({ sort: val, page: 1 });
735 handleViewChange(i: Profile, event: any) {
737 view: PersonDetailsView[Number(event.target.value)],
742 handleModBanShow(i: Profile) {
743 i.setState({ showBanDialog: true });
746 handleModBanReasonChange(i: Profile, event: any) {
747 i.setState({ banReason: event.target.value });
750 handleModBanExpireDaysChange(i: Profile, event: any) {
751 i.setState({ banExpireDays: event.target.value });
754 handleModRemoveDataChange(i: Profile, event: any) {
755 i.setState({ removeData: event.target.checked });
758 handleModBanSubmitCancel(i: Profile, event?: any) {
759 event.preventDefault();
760 i.setState({ showBanDialog: false });
763 handleModBanSubmit(i: Profile, event?: any) {
764 if (event) event.preventDefault();
767 .map(r => r.person_view.person)
770 // If its an unban, restore all their data
771 let ban = !person.banned;
773 i.setState({ removeData: false });
775 let form = new BanPerson({
776 person_id: person.id,
778 remove_data: Some(i.state.removeData),
779 reason: i.state.banReason,
780 expires: i.state.banExpireDays.map(futureDaysToUnixTime),
781 auth: auth().unwrap(),
783 WebSocketService.Instance.send(wsClient.banPerson(form));
785 i.setState({ showBanDialog: false });
791 parseMessage(msg: any) {
792 let op = wsUserOp(msg);
795 toast(i18n.t(msg.error), "danger");
796 if (msg.error == "couldnt_find_that_username_or_email") {
797 this.context.router.history.push("/");
800 } else if (msg.reconnect) {
801 this.fetchUserData();
802 } else if (op == UserOperation.GetPersonDetails) {
803 // Since the PersonDetails contains posts/comments as well as some general user info we listen here as well
804 // and set the parent state if it is not set or differs
805 // TODO this might need to get abstracted
806 let data = wsJsonToRes<GetPersonDetailsResponse>(
808 GetPersonDetailsResponse
810 this.setState({ personRes: Some(data), loading: false });
811 this.setPersonBlock();
812 restoreScrollPosition(this.context);
813 } else if (op == UserOperation.AddAdmin) {
814 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
815 this.setState(s => ((s.siteRes.admins = data.admins), s));
816 } else if (op == UserOperation.CreateCommentLike) {
817 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
818 createCommentLikeRes(
820 this.state.personRes.map(r => r.comments).unwrapOr([])
822 this.setState(this.state);
824 op == UserOperation.EditComment ||
825 op == UserOperation.DeleteComment ||
826 op == UserOperation.RemoveComment
828 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
831 this.state.personRes.map(r => r.comments).unwrapOr([])
833 this.setState(this.state);
834 } else if (op == UserOperation.CreateComment) {
835 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
836 UserService.Instance.myUserInfo.match({
838 if (data.comment_view.creator.id == mui.local_user_view.person.id) {
839 toast(i18n.t("reply_sent"));
844 } else if (op == UserOperation.SaveComment) {
845 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
848 this.state.personRes.map(r => r.comments).unwrapOr([])
850 this.setState(this.state);
852 op == UserOperation.EditPost ||
853 op == UserOperation.DeletePost ||
854 op == UserOperation.RemovePost ||
855 op == UserOperation.LockPost ||
856 op == UserOperation.StickyPost ||
857 op == UserOperation.SavePost
859 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
862 this.state.personRes.map(r => r.posts).unwrapOr([])
864 this.setState(this.state);
865 } else if (op == UserOperation.CreatePostLike) {
866 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
867 createPostLikeFindRes(
869 this.state.personRes.map(r => r.posts).unwrapOr([])
871 this.setState(this.state);
872 } else if (op == UserOperation.BanPerson) {
873 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
874 this.state.personRes.match({
877 .filter(c => c.creator.id == data.person_view.person.id)
878 .forEach(c => (c.creator.banned = data.banned));
880 .filter(c => c.creator.id == data.person_view.person.id)
881 .forEach(c => (c.creator.banned = data.banned));
882 let pv = res.person_view;
884 if (pv.person.id == data.person_view.person.id) {
885 pv.person.banned = data.banned;
887 this.setState(this.state);
891 } else if (op == UserOperation.BlockPerson) {
892 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
893 updatePersonBlock(data);
894 this.setPersonBlock();
895 this.setState(this.state);
897 op == UserOperation.PurgePerson ||
898 op == UserOperation.PurgePost ||
899 op == UserOperation.PurgeComment ||
900 op == UserOperation.PurgeCommunity
902 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
904 toast(i18n.t("purge_success"));
905 this.context.router.history.push(`/`);