summaryrefslogtreecommitdiff
path: root/packages/megalodon/src/parser.ts
blob: 2ddf2ac2e692eb493fb2438418ffdfa5b67bd9fb (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
import { EventEmitter } from "events";
import Entity from "./entity";

/**
 * Parser
 * Parse response data in streaming.
 **/
export class Parser extends EventEmitter {
	private message: string;

	constructor() {
		super();
		this.message = "";
	}

	public parse(chunk: string) {
		// skip heartbeats
		if (chunk === ":thump\n") {
			this.emit("heartbeat", {});
			return;
		}

		this.message += chunk;
		chunk = this.message;

		const size: number = chunk.length;
		let start = 0;
		let offset = 0;
		let curr: string | undefined;
		let next: string | undefined;

		while (offset < size) {
			curr = chunk[offset];
			next = chunk[offset + 1];

			if (curr === "\n" && next === "\n") {
				const piece: string = chunk.slice(start, offset);

				offset += 2;
				start = offset;

				if (!piece.length) continue; // empty object

				const root: Array<string> = piece.split("\n");

				// should never happen, as long as mastodon doesn't change API messages
				if (root.length !== 2) continue;

				// remove event and data markers
				const event: string = root[0].substr(7);
				const data: string = root[1].substr(6);

				let jsonObj = {};
				try {
					jsonObj = JSON.parse(data);
				} catch (err) {
					// delete event does not have json object
					if (event !== "delete") {
						this.emit(
							"error",
							new Error(
								`Error parsing API reply: '${piece}', error message: '${err}'`,
							),
						);
						continue;
					}
				}
				switch (event) {
					case "update":
						this.emit("update", jsonObj as Entity.Status);
						break;
					case "notification":
						this.emit("notification", jsonObj as Entity.Notification);
						break;
					case "conversation":
						this.emit("conversation", jsonObj as Entity.Conversation);
						break;
					case "delete":
						// When delete, data is an ID of the deleted status
						this.emit("delete", data);
						break;
					default:
						this.emit(
							"error",
							new Error(`Unknown event has received: ${event}`),
						);
						continue;
				}
			}
			offset++;
		}
		this.message = chunk.slice(start, size);
	}
}