/
monetization-handler.ts
265 lines (230 loc) · 8.49 KB
/
monetization-handler.ts
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { BaseMonetizationEventDetail, Monetization, MonetizationProgressEventDetail, MonetizationState, MonetizationStopEventDetail } from 'types-wm';
import { v4 as uuidv4 } from "uuid";
/**
* Fetch this class from your WmpClient object, instead of instantiating it yourself!
*
* ```ts
* myWmpClient.getMonetizationHandler()
* ```
*/
export class MonetizationHandler {
private wm: Monetization
paymentPointer: string | null = null;
monetizationId: string | null = null;
constructor() {
// Test WM capability
this.wm = document.monetization;
if (!this.isMonetizationSupported()) {
throw new Error('No web monetization support in browser!')
}
// Detect tags
this.startDetection();
}
/**
* Is Web Monetization supported (document.monetization != undefined)?
*/
isMonetizationSupported(): boolean {
return this.wm != undefined && this.wm != null;
}
/**
* Checks the document.monetization.state property for a `'pending'` or `'stopped'` state.
* @returns True if state property is defined and not `'started'`
* @throws If state is not one of `'pending'`, `'stopped'` or `'started'`
*/
isReadyForPayment(): boolean {
if (this.wm.state != 'pending' && this.wm.state != 'stopped' && this.wm.state != 'started') {
throw new Error('No meta[name="monetization"] tag found!')
} else {
return this.wm.state != 'started';
}
}
/**
* Start detecting meta tags
*/
private startDetection() {
const found = this.searchStaticMetaTag();
// Not found, means WM is detected, but no tag found yet
if (!found) { this.setMonetizationState('stopped'); }
// Keep searching for meta tag changes
this.listenForMetaTagChanges();
}
/**
* Search for static meta tag.
* @returns True if found, false otherwise
*/
private searchStaticMetaTag(): boolean {
let metas = document.getElementsByTagName('meta');
let meta = metas.namedItem('monetization');
if (meta && meta.content) {
this.setPaymentPointer(meta.content);
return true;
}
return false;
}
/**
* Start listening for changes on the meta[name=monetization] in the head section
*/
private listenForMetaTagChanges() {
const observerHead = new MutationObserver(list => {
list.forEach(record => {
if (record.addedNodes.length > 0) {
record.addedNodes.forEach(node => {
const el = node as HTMLElement;
if (el.getAttribute('name') == 'monetization' && el.getAttribute('content') != this.paymentPointer) {
this.setPaymentPointer(el.getAttribute('content')!!);
// add observer on meta tag for attribute changes
observerMeta.observe(el, { attributes: true, childList: false, subtree: false });
}
});
}
if (record.removedNodes.length > 0) {
record.removedNodes.forEach(node => {
const el = node as HTMLElement;
if (el.getAttribute('name') == 'monetization' && el.getAttribute('content') == this.paymentPointer) {
this.resetPaymentPointer();
// disconnect existing observer for meta tag
observerMeta.disconnect();
}
});
}
});
});
const observerMeta = new MutationObserver(list => {
list.forEach(record => {
if (record.type == 'attributes' && record.attributeName == 'content') {
const el = record.target as HTMLElement;
this.setPaymentPointer(el.getAttribute('content')!!);
}
});
});
observerHead.observe(document.head, { attributes: false, childList: true, subtree: false })
// If meta tag present: add observer for meta tag
const targetNode = document.querySelector("meta[name='monetization']");
if (targetNode) {
observerMeta.observe(targetNode, { attributes: true, childList: false, subtree: false });
}
}
/**
* Returns wether the document.monetization.state equals 'started'
* @returns True if state equals 'started'
*/
isStarted(): boolean {
return this.wm.state == 'started';
}
/**
* Returns wether the document.monetization.state equals 'stopped'
* @returns True if state equals 'stopped'
*/
isStopped(): boolean {
return this.wm.state == 'stopped';
}
/**
* Returns wether the document.monetization.state equals 'pending'
* @returns True if state equals 'pending'
*/
isPending(): boolean {
return this.wm.state == 'pending';
}
/**
* Sets the monetization state. And optionally sends a matching event from the monetization event source.
* @param state New state to set
* @param event Event details to dispatch on the monetization eventsource.
*/
private setMonetizationState(state: MonetizationState, detail?: BaseMonetizationEventDetail | MonetizationStopEventDetail) {
this.wm.state = state;
let event: CustomEvent<BaseMonetizationEventDetail | MonetizationStopEventDetail>;
switch (state) {
case 'started':
event = new CustomEvent('monetizationstart', { detail });
break;
case 'stopped':
event = new CustomEvent('monetizationstop', { detail });
break;
case 'pending':
event = new CustomEvent('monetizationpending', { detail });
break;
}
this.wm.dispatchEvent(event);
}
/**
* Sends a monetizationprogress event from the monetization event source.
* @param detail The details to be sent with the event.
*/
private sendProgressEvent(detail: MonetizationProgressEventDetail) {
this.wm.dispatchEvent(new CustomEvent('monetizationprogress', { detail }));
}
/**
* Sets a new payment pointer string and generates a unique (uuid v4) monetizationId.
* @param pointer The new payment pointer string
*/
private setPaymentPointer(pointer: string) {
if (pointer != this.paymentPointer) {
if (this.isStarted()) {
this.firePaymentStopped(true);
}
this.paymentPointer = pointer;
this.monetizationId = uuidv4();
this.wmPending();
}
}
/**
* Resets the paymnet pointer back to null.
*/
private resetPaymentPointer() {
if (this.paymentPointer != null) {
this.firePaymentStopped(true);
this.paymentPointer = null;
this.monetizationId = null;
}
}
/**
* Monetization meta tag found, no payments sent yet
*/
private wmPending() {
const detail = {
paymentPointer: this.paymentPointer,
requestId: this.monetizationId
};
this.setMonetizationState('pending', detail);
}
/**
* Payment stream started, first payment sent.
* Fires proper events.
*/
firePaymentStarted(): void {
const detail = {
paymentPointer: this.paymentPointer,
requestId: this.monetizationId,
};
this.setMonetizationState('started', detail);
}
/**
* Payment stream stopped.
* Fires proper events.
* @param finalized True when meta tag was removed or payment pointer changed
*/
firePaymentStopped(finalized: boolean): void {
const detail = {
paymentPointer: this.paymentPointer,
requestId: this.monetizationId,
finalized
};
this.setMonetizationState('stopped', detail);
}
/**
* Payment busy, report progress.
* Fires proper events.
* @param evt The event to parse the `data` property from
*/
firePaymentProgress(evt: MessageEvent): void {
const data = JSON.parse(evt.data);
const detail = {
paymentPointer: this.paymentPointer,
requestId: this.monetizationId,
amount: data.amount,
assetCode: data.assetCode,
assetScale: data.assetScale
}
this.sendProgressEvent(detail);
}
}