]> Untitled Git - lemmy.git/blob - ui/src/components/user.tsx
Merge remote-tracking branch 'weblate/main' into main
[lemmy.git] / ui / src / components / user.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Link } from 'inferno-router';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import {
6   UserOperation,
7   CommunityUser,
8   SortType,
9   ListingType,
10   UserView,
11   UserSettingsForm,
12   LoginResponse,
13   DeleteAccountForm,
14   WebSocketJsonResponse,
15   GetSiteResponse,
16   UserDetailsView,
17   UserDetailsResponse,
18   AddAdminResponse,
19 } from '../interfaces';
20 import { WebSocketService, UserService } from '../services';
21 import {
22   wsJsonToRes,
23   fetchLimit,
24   routeSortTypeToEnum,
25   capitalizeFirstLetter,
26   themes,
27   setTheme,
28   languages,
29   showAvatars,
30   toast,
31   setupTippy,
32 } from '../utils';
33 import { UserListing } from './user-listing';
34 import { SortSelect } from './sort-select';
35 import { ListingTypeSelect } from './listing-type-select';
36 import { MomentTime } from './moment-time';
37 import { i18n } from '../i18next';
38 import moment from 'moment';
39 import { UserDetails } from './user-details';
40
41 interface UserState {
42   user: UserView;
43   user_id: number;
44   username: string;
45   follows: Array<CommunityUser>;
46   moderates: Array<CommunityUser>;
47   view: UserDetailsView;
48   sort: SortType;
49   page: number;
50   loading: boolean;
51   avatarLoading: boolean;
52   userSettingsForm: UserSettingsForm;
53   userSettingsLoading: boolean;
54   deleteAccountLoading: boolean;
55   deleteAccountShowConfirm: boolean;
56   deleteAccountForm: DeleteAccountForm;
57   siteRes: GetSiteResponse;
58 }
59
60 interface UserProps {
61   view: UserDetailsView;
62   sort: SortType;
63   page: number;
64   user_id: number | null;
65   username: string;
66 }
67
68 interface UrlParams {
69   view?: string;
70   sort?: string;
71   page?: number;
72 }
73
74 export class User extends Component<any, UserState> {
75   private subscription: Subscription;
76   private emptyState: UserState = {
77     user: {
78       id: null,
79       name: null,
80       published: null,
81       number_of_posts: null,
82       post_score: null,
83       number_of_comments: null,
84       comment_score: null,
85       banned: null,
86       avatar: null,
87       show_avatars: null,
88       send_notifications_to_email: null,
89       actor_id: null,
90       local: null,
91     },
92     user_id: null,
93     username: null,
94     follows: [],
95     moderates: [],
96     loading: true,
97     avatarLoading: false,
98     view: User.getViewFromProps(this.props.match.view),
99     sort: User.getSortTypeFromProps(this.props.match.sort),
100     page: User.getPageFromProps(this.props.match.page),
101     userSettingsForm: {
102       show_nsfw: null,
103       theme: null,
104       default_sort_type: null,
105       default_listing_type: null,
106       lang: null,
107       show_avatars: null,
108       send_notifications_to_email: null,
109       auth: null,
110     },
111     userSettingsLoading: null,
112     deleteAccountLoading: null,
113     deleteAccountShowConfirm: false,
114     deleteAccountForm: {
115       password: null,
116     },
117     siteRes: {
118       admins: [],
119       banned: [],
120       online: undefined,
121       site: {
122         id: undefined,
123         name: undefined,
124         creator_id: undefined,
125         published: undefined,
126         creator_name: undefined,
127         number_of_users: undefined,
128         number_of_posts: undefined,
129         number_of_comments: undefined,
130         number_of_communities: undefined,
131         enable_downvotes: undefined,
132         open_registration: undefined,
133         enable_nsfw: undefined,
134       },
135       version: undefined,
136     },
137   };
138
139   constructor(props: any, context: any) {
140     super(props, context);
141
142     this.state = this.emptyState;
143     this.handleSortChange = this.handleSortChange.bind(this);
144     this.handleUserSettingsSortTypeChange = this.handleUserSettingsSortTypeChange.bind(
145       this
146     );
147     this.handleUserSettingsListingTypeChange = this.handleUserSettingsListingTypeChange.bind(
148       this
149     );
150     this.handlePageChange = this.handlePageChange.bind(this);
151
152     this.state.user_id = Number(this.props.match.params.id) || null;
153     this.state.username = this.props.match.params.username;
154
155     this.subscription = WebSocketService.Instance.subject
156       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
157       .subscribe(
158         msg => this.parseMessage(msg),
159         err => console.error(err),
160         () => console.log('complete')
161       );
162
163     WebSocketService.Instance.getSite();
164   }
165
166   get isCurrentUser() {
167     return (
168       UserService.Instance.user &&
169       UserService.Instance.user.id == this.state.user.id
170     );
171   }
172
173   static getViewFromProps(view: any): UserDetailsView {
174     return view
175       ? UserDetailsView[capitalizeFirstLetter(view)]
176       : UserDetailsView.Overview;
177   }
178
179   static getSortTypeFromProps(sort: any): SortType {
180     return sort ? routeSortTypeToEnum(sort) : SortType.New;
181   }
182
183   static getPageFromProps(page: any): number {
184     return page ? Number(page) : 1;
185   }
186
187   componentWillUnmount() {
188     this.subscription.unsubscribe();
189   }
190
191   static getDerivedStateFromProps(props: any): UserProps {
192     return {
193       view: this.getViewFromProps(props.match.params.view),
194       sort: this.getSortTypeFromProps(props.match.params.sort),
195       page: this.getPageFromProps(props.match.params.page),
196       user_id: Number(props.match.params.id) || null,
197       username: props.match.params.username,
198     };
199   }
200
201   componentDidUpdate(lastProps: any, _lastState: UserState, _snapshot: any) {
202     // Necessary if you are on a post and you click another post (same route)
203     if (
204       lastProps.location.pathname.split('/')[2] !==
205       lastProps.history.location.pathname.split('/')[2]
206     ) {
207       // Couldnt get a refresh working. This does for now.
208       location.reload();
209     }
210     document.title = `/u/${this.state.username} - ${this.state.siteRes.site.name}`;
211     setupTippy();
212   }
213
214   render() {
215     return (
216       <div class="container">
217         <div class="row">
218           <div class="col-12 col-md-8">
219             <h5>
220               {this.state.user.avatar && showAvatars() && (
221                 <img
222                   height="80"
223                   width="80"
224                   src={this.state.user.avatar}
225                   class="rounded-circle mr-2"
226                 />
227               )}
228               <span>/u/{this.state.username}</span>
229             </h5>
230             {this.state.loading ? (
231               <h5>
232                 <svg class="icon icon-spinner spin">
233                   <use xlinkHref="#icon-spinner"></use>
234                 </svg>
235               </h5>
236             ) : (
237               this.selects()
238             )}
239             <UserDetails
240               user_id={this.state.user_id}
241               username={this.state.username}
242               sort={SortType[this.state.sort]}
243               page={this.state.page}
244               limit={fetchLimit}
245               enableDownvotes={this.state.siteRes.site.enable_downvotes}
246               enableNsfw={this.state.siteRes.site.enable_nsfw}
247               admins={this.state.siteRes.admins}
248               view={this.state.view}
249               onPageChange={this.handlePageChange}
250             />
251           </div>
252
253           {!this.state.loading && (
254             <div class="col-12 col-md-4">
255               {this.userInfo()}
256               {this.isCurrentUser && this.userSettings()}
257               {this.moderates()}
258               {this.follows()}
259             </div>
260           )}
261         </div>
262       </div>
263     );
264   }
265
266   viewRadios() {
267     return (
268       <div class="btn-group btn-group-toggle">
269         <label
270           className={`btn btn-outline-secondary pointer 
271             ${this.state.view == UserDetailsView.Overview && 'active'}
272           `}
273         >
274           <input
275             type="radio"
276             value={UserDetailsView.Overview}
277             checked={this.state.view === UserDetailsView.Overview}
278             onChange={linkEvent(this, this.handleViewChange)}
279           />
280           {i18n.t('overview')}
281         </label>
282         <label
283           className={`btn btn-outline-secondary pointer 
284             ${this.state.view == UserDetailsView.Comments && 'active'}
285           `}
286         >
287           <input
288             type="radio"
289             value={UserDetailsView.Comments}
290             checked={this.state.view == UserDetailsView.Comments}
291             onChange={linkEvent(this, this.handleViewChange)}
292           />
293           {i18n.t('comments')}
294         </label>
295         <label
296           className={`btn btn-outline-secondary pointer 
297             ${this.state.view == UserDetailsView.Posts && 'active'}
298           `}
299         >
300           <input
301             type="radio"
302             value={UserDetailsView.Posts}
303             checked={this.state.view == UserDetailsView.Posts}
304             onChange={linkEvent(this, this.handleViewChange)}
305           />
306           {i18n.t('posts')}
307         </label>
308         <label
309           className={`btn btn-outline-secondary pointer 
310             ${this.state.view == UserDetailsView.Saved && 'active'}
311           `}
312         >
313           <input
314             type="radio"
315             value={UserDetailsView.Saved}
316             checked={this.state.view == UserDetailsView.Saved}
317             onChange={linkEvent(this, this.handleViewChange)}
318           />
319           {i18n.t('saved')}
320         </label>
321       </div>
322     );
323   }
324
325   selects() {
326     return (
327       <div className="mb-2">
328         <span class="mr-3">{this.viewRadios()}</span>
329         <SortSelect
330           sort={this.state.sort}
331           onChange={this.handleSortChange}
332           hideHot
333         />
334         <a
335           href={`/feeds/u/${this.state.username}.xml?sort=${
336             SortType[this.state.sort]
337           }`}
338           target="_blank"
339           rel="noopener"
340           title="RSS"
341         >
342           <svg class="icon mx-2 text-muted small">
343             <use xlinkHref="#icon-rss">#</use>
344           </svg>
345         </a>
346       </div>
347     );
348   }
349
350   userInfo() {
351     let user = this.state.user;
352     return (
353       <div>
354         <div class="card bg-transparent border-secondary mb-3">
355           <div class="card-body">
356             <h5>
357               <ul class="list-inline mb-0">
358                 <li className="list-inline-item">
359                   <UserListing user={user} realLink />
360                 </li>
361                 {user.banned && (
362                   <li className="list-inline-item badge badge-danger">
363                     {i18n.t('banned')}
364                   </li>
365                 )}
366               </ul>
367             </h5>
368             <div className="d-flex align-items-center mb-2">
369               <svg class="icon">
370                 <use xlinkHref="#icon-cake"></use>
371               </svg>
372               <span className="ml-2">
373                 {i18n.t('cake_day_title')}{' '}
374                 {moment.utc(user.published).local().format('MMM DD, YYYY')}
375               </span>
376             </div>
377             <div>
378               {i18n.t('joined')} <MomentTime data={user} showAgo />
379             </div>
380             <div class="table-responsive mt-1">
381               <table class="table table-bordered table-sm mt-2 mb-0">
382                 {/*
383                 <tr>
384                   <td class="text-center" colSpan={2}>
385                     {i18n.t('number_of_points', {
386                       count: user.post_score + user.comment_score,
387                     })}
388                   </td>
389                 </tr>
390                 */}
391                 <tr>
392                   {/* 
393                   <td>
394                     {i18n.t('number_of_points', { count: user.post_score })}
395                   </td>
396                   */}
397                   <td>
398                     {i18n.t('number_of_posts', { count: user.number_of_posts })}
399                   </td>
400                   {/* 
401                 </tr>
402                 <tr>
403                   <td>
404                     {i18n.t('number_of_points', { count: user.comment_score })}
405                   </td>
406                   */}
407                   <td>
408                     {i18n.t('number_of_comments', {
409                       count: user.number_of_comments,
410                     })}
411                   </td>
412                 </tr>
413               </table>
414             </div>
415             {this.isCurrentUser ? (
416               <button
417                 class="btn btn-block btn-secondary mt-3"
418                 onClick={linkEvent(this, this.handleLogoutClick)}
419               >
420                 {i18n.t('logout')}
421               </button>
422             ) : (
423               <>
424                 <a
425                   className={`btn btn-block btn-secondary mt-3 ${
426                     !this.state.user.matrix_user_id && 'disabled'
427                   }`}
428                   target="_blank"
429                   rel="noopener"
430                   href={`https://matrix.to/#/${this.state.user.matrix_user_id}`}
431                 >
432                   {i18n.t('send_secure_message')}
433                 </a>
434                 <Link
435                   class="btn btn-block btn-secondary mt-3"
436                   to={`/create_private_message?recipient_id=${this.state.user.id}`}
437                 >
438                   {i18n.t('send_message')}
439                 </Link>
440               </>
441             )}
442           </div>
443         </div>
444       </div>
445     );
446   }
447
448   userSettings() {
449     return (
450       <div>
451         <div class="card bg-transparent border-secondary mb-3">
452           <div class="card-body">
453             <h5>{i18n.t('settings')}</h5>
454             <form onSubmit={linkEvent(this, this.handleUserSettingsSubmit)}>
455               <div class="form-group">
456                 <label>{i18n.t('avatar')}</label>
457                 <form class="d-inline">
458                   <label
459                     htmlFor="file-upload"
460                     class="pointer ml-4 text-muted small font-weight-bold"
461                   >
462                     {!this.checkSettingsAvatar ? (
463                       <span class="btn btn-secondary">
464                         {i18n.t('upload_avatar')}
465                       </span>
466                     ) : (
467                       <img
468                         height="80"
469                         width="80"
470                         src={this.state.userSettingsForm.avatar}
471                         class="rounded-circle"
472                       />
473                     )}
474                   </label>
475                   <input
476                     id="file-upload"
477                     type="file"
478                     accept="image/*,video/*"
479                     name="file"
480                     class="d-none"
481                     disabled={!UserService.Instance.user}
482                     onChange={linkEvent(this, this.handleImageUpload)}
483                   />
484                 </form>
485               </div>
486               {this.checkSettingsAvatar && (
487                 <div class="form-group">
488                   <button
489                     class="btn btn-secondary btn-block"
490                     onClick={linkEvent(this, this.removeAvatar)}
491                   >
492                     {`${capitalizeFirstLetter(i18n.t('remove'))} ${i18n.t(
493                       'avatar'
494                     )}`}
495                   </button>
496                 </div>
497               )}
498               <div class="form-group">
499                 <label>{i18n.t('language')}</label>
500                 <select
501                   value={this.state.userSettingsForm.lang}
502                   onChange={linkEvent(this, this.handleUserSettingsLangChange)}
503                   class="ml-2 custom-select w-auto"
504                 >
505                   <option disabled>{i18n.t('language')}</option>
506                   <option value="browser">{i18n.t('browser_default')}</option>
507                   <option disabled>──</option>
508                   {languages.map(lang => (
509                     <option value={lang.code}>{lang.name}</option>
510                   ))}
511                 </select>
512               </div>
513               <div class="form-group">
514                 <label>{i18n.t('theme')}</label>
515                 <select
516                   value={this.state.userSettingsForm.theme}
517                   onChange={linkEvent(this, this.handleUserSettingsThemeChange)}
518                   class="ml-2 custom-select w-auto"
519                 >
520                   <option disabled>{i18n.t('theme')}</option>
521                   {themes.map(theme => (
522                     <option value={theme}>{theme}</option>
523                   ))}
524                 </select>
525               </div>
526               <form className="form-group">
527                 <label>
528                   <div class="mr-2">{i18n.t('sort_type')}</div>
529                 </label>
530                 <ListingTypeSelect
531                   type_={this.state.userSettingsForm.default_listing_type}
532                   onChange={this.handleUserSettingsListingTypeChange}
533                 />
534               </form>
535               <form className="form-group">
536                 <label>
537                   <div class="mr-2">{i18n.t('type')}</div>
538                 </label>
539                 <SortSelect
540                   sort={this.state.userSettingsForm.default_sort_type}
541                   onChange={this.handleUserSettingsSortTypeChange}
542                 />
543               </form>
544               <div class="form-group row">
545                 <label class="col-lg-3 col-form-label" htmlFor="user-email">
546                   {i18n.t('email')}
547                 </label>
548                 <div class="col-lg-9">
549                   <input
550                     type="email"
551                     id="user-email"
552                     class="form-control"
553                     placeholder={i18n.t('optional')}
554                     value={this.state.userSettingsForm.email}
555                     onInput={linkEvent(
556                       this,
557                       this.handleUserSettingsEmailChange
558                     )}
559                     minLength={3}
560                   />
561                 </div>
562               </div>
563               <div class="form-group row">
564                 <label class="col-lg-5 col-form-label">
565                   <a
566                     href="https://about.riot.im/"
567                     target="_blank"
568                     rel="noopener"
569                   >
570                     {i18n.t('matrix_user_id')}
571                   </a>
572                 </label>
573                 <div class="col-lg-7">
574                   <input
575                     type="text"
576                     class="form-control"
577                     placeholder="@user:example.com"
578                     value={this.state.userSettingsForm.matrix_user_id}
579                     onInput={linkEvent(
580                       this,
581                       this.handleUserSettingsMatrixUserIdChange
582                     )}
583                     minLength={3}
584                   />
585                 </div>
586               </div>
587               <div class="form-group row">
588                 <label class="col-lg-5 col-form-label" htmlFor="user-password">
589                   {i18n.t('new_password')}
590                 </label>
591                 <div class="col-lg-7">
592                   <input
593                     type="password"
594                     id="user-password"
595                     class="form-control"
596                     value={this.state.userSettingsForm.new_password}
597                     autoComplete="new-password"
598                     onInput={linkEvent(
599                       this,
600                       this.handleUserSettingsNewPasswordChange
601                     )}
602                   />
603                 </div>
604               </div>
605               <div class="form-group row">
606                 <label
607                   class="col-lg-5 col-form-label"
608                   htmlFor="user-verify-password"
609                 >
610                   {i18n.t('verify_password')}
611                 </label>
612                 <div class="col-lg-7">
613                   <input
614                     type="password"
615                     id="user-verify-password"
616                     class="form-control"
617                     value={this.state.userSettingsForm.new_password_verify}
618                     autoComplete="new-password"
619                     onInput={linkEvent(
620                       this,
621                       this.handleUserSettingsNewPasswordVerifyChange
622                     )}
623                   />
624                 </div>
625               </div>
626               <div class="form-group row">
627                 <label
628                   class="col-lg-5 col-form-label"
629                   htmlFor="user-old-password"
630                 >
631                   {i18n.t('old_password')}
632                 </label>
633                 <div class="col-lg-7">
634                   <input
635                     type="password"
636                     id="user-old-password"
637                     class="form-control"
638                     value={this.state.userSettingsForm.old_password}
639                     autoComplete="new-password"
640                     onInput={linkEvent(
641                       this,
642                       this.handleUserSettingsOldPasswordChange
643                     )}
644                   />
645                 </div>
646               </div>
647               {this.state.siteRes.site.enable_nsfw && (
648                 <div class="form-group">
649                   <div class="form-check">
650                     <input
651                       class="form-check-input"
652                       id="user-show-nsfw"
653                       type="checkbox"
654                       checked={this.state.userSettingsForm.show_nsfw}
655                       onChange={linkEvent(
656                         this,
657                         this.handleUserSettingsShowNsfwChange
658                       )}
659                     />
660                     <label class="form-check-label" htmlFor="user-show-nsfw">
661                       {i18n.t('show_nsfw')}
662                     </label>
663                   </div>
664                 </div>
665               )}
666               <div class="form-group">
667                 <div class="form-check">
668                   <input
669                     class="form-check-input"
670                     id="user-show-avatars"
671                     type="checkbox"
672                     checked={this.state.userSettingsForm.show_avatars}
673                     onChange={linkEvent(
674                       this,
675                       this.handleUserSettingsShowAvatarsChange
676                     )}
677                   />
678                   <label class="form-check-label" htmlFor="user-show-avatars">
679                     {i18n.t('show_avatars')}
680                   </label>
681                 </div>
682               </div>
683               <div class="form-group">
684                 <div class="form-check">
685                   <input
686                     class="form-check-input"
687                     id="user-send-notifications-to-email"
688                     type="checkbox"
689                     disabled={!this.state.user.email}
690                     checked={
691                       this.state.userSettingsForm.send_notifications_to_email
692                     }
693                     onChange={linkEvent(
694                       this,
695                       this.handleUserSettingsSendNotificationsToEmailChange
696                     )}
697                   />
698                   <label
699                     class="form-check-label"
700                     htmlFor="user-send-notifications-to-email"
701                   >
702                     {i18n.t('send_notifications_to_email')}
703                   </label>
704                 </div>
705               </div>
706               <div class="form-group">
707                 <button type="submit" class="btn btn-block btn-secondary mr-4">
708                   {this.state.userSettingsLoading ? (
709                     <svg class="icon icon-spinner spin">
710                       <use xlinkHref="#icon-spinner"></use>
711                     </svg>
712                   ) : (
713                     capitalizeFirstLetter(i18n.t('save'))
714                   )}
715                 </button>
716               </div>
717               <hr />
718               <div class="form-group mb-0">
719                 <button
720                   class="btn btn-block btn-danger"
721                   onClick={linkEvent(
722                     this,
723                     this.handleDeleteAccountShowConfirmToggle
724                   )}
725                 >
726                   {i18n.t('delete_account')}
727                 </button>
728                 {this.state.deleteAccountShowConfirm && (
729                   <>
730                     <div class="my-2 alert alert-danger" role="alert">
731                       {i18n.t('delete_account_confirm')}
732                     </div>
733                     <input
734                       type="password"
735                       value={this.state.deleteAccountForm.password}
736                       autoComplete="new-password"
737                       onInput={linkEvent(
738                         this,
739                         this.handleDeleteAccountPasswordChange
740                       )}
741                       class="form-control my-2"
742                     />
743                     <button
744                       class="btn btn-danger mr-4"
745                       disabled={!this.state.deleteAccountForm.password}
746                       onClick={linkEvent(this, this.handleDeleteAccount)}
747                     >
748                       {this.state.deleteAccountLoading ? (
749                         <svg class="icon icon-spinner spin">
750                           <use xlinkHref="#icon-spinner"></use>
751                         </svg>
752                       ) : (
753                         capitalizeFirstLetter(i18n.t('delete'))
754                       )}
755                     </button>
756                     <button
757                       class="btn btn-secondary"
758                       onClick={linkEvent(
759                         this,
760                         this.handleDeleteAccountShowConfirmToggle
761                       )}
762                     >
763                       {i18n.t('cancel')}
764                     </button>
765                   </>
766                 )}
767               </div>
768             </form>
769           </div>
770         </div>
771       </div>
772     );
773   }
774
775   moderates() {
776     return (
777       <div>
778         {this.state.moderates.length > 0 && (
779           <div class="card bg-transparent border-secondary mb-3">
780             <div class="card-body">
781               <h5>{i18n.t('moderates')}</h5>
782               <ul class="list-unstyled mb-0">
783                 {this.state.moderates.map(community => (
784                   <li>
785                     <Link to={`/c/${community.community_name}`}>
786                       {community.community_name}
787                     </Link>
788                   </li>
789                 ))}
790               </ul>
791             </div>
792           </div>
793         )}
794       </div>
795     );
796   }
797
798   follows() {
799     return (
800       <div>
801         {this.state.follows.length > 0 && (
802           <div class="card bg-transparent border-secondary mb-3">
803             <div class="card-body">
804               <h5>{i18n.t('subscribed')}</h5>
805               <ul class="list-unstyled mb-0">
806                 {this.state.follows.map(community => (
807                   <li>
808                     <Link to={`/c/${community.community_name}`}>
809                       {community.community_name}
810                     </Link>
811                   </li>
812                 ))}
813               </ul>
814             </div>
815           </div>
816         )}
817       </div>
818     );
819   }
820
821   updateUrl(paramUpdates: UrlParams) {
822     const page = paramUpdates.page || this.state.page;
823     const viewStr =
824       paramUpdates.view || UserDetailsView[this.state.view].toLowerCase();
825     const sortStr =
826       paramUpdates.sort || SortType[this.state.sort].toLowerCase();
827     this.props.history.push(
828       `/u/${this.state.username}/view/${viewStr}/sort/${sortStr}/page/${page}`
829     );
830   }
831
832   handlePageChange(page: number) {
833     this.updateUrl({ page });
834   }
835
836   handleSortChange(val: SortType) {
837     this.updateUrl({ sort: SortType[val].toLowerCase(), page: 1 });
838   }
839
840   handleViewChange(i: User, event: any) {
841     i.updateUrl({
842       view: UserDetailsView[Number(event.target.value)].toLowerCase(),
843       page: 1,
844     });
845   }
846
847   handleUserSettingsShowNsfwChange(i: User, event: any) {
848     i.state.userSettingsForm.show_nsfw = event.target.checked;
849     i.setState(i.state);
850   }
851
852   handleUserSettingsShowAvatarsChange(i: User, event: any) {
853     i.state.userSettingsForm.show_avatars = event.target.checked;
854     UserService.Instance.user.show_avatars = event.target.checked; // Just for instant updates
855     i.setState(i.state);
856   }
857
858   handleUserSettingsSendNotificationsToEmailChange(i: User, event: any) {
859     i.state.userSettingsForm.send_notifications_to_email = event.target.checked;
860     i.setState(i.state);
861   }
862
863   handleUserSettingsThemeChange(i: User, event: any) {
864     i.state.userSettingsForm.theme = event.target.value;
865     setTheme(event.target.value, true);
866     i.setState(i.state);
867   }
868
869   handleUserSettingsLangChange(i: User, event: any) {
870     i.state.userSettingsForm.lang = event.target.value;
871     i18n.changeLanguage(i.state.userSettingsForm.lang);
872     i.setState(i.state);
873   }
874
875   handleUserSettingsSortTypeChange(val: SortType) {
876     this.state.userSettingsForm.default_sort_type = val;
877     this.setState(this.state);
878   }
879
880   handleUserSettingsListingTypeChange(val: ListingType) {
881     this.state.userSettingsForm.default_listing_type = val;
882     this.setState(this.state);
883   }
884
885   handleUserSettingsEmailChange(i: User, event: any) {
886     i.state.userSettingsForm.email = event.target.value;
887     if (i.state.userSettingsForm.email == '' && !i.state.user.email) {
888       i.state.userSettingsForm.email = undefined;
889     }
890     i.setState(i.state);
891   }
892
893   handleUserSettingsMatrixUserIdChange(i: User, event: any) {
894     i.state.userSettingsForm.matrix_user_id = event.target.value;
895     if (
896       i.state.userSettingsForm.matrix_user_id == '' &&
897       !i.state.user.matrix_user_id
898     ) {
899       i.state.userSettingsForm.matrix_user_id = undefined;
900     }
901     i.setState(i.state);
902   }
903
904   handleUserSettingsNewPasswordChange(i: User, event: any) {
905     i.state.userSettingsForm.new_password = event.target.value;
906     if (i.state.userSettingsForm.new_password == '') {
907       i.state.userSettingsForm.new_password = undefined;
908     }
909     i.setState(i.state);
910   }
911
912   handleUserSettingsNewPasswordVerifyChange(i: User, event: any) {
913     i.state.userSettingsForm.new_password_verify = event.target.value;
914     if (i.state.userSettingsForm.new_password_verify == '') {
915       i.state.userSettingsForm.new_password_verify = undefined;
916     }
917     i.setState(i.state);
918   }
919
920   handleUserSettingsOldPasswordChange(i: User, event: any) {
921     i.state.userSettingsForm.old_password = event.target.value;
922     if (i.state.userSettingsForm.old_password == '') {
923       i.state.userSettingsForm.old_password = undefined;
924     }
925     i.setState(i.state);
926   }
927
928   handleImageUpload(i: User, event: any) {
929     event.preventDefault();
930     let file = event.target.files[0];
931     const imageUploadUrl = `/pictrs/image`;
932     const formData = new FormData();
933     formData.append('images[]', file);
934
935     i.state.avatarLoading = true;
936     i.setState(i.state);
937
938     fetch(imageUploadUrl, {
939       method: 'POST',
940       body: formData,
941     })
942       .then(res => res.json())
943       .then(res => {
944         console.log('pictrs upload:');
945         console.log(res);
946         if (res.msg == 'ok') {
947           let hash = res.files[0].file;
948           let url = `${window.location.origin}/pictrs/image/${hash}`;
949           i.state.userSettingsForm.avatar = url;
950           i.state.avatarLoading = false;
951           i.setState(i.state);
952         } else {
953           i.state.avatarLoading = false;
954           i.setState(i.state);
955           toast(JSON.stringify(res), 'danger');
956         }
957       })
958       .catch(error => {
959         i.state.avatarLoading = false;
960         i.setState(i.state);
961         toast(error, 'danger');
962       });
963   }
964
965   removeAvatar(i: User, event: any) {
966     event.preventDefault();
967     i.state.userSettingsLoading = true;
968     i.state.userSettingsForm.avatar = '';
969     i.setState(i.state);
970
971     WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
972   }
973
974   get checkSettingsAvatar(): boolean {
975     return (
976       this.state.userSettingsForm.avatar &&
977       this.state.userSettingsForm.avatar != ''
978     );
979   }
980
981   handleUserSettingsSubmit(i: User, event: any) {
982     event.preventDefault();
983     i.state.userSettingsLoading = true;
984     i.setState(i.state);
985
986     WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
987   }
988
989   handleDeleteAccountShowConfirmToggle(i: User, event: any) {
990     event.preventDefault();
991     i.state.deleteAccountShowConfirm = !i.state.deleteAccountShowConfirm;
992     i.setState(i.state);
993   }
994
995   handleDeleteAccountPasswordChange(i: User, event: any) {
996     i.state.deleteAccountForm.password = event.target.value;
997     i.setState(i.state);
998   }
999
1000   handleLogoutClick(i: User) {
1001     UserService.Instance.logout();
1002     i.context.router.history.push('/');
1003   }
1004
1005   handleDeleteAccount(i: User, event: any) {
1006     event.preventDefault();
1007     i.state.deleteAccountLoading = true;
1008     i.setState(i.state);
1009
1010     WebSocketService.Instance.deleteAccount(i.state.deleteAccountForm);
1011   }
1012
1013   parseMessage(msg: WebSocketJsonResponse) {
1014     console.log(msg);
1015     const res = wsJsonToRes(msg);
1016     if (msg.error) {
1017       toast(i18n.t(msg.error), 'danger');
1018       if (msg.error == 'couldnt_find_that_username_or_email') {
1019         this.context.router.history.push('/');
1020       }
1021       this.setState({
1022         deleteAccountLoading: false,
1023         avatarLoading: false,
1024         userSettingsLoading: false,
1025       });
1026       return;
1027     } else if (res.op == UserOperation.GetUserDetails) {
1028       // Since the UserDetails contains posts/comments as well as some general user info we listen here as well
1029       // and set the parent state if it is not set or differs
1030       const data = res.data as UserDetailsResponse;
1031
1032       if (this.state.user.id !== data.user.id) {
1033         this.state.user = data.user;
1034         this.state.follows = data.follows;
1035         this.state.moderates = data.moderates;
1036
1037         if (this.isCurrentUser) {
1038           this.state.userSettingsForm.show_nsfw =
1039             UserService.Instance.user.show_nsfw;
1040           this.state.userSettingsForm.theme = UserService.Instance.user.theme
1041             ? UserService.Instance.user.theme
1042             : 'darkly';
1043           this.state.userSettingsForm.default_sort_type =
1044             UserService.Instance.user.default_sort_type;
1045           this.state.userSettingsForm.default_listing_type =
1046             UserService.Instance.user.default_listing_type;
1047           this.state.userSettingsForm.lang = UserService.Instance.user.lang;
1048           this.state.userSettingsForm.avatar = UserService.Instance.user.avatar;
1049           this.state.userSettingsForm.email = this.state.user.email;
1050           this.state.userSettingsForm.send_notifications_to_email = this.state.user.send_notifications_to_email;
1051           this.state.userSettingsForm.show_avatars =
1052             UserService.Instance.user.show_avatars;
1053           this.state.userSettingsForm.matrix_user_id = this.state.user.matrix_user_id;
1054         }
1055         this.state.loading = false;
1056         this.setState(this.state);
1057       }
1058     } else if (res.op == UserOperation.SaveUserSettings) {
1059       const data = res.data as LoginResponse;
1060       UserService.Instance.login(data);
1061       this.setState({
1062         userSettingsLoading: false,
1063       });
1064       window.scrollTo(0, 0);
1065     } else if (res.op == UserOperation.DeleteAccount) {
1066       this.setState({
1067         deleteAccountLoading: false,
1068         deleteAccountShowConfirm: false,
1069       });
1070       this.context.router.history.push('/');
1071     } else if (res.op == UserOperation.GetSite) {
1072       const data = res.data as GetSiteResponse;
1073       this.state.siteRes = data;
1074       this.setState(this.state);
1075     } else if (res.op == UserOperation.AddAdmin) {
1076       const data = res.data as AddAdminResponse;
1077       this.state.siteRes.admins = data.admins;
1078       this.setState(this.state);
1079     }
1080   }
1081 }