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