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();
135 let form = new GetPersonDetails({
136 username: Some(this.state.userName),
139 sort: Some(this.state.sort),
140 saved_only: Some(this.state.view === PersonDetailsView.Saved),
141 page: Some(this.state.page),
142 limit: Some(fetchLimit),
143 auth: auth(false).ok(),
145 WebSocketService.Instance.send(wsClient.getPersonDetails(form));
148 get amCurrentUser() {
149 return UserService.Instance.myUserInfo.match({
151 this.state.personRes.match({
153 mui.local_user_view.person.id == res.person_view.person.id,
161 UserService.Instance.myUserInfo.match({
163 this.state.personRes.match({
166 personBlocked: mui.person_blocks
167 .map(a => a.target.id)
168 .includes(res.person_view.person.id),
176 static getViewFromProps(view: string): PersonDetailsView {
177 return view ? PersonDetailsView[view] : PersonDetailsView.Overview;
180 static getSortTypeFromProps(sort: string): SortType {
181 return sort ? routeSortTypeToEnum(sort) : SortType.New;
184 static getPageFromProps(page: number): number {
185 return page ? Number(page) : 1;
188 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
189 let pathSplit = req.path.split("/");
191 let username = pathSplit[2];
192 let view = this.getViewFromProps(pathSplit[4]);
193 let sort = Some(this.getSortTypeFromProps(pathSplit[6]));
194 let page = Some(this.getPageFromProps(Number(pathSplit[8])));
196 let form = new GetPersonDetails({
197 username: Some(username),
201 saved_only: Some(view === PersonDetailsView.Saved),
203 limit: Some(fetchLimit),
206 return [req.client.getPersonDetails(form)];
209 componentDidMount() {
210 this.setPersonBlock();
214 componentWillUnmount() {
215 this.subscription.unsubscribe();
216 saveScrollPosition(this.context);
219 static getDerivedStateFromProps(props: any): ProfileProps {
221 view: this.getViewFromProps(props.match.params.view),
222 sort: this.getSortTypeFromProps(props.match.params.sort),
223 page: this.getPageFromProps(props.match.params.page),
224 person_id: Number(props.match.params.id) || null,
225 username: props.match.params.username,
229 componentDidUpdate(lastProps: any) {
230 // Necessary if you are on a post and you click another post (same route)
232 lastProps.location.pathname.split("/")[2] !==
233 lastProps.history.location.pathname.split("/")[2]
235 // Couldnt get a refresh working. This does for now.
240 get documentTitle(): string {
241 return this.state.personRes.match({
243 `@${res.person_view.person.name} - ${this.state.siteRes.site_view.site.name}`,
250 <div className="container-lg">
251 {this.state.loading ? (
256 this.state.personRes.match({
258 <div className="row">
259 <div className="col-12 col-md-8">
262 title={this.documentTitle}
263 path={this.context.router.route.match.url}
264 description={res.person_view.person.bio}
265 image={res.person_view.person.avatar}
270 {!this.state.loading && this.selects()}
273 admins={this.state.siteRes.admins}
274 sort={this.state.sort}
275 page={this.state.page}
277 enableDownvotes={enableDownvotes(this.state.siteRes)}
278 enableNsfw={enableNsfw(this.state.siteRes)}
279 view={this.state.view}
280 onPageChange={this.handlePageChange}
281 allLanguages={this.state.siteRes.all_languages}
285 {!this.state.loading && (
286 <div className="col-12 col-md-4">
288 {this.amCurrentUser && this.follows()}
302 <div className="btn-group btn-group-toggle flex-wrap mb-2">
304 className={`btn btn-outline-secondary pointer
305 ${this.state.view == PersonDetailsView.Overview && "active"}
310 value={PersonDetailsView.Overview}
311 checked={this.state.view === PersonDetailsView.Overview}
312 onChange={linkEvent(this, this.handleViewChange)}
317 className={`btn btn-outline-secondary pointer
318 ${this.state.view == PersonDetailsView.Comments && "active"}
323 value={PersonDetailsView.Comments}
324 checked={this.state.view == PersonDetailsView.Comments}
325 onChange={linkEvent(this, this.handleViewChange)}
330 className={`btn btn-outline-secondary pointer
331 ${this.state.view == PersonDetailsView.Posts && "active"}
336 value={PersonDetailsView.Posts}
337 checked={this.state.view == PersonDetailsView.Posts}
338 onChange={linkEvent(this, this.handleViewChange)}
343 className={`btn btn-outline-secondary pointer
344 ${this.state.view == PersonDetailsView.Saved && "active"}
349 value={PersonDetailsView.Saved}
350 checked={this.state.view == PersonDetailsView.Saved}
351 onChange={linkEvent(this, this.handleViewChange)}
360 let profileRss = `/feeds/u/${this.state.userName}.xml?sort=${this.state.sort}`;
363 <div className="mb-2">
364 <span className="mr-3">{this.viewRadios()}</span>
366 sort={this.state.sort}
367 onChange={this.handleSortChange}
371 <a href={profileRss} rel={relTags} title="RSS">
372 <Icon icon="rss" classes="text-muted small mx-2" />
374 <link rel="alternate" type="application/atom+xml" href={profileRss} />
378 handleBlockPerson(personId: number) {
380 let blockUserForm = new BlockPerson({
383 auth: auth().unwrap(),
385 WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
388 handleUnblockPerson(recipientId: number) {
389 let blockUserForm = new BlockPerson({
390 person_id: recipientId,
392 auth: auth().unwrap(),
394 WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
398 return this.state.personRes
399 .map(r => r.person_view)
404 banner={pv.person.banner}
405 icon={pv.person.avatar}
407 <div className="mb-3">
409 <div className="mb-0 d-flex flex-wrap">
411 {pv.person.display_name.match({
412 some: displayName => (
413 <h5 className="mb-0">{displayName}</h5>
417 <ul className="list-inline mb-2">
418 <li className="list-inline-item">
427 {isBanned(pv.person) && (
428 <li className="list-inline-item badge badge-danger">
432 {pv.person.admin && (
433 <li className="list-inline-item badge badge-light">
437 {pv.person.bot_account && (
438 <li className="list-inline-item badge badge-light">
439 {i18n.t("bot_account").toLowerCase()}
445 <div className="flex-grow-1 unselectable pointer mx-2"></div>
446 {!this.amCurrentUser &&
447 UserService.Instance.myUserInfo.isSome() && (
450 className={`d-flex align-self-start btn btn-secondary mr-2 ${
451 !pv.person.matrix_user_id && "invisible"
454 href={`https://matrix.to/#/${pv.person.matrix_user_id}`}
456 {i18n.t("send_secure_message")}
460 "d-flex align-self-start btn btn-secondary mr-2"
462 to={`/create_private_message/recipient/${pv.person.id}`}
464 {i18n.t("send_message")}
466 {this.state.personBlocked ? (
469 "d-flex align-self-start btn btn-secondary mr-2"
473 this.handleUnblockPerson
476 {i18n.t("unblock_user")}
481 "d-flex align-self-start btn btn-secondary mr-2"
485 this.handleBlockPerson
488 {i18n.t("block_user")}
496 Some(this.state.siteRes.admins),
499 !isAdmin(Some(this.state.siteRes.admins), pv.person.id) &&
500 !this.state.showBanDialog &&
501 (!isBanned(pv.person) ? (
504 "d-flex align-self-start btn btn-secondary mr-2"
506 onClick={linkEvent(this, this.handleModBanShow)}
507 aria-label={i18n.t("ban")}
509 {capitalizeFirstLetter(i18n.t("ban"))}
514 "d-flex align-self-start btn btn-secondary mr-2"
516 onClick={linkEvent(this, this.handleModBanSubmit)}
517 aria-label={i18n.t("unban")}
519 {capitalizeFirstLetter(i18n.t("unban"))}
523 {pv.person.bio.match({
525 <div className="d-flex align-items-center mb-2">
528 dangerouslySetInnerHTML={mdToHtml(bio)}
535 <ul className="list-inline mb-2">
536 <li className="list-inline-item badge badge-light">
537 {i18n.t("number_of_posts", {
538 count: pv.counts.post_count,
539 formattedCount: numToSI(pv.counts.post_count),
542 <li className="list-inline-item badge badge-light">
543 {i18n.t("number_of_comments", {
544 count: pv.counts.comment_count,
545 formattedCount: numToSI(pv.counts.comment_count),
550 <div className="text-muted">
551 {i18n.t("joined")}{" "}
553 published={pv.person.published}
559 <div className="d-flex align-items-center text-muted mb-2">
561 <span className="ml-2">
562 {i18n.t("cake_day_title")}{" "}
564 .utc(pv.person.published)
566 .format("MMM DD, YYYY")}
578 return this.state.personRes
579 .map(r => r.person_view)
583 {this.state.showBanDialog && (
584 <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
585 <div className="form-group row col-12">
587 className="col-form-label"
588 htmlFor="profile-ban-reason"
594 id="profile-ban-reason"
595 className="form-control mr-2"
596 placeholder={i18n.t("reason")}
597 value={toUndefined(this.state.banReason)}
598 onInput={linkEvent(this, this.handleModBanReasonChange)}
600 <label className="col-form-label" htmlFor={`mod-ban-expires`}>
605 id={`mod-ban-expires`}
606 className="form-control mr-2"
607 placeholder={i18n.t("number_of_days")}
608 value={toUndefined(this.state.banExpireDays)}
609 onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
611 <div className="form-group">
612 <div className="form-check">
614 className="form-check-input"
615 id="mod-ban-remove-data"
617 checked={this.state.removeData}
620 this.handleModRemoveDataChange
624 className="form-check-label"
625 htmlFor="mod-ban-remove-data"
626 title={i18n.t("remove_content_more")}
628 {i18n.t("remove_content")}
633 {/* TODO hold off on expires until later */}
634 {/* <div class="form-group row"> */}
635 {/* <label class="col-form-label">Expires</label> */}
636 {/* <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
638 <div className="form-group row">
641 className="btn btn-secondary mr-2"
642 aria-label={i18n.t("cancel")}
643 onClick={linkEvent(this, this.handleModBanSubmitCancel)}
649 className="btn btn-secondary"
650 aria-label={i18n.t("ban")}
652 {i18n.t("ban")} {pv.person.name}
664 return this.state.personRes
665 .map(r => r.moderates)
668 if (moderates.length > 0) {
670 <div className="card border-secondary mb-3">
671 <div className="card-body">
672 <h5>{i18n.t("moderates")}</h5>
673 <ul className="list-unstyled mb-0">
674 {moderates.map(cmv => (
675 <li key={cmv.community.id}>
676 <CommunityLink community={cmv.community} />
692 return UserService.Instance.myUserInfo
696 if (follows.length > 0) {
698 <div className="card border-secondary mb-3">
699 <div className="card-body">
700 <h5>{i18n.t("subscribed")}</h5>
701 <ul className="list-unstyled mb-0">
702 {follows.map(cfv => (
703 <li key={cfv.community.id}>
704 <CommunityLink community={cfv.community} />
719 updateUrl(paramUpdates: UrlParams) {
720 const page = paramUpdates.page || this.state.page;
721 const viewStr = paramUpdates.view || PersonDetailsView[this.state.view];
722 const sortStr = paramUpdates.sort || this.state.sort;
724 let typeView = `/u/${this.state.userName}`;
726 this.props.history.push(
727 `${typeView}/view/${viewStr}/sort/${sortStr}/page/${page}`
729 this.setState({ loading: true });
730 this.fetchUserData();
733 handlePageChange(page: number) {
734 this.updateUrl({ page: page });
737 handleSortChange(val: SortType) {
738 this.updateUrl({ sort: val, page: 1 });
741 handleViewChange(i: Profile, event: any) {
743 view: PersonDetailsView[Number(event.target.value)],
748 handleModBanShow(i: Profile) {
749 i.setState({ showBanDialog: true });
752 handleModBanReasonChange(i: Profile, event: any) {
753 i.setState({ banReason: event.target.value });
756 handleModBanExpireDaysChange(i: Profile, event: any) {
757 i.setState({ banExpireDays: event.target.value });
760 handleModRemoveDataChange(i: Profile, event: any) {
761 i.setState({ removeData: event.target.checked });
764 handleModBanSubmitCancel(i: Profile, event?: any) {
765 event.preventDefault();
766 i.setState({ showBanDialog: false });
769 handleModBanSubmit(i: Profile, event?: any) {
770 if (event) event.preventDefault();
773 .map(r => r.person_view.person)
776 // If its an unban, restore all their data
777 let ban = !person.banned;
779 i.setState({ removeData: false });
781 let form = new BanPerson({
782 person_id: person.id,
784 remove_data: Some(i.state.removeData),
785 reason: i.state.banReason,
786 expires: i.state.banExpireDays.map(futureDaysToUnixTime),
787 auth: auth().unwrap(),
789 WebSocketService.Instance.send(wsClient.banPerson(form));
791 i.setState({ showBanDialog: false });
797 parseMessage(msg: any) {
798 let op = wsUserOp(msg);
801 toast(i18n.t(msg.error), "danger");
802 if (msg.error == "couldnt_find_that_username_or_email") {
803 this.context.router.history.push("/");
806 } else if (msg.reconnect) {
807 this.fetchUserData();
808 } else if (op == UserOperation.GetPersonDetails) {
809 // Since the PersonDetails contains posts/comments as well as some general user info we listen here as well
810 // and set the parent state if it is not set or differs
811 // TODO this might need to get abstracted
812 let data = wsJsonToRes<GetPersonDetailsResponse>(
814 GetPersonDetailsResponse
816 this.setState({ personRes: Some(data), loading: false });
817 this.setPersonBlock();
818 restoreScrollPosition(this.context);
819 } else if (op == UserOperation.AddAdmin) {
820 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
821 this.setState(s => ((s.siteRes.admins = data.admins), s));
822 } else if (op == UserOperation.CreateCommentLike) {
823 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
824 createCommentLikeRes(
826 this.state.personRes.map(r => r.comments).unwrapOr([])
828 this.setState(this.state);
830 op == UserOperation.EditComment ||
831 op == UserOperation.DeleteComment ||
832 op == UserOperation.RemoveComment
834 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
837 this.state.personRes.map(r => r.comments).unwrapOr([])
839 this.setState(this.state);
840 } else if (op == UserOperation.CreateComment) {
841 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
842 UserService.Instance.myUserInfo.match({
844 if (data.comment_view.creator.id == mui.local_user_view.person.id) {
845 toast(i18n.t("reply_sent"));
850 } else if (op == UserOperation.SaveComment) {
851 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
854 this.state.personRes.map(r => r.comments).unwrapOr([])
856 this.setState(this.state);
858 op == UserOperation.EditPost ||
859 op == UserOperation.DeletePost ||
860 op == UserOperation.RemovePost ||
861 op == UserOperation.LockPost ||
862 op == UserOperation.StickyPost ||
863 op == UserOperation.SavePost
865 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
868 this.state.personRes.map(r => r.posts).unwrapOr([])
870 this.setState(this.state);
871 } else if (op == UserOperation.CreatePostLike) {
872 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
873 createPostLikeFindRes(
875 this.state.personRes.map(r => r.posts).unwrapOr([])
877 this.setState(this.state);
878 } else if (op == UserOperation.BanPerson) {
879 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
880 this.state.personRes.match({
883 .filter(c => c.creator.id == data.person_view.person.id)
884 .forEach(c => (c.creator.banned = data.banned));
886 .filter(c => c.creator.id == data.person_view.person.id)
887 .forEach(c => (c.creator.banned = data.banned));
888 let pv = res.person_view;
890 if (pv.person.id == data.person_view.person.id) {
891 pv.person.banned = data.banned;
893 this.setState(this.state);
897 } else if (op == UserOperation.BlockPerson) {
898 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
899 updatePersonBlock(data);
900 this.setPersonBlock();
901 this.setState(this.state);
903 op == UserOperation.PurgePerson ||
904 op == UserOperation.PurgePost ||
905 op == UserOperation.PurgeComment ||
906 op == UserOperation.PurgeCommunity
908 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
910 toast(i18n.t("purge_success"));
911 this.context.router.history.push(`/`);