summaryrefslogtreecommitdiff
path: root/src/renderer/gameserver/news.ts
blob: 656238ca06e0efa1bc5c21eef9b4c63279c1d55d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export enum NewsType {
  Markdown, // Without html + yaml
  ManaPlus //update news txt
}

export namespace News { // Fetches only the most recent entry
  export async function get(url:string,parser:NewsType):Promise<string>{
    try {
      //1. load
      const unsafe_content = await request(`${url}?${Math.random()}`);
      //2. sanitize
      const content = killHTML( unsafe_content );
      //3. parse
      if(parser == NewsType.ManaPlus){
        return manaTextParser(content);
      } else if (parser == NewsType.Markdown){
        return "Parsing Failed: Markdown Parser is not implemented yet";
      }
    } catch (e){
      console.log(e);
      return `Failed to get the news, please select the news category on the right to view all news`;
    }
  }
}

function request(url:string):Promise<string>{
  return new Promise((res, rej)=>{
      var xhr = new XMLHttpRequest();
      xhr.addEventListener("error", (ev)=>{
        rej(ev);
      });
      xhr.open('GET', url);
      xhr.onload = function() {
        if (xhr.status === 200) {
          res(xhr.responseText);
        }
        else {
          rej(new Error(`xhr.status: ${xhr.status} != 200`));
        }
      };
      xhr.send();
  });
}

function killHTML(raw:string):string{
  return raw.replace(/<|>/,"⚠️");
}

function manaTextParser(input:string){
  const tmwLegacy = "##7Legacy Server##0";
  let result = input;
  if(result.indexOf(tmwLegacy) !== -1){
    const i = result.indexOf(tmwLegacy) + tmwLegacy.length;
    result = result.slice(0, result.indexOf(tmwLegacy, i));
    result = result.replace(/\n \n /, "");
  }
  result = result.replace(/\[@@(.+?)\|(.+?)@@\]/g,'<a href="$1">$2</a>')
  .replace(/##B(.+?)##b/g,'<b>$1</b>')
  .replace(/##0 Actual Release: ##1 *(.+)/,'<h2>$1</h2>')
  .replace(/\n/g,"<br>");
  if(result.indexOf(tmwLegacy) === -1)
    result = result.replace(/br>([^]+?)<br></g,'br><p>$1</p><br><').replace(/<br>/g,"");
  return result.replace(/##\d/g,"");
}