summary refs log tree commit diff
path: root/main.ts
blob: 418b3bf01580b6f9b0996de610b1295888205a16 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { EventEmitter } from "node:events";

interface MessageArg {
    message: string,
    replyTo?: string
}

export default class MAELINK extends EventEmitter {
    private token: string | null = null;
    private _ws: WebSocket;
    private http: string;
    username?: string;

    get ws(): WebSocket {
        return this._ws
    }

    get(path: string, headers: Record<string, string> = {}) {
        console.log(this.http + path);
        if (this.token) headers = {...headers, token: this.token};
        return fetch(this.http + path, {
            headers,
        })
    }

    post(path: string, body: string | object, headers: Record<string, string> = {}) {
        console.log(this.http + path);
        if (this.token) headers = {...headers, token: this.token};
        if (typeof body == "object") {
            headers['content-type'] = 'application/json'
            body = JSON.stringify(body);
        }
        return fetch(this.http + path, {
            headers,
            body,
            method: 'POST'
        })
    }

    constructor (
        server: string = 'wss://maelink-ws.derpygamer2142.com', 
        http: string = 'https://maelink-http.derpygamer2142.com'
    ) {
        super()
        this._ws = new WebSocket(server)
        this.http = http
        // deno-lint-ignore no-this-alias
        const client = this;
        this._ws.addEventListener('message', function (ev) {
            const data = JSON.parse(ev.data);
            client.emit('message', data)
            client.emit('cmd_'+data.cmd, data)
            switch (data.cmd) {
                case 'post_home':
                    client.emit('post', data.post)
                    break;
            
                default:
                    break;
            }
        })
    }

    async login(username: string, password: string) {
        const resp = await this.post('/login', { username, password });
        if (resp.status != 200) throw 'Status not ok, status is ' + resp.status;
        const data = await resp.json()
        if (data.status !== 'success') throw 'Login failed: ' + data.message
        this.token = data.token
        this.username = username
        return data
    }

    sendMessage(message: string | MessageArg) {
        if (!this.token) throw 'You must be logged in to send messages'
        if (!message || typeof message == 'object' && message.message.length < 1) throw 'Message cannot be empty'
        this._ws.send(JSON.stringify({
            cmd: 'post',
            p: typeof message == 'object' ? message.message : message,
            token: this.token,
            reply_to: typeof message == 'object' ? message.replyTo : undefined
        }));
    }

    fetchMessages(offset: number = 0) {
        return new Promise((resolve, reject) => {
            this._ws.send(JSON.stringify({
                cmd: "fetch",
                offset: offset
            }))
            this.once('cmd_fetch', (resp) => {
                if (resp.status !== 'success') return reject();
                resolve(resp.posts)
            })
        })
    }
}