forked from dgreif/ring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
244 lines (212 loc) · 6.41 KB
/
api.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
import { clientApi, RingAuth, RingRestClient } from './rest-client'
import { Location } from './location'
import {
ActiveDing,
BaseStation,
BeamBridge,
CameraData,
UserLocation
} from './ring-types'
import { RingCamera } from './ring-camera'
import { EMPTY, merge, Subject } from 'rxjs'
import { debounceTime, switchMap, throttleTime } from 'rxjs/operators'
import { enableDebug } from './util'
import { setPreferredExternalPorts } from './rtp-utils'
export interface RingApiOptions {
locationIds?: string[]
cameraStatusPollingSeconds?: number
cameraDingsPollingSeconds?: number
debug?: boolean
externalPorts?: {
start: number
end: number
}
}
export class RingApi {
public readonly restClient = new RingRestClient(this.options)
public readonly onRefreshTokenUpdated = this.restClient.onRefreshTokenUpdated.asObservable()
private locations = this.fetchAndBuildLocations()
constructor(public readonly options: RingApiOptions & RingAuth) {
if (options.debug) {
enableDebug()
}
const { externalPorts } = options
if (typeof externalPorts === 'object') {
const { start, end } = externalPorts,
portConfigIssues: string[] = []
if (!start || !end) {
portConfigIssues.push('start and end must both be defined')
}
if (start >= end) {
portConfigIssues.push('start must be larger than end')
}
if (start < 1024) {
portConfigIssues.push(
'start must be larger than 1024, preferably larger than 10000 to avoid conflicts'
)
}
if (end > 65535) {
portConfigIssues.push('end must be smaller than 65536')
}
if (portConfigIssues.length) {
throw new Error(
'Invalid externalPorts config: ' + portConfigIssues.join('; ')
)
}
setPreferredExternalPorts(start, end)
}
}
async fetchRingDevices() {
const {
doorbots,
authorized_doorbots: authorizedDoorbots,
stickup_cams: stickupCams,
base_stations: baseStations,
beams_bridges: beamBridges
} = await this.restClient.request<{
doorbots: CameraData[]
authorized_doorbots: CameraData[]
stickup_cams: CameraData[]
base_stations: BaseStation[]
beams_bridges: BeamBridge[]
}>({ url: clientApi('ring_devices') })
return {
doorbots,
authorizedDoorbots,
stickupCams,
allCameras: doorbots.concat(stickupCams, authorizedDoorbots),
baseStations,
beamBridges
}
}
fetchActiveDings() {
return this.restClient.request<ActiveDing[]>({
url: clientApi('dings/active')
})
}
private listenForCameraUpdates(cameras: RingCamera[]) {
const {
cameraStatusPollingSeconds,
cameraDingsPollingSeconds
} = this.options,
onCamerasRequestUpdate = merge(
...cameras.map(camera => camera.onRequestUpdate)
),
onCamerasRequestActiveDings = merge(
...cameras.map(camera => camera.onRequestActiveDings)
),
onUpdateReceived = new Subject(),
onActiveDingsReceived = new Subject(),
onPollForStatusUpdate = cameraStatusPollingSeconds
? onUpdateReceived.pipe(debounceTime(cameraStatusPollingSeconds * 1000))
: EMPTY,
onPollForActiveDings = cameraDingsPollingSeconds
? onActiveDingsReceived.pipe(
debounceTime(cameraDingsPollingSeconds * 1000)
)
: EMPTY,
camerasById = cameras.reduce((byId, camera) => {
byId[camera.id] = camera
return byId
}, {} as { [id: number]: RingCamera })
if (!cameras.length) {
return
}
merge(onCamerasRequestUpdate, onPollForStatusUpdate)
.pipe(
throttleTime(500),
switchMap(async () => {
const response = await this.fetchRingDevices().catch(() => null)
return response && response.allCameras
})
)
.subscribe(cameraData => {
onUpdateReceived.next()
if (!cameraData) {
return
}
cameraData.forEach(data => {
const camera = camerasById[data.id]
if (camera) {
camera.updateData(data)
}
})
})
if (cameraStatusPollingSeconds) {
onUpdateReceived.next() // kick off polling
}
merge(onCamerasRequestActiveDings, onPollForActiveDings).subscribe(
async () => {
const activeDings = await this.fetchActiveDings().catch(() => null)
onActiveDingsReceived.next()
if (!activeDings || !activeDings.length) {
return
}
activeDings.forEach(activeDing => {
const camera = camerasById[activeDing.doorbot_id]
if (camera) {
camera.processActiveDing(activeDing)
}
})
}
)
if (cameraDingsPollingSeconds) {
onActiveDingsReceived.next() // kick off polling
}
}
async fetchRawLocations() {
const { user_locations: rawLocations } = await this.restClient.request<{
user_locations: UserLocation[]
}>({ url: 'https://app.ring.com/rhq/v1/devices/v1/locations' })
return rawLocations
}
async fetchAndBuildLocations() {
const rawLocations = await this.fetchRawLocations(),
{
authorizedDoorbots,
doorbots,
allCameras,
baseStations,
beamBridges
} = await this.fetchRingDevices(),
locationIdsWithHubs = [...baseStations, ...beamBridges].map(
x => x.location_id
),
cameras = allCameras.map(
data =>
new RingCamera(
data,
doorbots.includes(data) || authorizedDoorbots.includes(data),
this.restClient
)
),
locations = rawLocations
.filter(location => {
return (
!Array.isArray(this.options.locationIds) ||
this.options.locationIds.includes(location.location_id)
)
})
.map(
location =>
new Location(
location,
cameras.filter(x => x.data.location_id === location.location_id),
locationIdsWithHubs.includes(location.location_id),
this.restClient
)
)
this.listenForCameraUpdates(cameras)
return locations
}
getLocations() {
return this.locations
}
async getCameras() {
const locations = await this.locations
return locations.reduce(
(cameras, location) => [...cameras, ...location.cameras],
[] as RingCamera[]
)
}
}