]> Untitled Git - lemmy-ui.git/blob - src/shared/components/person/profile.tsx
Merge branch 'main' into fix-nsfw-blur-spill
[lemmy-ui.git] / src / shared / components / person / profile.tsx
1 import classNames from "classnames";
2 import { NoOptionI18nKeys } from "i18next";
3 import { Component, linkEvent } from "inferno";
4 import { Link } from "inferno-router";
5 import { RouteComponentProps } from "inferno-router/dist/Route";
6 import {
7   AddAdmin,
8   AddModToCommunity,
9   BanFromCommunity,
10   BanFromCommunityResponse,
11   BanPerson,
12   BanPersonResponse,
13   BlockPerson,
14   CommentId,
15   CommentReplyResponse,
16   CommentResponse,
17   Community,
18   CommunityModeratorView,
19   CreateComment,
20   CreateCommentLike,
21   CreateCommentReport,
22   CreatePostLike,
23   CreatePostReport,
24   DeleteComment,
25   DeletePost,
26   DistinguishComment,
27   EditComment,
28   EditPost,
29   FeaturePost,
30   GetPersonDetails,
31   GetPersonDetailsResponse,
32   GetSiteResponse,
33   LockPost,
34   MarkCommentReplyAsRead,
35   MarkPersonMentionAsRead,
36   PersonView,
37   PostResponse,
38   PurgeComment,
39   PurgeItemResponse,
40   PurgePerson,
41   PurgePost,
42   RemoveComment,
43   RemovePost,
44   SaveComment,
45   SavePost,
46   SortType,
47   TransferCommunity,
48 } from "lemmy-js-client";
49 import moment from "moment";
50 import { i18n } from "../../i18next";
51 import { InitialFetchRequest, PersonDetailsView } from "../../interfaces";
52 import { UserService } from "../../services";
53 import { FirstLoadService } from "../../services/FirstLoadService";
54 import { HttpService, RequestState } from "../../services/HttpService";
55 import {
56   QueryParams,
57   RouteDataResponse,
58   canMod,
59   capitalizeFirstLetter,
60   editComment,
61   editPost,
62   editWith,
63   enableDownvotes,
64   enableNsfw,
65   fetchLimit,
66   futureDaysToUnixTime,
67   getCommentParentId,
68   getPageFromString,
69   getQueryParams,
70   getQueryString,
71   isAdmin,
72   isBanned,
73   mdToHtml,
74   myAuth,
75   myAuthRequired,
76   numToSI,
77   relTags,
78   restoreScrollPosition,
79   saveScrollPosition,
80   setIsoData,
81   setupTippy,
82   toast,
83   updatePersonBlock,
84 } from "../../utils";
85 import { BannerIconHeader } from "../common/banner-icon-header";
86 import { HtmlTags } from "../common/html-tags";
87 import { Icon, Spinner } from "../common/icon";
88 import { MomentTime } from "../common/moment-time";
89 import { SortSelect } from "../common/sort-select";
90 import { CommunityLink } from "../community/community-link";
91 import { PersonDetails } from "./person-details";
92 import { PersonListing } from "./person-listing";
93
94 type ProfileData = RouteDataResponse<{
95   personResponse: GetPersonDetailsResponse;
96 }>;
97
98 interface ProfileState {
99   personRes: RequestState<GetPersonDetailsResponse>;
100   personBlocked: boolean;
101   banReason?: string;
102   banExpireDays?: number;
103   showBanDialog: boolean;
104   removeData: boolean;
105   siteRes: GetSiteResponse;
106   finished: Map<CommentId, boolean | undefined>;
107   isIsomorphic: boolean;
108 }
109
110 interface ProfileProps {
111   view: PersonDetailsView;
112   sort: SortType;
113   page: number;
114 }
115
116 function getProfileQueryParams() {
117   return getQueryParams<ProfileProps>({
118     view: getViewFromProps,
119     page: getPageFromString,
120     sort: getSortTypeFromQuery,
121   });
122 }
123
124 function getSortTypeFromQuery(sort?: string): SortType {
125   return sort ? (sort as SortType) : "New";
126 }
127
128 function getViewFromProps(view?: string): PersonDetailsView {
129   return view
130     ? PersonDetailsView[view] ?? PersonDetailsView.Overview
131     : PersonDetailsView.Overview;
132 }
133
134 const getCommunitiesListing = (
135   translationKey: NoOptionI18nKeys,
136   communityViews?: { community: Community }[]
137 ) =>
138   communityViews &&
139   communityViews.length > 0 && (
140     <div className="card border-secondary mb-3">
141       <div className="card-body">
142         <h5>{i18n.t(translationKey)}</h5>
143         <ul className="list-unstyled mb-0">
144           {communityViews.map(({ community }) => (
145             <li key={community.id}>
146               <CommunityLink community={community} />
147             </li>
148           ))}
149         </ul>
150       </div>
151     </div>
152   );
153
154 const Moderates = ({ moderates }: { moderates?: CommunityModeratorView[] }) =>
155   getCommunitiesListing("moderates", moderates);
156
157 const Follows = () =>
158   getCommunitiesListing("subscribed", UserService.Instance.myUserInfo?.follows);
159
160 export class Profile extends Component<
161   RouteComponentProps<{ username: string }>,
162   ProfileState
163 > {
164   private isoData = setIsoData<ProfileData>(this.context);
165   state: ProfileState = {
166     personRes: { state: "empty" },
167     personBlocked: false,
168     siteRes: this.isoData.site_res,
169     showBanDialog: false,
170     removeData: false,
171     finished: new Map(),
172     isIsomorphic: false,
173   };
174
175   constructor(props: RouteComponentProps<{ username: string }>, context: any) {
176     super(props, context);
177
178     this.handleSortChange = this.handleSortChange.bind(this);
179     this.handlePageChange = this.handlePageChange.bind(this);
180
181     this.handleBlockPerson = this.handleBlockPerson.bind(this);
182     this.handleUnblockPerson = this.handleUnblockPerson.bind(this);
183
184     this.handleCreateComment = this.handleCreateComment.bind(this);
185     this.handleEditComment = this.handleEditComment.bind(this);
186     this.handleSaveComment = this.handleSaveComment.bind(this);
187     this.handleBlockPersonAlt = this.handleBlockPersonAlt.bind(this);
188     this.handleDeleteComment = this.handleDeleteComment.bind(this);
189     this.handleRemoveComment = this.handleRemoveComment.bind(this);
190     this.handleCommentVote = this.handleCommentVote.bind(this);
191     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
192     this.handleAddAdmin = this.handleAddAdmin.bind(this);
193     this.handlePurgePerson = this.handlePurgePerson.bind(this);
194     this.handlePurgeComment = this.handlePurgeComment.bind(this);
195     this.handleCommentReport = this.handleCommentReport.bind(this);
196     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
197     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
198     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
199     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
200     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
201     this.handleBanPerson = this.handleBanPerson.bind(this);
202     this.handlePostVote = this.handlePostVote.bind(this);
203     this.handlePostEdit = this.handlePostEdit.bind(this);
204     this.handlePostReport = this.handlePostReport.bind(this);
205     this.handleLockPost = this.handleLockPost.bind(this);
206     this.handleDeletePost = this.handleDeletePost.bind(this);
207     this.handleRemovePost = this.handleRemovePost.bind(this);
208     this.handleSavePost = this.handleSavePost.bind(this);
209     this.handlePurgePost = this.handlePurgePost.bind(this);
210     this.handleFeaturePost = this.handleFeaturePost.bind(this);
211
212     // Only fetch the data if coming from another route
213     if (FirstLoadService.isFirstLoad) {
214       this.state = {
215         ...this.state,
216         personRes: this.isoData.routeData.personResponse,
217         isIsomorphic: true,
218       };
219     }
220   }
221
222   async componentDidMount() {
223     if (!this.state.isIsomorphic) {
224       await this.fetchUserData();
225     }
226     setupTippy();
227   }
228
229   componentWillUnmount() {
230     saveScrollPosition(this.context);
231   }
232
233   async fetchUserData() {
234     const { page, sort, view } = getProfileQueryParams();
235
236     this.setState({ personRes: { state: "empty" } });
237     this.setState({
238       personRes: await HttpService.client.getPersonDetails({
239         username: this.props.match.params.username,
240         sort,
241         saved_only: view === PersonDetailsView.Saved,
242         page,
243         limit: fetchLimit,
244         auth: myAuth(),
245       }),
246     });
247     restoreScrollPosition(this.context);
248     this.setPersonBlock();
249   }
250
251   get amCurrentUser() {
252     if (this.state.personRes.state === "success") {
253       return (
254         UserService.Instance.myUserInfo?.local_user_view.person.id ===
255         this.state.personRes.data.person_view.person.id
256       );
257     } else {
258       return false;
259     }
260   }
261
262   setPersonBlock() {
263     const mui = UserService.Instance.myUserInfo;
264     const res = this.state.personRes;
265
266     if (mui && res.state === "success") {
267       this.setState({
268         personBlocked: mui.person_blocks.some(
269           ({ target: { id } }) => id === res.data.person_view.person.id
270         ),
271       });
272     }
273   }
274
275   static async fetchInitialData({
276     client,
277     path,
278     query: { page, sort, view: urlView },
279     auth,
280   }: InitialFetchRequest<QueryParams<ProfileProps>>): Promise<ProfileData> {
281     const pathSplit = path.split("/");
282
283     const username = pathSplit[2];
284     const view = getViewFromProps(urlView);
285
286     const form: GetPersonDetails = {
287       username: username,
288       sort: getSortTypeFromQuery(sort),
289       saved_only: view === PersonDetailsView.Saved,
290       page: getPageFromString(page),
291       limit: fetchLimit,
292       auth,
293     };
294
295     return {
296       personResponse: await client.getPersonDetails(form),
297     };
298   }
299
300   get documentTitle(): string {
301     const siteName = this.state.siteRes.site_view.site.name;
302     const res = this.state.personRes;
303     return res.state == "success"
304       ? `@${res.data.person_view.person.name} - ${siteName}`
305       : siteName;
306   }
307
308   renderPersonRes() {
309     switch (this.state.personRes.state) {
310       case "loading":
311         return (
312           <h5>
313             <Spinner large />
314           </h5>
315         );
316       case "success": {
317         const siteRes = this.state.siteRes;
318         const personRes = this.state.personRes.data;
319         const { page, sort, view } = getProfileQueryParams();
320
321         return (
322           <div className="row">
323             <div className="col-12 col-md-8">
324               <HtmlTags
325                 title={this.documentTitle}
326                 path={this.context.router.route.match.url}
327                 description={personRes.person_view.person.bio}
328                 image={personRes.person_view.person.avatar}
329               />
330
331               {this.userInfo(personRes.person_view)}
332
333               <hr />
334
335               {this.selects}
336
337               <PersonDetails
338                 personRes={personRes}
339                 admins={siteRes.admins}
340                 sort={sort}
341                 page={page}
342                 limit={fetchLimit}
343                 finished={this.state.finished}
344                 enableDownvotes={enableDownvotes(siteRes)}
345                 enableNsfw={enableNsfw(siteRes)}
346                 view={view}
347                 onPageChange={this.handlePageChange}
348                 allLanguages={siteRes.all_languages}
349                 siteLanguages={siteRes.discussion_languages}
350                 // TODO all the forms here
351                 onSaveComment={this.handleSaveComment}
352                 onBlockPerson={this.handleBlockPersonAlt}
353                 onDeleteComment={this.handleDeleteComment}
354                 onRemoveComment={this.handleRemoveComment}
355                 onCommentVote={this.handleCommentVote}
356                 onCommentReport={this.handleCommentReport}
357                 onDistinguishComment={this.handleDistinguishComment}
358                 onAddModToCommunity={this.handleAddModToCommunity}
359                 onAddAdmin={this.handleAddAdmin}
360                 onTransferCommunity={this.handleTransferCommunity}
361                 onPurgeComment={this.handlePurgeComment}
362                 onPurgePerson={this.handlePurgePerson}
363                 onCommentReplyRead={this.handleCommentReplyRead}
364                 onPersonMentionRead={this.handlePersonMentionRead}
365                 onBanPersonFromCommunity={this.handleBanFromCommunity}
366                 onBanPerson={this.handleBanPerson}
367                 onCreateComment={this.handleCreateComment}
368                 onEditComment={this.handleEditComment}
369                 onPostEdit={this.handlePostEdit}
370                 onPostVote={this.handlePostVote}
371                 onPostReport={this.handlePostReport}
372                 onLockPost={this.handleLockPost}
373                 onDeletePost={this.handleDeletePost}
374                 onRemovePost={this.handleRemovePost}
375                 onSavePost={this.handleSavePost}
376                 onPurgePost={this.handlePurgePost}
377                 onFeaturePost={this.handleFeaturePost}
378               />
379             </div>
380
381             <div className="col-12 col-md-4">
382               <Moderates moderates={personRes.moderates} />
383               {this.amCurrentUser && <Follows />}
384             </div>
385           </div>
386         );
387       }
388     }
389   }
390
391   render() {
392     return <div className="container-lg">{this.renderPersonRes()}</div>;
393   }
394
395   get viewRadios() {
396     return (
397       <div className="btn-group btn-group-toggle flex-wrap mb-2">
398         {this.getRadio(PersonDetailsView.Overview)}
399         {this.getRadio(PersonDetailsView.Comments)}
400         {this.getRadio(PersonDetailsView.Posts)}
401         {this.amCurrentUser && this.getRadio(PersonDetailsView.Saved)}
402       </div>
403     );
404   }
405
406   getRadio(view: PersonDetailsView) {
407     const { view: urlView } = getProfileQueryParams();
408     const active = view === urlView;
409
410     return (
411       <label
412         className={classNames("btn btn-outline-secondary pointer", {
413           active,
414         })}
415       >
416         <input
417           type="radio"
418           value={view}
419           checked={active}
420           onChange={linkEvent(this, this.handleViewChange)}
421         />
422         {i18n.t(view.toLowerCase() as NoOptionI18nKeys)}
423       </label>
424     );
425   }
426
427   get selects() {
428     const { sort } = getProfileQueryParams();
429     const { username } = this.props.match.params;
430
431     const profileRss = `/feeds/u/${username}.xml?sort=${sort}`;
432
433     return (
434       <div className="mb-2">
435         <span className="mr-3">{this.viewRadios}</span>
436         <SortSelect
437           sort={sort}
438           onChange={this.handleSortChange}
439           hideHot
440           hideMostComments
441         />
442         <a href={profileRss} rel={relTags} title="RSS">
443           <Icon icon="rss" classes="text-muted small mx-2" />
444         </a>
445         <link rel="alternate" type="application/atom+xml" href={profileRss} />
446       </div>
447     );
448   }
449
450   userInfo(pv: PersonView) {
451     const {
452       personBlocked,
453       siteRes: { admins },
454       showBanDialog,
455     } = this.state;
456
457     return (
458       pv && (
459         <div>
460           {!isBanned(pv.person) && (
461             <BannerIconHeader
462               banner={pv.person.banner}
463               icon={pv.person.avatar}
464             />
465           )}
466           <div className="mb-3">
467             <div className="">
468               <div className="mb-0 d-flex flex-wrap">
469                 <div>
470                   {pv.person.display_name && (
471                     <h5 className="mb-0">{pv.person.display_name}</h5>
472                   )}
473                   <ul className="list-inline mb-2">
474                     <li className="list-inline-item">
475                       <PersonListing
476                         person={pv.person}
477                         realLink
478                         useApubName
479                         muted
480                         hideAvatar
481                       />
482                     </li>
483                     {isBanned(pv.person) && (
484                       <li className="list-inline-item badge badge-danger">
485                         {i18n.t("banned")}
486                       </li>
487                     )}
488                     {pv.person.deleted && (
489                       <li className="list-inline-item badge badge-danger">
490                         {i18n.t("deleted")}
491                       </li>
492                     )}
493                     {pv.person.admin && (
494                       <li className="list-inline-item badge badge-light">
495                         {i18n.t("admin")}
496                       </li>
497                     )}
498                     {pv.person.bot_account && (
499                       <li className="list-inline-item badge badge-light">
500                         {i18n.t("bot_account").toLowerCase()}
501                       </li>
502                     )}
503                   </ul>
504                 </div>
505                 {this.banDialog(pv)}
506                 <div className="flex-grow-1 unselectable pointer mx-2"></div>
507                 {!this.amCurrentUser && UserService.Instance.myUserInfo && (
508                   <>
509                     <a
510                       className={`d-flex align-self-start btn btn-secondary mr-2 ${
511                         !pv.person.matrix_user_id && "invisible"
512                       }`}
513                       rel={relTags}
514                       href={`https://matrix.to/#/${pv.person.matrix_user_id}`}
515                     >
516                       {i18n.t("send_secure_message")}
517                     </a>
518                     <Link
519                       className={
520                         "d-flex align-self-start btn btn-secondary mr-2"
521                       }
522                       to={`/create_private_message/${pv.person.id}`}
523                     >
524                       {i18n.t("send_message")}
525                     </Link>
526                     {personBlocked ? (
527                       <button
528                         className={
529                           "d-flex align-self-start btn btn-secondary mr-2"
530                         }
531                         onClick={linkEvent(
532                           pv.person.id,
533                           this.handleUnblockPerson
534                         )}
535                       >
536                         {i18n.t("unblock_user")}
537                       </button>
538                     ) : (
539                       <button
540                         className={
541                           "d-flex align-self-start btn btn-secondary mr-2"
542                         }
543                         onClick={linkEvent(
544                           pv.person.id,
545                           this.handleBlockPerson
546                         )}
547                       >
548                         {i18n.t("block_user")}
549                       </button>
550                     )}
551                   </>
552                 )}
553
554                 {canMod(pv.person.id, undefined, admins) &&
555                   !isAdmin(pv.person.id, admins) &&
556                   !showBanDialog &&
557                   (!isBanned(pv.person) ? (
558                     <button
559                       className={
560                         "d-flex align-self-start btn btn-secondary mr-2"
561                       }
562                       onClick={linkEvent(this, this.handleModBanShow)}
563                       aria-label={i18n.t("ban")}
564                     >
565                       {capitalizeFirstLetter(i18n.t("ban"))}
566                     </button>
567                   ) : (
568                     <button
569                       className={
570                         "d-flex align-self-start btn btn-secondary mr-2"
571                       }
572                       onClick={linkEvent(this, this.handleModBanSubmit)}
573                       aria-label={i18n.t("unban")}
574                     >
575                       {capitalizeFirstLetter(i18n.t("unban"))}
576                     </button>
577                   ))}
578               </div>
579               {pv.person.bio && (
580                 <div className="d-flex align-items-center mb-2">
581                   <div
582                     className="md-div"
583                     dangerouslySetInnerHTML={mdToHtml(pv.person.bio)}
584                   />
585                 </div>
586               )}
587               <div>
588                 <ul className="list-inline mb-2">
589                   <li className="list-inline-item badge badge-light">
590                     {i18n.t("number_of_posts", {
591                       count: Number(pv.counts.post_count),
592                       formattedCount: numToSI(pv.counts.post_count),
593                     })}
594                   </li>
595                   <li className="list-inline-item badge badge-light">
596                     {i18n.t("number_of_comments", {
597                       count: Number(pv.counts.comment_count),
598                       formattedCount: numToSI(pv.counts.comment_count),
599                     })}
600                   </li>
601                 </ul>
602               </div>
603               <div className="text-muted">
604                 {i18n.t("joined")}{" "}
605                 <MomentTime
606                   published={pv.person.published}
607                   showAgo
608                   ignoreUpdated
609                 />
610               </div>
611               <div className="d-flex align-items-center text-muted mb-2">
612                 <Icon icon="cake" />
613                 <span className="ml-2">
614                   {i18n.t("cake_day_title")}{" "}
615                   {moment
616                     .utc(pv.person.published)
617                     .local()
618                     .format("MMM DD, YYYY")}
619                 </span>
620               </div>
621               {!UserService.Instance.myUserInfo && (
622                 <div className="alert alert-info" role="alert">
623                   {i18n.t("profile_not_logged_in_alert")}
624                 </div>
625               )}
626             </div>
627           </div>
628         </div>
629       )
630     );
631   }
632
633   banDialog(pv: PersonView) {
634     const { showBanDialog } = this.state;
635
636     return (
637       showBanDialog && (
638         <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
639           <div className="form-group row col-12">
640             <label className="col-form-label" htmlFor="profile-ban-reason">
641               {i18n.t("reason")}
642             </label>
643             <input
644               type="text"
645               id="profile-ban-reason"
646               className="form-control mr-2"
647               placeholder={i18n.t("reason")}
648               value={this.state.banReason}
649               onInput={linkEvent(this, this.handleModBanReasonChange)}
650             />
651             <label className="col-form-label" htmlFor={`mod-ban-expires`}>
652               {i18n.t("expires")}
653             </label>
654             <input
655               type="number"
656               id={`mod-ban-expires`}
657               className="form-control mr-2"
658               placeholder={i18n.t("number_of_days")}
659               value={this.state.banExpireDays}
660               onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
661             />
662             <div className="form-group">
663               <div className="form-check">
664                 <input
665                   className="form-check-input"
666                   id="mod-ban-remove-data"
667                   type="checkbox"
668                   checked={this.state.removeData}
669                   onChange={linkEvent(this, this.handleModRemoveDataChange)}
670                 />
671                 <label
672                   className="form-check-label"
673                   htmlFor="mod-ban-remove-data"
674                   title={i18n.t("remove_content_more")}
675                 >
676                   {i18n.t("remove_content")}
677                 </label>
678               </div>
679             </div>
680           </div>
681           {/* TODO hold off on expires until later */}
682           {/* <div class="form-group row"> */}
683           {/*   <label class="col-form-label">Expires</label> */}
684           {/*   <input type="date" class="form-control mr-2" placeholder={i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
685           {/* </div> */}
686           <div className="form-group row">
687             <button
688               type="reset"
689               className="btn btn-secondary mr-2"
690               aria-label={i18n.t("cancel")}
691               onClick={linkEvent(this, this.handleModBanSubmitCancel)}
692             >
693               {i18n.t("cancel")}
694             </button>
695             <button
696               type="submit"
697               className="btn btn-secondary"
698               aria-label={i18n.t("ban")}
699             >
700               {i18n.t("ban")} {pv.person.name}
701             </button>
702           </div>
703         </form>
704       )
705     );
706   }
707
708   async updateUrl({ page, sort, view }: Partial<ProfileProps>) {
709     const {
710       page: urlPage,
711       sort: urlSort,
712       view: urlView,
713     } = getProfileQueryParams();
714
715     const queryParams: QueryParams<ProfileProps> = {
716       page: (page ?? urlPage).toString(),
717       sort: sort ?? urlSort,
718       view: view ?? urlView,
719     };
720
721     const { username } = this.props.match.params;
722
723     this.props.history.push(`/u/${username}${getQueryString(queryParams)}`);
724     await this.fetchUserData();
725   }
726
727   handlePageChange(page: number) {
728     this.updateUrl({ page });
729   }
730
731   handleSortChange(sort: SortType) {
732     this.updateUrl({ sort, page: 1 });
733   }
734
735   handleViewChange(i: Profile, event: any) {
736     i.updateUrl({
737       view: PersonDetailsView[event.target.value],
738       page: 1,
739     });
740   }
741
742   handleModBanShow(i: Profile) {
743     i.setState({ showBanDialog: true });
744   }
745
746   handleModBanReasonChange(i: Profile, event: any) {
747     i.setState({ banReason: event.target.value });
748   }
749
750   handleModBanExpireDaysChange(i: Profile, event: any) {
751     i.setState({ banExpireDays: event.target.value });
752   }
753
754   handleModRemoveDataChange(i: Profile, event: any) {
755     i.setState({ removeData: event.target.checked });
756   }
757
758   handleModBanSubmitCancel(i: Profile) {
759     i.setState({ showBanDialog: false });
760   }
761
762   async handleModBanSubmit(i: Profile, event: any) {
763     event.preventDefault();
764     const { removeData, banReason, banExpireDays } = i.state;
765
766     const personRes = i.state.personRes;
767
768     if (personRes.state == "success") {
769       const person = personRes.data.person_view.person;
770       const ban = !person.banned;
771
772       // If its an unban, restore all their data
773       if (!ban) {
774         i.setState({ removeData: false });
775       }
776
777       const res = await HttpService.client.banPerson({
778         person_id: person.id,
779         ban,
780         remove_data: removeData,
781         reason: banReason,
782         expires: futureDaysToUnixTime(banExpireDays),
783         auth: myAuthRequired(),
784       });
785       // TODO
786       this.updateBan(res);
787       i.setState({ showBanDialog: false });
788     }
789   }
790
791   async toggleBlockPerson(recipientId: number, block: boolean) {
792     const res = await HttpService.client.blockPerson({
793       person_id: recipientId,
794       block,
795       auth: myAuthRequired(),
796     });
797     if (res.state == "success") {
798       updatePersonBlock(res.data);
799     }
800   }
801
802   handleUnblockPerson(personId: number) {
803     this.toggleBlockPerson(personId, false);
804   }
805
806   handleBlockPerson(personId: number) {
807     this.toggleBlockPerson(personId, true);
808   }
809
810   async handleAddModToCommunity(form: AddModToCommunity) {
811     // TODO not sure what to do here
812     await HttpService.client.addModToCommunity(form);
813   }
814
815   async handlePurgePerson(form: PurgePerson) {
816     const purgePersonRes = await HttpService.client.purgePerson(form);
817     this.purgeItem(purgePersonRes);
818   }
819
820   async handlePurgeComment(form: PurgeComment) {
821     const purgeCommentRes = await HttpService.client.purgeComment(form);
822     this.purgeItem(purgeCommentRes);
823   }
824
825   async handlePurgePost(form: PurgePost) {
826     const purgeRes = await HttpService.client.purgePost(form);
827     this.purgeItem(purgeRes);
828   }
829
830   async handleBlockPersonAlt(form: BlockPerson) {
831     const blockPersonRes = await HttpService.client.blockPerson(form);
832     if (blockPersonRes.state === "success") {
833       updatePersonBlock(blockPersonRes.data);
834     }
835   }
836
837   async handleCreateComment(form: CreateComment) {
838     const createCommentRes = await HttpService.client.createComment(form);
839     this.createAndUpdateComments(createCommentRes);
840
841     return createCommentRes;
842   }
843
844   async handleEditComment(form: EditComment) {
845     const editCommentRes = await HttpService.client.editComment(form);
846     this.findAndUpdateComment(editCommentRes);
847
848     return editCommentRes;
849   }
850
851   async handleDeleteComment(form: DeleteComment) {
852     const deleteCommentRes = await HttpService.client.deleteComment(form);
853     this.findAndUpdateComment(deleteCommentRes);
854   }
855
856   async handleDeletePost(form: DeletePost) {
857     const deleteRes = await HttpService.client.deletePost(form);
858     this.findAndUpdatePost(deleteRes);
859   }
860
861   async handleRemovePost(form: RemovePost) {
862     const removeRes = await HttpService.client.removePost(form);
863     this.findAndUpdatePost(removeRes);
864   }
865
866   async handleRemoveComment(form: RemoveComment) {
867     const removeCommentRes = await HttpService.client.removeComment(form);
868     this.findAndUpdateComment(removeCommentRes);
869   }
870
871   async handleSaveComment(form: SaveComment) {
872     const saveCommentRes = await HttpService.client.saveComment(form);
873     this.findAndUpdateComment(saveCommentRes);
874   }
875
876   async handleSavePost(form: SavePost) {
877     const saveRes = await HttpService.client.savePost(form);
878     this.findAndUpdatePost(saveRes);
879   }
880
881   async handleFeaturePost(form: FeaturePost) {
882     const featureRes = await HttpService.client.featurePost(form);
883     this.findAndUpdatePost(featureRes);
884   }
885
886   async handleCommentVote(form: CreateCommentLike) {
887     const voteRes = await HttpService.client.likeComment(form);
888     this.findAndUpdateComment(voteRes);
889   }
890
891   async handlePostVote(form: CreatePostLike) {
892     const voteRes = await HttpService.client.likePost(form);
893     this.findAndUpdatePost(voteRes);
894   }
895
896   async handlePostEdit(form: EditPost) {
897     const res = await HttpService.client.editPost(form);
898     this.findAndUpdatePost(res);
899   }
900
901   async handleCommentReport(form: CreateCommentReport) {
902     const reportRes = await HttpService.client.createCommentReport(form);
903     if (reportRes.state === "success") {
904       toast(i18n.t("report_created"));
905     }
906   }
907
908   async handlePostReport(form: CreatePostReport) {
909     const reportRes = await HttpService.client.createPostReport(form);
910     if (reportRes.state === "success") {
911       toast(i18n.t("report_created"));
912     }
913   }
914
915   async handleLockPost(form: LockPost) {
916     const lockRes = await HttpService.client.lockPost(form);
917     this.findAndUpdatePost(lockRes);
918   }
919
920   async handleDistinguishComment(form: DistinguishComment) {
921     const distinguishRes = await HttpService.client.distinguishComment(form);
922     this.findAndUpdateComment(distinguishRes);
923   }
924
925   async handleAddAdmin(form: AddAdmin) {
926     const addAdminRes = await HttpService.client.addAdmin(form);
927
928     if (addAdminRes.state == "success") {
929       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
930     }
931   }
932
933   async handleTransferCommunity(form: TransferCommunity) {
934     await HttpService.client.transferCommunity(form);
935     toast(i18n.t("transfer_community"));
936   }
937
938   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
939     const readRes = await HttpService.client.markCommentReplyAsRead(form);
940     this.findAndUpdateCommentReply(readRes);
941   }
942
943   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
944     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
945     await HttpService.client.markPersonMentionAsRead(form);
946   }
947
948   async handleBanFromCommunity(form: BanFromCommunity) {
949     const banRes = await HttpService.client.banFromCommunity(form);
950     this.updateBanFromCommunity(banRes);
951   }
952
953   async handleBanPerson(form: BanPerson) {
954     const banRes = await HttpService.client.banPerson(form);
955     this.updateBan(banRes);
956   }
957
958   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
959     // Maybe not necessary
960     if (banRes.state === "success") {
961       this.setState(s => {
962         if (s.personRes.state == "success") {
963           s.personRes.data.posts
964             .filter(c => c.creator.id === banRes.data.person_view.person.id)
965             .forEach(
966               c => (c.creator_banned_from_community = banRes.data.banned)
967             );
968
969           s.personRes.data.comments
970             .filter(c => c.creator.id === banRes.data.person_view.person.id)
971             .forEach(
972               c => (c.creator_banned_from_community = banRes.data.banned)
973             );
974         }
975         return s;
976       });
977     }
978   }
979
980   updateBan(banRes: RequestState<BanPersonResponse>) {
981     // Maybe not necessary
982     if (banRes.state == "success") {
983       this.setState(s => {
984         if (s.personRes.state == "success") {
985           s.personRes.data.posts
986             .filter(c => c.creator.id == banRes.data.person_view.person.id)
987             .forEach(c => (c.creator.banned = banRes.data.banned));
988           s.personRes.data.comments
989             .filter(c => c.creator.id == banRes.data.person_view.person.id)
990             .forEach(c => (c.creator.banned = banRes.data.banned));
991         }
992         return s;
993       });
994     }
995   }
996
997   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
998     if (purgeRes.state == "success") {
999       toast(i18n.t("purge_success"));
1000       this.context.router.history.push(`/`);
1001     }
1002   }
1003
1004   findAndUpdateComment(res: RequestState<CommentResponse>) {
1005     this.setState(s => {
1006       if (s.personRes.state == "success" && res.state == "success") {
1007         s.personRes.data.comments = editComment(
1008           res.data.comment_view,
1009           s.personRes.data.comments
1010         );
1011         s.finished.set(res.data.comment_view.comment.id, true);
1012       }
1013       return s;
1014     });
1015   }
1016
1017   createAndUpdateComments(res: RequestState<CommentResponse>) {
1018     this.setState(s => {
1019       if (s.personRes.state == "success" && res.state == "success") {
1020         s.personRes.data.comments.unshift(res.data.comment_view);
1021         // Set finished for the parent
1022         s.finished.set(
1023           getCommentParentId(res.data.comment_view.comment) ?? 0,
1024           true
1025         );
1026       }
1027       return s;
1028     });
1029   }
1030
1031   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1032     this.setState(s => {
1033       if (s.personRes.state == "success" && res.state == "success") {
1034         s.personRes.data.comments = editWith(
1035           res.data.comment_reply_view,
1036           s.personRes.data.comments
1037         );
1038       }
1039       return s;
1040     });
1041   }
1042
1043   findAndUpdatePost(res: RequestState<PostResponse>) {
1044     this.setState(s => {
1045       if (s.personRes.state == "success" && res.state == "success") {
1046         s.personRes.data.posts = editPost(
1047           res.data.post_view,
1048           s.personRes.data.posts
1049         );
1050       }
1051       return s;
1052     });
1053   }
1054 }