forked from dgreif/ring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathring-intercom.ts
113 lines (98 loc) · 2.54 KB
/
ring-intercom.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
import {
IntercomHandsetAudioData,
PushNotification,
PushNotificationAction,
} from './ring-types'
import { clientApi, commandsApi, RingRestClient } from './rest-client'
import { BehaviorSubject, Subject } from 'rxjs'
import { distinctUntilChanged, map } from 'rxjs/operators'
import { getBatteryLevel } from './ring-camera'
import { logError } from './util'
export class RingIntercom {
id
deviceType
onData
onRequestUpdate = new Subject()
onBatteryLevel
onDing = new Subject<void>()
onUnlocked = new Subject<void>()
constructor(
private initialData: IntercomHandsetAudioData,
private restClient: RingRestClient
) {
this.id = this.initialData.id
this.deviceType = this.initialData.kind
this.onData = new BehaviorSubject<IntercomHandsetAudioData>(
this.initialData
)
this.onBatteryLevel = this.onData.pipe(
map((data) => getBatteryLevel(data)),
distinctUntilChanged()
)
if (!initialData.subscribed) {
this.subscribeToDingEvents().catch((e) => {
logError(
'Failed to subscribe ' + initialData.description + ' to ding events'
)
logError(e)
})
}
}
updateData(update: IntercomHandsetAudioData) {
this.onData.next(update)
}
requestUpdate() {
this.onRequestUpdate.next(null)
}
get data() {
return this.onData.getValue()
}
get name() {
return this.data.description
}
get isOffline() {
return this.data.alerts.connection === 'offline'
}
get batteryLevel() {
return getBatteryLevel(this.data)
}
unlock() {
return this.restClient.request<unknown>({
method: 'PUT',
url: commandsApi(`devices/${this.id}/device_rpc`),
json: {
command_name: 'device_rpc',
request: {
jsonrpc: '2.0',
method: 'unlock_door',
params: {
door_id: 0,
user_id: 0,
},
},
},
})
}
private doorbotUrl(path = '') {
return clientApi(`doorbots/${this.id}/${path}`)
}
subscribeToDingEvents() {
return this.restClient.request({
method: 'POST',
url: this.doorbotUrl('subscribe'),
})
}
unsubscribeFromDingEvents() {
return this.restClient.request({
method: 'POST',
url: this.doorbotUrl('unsubscribe'),
})
}
processPushNotification(notification: PushNotification) {
if (notification.action === PushNotificationAction.Ding) {
this.onDing.next()
} else if (notification.action === PushNotificationAction.IntercomUnlock) {
this.onUnlocked.next()
}
}
}