]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Adding private message reporting. Fixes #782 (#806)
[lemmy-ui.git] / src / shared / utils.ts
1 import { Err, None, Ok, Option, Result, Some } from "@sniptt/monads";
2 import { ClassConstructor, deserialize, serialize } from "class-transformer";
3 import emojiShortName from "emoji-short-name";
4 import {
5   BlockCommunityResponse,
6   BlockPersonResponse,
7   Comment as CommentI,
8   CommentNode as CommentNodeI,
9   CommentReportView,
10   CommentSortType,
11   CommentView,
12   CommunityBlockView,
13   CommunityModeratorView,
14   CommunityView,
15   GetSiteMetadata,
16   GetSiteResponse,
17   LemmyHttp,
18   LemmyWebsocket,
19   ListingType,
20   MyUserInfo,
21   PersonBlockView,
22   PersonSafe,
23   PersonViewSafe,
24   PostReportView,
25   PostView,
26   PrivateMessageReportView,
27   PrivateMessageView,
28   RegistrationApplicationView,
29   Search,
30   SearchType,
31   SortType,
32 } from "lemmy-js-client";
33 import markdown_it from "markdown-it";
34 import markdown_it_container from "markdown-it-container";
35 import markdown_it_footnote from "markdown-it-footnote";
36 import markdown_it_html5_embed from "markdown-it-html5-embed";
37 import markdown_it_sub from "markdown-it-sub";
38 import markdown_it_sup from "markdown-it-sup";
39 import moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { httpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
48
49 var Tribute: any;
50 if (isBrowser()) {
51   Tribute = require("tributejs");
52 }
53
54 export const wsClient = new LemmyWebsocket();
55
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
58 // TODO
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
66 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
71
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40;
74 export const trendingFetchLimit = 6;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77
78 export const relTags = "noopener nofollow";
79
80 const DEFAULT_ALPHABET =
81   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
82
83 function getRandomCharFromAlphabet(alphabet: string): string {
84   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
85 }
86
87 export function randomStr(
88   idDesiredLength = 20,
89   alphabet = DEFAULT_ALPHABET
90 ): string {
91   /**
92    * Create n-long array and map it to random chars from given alphabet.
93    * Then join individual chars as string
94    */
95   return Array.from({ length: idDesiredLength })
96     .map(() => {
97       return getRandomCharFromAlphabet(alphabet);
98     })
99     .join("");
100 }
101
102 export const md = new markdown_it({
103   html: false,
104   linkify: true,
105   typographer: true,
106 })
107   .use(markdown_it_sub)
108   .use(markdown_it_sup)
109   .use(markdown_it_footnote)
110   .use(markdown_it_html5_embed, {
111     html5embed: {
112       useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
113       attributes: {
114         audio: 'controls preload="metadata"',
115         video:
116           'width="100%" max-height="100%" controls loop preload="metadata"',
117       },
118     },
119   })
120   .use(markdown_it_container, "spoiler", {
121     validate: function (params: any) {
122       return params.trim().match(/^spoiler\s+(.*)$/);
123     },
124
125     render: function (tokens: any, idx: any) {
126       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
127
128       if (tokens[idx].nesting === 1) {
129         // opening tag
130         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
131       } else {
132         // closing tag
133         return "</details>\n";
134       }
135     },
136   });
137
138 export function hotRankComment(comment_view: CommentView): number {
139   return hotRank(comment_view.counts.score, comment_view.comment.published);
140 }
141
142 export function hotRankActivePost(post_view: PostView): number {
143   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
144 }
145
146 export function hotRankPost(post_view: PostView): number {
147   return hotRank(post_view.counts.score, post_view.post.published);
148 }
149
150 export function hotRank(score: number, timeStr: string): number {
151   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
152   let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
153   let now: Date = new Date();
154   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
155
156   let rank =
157     (10000 * Math.log10(Math.max(1, 3 + score))) /
158     Math.pow(hoursElapsed + 2, 1.8);
159
160   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
161
162   return rank;
163 }
164
165 export function mdToHtml(text: string) {
166   return { __html: md.render(text) };
167 }
168
169 export function getUnixTime(text: string): number {
170   return text ? new Date(text).getTime() / 1000 : undefined;
171 }
172
173 export function futureDaysToUnixTime(days: number): number {
174   return days
175     ? Math.trunc(
176         new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
177       )
178     : undefined;
179 }
180
181 export function canMod(
182   mods: Option<CommunityModeratorView[]>,
183   admins: Option<PersonViewSafe[]>,
184   creator_id: number,
185   myUserInfo = UserService.Instance.myUserInfo,
186   onSelf = false
187 ): boolean {
188   // You can do moderator actions only on the mods added after you.
189   let adminsThenMods = admins
190     .unwrapOr([])
191     .map(a => a.person.id)
192     .concat(mods.unwrapOr([]).map(m => m.moderator.id));
193
194   return myUserInfo.match({
195     some: me => {
196       let myIndex = adminsThenMods.findIndex(
197         id => id == me.local_user_view.person.id
198       );
199       if (myIndex == -1) {
200         return false;
201       } else {
202         // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
203         adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
204         return !adminsThenMods.includes(creator_id);
205       }
206     },
207     none: false,
208   });
209 }
210
211 export function canAdmin(
212   admins: Option<PersonViewSafe[]>,
213   creator_id: number,
214   myUserInfo = UserService.Instance.myUserInfo,
215   onSelf = false
216 ): boolean {
217   return canMod(None, admins, creator_id, myUserInfo, onSelf);
218 }
219
220 export function isMod(
221   mods: Option<CommunityModeratorView[]>,
222   creator_id: number
223 ): boolean {
224   return mods.match({
225     some: mods => mods.map(m => m.moderator.id).includes(creator_id),
226     none: false,
227   });
228 }
229
230 export function amMod(
231   mods: Option<CommunityModeratorView[]>,
232   myUserInfo = UserService.Instance.myUserInfo
233 ): boolean {
234   return myUserInfo.match({
235     some: mui => isMod(mods, mui.local_user_view.person.id),
236     none: false,
237   });
238 }
239
240 export function isAdmin(
241   admins: Option<PersonViewSafe[]>,
242   creator_id: number
243 ): boolean {
244   return admins.match({
245     some: admins => admins.map(a => a.person.id).includes(creator_id),
246     none: false,
247   });
248 }
249
250 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
251   return myUserInfo
252     .map(mui => mui.local_user_view.person.admin)
253     .unwrapOr(false);
254 }
255
256 export function amCommunityCreator(
257   mods: Option<CommunityModeratorView[]>,
258   creator_id: number,
259   myUserInfo = UserService.Instance.myUserInfo
260 ): boolean {
261   return mods.match({
262     some: mods =>
263       myUserInfo
264         .map(mui => mui.local_user_view.person.id)
265         .match({
266           some: myId =>
267             myId == mods[0].moderator.id &&
268             // Don't allow mod actions on yourself
269             myId != creator_id,
270           none: false,
271         }),
272     none: false,
273   });
274 }
275
276 export function amSiteCreator(
277   admins: Option<PersonViewSafe[]>,
278   creator_id: number,
279   myUserInfo = UserService.Instance.myUserInfo
280 ): boolean {
281   return admins.match({
282     some: admins =>
283       myUserInfo
284         .map(mui => mui.local_user_view.person.id)
285         .match({
286           some: myId =>
287             myId == admins[0].person.id &&
288             // Don't allow mod actions on yourself
289             myId != creator_id,
290           none: false,
291         }),
292     none: false,
293   });
294 }
295
296 export function amTopMod(
297   mods: Option<CommunityModeratorView[]>,
298   myUserInfo = UserService.Instance.myUserInfo
299 ): boolean {
300   return mods.match({
301     some: mods =>
302       myUserInfo.match({
303         some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
304         none: false,
305       }),
306     none: false,
307   });
308 }
309
310 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
311 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
312
313 export function isImage(url: string) {
314   return imageRegex.test(url);
315 }
316
317 export function isVideo(url: string) {
318   return videoRegex.test(url);
319 }
320
321 export function validURL(str: string) {
322   return !!new URL(str);
323 }
324
325 export function communityRSSUrl(actorId: string, sort: string): string {
326   let url = new URL(actorId);
327   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
328 }
329
330 export function validEmail(email: string) {
331   let re =
332     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
333   return re.test(String(email).toLowerCase());
334 }
335
336 export function capitalizeFirstLetter(str: string): string {
337   return str.charAt(0).toUpperCase() + str.slice(1);
338 }
339
340 export function routeSortTypeToEnum(sort: string): SortType {
341   return SortType[sort];
342 }
343
344 export function listingTypeFromNum(type_: number): ListingType {
345   return Object.values(ListingType)[type_];
346 }
347
348 export function sortTypeFromNum(type_: number): SortType {
349   return Object.values(SortType)[type_];
350 }
351
352 export function routeListingTypeToEnum(type: string): ListingType {
353   return ListingType[type];
354 }
355
356 export function routeDataTypeToEnum(type: string): DataType {
357   return DataType[capitalizeFirstLetter(type)];
358 }
359
360 export function routeSearchTypeToEnum(type: string): SearchType {
361   return SearchType[type];
362 }
363
364 export async function getSiteMetadata(url: string) {
365   let form = new GetSiteMetadata({
366     url,
367   });
368   let client = new LemmyHttp(httpBase);
369   return client.getSiteMetadata(form);
370 }
371
372 export function debounce(func: any, wait = 1000, immediate = false) {
373   // 'private' variable for instance
374   // The returned function will be able to reference this due to closure.
375   // Each call to the returned function will share this common timer.
376   let timeout: any;
377
378   // Calling debounce returns a new anonymous function
379   return function () {
380     // reference the context and args for the setTimeout function
381     var args = arguments;
382
383     // Should the function be called now? If immediate is true
384     //   and not already in a timeout then the answer is: Yes
385     var callNow = immediate && !timeout;
386
387     // This is the basic debounce behaviour where you can call this
388     //   function several times, but it will only execute once
389     //   [before or after imposing a delay].
390     //   Each time the returned function is called, the timer starts over.
391     clearTimeout(timeout);
392
393     // Set the new timeout
394     timeout = setTimeout(function () {
395       // Inside the timeout function, clear the timeout variable
396       // which will let the next execution run when in 'immediate' mode
397       timeout = null;
398
399       // Check if the function already ran with the immediate flag
400       if (!immediate) {
401         // Call the original function with apply
402         // apply lets you define the 'this' object as well as the arguments
403         //    (both captured before setTimeout)
404         func.apply(this, args);
405       }
406     }, wait);
407
408     // Immediate mode and no wait timer? Execute the function..
409     if (callNow) func.apply(this, args);
410   };
411 }
412
413 export function getLanguages(
414   override?: string,
415   myUserInfo = UserService.Instance.myUserInfo
416 ): string[] {
417   let myLang = myUserInfo
418     .map(m => m.local_user_view.local_user.interface_language)
419     .unwrapOr("browser");
420   let lang = override || myLang;
421
422   if (lang == "browser" && isBrowser()) {
423     return getBrowserLanguages();
424   } else {
425     return [lang];
426   }
427 }
428
429 function getBrowserLanguages(): string[] {
430   // Intersect lemmy's langs, with the browser langs
431   let langs = languages ? languages.map(l => l.code) : ["en"];
432
433   // NOTE, mobile browsers seem to be missing this list, so append en
434   let allowedLangs = navigator.languages
435     .concat("en")
436     .filter(v => langs.includes(v));
437   return allowedLangs;
438 }
439
440 export async function fetchThemeList(): Promise<string[]> {
441   return fetch("/css/themelist").then(res => res.json());
442 }
443
444 export async function setTheme(theme: string, forceReload = false) {
445   if (!isBrowser()) {
446     return;
447   }
448   if (theme === "browser" && !forceReload) {
449     return;
450   }
451   // This is only run on a force reload
452   if (theme == "browser") {
453     theme = "darkly";
454   }
455
456   let themeList = await fetchThemeList();
457
458   // Unload all the other themes
459   for (var i = 0; i < themeList.length; i++) {
460     let styleSheet = document.getElementById(themeList[i]);
461     if (styleSheet) {
462       styleSheet.setAttribute("disabled", "disabled");
463     }
464   }
465
466   document
467     .getElementById("default-light")
468     ?.setAttribute("disabled", "disabled");
469   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
470
471   // Load the theme dynamically
472   let cssLoc = `/css/themes/${theme}.css`;
473
474   loadCss(theme, cssLoc);
475   document.getElementById(theme).removeAttribute("disabled");
476 }
477
478 export function loadCss(id: string, loc: string) {
479   if (!document.getElementById(id)) {
480     var head = document.getElementsByTagName("head")[0];
481     var link = document.createElement("link");
482     link.id = id;
483     link.rel = "stylesheet";
484     link.type = "text/css";
485     link.href = loc;
486     link.media = "all";
487     head.appendChild(link);
488   }
489 }
490
491 export function objectFlip(obj: any) {
492   const ret = {};
493   Object.keys(obj).forEach(key => {
494     ret[obj[key]] = key;
495   });
496   return ret;
497 }
498
499 export function showAvatars(
500   myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
501 ): boolean {
502   return myUserInfo
503     .map(m => m.local_user_view.local_user.show_avatars)
504     .unwrapOr(true);
505 }
506
507 export function showScores(
508   myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
509 ): boolean {
510   return myUserInfo
511     .map(m => m.local_user_view.local_user.show_scores)
512     .unwrapOr(true);
513 }
514
515 export function isCakeDay(published: string): boolean {
516   // moment(undefined) or moment.utc(undefined) returns the current date/time
517   // moment(null) or moment.utc(null) returns null
518   const createDate = moment.utc(published).local();
519   const currentDate = moment(new Date());
520
521   return (
522     createDate.date() === currentDate.date() &&
523     createDate.month() === currentDate.month() &&
524     createDate.year() !== currentDate.year()
525   );
526 }
527
528 export function toast(text: string, background = "success") {
529   if (isBrowser()) {
530     let backgroundColor = `var(--${background})`;
531     Toastify({
532       text: text,
533       backgroundColor: backgroundColor,
534       gravity: "bottom",
535       position: "left",
536     }).showToast();
537   }
538 }
539
540 export function pictrsDeleteToast(
541   clickToDeleteText: string,
542   deletePictureText: string,
543   deleteUrl: string
544 ) {
545   if (isBrowser()) {
546     let backgroundColor = `var(--light)`;
547     let toast = Toastify({
548       text: clickToDeleteText,
549       backgroundColor: backgroundColor,
550       gravity: "top",
551       position: "right",
552       duration: 10000,
553       onClick: () => {
554         if (toast) {
555           window.location.replace(deleteUrl);
556           alert(deletePictureText);
557           toast.hideToast();
558         }
559       },
560       close: true,
561     }).showToast();
562   }
563 }
564
565 interface NotifyInfo {
566   name: string;
567   icon: Option<string>;
568   link: string;
569   body: string;
570 }
571
572 export function messageToastify(info: NotifyInfo, router: any) {
573   if (isBrowser()) {
574     let htmlBody = info.body ? md.render(info.body) : "";
575     let backgroundColor = `var(--light)`;
576
577     let toast = Toastify({
578       text: `${htmlBody}<br />${info.name}`,
579       avatar: info.icon,
580       backgroundColor: backgroundColor,
581       className: "text-dark",
582       close: true,
583       gravity: "top",
584       position: "right",
585       duration: 5000,
586       escapeMarkup: false,
587       onClick: () => {
588         if (toast) {
589           toast.hideToast();
590           router.history.push(info.link);
591         }
592       },
593     }).showToast();
594   }
595 }
596
597 export function notifyPost(post_view: PostView, router: any) {
598   let info: NotifyInfo = {
599     name: post_view.community.name,
600     icon: post_view.community.icon,
601     link: `/post/${post_view.post.id}`,
602     body: post_view.post.name,
603   };
604   notify(info, router);
605 }
606
607 export function notifyComment(comment_view: CommentView, router: any) {
608   let info: NotifyInfo = {
609     name: comment_view.creator.name,
610     icon: comment_view.creator.avatar,
611     link: `/comment/${comment_view.comment.id}`,
612     body: comment_view.comment.content,
613   };
614   notify(info, router);
615 }
616
617 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
618   let info: NotifyInfo = {
619     name: pmv.creator.name,
620     icon: pmv.creator.avatar,
621     link: `/inbox`,
622     body: pmv.private_message.content,
623   };
624   notify(info, router);
625 }
626
627 function notify(info: NotifyInfo, router: any) {
628   messageToastify(info, router);
629
630   if (Notification.permission !== "granted") Notification.requestPermission();
631   else {
632     var notification = new Notification(info.name, {
633       ...{ body: info.body },
634       ...(info.icon.isSome() && { icon: info.icon.unwrap() }),
635     });
636
637     notification.onclick = (ev: Event): any => {
638       ev.preventDefault();
639       router.history.push(info.link);
640     };
641   }
642 }
643
644 export function setupTribute() {
645   return new Tribute({
646     noMatchTemplate: function () {
647       return "";
648     },
649     collection: [
650       // Emojis
651       {
652         trigger: ":",
653         menuItemTemplate: (item: any) => {
654           let shortName = `:${item.original.key}:`;
655           return `${item.original.val} ${shortName}`;
656         },
657         selectTemplate: (item: any) => {
658           return `${item.original.val}`;
659         },
660         values: Object.entries(emojiShortName).map(e => {
661           return { key: e[1], val: e[0] };
662         }),
663         allowSpaces: false,
664         autocompleteMode: true,
665         // TODO
666         // menuItemLimit: mentionDropdownFetchLimit,
667         menuShowMinLength: 2,
668       },
669       // Persons
670       {
671         trigger: "@",
672         selectTemplate: (item: any) => {
673           let it: PersonTribute = item.original;
674           return `[${it.key}](${it.view.person.actor_id})`;
675         },
676         values: debounce(async (text: string, cb: any) => {
677           cb(await personSearch(text));
678         }),
679         allowSpaces: false,
680         autocompleteMode: true,
681         // TODO
682         // menuItemLimit: mentionDropdownFetchLimit,
683         menuShowMinLength: 2,
684       },
685
686       // Communities
687       {
688         trigger: "!",
689         selectTemplate: (item: any) => {
690           let it: CommunityTribute = item.original;
691           return `[${it.key}](${it.view.community.actor_id})`;
692         },
693         values: debounce(async (text: string, cb: any) => {
694           cb(await communitySearch(text));
695         }),
696         allowSpaces: false,
697         autocompleteMode: true,
698         // TODO
699         // menuItemLimit: mentionDropdownFetchLimit,
700         menuShowMinLength: 2,
701       },
702     ],
703   });
704 }
705
706 var tippyInstance: any;
707 if (isBrowser()) {
708   tippyInstance = tippy("[data-tippy-content]");
709 }
710
711 export function setupTippy() {
712   if (isBrowser()) {
713     tippyInstance.forEach((e: any) => e.destroy());
714     tippyInstance = tippy("[data-tippy-content]", {
715       delay: [500, 0],
716       // Display on "long press"
717       touch: ["hold", 500],
718     });
719   }
720 }
721
722 interface PersonTribute {
723   key: string;
724   view: PersonViewSafe;
725 }
726
727 async function personSearch(text: string): Promise<PersonTribute[]> {
728   let users = (await fetchUsers(text)).users;
729   let persons: PersonTribute[] = users.map(pv => {
730     let tribute: PersonTribute = {
731       key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
732       view: pv,
733     };
734     return tribute;
735   });
736   return persons;
737 }
738
739 interface CommunityTribute {
740   key: string;
741   view: CommunityView;
742 }
743
744 async function communitySearch(text: string): Promise<CommunityTribute[]> {
745   let comms = (await fetchCommunities(text)).communities;
746   let communities: CommunityTribute[] = comms.map(cv => {
747     let tribute: CommunityTribute = {
748       key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
749       view: cv,
750     };
751     return tribute;
752   });
753   return communities;
754 }
755
756 export function getListingTypeFromProps(
757   props: any,
758   defaultListingType: ListingType,
759   myUserInfo = UserService.Instance.myUserInfo
760 ): ListingType {
761   return props.match.params.listing_type
762     ? routeListingTypeToEnum(props.match.params.listing_type)
763     : myUserInfo.match({
764         some: me =>
765           Object.values(ListingType)[
766             me.local_user_view.local_user.default_listing_type
767           ],
768         none: defaultListingType,
769       });
770 }
771
772 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
773   return props.match.params.listing_type
774     ? routeListingTypeToEnum(props.match.params.listing_type)
775     : ListingType.Local;
776 }
777
778 // TODO might need to add a user setting for this too
779 export function getDataTypeFromProps(props: any): DataType {
780   return props.match.params.data_type
781     ? routeDataTypeToEnum(props.match.params.data_type)
782     : DataType.Post;
783 }
784
785 export function getSortTypeFromProps(
786   props: any,
787   myUserInfo = UserService.Instance.myUserInfo
788 ): SortType {
789   return props.match.params.sort
790     ? routeSortTypeToEnum(props.match.params.sort)
791     : myUserInfo.match({
792         some: mui =>
793           Object.values(SortType)[
794             mui.local_user_view.local_user.default_sort_type
795           ],
796         none: SortType.Active,
797       });
798 }
799
800 export function getPageFromProps(props: any): number {
801   return props.match.params.page ? Number(props.match.params.page) : 1;
802 }
803
804 export function getRecipientIdFromProps(props: any): number {
805   return props.match.params.recipient_id
806     ? Number(props.match.params.recipient_id)
807     : 1;
808 }
809
810 export function getIdFromProps(props: any): Option<number> {
811   let id: string = props.match.params.post_id;
812   return id ? Some(Number(id)) : None;
813 }
814
815 export function getCommentIdFromProps(props: any): Option<number> {
816   let id: string = props.match.params.comment_id;
817   return id ? Some(Number(id)) : None;
818 }
819
820 export function getUsernameFromProps(props: any): string {
821   return props.match.params.username;
822 }
823
824 export function editCommentRes(data: CommentView, comments: CommentView[]) {
825   let found = comments.find(c => c.comment.id == data.comment.id);
826   if (found) {
827     found.comment.content = data.comment.content;
828     found.comment.distinguished = data.comment.distinguished;
829     found.comment.updated = data.comment.updated;
830     found.comment.removed = data.comment.removed;
831     found.comment.deleted = data.comment.deleted;
832     found.counts.upvotes = data.counts.upvotes;
833     found.counts.downvotes = data.counts.downvotes;
834     found.counts.score = data.counts.score;
835   }
836 }
837
838 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
839   let found = comments.find(c => c.comment.id == data.comment.id);
840   if (found) {
841     found.saved = data.saved;
842   }
843 }
844
845 // TODO Should only use the return now, no state?
846 export function updatePersonBlock(
847   data: BlockPersonResponse,
848   myUserInfo = UserService.Instance.myUserInfo
849 ): Option<PersonBlockView[]> {
850   return myUserInfo.match({
851     some: (mui: MyUserInfo) => {
852       if (data.blocked) {
853         mui.person_blocks.push({
854           person: mui.local_user_view.person,
855           target: data.person_view.person,
856         });
857         toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
858       } else {
859         mui.person_blocks = mui.person_blocks.filter(
860           i => i.target.id != data.person_view.person.id
861         );
862         toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
863       }
864       return Some(mui.person_blocks);
865     },
866     none: None,
867   });
868 }
869
870 export function updateCommunityBlock(
871   data: BlockCommunityResponse,
872   myUserInfo = UserService.Instance.myUserInfo
873 ): Option<CommunityBlockView[]> {
874   return myUserInfo.match({
875     some: (mui: MyUserInfo) => {
876       if (data.blocked) {
877         mui.community_blocks.push({
878           person: mui.local_user_view.person,
879           community: data.community_view.community,
880         });
881         toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
882       } else {
883         mui.community_blocks = mui.community_blocks.filter(
884           i => i.community.id != data.community_view.community.id
885         );
886         toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
887       }
888       return Some(mui.community_blocks);
889     },
890     none: None,
891   });
892 }
893
894 export function createCommentLikeRes(
895   data: CommentView,
896   comments: CommentView[]
897 ) {
898   let found = comments.find(c => c.comment.id === data.comment.id);
899   if (found) {
900     found.counts.score = data.counts.score;
901     found.counts.upvotes = data.counts.upvotes;
902     found.counts.downvotes = data.counts.downvotes;
903     if (data.my_vote !== null) {
904       found.my_vote = data.my_vote;
905     }
906   }
907 }
908
909 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
910   let found = posts.find(p => p.post.id == data.post.id);
911   if (found) {
912     createPostLikeRes(data, found);
913   }
914 }
915
916 export function createPostLikeRes(data: PostView, post_view: PostView) {
917   if (post_view) {
918     post_view.counts.score = data.counts.score;
919     post_view.counts.upvotes = data.counts.upvotes;
920     post_view.counts.downvotes = data.counts.downvotes;
921     if (data.my_vote !== null) {
922       post_view.my_vote = data.my_vote;
923     }
924   }
925 }
926
927 export function editPostFindRes(data: PostView, posts: PostView[]) {
928   let found = posts.find(p => p.post.id == data.post.id);
929   if (found) {
930     editPostRes(data, found);
931   }
932 }
933
934 export function editPostRes(data: PostView, post: PostView) {
935   if (post) {
936     post.post.url = data.post.url;
937     post.post.name = data.post.name;
938     post.post.nsfw = data.post.nsfw;
939     post.post.deleted = data.post.deleted;
940     post.post.removed = data.post.removed;
941     post.post.stickied = data.post.stickied;
942     post.post.body = data.post.body;
943     post.post.locked = data.post.locked;
944     post.saved = data.saved;
945   }
946 }
947
948 // TODO possible to make these generic?
949 export function updatePostReportRes(
950   data: PostReportView,
951   reports: PostReportView[]
952 ) {
953   let found = reports.find(p => p.post_report.id == data.post_report.id);
954   if (found) {
955     found.post_report = data.post_report;
956   }
957 }
958
959 export function updateCommentReportRes(
960   data: CommentReportView,
961   reports: CommentReportView[]
962 ) {
963   let found = reports.find(c => c.comment_report.id == data.comment_report.id);
964   if (found) {
965     found.comment_report = data.comment_report;
966   }
967 }
968
969 export function updatePrivateMessageReportRes(
970   data: PrivateMessageReportView,
971   reports: PrivateMessageReportView[]
972 ) {
973   let found = reports.find(
974     c => c.private_message_report.id == data.private_message_report.id
975   );
976   if (found) {
977     found.private_message_report = data.private_message_report;
978   }
979 }
980
981 export function updateRegistrationApplicationRes(
982   data: RegistrationApplicationView,
983   applications: RegistrationApplicationView[]
984 ) {
985   let found = applications.find(
986     ra => ra.registration_application.id == data.registration_application.id
987   );
988   if (found) {
989     found.registration_application = data.registration_application;
990     found.admin = data.admin;
991     found.creator_local_user = data.creator_local_user;
992   }
993 }
994
995 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
996   let nodes: CommentNodeI[] = [];
997   for (let comment of comments) {
998     nodes.push({ comment_view: comment, children: [], depth: 0 });
999   }
1000   return nodes;
1001 }
1002
1003 export function convertCommentSortType(sort: SortType): CommentSortType {
1004   if (
1005     sort == SortType.TopAll ||
1006     sort == SortType.TopDay ||
1007     sort == SortType.TopWeek ||
1008     sort == SortType.TopMonth ||
1009     sort == SortType.TopYear
1010   ) {
1011     return CommentSortType.Top;
1012   } else if (sort == SortType.New) {
1013     return CommentSortType.New;
1014   } else if (sort == SortType.Hot || sort == SortType.Active) {
1015     return CommentSortType.Hot;
1016   } else {
1017     return CommentSortType.Hot;
1018   }
1019 }
1020
1021 export function buildCommentsTree(
1022   comments: CommentView[],
1023   parentComment: boolean
1024 ): CommentNodeI[] {
1025   let map = new Map<number, CommentNodeI>();
1026   let depthOffset = !parentComment
1027     ? 0
1028     : getDepthFromComment(comments[0].comment);
1029
1030   for (let comment_view of comments) {
1031     let node: CommentNodeI = {
1032       comment_view: comment_view,
1033       children: [],
1034       depth: getDepthFromComment(comment_view.comment) - depthOffset,
1035     };
1036     map.set(comment_view.comment.id, { ...node });
1037   }
1038
1039   let tree: CommentNodeI[] = [];
1040
1041   // if its a parent comment fetch, then push the first comment to the top node.
1042   if (parentComment) {
1043     tree.push(map.get(comments[0].comment.id));
1044   }
1045
1046   for (let comment_view of comments) {
1047     let child = map.get(comment_view.comment.id);
1048     let parent_id = getCommentParentId(comment_view.comment);
1049     parent_id.match({
1050       some: parentId => {
1051         let parent = map.get(parentId);
1052         // Necessary because blocked comment might not exist
1053         if (parent) {
1054           parent.children.push(child);
1055         }
1056       },
1057       none: () => {
1058         if (!parentComment) {
1059           tree.push(child);
1060         }
1061       },
1062     });
1063   }
1064
1065   return tree;
1066 }
1067
1068 export function getCommentParentId(comment: CommentI): Option<number> {
1069   let split = comment.path.split(".");
1070   // remove the 0
1071   split.shift();
1072
1073   if (split.length > 1) {
1074     return Some(Number(split[split.length - 2]));
1075   } else {
1076     return None;
1077   }
1078 }
1079
1080 export function getDepthFromComment(comment: CommentI): number {
1081   return comment.path.split(".").length - 2;
1082 }
1083
1084 export function insertCommentIntoTree(
1085   tree: CommentNodeI[],
1086   cv: CommentView,
1087   parentComment: boolean
1088 ) {
1089   // Building a fake node to be used for later
1090   let node: CommentNodeI = {
1091     comment_view: cv,
1092     children: [],
1093     depth: 0,
1094   };
1095
1096   getCommentParentId(cv.comment).match({
1097     some: parentId => {
1098       let parentComment = searchCommentTree(tree, parentId);
1099       parentComment.match({
1100         some: pComment => {
1101           node.depth = pComment.depth + 1;
1102           pComment.children.unshift(node);
1103         },
1104         none: void 0,
1105       });
1106     },
1107     none: () => {
1108       if (!parentComment) {
1109         tree.unshift(node);
1110       }
1111     },
1112   });
1113 }
1114
1115 export function searchCommentTree(
1116   tree: CommentNodeI[],
1117   id: number
1118 ): Option<CommentNodeI> {
1119   for (let node of tree) {
1120     if (node.comment_view.comment.id === id) {
1121       return Some(node);
1122     }
1123
1124     for (const child of node.children) {
1125       let res = searchCommentTree([child], id);
1126
1127       if (res.isSome()) {
1128         return res;
1129       }
1130     }
1131   }
1132   return None;
1133 }
1134
1135 export const colorList: string[] = [
1136   hsl(0),
1137   hsl(50),
1138   hsl(100),
1139   hsl(150),
1140   hsl(200),
1141   hsl(250),
1142   hsl(300),
1143 ];
1144
1145 function hsl(num: number) {
1146   return `hsla(${num}, 35%, 50%, 1)`;
1147 }
1148
1149 export function hostname(url: string): string {
1150   let cUrl = new URL(url);
1151   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1152 }
1153
1154 export function validTitle(title?: string): boolean {
1155   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1156   if (!title || title.length < 3) return true;
1157
1158   const regex = new RegExp(/.*\S.*/, "g");
1159
1160   return regex.test(title);
1161 }
1162
1163 export function siteBannerCss(banner: string): string {
1164   return ` \
1165     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1166     background-attachment: fixed; \
1167     background-position: top; \
1168     background-repeat: no-repeat; \
1169     background-size: 100% cover; \
1170
1171     width: 100%; \
1172     max-height: 100vh; \
1173     `;
1174 }
1175
1176 export function isBrowser() {
1177   return typeof window !== "undefined";
1178 }
1179
1180 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1181   context: any,
1182   cls1?: ClassConstructor<Type1>,
1183   cls2?: ClassConstructor<Type2>,
1184   cls3?: ClassConstructor<Type3>,
1185   cls4?: ClassConstructor<Type4>,
1186   cls5?: ClassConstructor<Type5>
1187 ): IsoData {
1188   // If its the browser, you need to deserialize the data from the window
1189   if (isBrowser()) {
1190     let json = window.isoData;
1191     let routeData = json.routeData;
1192     let routeDataOut: any[] = [];
1193
1194     // Can't do array looping because of specific type constructor required
1195     if (routeData[0]) {
1196       routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1197     }
1198     if (routeData[1]) {
1199       routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1200     }
1201     if (routeData[2]) {
1202       routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1203     }
1204     if (routeData[3]) {
1205       routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1206     }
1207     if (routeData[4]) {
1208       routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1209     }
1210     let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1211
1212     let isoData: IsoData = {
1213       path: json.path,
1214       site_res,
1215       routeData: routeDataOut,
1216     };
1217     return isoData;
1218   } else return context.router.staticContext;
1219 }
1220
1221 /**
1222  * Necessary since window ISOData can't store function types like Option
1223  */
1224 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1225   return deserialize(cls, serialize(data));
1226 }
1227
1228 export function wsSubscribe(parseMessage: any): Subscription {
1229   if (isBrowser()) {
1230     return WebSocketService.Instance.subject
1231       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1232       .subscribe(
1233         msg => parseMessage(msg),
1234         err => console.error(err),
1235         () => console.log("complete")
1236       );
1237   } else {
1238     return null;
1239   }
1240 }
1241
1242 moment.updateLocale("en", {
1243   relativeTime: {
1244     future: "in %s",
1245     past: "%s ago",
1246     s: "<1m",
1247     ss: "%ds",
1248     m: "1m",
1249     mm: "%dm",
1250     h: "1h",
1251     hh: "%dh",
1252     d: "1d",
1253     dd: "%dd",
1254     w: "1w",
1255     ww: "%dw",
1256     M: "1M",
1257     MM: "%dM",
1258     y: "1Y",
1259     yy: "%dY",
1260   },
1261 });
1262
1263 export function saveScrollPosition(context: any) {
1264   let path: string = context.router.route.location.pathname;
1265   let y = window.scrollY;
1266   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1267 }
1268
1269 export function restoreScrollPosition(context: any) {
1270   let path: string = context.router.route.location.pathname;
1271   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1272   window.scrollTo(0, y);
1273 }
1274
1275 export function showLocal(isoData: IsoData): boolean {
1276   return isoData.site_res.federated_instances
1277     .map(f => f.linked.length > 0)
1278     .unwrapOr(false);
1279 }
1280
1281 export interface ChoicesValue {
1282   value: string;
1283   label: string;
1284 }
1285
1286 export function communityToChoice(cv: CommunityView): ChoicesValue {
1287   let choice: ChoicesValue = {
1288     value: cv.community.id.toString(),
1289     label: communitySelectName(cv),
1290   };
1291   return choice;
1292 }
1293
1294 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1295   let choice: ChoicesValue = {
1296     value: pvs.person.id.toString(),
1297     label: personSelectName(pvs),
1298   };
1299   return choice;
1300 }
1301
1302 export async function fetchCommunities(q: string) {
1303   let form = new Search({
1304     q,
1305     type_: Some(SearchType.Communities),
1306     sort: Some(SortType.TopAll),
1307     listing_type: Some(ListingType.All),
1308     page: Some(1),
1309     limit: Some(fetchLimit),
1310     community_id: None,
1311     community_name: None,
1312     creator_id: None,
1313     auth: auth(false).ok(),
1314   });
1315   let client = new LemmyHttp(httpBase);
1316   return client.search(form);
1317 }
1318
1319 export async function fetchUsers(q: string) {
1320   let form = new Search({
1321     q,
1322     type_: Some(SearchType.Users),
1323     sort: Some(SortType.TopAll),
1324     listing_type: Some(ListingType.All),
1325     page: Some(1),
1326     limit: Some(fetchLimit),
1327     community_id: None,
1328     community_name: None,
1329     creator_id: None,
1330     auth: auth(false).ok(),
1331   });
1332   let client = new LemmyHttp(httpBase);
1333   return client.search(form);
1334 }
1335
1336 export const choicesConfig = {
1337   shouldSort: false,
1338   searchResultLimit: fetchLimit,
1339   classNames: {
1340     containerOuter: "choices custom-select px-0",
1341     containerInner:
1342       "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1343     input: "form-control",
1344     inputCloned: "choices__input--cloned",
1345     list: "choices__list",
1346     listItems: "choices__list--multiple",
1347     listSingle: "choices__list--single py-0",
1348     listDropdown: "choices__list--dropdown",
1349     item: "choices__item bg-secondary",
1350     itemSelectable: "choices__item--selectable",
1351     itemDisabled: "choices__item--disabled",
1352     itemChoice: "choices__item--choice",
1353     placeholder: "choices__placeholder",
1354     group: "choices__group",
1355     groupHeading: "choices__heading",
1356     button: "choices__button",
1357     activeState: "is-active",
1358     focusState: "is-focused",
1359     openState: "is-open",
1360     disabledState: "is-disabled",
1361     highlightedState: "text-info",
1362     selectedState: "text-info",
1363     flippedState: "is-flipped",
1364     loadingState: "is-loading",
1365     noResults: "has-no-results",
1366     noChoices: "has-no-choices",
1367   },
1368 };
1369
1370 export function communitySelectName(cv: CommunityView): string {
1371   return cv.community.local
1372     ? cv.community.title
1373     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1374 }
1375
1376 export function personSelectName(pvs: PersonViewSafe): string {
1377   let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1378   return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1379 }
1380
1381 export function initializeSite(site: GetSiteResponse) {
1382   UserService.Instance.myUserInfo = site.my_user;
1383   i18n.changeLanguage(getLanguages()[0]);
1384 }
1385
1386 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1387   maximumSignificantDigits: 3,
1388   //@ts-ignore
1389   notation: "compact",
1390   compactDisplay: "short",
1391 });
1392
1393 export function numToSI(value: number): string {
1394   return SHORTNUM_SI_FORMAT.format(value);
1395 }
1396
1397 export function isBanned(ps: PersonSafe): boolean {
1398   let expires = ps.ban_expires;
1399   // Add Z to convert from UTC date
1400   // TODO this check probably isn't necessary anymore
1401   if (expires.isSome()) {
1402     if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1403       return true;
1404     } else {
1405       return false;
1406     }
1407   } else {
1408     return ps.banned;
1409   }
1410 }
1411
1412 export function pushNotNull(array: any[], new_item?: any) {
1413   if (new_item) {
1414     array.push(...new_item);
1415   }
1416 }
1417
1418 export function auth(throwErr = true): Result<string, string> {
1419   return UserService.Instance.auth(throwErr);
1420 }
1421
1422 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1423   return siteRes.site_view.map(s => s.site.enable_downvotes).unwrapOr(true);
1424 }
1425
1426 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1427   return siteRes.site_view.map(s => s.site.enable_nsfw).unwrapOr(false);
1428 }
1429
1430 export function postToCommentSortType(sort: SortType): CommentSortType {
1431   if ([SortType.Active, SortType.Hot].includes(sort)) {
1432     return CommentSortType.Hot;
1433   } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1434     return CommentSortType.New;
1435   } else if (sort == SortType.Old) {
1436     return CommentSortType.Old;
1437   } else {
1438     return CommentSortType.Top;
1439   }
1440 }
1441
1442 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1443   let out = arr.at(index);
1444   if (out == undefined) {
1445     return Err("Index undefined");
1446   } else {
1447     return Ok(out);
1448   }
1449 }
1450
1451 export function myFirstDiscussionLanguageId(
1452   myUserInfo = UserService.Instance.myUserInfo
1453 ): Option<number> {
1454   return myUserInfo.andThen(mui =>
1455     arrayGet(mui.discussion_languages, 0)
1456       .ok()
1457       .map(i => i.id)
1458   );
1459 }
1460
1461 export function canCreateCommunity(
1462   siteRes: GetSiteResponse,
1463   myUserInfo = UserService.Instance.myUserInfo
1464 ): boolean {
1465   let adminOnly = siteRes.site_view
1466     .map(s => s.site.community_creation_admin_only)
1467     .unwrapOr(false);
1468   return !adminOnly || amAdmin(myUserInfo);
1469 }
1470
1471 export function isPostBlocked(
1472   pv: PostView,
1473   myUserInfo = UserService.Instance.myUserInfo
1474 ): boolean {
1475   return myUserInfo
1476     .map(
1477       mui =>
1478         mui.community_blocks
1479           .map(c => c.community.id)
1480           .includes(pv.community.id) ||
1481         mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1482     )
1483     .unwrapOr(false);
1484 }
1485
1486 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1487 export function nsfwCheck(
1488   pv: PostView,
1489   myUserInfo = UserService.Instance.myUserInfo
1490 ): boolean {
1491   let nsfw = pv.post.nsfw || pv.community.nsfw;
1492   return (
1493     !nsfw ||
1494     (nsfw &&
1495       myUserInfo
1496         .map(m => m.local_user_view.local_user.show_nsfw)
1497         .unwrapOr(false))
1498   );
1499 }