@scrypted/server 0.147.0 → 0.148.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/cluster/cluster-setup.js +16 -17
  2. package/dist/cluster/cluster-setup.js.map +1 -1
  3. package/dist/http-interfaces.js +16 -2
  4. package/dist/http-interfaces.js.map +1 -1
  5. package/dist/plugin/media.d.ts +5 -39
  6. package/dist/plugin/media.js +73 -109
  7. package/dist/plugin/media.js.map +1 -1
  8. package/dist/plugin/plugin-console.d.ts +2 -0
  9. package/dist/plugin/plugin-console.js +10 -0
  10. package/dist/plugin/plugin-console.js.map +1 -1
  11. package/dist/plugin/plugin-host.js +7 -3
  12. package/dist/plugin/plugin-host.js.map +1 -1
  13. package/dist/plugin/plugin-remote-worker.js.map +1 -1
  14. package/dist/plugin/plugin-remote.d.ts +15 -0
  15. package/dist/plugin/plugin-remote.js +36 -39
  16. package/dist/plugin/plugin-remote.js.map +1 -1
  17. package/dist/rpc-serializer.js +4 -0
  18. package/dist/rpc-serializer.js.map +1 -1
  19. package/dist/rpc.d.ts +2 -0
  20. package/dist/rpc.js +29 -1
  21. package/dist/rpc.js.map +1 -1
  22. package/dist/scrypted-cluster-main.js +20 -0
  23. package/dist/scrypted-cluster-main.js.map +1 -1
  24. package/dist/scrypted-server-main.js +31 -15
  25. package/dist/scrypted-server-main.js.map +1 -1
  26. package/dist/services/cluster-fork.js +3 -3
  27. package/dist/services/cluster-fork.js.map +1 -1
  28. package/dist/services/plugin.d.ts +1 -0
  29. package/dist/services/plugin.js +5 -0
  30. package/dist/services/plugin.js.map +1 -1
  31. package/package.json +1 -1
  32. package/python/cluster_setup.py +20 -20
  33. package/python/plugin_remote.py +0 -1
  34. package/python/rpc_reader.py +28 -8
  35. package/src/cluster/cluster-setup.ts +16 -17
  36. package/src/http-interfaces.ts +16 -2
  37. package/src/plugin/media.ts +95 -120
  38. package/src/plugin/plugin-console.ts +11 -0
  39. package/src/plugin/plugin-host.ts +14 -4
  40. package/src/plugin/plugin-remote-worker.ts +1 -1
  41. package/src/plugin/plugin-remote.ts +43 -41
  42. package/src/rpc-serializer.ts +4 -0
  43. package/src/rpc.ts +31 -1
  44. package/src/scrypted-cluster-main.ts +24 -0
  45. package/src/scrypted-server-main.ts +34 -16
  46. package/src/services/cluster-fork.ts +3 -3
  47. package/src/services/plugin.ts +6 -0
@@ -212,7 +212,7 @@ class ClusterSetup:
212
212
  return clusterPeerPromise
213
213
 
214
214
  async def connectRPCObject(self, value):
215
- __cluster = getattr(value, "__cluster")
215
+ __cluster = getattr(value, "__cluster", None)
216
216
  if type(__cluster) is not dict:
217
217
  return value
218
218
 
@@ -221,31 +221,31 @@ class ClusterSetup:
221
221
  if clusterObject.get("id", None) != self.clusterId:
222
222
  return value
223
223
 
224
+ if self.computeClusterObjectHash(clusterObject) != clusterObject.get("sha256", None):
225
+ raise Exception("invalid cluster object signature")
226
+
224
227
  address = clusterObject.get("address", None)
225
228
  port = clusterObject["port"]
226
229
  proxyId = clusterObject["proxyId"]
227
- if port == self.clusterPort:
230
+ if isClusterAddress(address) and port == self.clusterPort:
228
231
  return await self.connectClusterObject(clusterObject)
229
232
 
230
233
  clusterPeerPromise = self.ensureClusterPeer(address, port)
231
234
 
232
- try:
233
- clusterPeer = await clusterPeerPromise
234
- weakref = clusterPeer.remoteWeakProxies.get(proxyId, None)
235
- existing = weakref() if weakref else None
236
- if existing:
237
- return existing
238
-
239
- peerConnectRPCObject = clusterPeer.tags.get("connectRPCObject")
240
- if not peerConnectRPCObject:
241
- peerConnectRPCObject = await clusterPeer.getParam("connectRPCObject")
242
- clusterPeer.tags["connectRPCObject"] = peerConnectRPCObject
243
- newValue = await peerConnectRPCObject(clusterObject)
244
- if not newValue:
245
- raise Exception("rpc object not found?")
246
- return newValue
247
- except Exception as e:
248
- return value
235
+ clusterPeer = await clusterPeerPromise
236
+ weakref = clusterPeer.remoteWeakProxies.get(proxyId, None)
237
+ existing = weakref() if weakref else None
238
+ if existing:
239
+ return existing
240
+
241
+ peerConnectRPCObject = clusterPeer.tags.get("connectRPCObject")
242
+ if not peerConnectRPCObject:
243
+ peerConnectRPCObject = await clusterPeer.getParam("connectRPCObject")
244
+ clusterPeer.tags["connectRPCObject"] = peerConnectRPCObject
245
+ newValue = await peerConnectRPCObject(clusterObject)
246
+ if not newValue:
247
+ raise Exception("rpc object not found?")
248
+ return newValue
249
249
 
250
250
 
251
251
  class ClusterServerListener(TypedDict):
@@ -258,7 +258,7 @@ async def cluster_listen_zero(
258
258
  ) -> ClusterServerListener:
259
259
  SCRYPTED_CLUSTER_ADDRESS = os.getenv("SCRYPTED_CLUSTER_ADDRESS")
260
260
  if not SCRYPTED_CLUSTER_ADDRESS or SCRYPTED_CLUSTER_ADDRESS == "127.0.0.1":
261
- server = await asyncio.start_server(callback, host=None, port=0)
261
+ server = await asyncio.start_server(callback, host="127.0.0.1", port=0)
262
262
  port = server.sockets[0].getsockname()[1]
263
263
  return {
264
264
  "server": server,
@@ -663,7 +663,6 @@ class PluginRemote:
663
663
  "ioEvent",
664
664
  "setNativeId",
665
665
  ]
666
- self.peer.params["createMediaManager"] = lambda: api.getMediaManager()
667
666
 
668
667
  async def print_async(
669
668
  self,
@@ -9,6 +9,7 @@ import os
9
9
  import pickle
10
10
  import threading
11
11
  from asyncio.events import AbstractEventLoop
12
+ from collections import deque
12
13
  from concurrent.futures import ThreadPoolExecutor
13
14
  from typing import List
14
15
 
@@ -225,16 +226,35 @@ async def prepare_peer_readloop(loop: AbstractEventLoop, rpcTransport: RpcTransp
225
226
  await rpcTransport.prepare()
226
227
 
227
228
  mutex = threading.Lock()
229
+ sendState = threading.local()
230
+
231
+ def write(message, reject, serializationContext):
232
+ if serializationContext:
233
+ buffers = serializationContext.get("buffers", None)
234
+ if buffers:
235
+ for buffer in buffers:
236
+ rpcTransport.writeBuffer(buffer, reject)
237
+
238
+ rpcTransport.writeSerialized(message, reject)
228
239
 
229
240
  def send(message, reject=None, serializationContext=None):
230
- with mutex:
231
- if serializationContext:
232
- buffers = serializationContext.get("buffers", None)
233
- if buffers:
234
- for buffer in buffers:
235
- rpcTransport.writeBuffer(buffer, reject)
236
-
237
- rpcTransport.writeSerialized(message, reject)
241
+ # The transport's write lock is not reentrant, but send() can be reentered on the
242
+ # same thread, e.g. a garbage collector finalizer may run during an allocation
243
+ # inside writeSerialized while the lock is held. Queue reentrant messages and
244
+ # flush them after the current message is written, while still holding the lock.
245
+ pending = getattr(sendState, "pending", None)
246
+ if pending is not None:
247
+ pending.append((message, reject, serializationContext))
248
+ return
249
+
250
+ pending = sendState.pending = deque()
251
+ try:
252
+ with mutex:
253
+ write(message, reject, serializationContext)
254
+ while pending:
255
+ write(*pending.popleft())
256
+ finally:
257
+ sendState.pending = None
238
258
 
239
259
  peer = rpc.RpcPeer(send)
240
260
  peer.nameDeserializerMap["Buffer"] = SidebandBufferSerializer()
@@ -260,10 +260,15 @@ export function setupCluster(peer: RpcPeer) {
260
260
  const clusterObject = getClusterObject(clusterId, value);
261
261
  if (!clusterObject)
262
262
  return value;
263
+ // invalidate cluster objects that do not have a valid signature for this cluster.
264
+ if (computeClusterObjectHash(clusterObject, clusterSecret) !== clusterObject.sha256)
265
+ throw new Error('invalid cluster object signature');
263
266
  const { address, port, proxyId } = clusterObject;
264
267
  // handle the case when trying to connect to an object is on this cluster node,
265
268
  // returning the actual object, rather than initiating a loopback connection.
266
- if (port === clusterPort)
269
+ // ports alone are not unique across hosts, so this must also verify that the
270
+ // object's address belongs to this node.
271
+ if (isClusterAddress(address) && port === clusterPort)
267
272
  return connectClusterObject(clusterObject);
268
273
 
269
274
  // can use worker to worker ipc if the address and pid matches and both side are node.
@@ -281,22 +286,16 @@ export function setupCluster(peer: RpcPeer) {
281
286
  }
282
287
  }
283
288
 
284
- try {
285
- const clusterPeerPromise = ensureClusterPeer(address, port);
286
- const clusterPeer = await clusterPeerPromise;
287
- // may already have this proxy so check first.
288
- const existing = clusterPeer.remoteWeakProxies[proxyId]?.deref();
289
- if (existing)
290
- return existing;
291
- const newValue = await peerConnectRPCObject(clusterPeer, clusterObject);
292
- if (!newValue)
293
- throw new Error('rpc object not found?');
294
- return newValue;
295
- }
296
- catch (e) {
297
- console.error('failure rpc', clusterObject, e);
298
- return value;
299
- }
289
+ const clusterPeerPromise = ensureClusterPeer(address, port);
290
+ const clusterPeer = await clusterPeerPromise;
291
+ // may already have this proxy so check first.
292
+ const existing = clusterPeer.remoteWeakProxies[proxyId]?.deref();
293
+ if (existing)
294
+ return existing;
295
+ const newValue = await peerConnectRPCObject(clusterPeer, clusterObject);
296
+ if (!newValue)
297
+ throw new Error('rpc object not found?');
298
+ return newValue;
300
299
  }
301
300
 
302
301
  const onProxySerialization = (peer: RpcPeer, value: any, sourceKey: string) => {
@@ -101,8 +101,22 @@ export class HttpResponseImpl implements HttpResponse {
101
101
  return;
102
102
 
103
103
  const more = this.res.write(chunk);
104
- if (!more)
105
- await new Promise<void>(r => this.res.once('drain', r));
104
+ // a closed socket emits 'close', not 'drain', so wait on both.
105
+ // otherwise a client disconnecting under backpressure hangs
106
+ // this loop and the finally below never kills the peer.
107
+ if (!more) {
108
+ await new Promise<void>(r => {
109
+ const done = () => {
110
+ this.res.off('drain', done);
111
+ this.res.off('close', done);
112
+ this.res.off('error', done);
113
+ r();
114
+ };
115
+ this.res.once('drain', done);
116
+ this.res.once('close', done);
117
+ this.res.once('error', done);
118
+ });
119
+ }
106
120
 
107
121
  if (this.res.closed || this.res.destroyed)
108
122
  return;
@@ -1,6 +1,5 @@
1
1
  import { BufferConverter, DeviceManager, FFmpegInput, MediaConverter, MediaManager, MediaObjectCreateOptions, MediaObject as MediaObjectInterface, MediaStreamUrl, ScryptedDevice, ScryptedInterface, ScryptedInterfaceProperty, ScryptedMimeTypes, ScryptedNativeId, SystemDeviceState, SystemManager } from "@scrypted/types";
2
2
  import fs from 'fs';
3
- import https from 'https';
4
3
  import mime from 'mime-types';
5
4
  import Graph from 'node-dijkstra';
6
5
  import path from 'path';
@@ -20,10 +19,6 @@ function mimeMatches(target: MimeType, candidate: MimeType) {
20
19
  return typeMatches(target.type, candidate.type) && typeMatches(target.subtype, candidate.subtype);
21
20
  }
22
21
 
23
- const httpsAgent = new https.Agent({
24
- rejectUnauthorized: false
25
- });
26
-
27
22
  type IdBufferConverter = BufferConverter & {
28
23
  id: string;
29
24
  name: string;
@@ -33,56 +28,69 @@ function getBuiltinId(n: number) {
33
28
  return 'builtin-' + n;
34
29
  }
35
30
 
36
- function getExtraId(n: number) {
37
- return 'extra-' + n;
38
- }
39
-
40
31
  export abstract class MediaManagerBase implements MediaManager {
41
32
  builtinConverters: IdBufferConverter[] = [];
42
- extraConverters: IdBufferConverter[] = [];
43
33
 
44
- constructor() {
45
- for (const h of ['http', 'https']) {
34
+ #getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } };
35
+ #getDeviceById: <T>(id: string) => T & ScryptedDevice;
36
+ #getPluginDeviceId: () => string;
37
+ #getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console;
38
+
39
+ constructor(
40
+ getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
41
+ getDeviceById: <T>(id: string) => T & ScryptedDevice,
42
+ getPluginDeviceId: () => string,
43
+ getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console,
44
+ privileged: boolean,
45
+ ) {
46
+ this.#getSystemState = getSystemState;
47
+ this.#getDeviceById = getDeviceById;
48
+ this.#getPluginDeviceId = getPluginDeviceId;
49
+ this.#getMixinConsole = getMixinConsole;
50
+
51
+ if (privileged) {
52
+ for (const h of ['http', 'https']) {
53
+ this.builtinConverters.push({
54
+ id: getBuiltinId(this.builtinConverters.length),
55
+ name: 'HTTP Converter',
56
+ fromMimeType: ScryptedMimeTypes.SchemePrefix + h,
57
+ toMimeType: ScryptedMimeTypes.MediaObject,
58
+ convert: async (data, fromMimeType, toMimeType) => {
59
+ const ab = await fetch(data.toString());
60
+ const mimeType = ab.headers.get('Content-type') || toMimeType;
61
+ const mo = this.createMediaObject(Buffer.from(await ab.arrayBuffer()), mimeType);
62
+ return mo;
63
+ }
64
+ });
65
+ }
66
+
46
67
  this.builtinConverters.push({
47
68
  id: getBuiltinId(this.builtinConverters.length),
48
- name: 'HTTP Converter',
49
- fromMimeType: ScryptedMimeTypes.SchemePrefix + h,
69
+ name: 'File Converter',
70
+ fromMimeType: ScryptedMimeTypes.SchemePrefix + 'file',
50
71
  toMimeType: ScryptedMimeTypes.MediaObject,
51
72
  convert: async (data, fromMimeType, toMimeType) => {
52
- const ab = await fetch(data.toString());
53
- const mimeType = ab.headers.get('Content-type') || toMimeType;
54
- const mo = this.createMediaObject(Buffer.from(await ab.arrayBuffer()), mimeType);
73
+ const url = data.toString();
74
+ const filename = url.substring('file:'.length);
75
+
76
+ if (toMimeType === ScryptedMimeTypes.FFmpegInput) {
77
+ const ffmpegInput: FFmpegInput = {
78
+ url,
79
+ inputArguments: [
80
+ '-i', filename,
81
+ ]
82
+ };
83
+ return this.createFFmpegMediaObject(ffmpegInput);
84
+ }
85
+
86
+ const ab = await fs.promises.readFile(filename);
87
+ const mt = mime.lookup(filename);
88
+ const mo = this.createMediaObject(ab, mt || 'application/octet-stream');
55
89
  return mo;
56
90
  }
57
91
  });
58
92
  }
59
93
 
60
- this.builtinConverters.push({
61
- id: getBuiltinId(this.builtinConverters.length),
62
- name: 'File Converter',
63
- fromMimeType: ScryptedMimeTypes.SchemePrefix + 'file',
64
- toMimeType: ScryptedMimeTypes.MediaObject,
65
- convert: async (data, fromMimeType, toMimeType) => {
66
- const url = data.toString();
67
- const filename = url.substring('file:'.length);
68
-
69
- if (toMimeType === ScryptedMimeTypes.FFmpegInput) {
70
- const ffmpegInput: FFmpegInput = {
71
- url,
72
- inputArguments: [
73
- '-i', filename,
74
- ]
75
- };
76
- return this.createFFmpegMediaObject(ffmpegInput);
77
- }
78
-
79
- const ab = await fs.promises.readFile(filename);
80
- const mt = mime.lookup(filename);
81
- const mo = this.createMediaObject(ab, mt || 'application/octet-stream');
82
- return mo;
83
- }
84
- });
85
-
86
94
  this.builtinConverters.push({
87
95
  id: getBuiltinId(this.builtinConverters.length),
88
96
  name: 'Url to FFmpegInput Converter',
@@ -150,15 +158,6 @@ export abstract class MediaManagerBase implements MediaManager {
150
158
  });
151
159
  }
152
160
 
153
- async addConverter(converter: IdBufferConverter): Promise<void> {
154
- converter.id = getExtraId(this.extraConverters.length);
155
- this.extraConverters.push(converter);
156
- }
157
-
158
- async clearConverters(): Promise<void> {
159
- this.extraConverters = [];
160
- }
161
-
162
161
  async convertMediaObjectToJSON<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
163
162
  const json = await this.convertMediaObjectToBuffer(mediaObject, toMimeType);
164
163
  // backcompat
@@ -167,11 +166,6 @@ export abstract class MediaManagerBase implements MediaManager {
167
166
  return json as T;
168
167
  }
169
168
 
170
- abstract getSystemState(): { [id: string]: { [property: string]: SystemDeviceState } };
171
- abstract getDeviceById<T>(id: string): T & ScryptedDevice;
172
- abstract getPluginDeviceId(): string;
173
- abstract getMixinConsole(mixinId: string, nativeId: ScryptedNativeId): Console;
174
-
175
169
  async getFFmpegPath(): Promise<string> {
176
170
  return getScryptedFFmpegPath();
177
171
  }
@@ -187,11 +181,11 @@ export abstract class MediaManagerBase implements MediaManager {
187
181
  return ret;
188
182
  }
189
183
 
190
- getConverters(): IdBufferConverter[] {
191
- const bufferConverters = Object.entries(this.getSystemState())
184
+ #getConverters(): IdBufferConverter[] {
185
+ const bufferConverters = Object.entries(this.#getSystemState())
192
186
  .filter(([id, state]) => state[ScryptedInterfaceProperty.interfaces]?.value?.includes(ScryptedInterface.BufferConverter))
193
187
  .map(([id]) => {
194
- const device = this.getDeviceById<BufferConverter>(id);
188
+ const device = this.#getDeviceById<BufferConverter>(id);
195
189
  return {
196
190
  id,
197
191
  name: device.name,
@@ -203,10 +197,10 @@ export abstract class MediaManagerBase implements MediaManager {
203
197
  } as IdBufferConverter;
204
198
  });
205
199
 
206
- const mediaConverters = Object.entries(this.getSystemState())
200
+ const mediaConverters = Object.entries(this.#getSystemState())
207
201
  .filter(([id, state]) => state[ScryptedInterfaceProperty.interfaces]?.value?.includes(ScryptedInterface.MediaConverter))
208
202
  .map(([id]) => {
209
- const device = this.getDeviceById<MediaConverter & BufferConverter>(id);
203
+ const device = this.#getDeviceById<MediaConverter & BufferConverter>(id);
210
204
 
211
205
  try {
212
206
  return (device.converters || []).map(([fromMimeType, toMimeType], index) => {
@@ -234,51 +228,47 @@ export abstract class MediaManagerBase implements MediaManager {
234
228
  // builtins should be after system converters. these should not be overriden by system,
235
229
  // as it could cause system instability with misconfiguration.
236
230
  converters.push(...this.builtinConverters);
237
-
238
- // extra converters are added last and do allow overriding builtins, as
239
- // the instability would be confined to a single plugin.
240
- converters.push(...this.extraConverters);
241
231
  return converters;
242
232
  }
243
233
 
244
- ensureMediaObjectRemote(mediaObject: string | MediaObjectInterface): MediaObjectRemote {
234
+ #ensureMediaObjectRemote(mediaObject: string | MediaObjectInterface): MediaObjectRemote {
245
235
  if (typeof mediaObject === 'string') {
246
236
  const mt = mime.lookup(mediaObject);
247
- return this.createMediaObjectRemote(mediaObject, mt || 'application/octet-stream');
237
+ return this.#createMediaObjectRemote(mediaObject, mt || 'application/octet-stream');
248
238
  }
249
239
  return mediaObject as MediaObjectRemote;
250
240
  }
251
241
 
252
242
  async convertMediaObject<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
253
- const converted = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
243
+ const converted = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
254
244
  return converted.data;
255
245
  }
256
246
 
257
247
  async convertMediaObjectToInsecureLocalUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
258
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
259
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
260
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.InsecureLocalUrl);
248
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
249
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
250
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.InsecureLocalUrl);
261
251
  return url.data.toString();
262
252
  }
263
253
 
264
254
  async convertMediaObjectToBuffer(mediaObject: MediaObjectInterface, toMimeType: string): Promise<Buffer> {
265
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
255
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
266
256
  return intermediate.data as Buffer;
267
257
  }
268
258
  async convertMediaObjectToLocalUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
269
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
270
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
271
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.LocalUrl);
259
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
260
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
261
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.LocalUrl);
272
262
  return url.data.toString();
273
263
  }
274
264
  async convertMediaObjectToUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
275
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
276
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
277
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.Url);
265
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
266
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
267
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.Url);
278
268
  return url.data.toString();
279
269
  }
280
270
 
281
- createMediaObjectRemote<T extends MediaObjectCreateOptions>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
271
+ #createMediaObjectRemote<T extends MediaObjectCreateOptions>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
282
272
  if (!mimeType)
283
273
  throw new Error('no mimeType provided');
284
274
  if (mimeType === ScryptedMimeTypes.MediaObject)
@@ -287,7 +277,7 @@ export abstract class MediaManagerBase implements MediaManager {
287
277
  if (data.constructor?.name === Object.name)
288
278
  data = Buffer.from(JSON.stringify(data));
289
279
 
290
- const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.getPluginDeviceId();
280
+ const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.#getPluginDeviceId();
291
281
  options ||= {} as T;
292
282
  options.sourceId = sourceId;
293
283
 
@@ -295,7 +285,7 @@ export abstract class MediaManagerBase implements MediaManager {
295
285
  }
296
286
 
297
287
  async createFFmpegMediaObject<T extends MediaObjectCreateOptions>(ffMpegInput: FFmpegInput, options?: T): Promise<MediaObjectInterface & T> {
298
- return this.createMediaObjectRemote(Buffer.from(JSON.stringify(ffMpegInput)), ScryptedMimeTypes.FFmpegInput, options);
288
+ return this.#createMediaObjectRemote(Buffer.from(JSON.stringify(ffMpegInput)), ScryptedMimeTypes.FFmpegInput, options);
299
289
  }
300
290
 
301
291
  async createMediaObjectFromUrl<T extends MediaObjectCreateOptions>(data: string, options?: T): Promise<MediaObjectInterface & T> {
@@ -303,14 +293,14 @@ export abstract class MediaManagerBase implements MediaManager {
303
293
  const scheme = url.protocol.slice(0, -1);
304
294
  const mimeType = ScryptedMimeTypes.SchemePrefix + scheme;
305
295
 
306
- return this.createMediaObjectRemote(data, mimeType, options);
296
+ return this.#createMediaObjectRemote(data, mimeType, options);
307
297
  }
308
298
 
309
299
  async createMediaObject<T extends MediaObjectCreateOptions>(data: any, mimeType: string, options?: T): Promise<MediaObjectInterface & T> {
310
- return this.createMediaObjectRemote(data, mimeType, options);
300
+ return this.#createMediaObjectRemote(data, mimeType, options);
311
301
  }
312
302
 
313
- async convert(converters: IdBufferConverter[], mediaObject: MediaObjectRemote, toMimeType: string): Promise<{ data: Buffer | string | any, mimeType: string }> {
303
+ async #convert(converters: IdBufferConverter[], mediaObject: MediaObjectRemote, toMimeType: string): Promise<{ data: Buffer | string | any, mimeType: string }> {
314
304
  // console.log('converting', mediaObject.mimeType, toMimeType);
315
305
  const mediaMime = new MimeType(mediaObject.mimeType);
316
306
  const outputMime = new MimeType(toMimeType);
@@ -324,8 +314,8 @@ export abstract class MediaManagerBase implements MediaManager {
324
314
 
325
315
  let sourceId = mediaObject?.sourceId;
326
316
  if (typeof sourceId !== 'string')
327
- sourceId = this.getPluginDeviceId();
328
- const console = this.getMixinConsole(sourceId, undefined);
317
+ sourceId = this.#getPluginDeviceId();
318
+ const console = this.#getMixinConsole(sourceId, undefined);
329
319
 
330
320
  const converterMap = new Map<string, IdBufferConverter>();
331
321
  for (const c of converters) {
@@ -472,42 +462,27 @@ export abstract class MediaManagerBase implements MediaManager {
472
462
  }
473
463
 
474
464
  export class MediaManagerImpl extends MediaManagerBase {
475
- constructor(public systemManager: SystemManager, public deviceManager: DeviceManager) {
476
- super();
477
- }
478
-
479
- getSystemState(): { [id: string]: { [property: string]: SystemDeviceState; }; } {
480
- return this.systemManager.getSystemState();
481
- }
482
-
483
- getDeviceById<T>(id: string): T {
484
- return this.systemManager.getDeviceById<T>(id);
485
- }
486
-
487
- getPluginDeviceId(): string {
488
- return this.deviceManager.getDeviceState().id;
489
- }
490
-
491
- getMixinConsole(mixinId: string, nativeId: string): Console {
492
- if (typeof mixinId !== 'string')
493
- return this.deviceManager.getDeviceConsole(nativeId);
494
- return this.deviceManager.getMixinConsole(mixinId, nativeId);
465
+ constructor(systemManager: SystemManager, deviceManager: DeviceManager) {
466
+ super(
467
+ () => systemManager.getSystemState(),
468
+ <T>(id: string) => systemManager.getDeviceById<T>(id),
469
+ () => deviceManager.getDeviceState().id,
470
+ (mixinId, nativeId) => {
471
+ if (typeof mixinId !== 'string')
472
+ return deviceManager.getDeviceConsole(nativeId);
473
+ return deviceManager.getMixinConsole(mixinId, nativeId);
474
+ },
475
+ true,
476
+ );
495
477
  }
496
478
  }
497
479
 
498
480
  export class MediaManagerHostImpl extends MediaManagerBase {
499
- constructor(public pluginDeviceId: string,
500
- public getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
501
- public console: Console,
502
- public getDeviceById: (id: string) => any) {
503
- super();
504
- }
505
-
506
- getPluginDeviceId(): string {
507
- return this.pluginDeviceId;
508
- }
509
-
510
- getMixinConsole(mixinId: string, nativeId: string): Console {
511
- return this.console;
481
+ constructor(pluginDeviceId: string,
482
+ getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
483
+ console: Console,
484
+ getDeviceById: (id: string) => any,
485
+ privileged: boolean) {
486
+ super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, privileged);
512
487
  }
513
488
  }
@@ -11,6 +11,7 @@ export interface ConsoleServer {
11
11
  writePort: number,
12
12
  destroy(): void;
13
13
  clear(nativeId: ScryptedNativeId): void;
14
+ read(nativeId: ScryptedNativeId): Buffer;
14
15
  }
15
16
 
16
17
  export interface StdPassThroughs {
@@ -305,12 +306,22 @@ export async function createConsoleServer(remoteStdout: Readable, remoteStderr:
305
306
 
306
307
  return {
307
308
  clear(nativeId: ScryptedNativeId) {
309
+ if (!nativeId)
310
+ nativeId = undefined;
308
311
  const pt = outputs.get(nativeId);
309
312
  if (pt) {
310
313
  pt.buffers = [];
311
314
  addHeader(pt);
312
315
  }
313
316
  },
317
+ read(nativeId: ScryptedNativeId) {
318
+ if (!nativeId)
319
+ nativeId = undefined;
320
+ const pt = outputs.get(nativeId);
321
+ if (!pt)
322
+ return Buffer.alloc(0);
323
+ return Buffer.concat(pt.buffers);
324
+ },
314
325
  destroy() {
315
326
  for (const socket of sockets) {
316
327
  socket.destroy();
@@ -23,7 +23,7 @@ import { ConsoleServer, createConsoleServer } from './plugin-console';
23
23
  import { PluginDebug } from './plugin-debug';
24
24
  import { PluginHostAPI } from './plugin-host-api';
25
25
  import { LazyRemote } from './plugin-lazy-remote';
26
- import { setupPluginRemote } from './plugin-remote';
26
+ import { getAccessControlSystemState, setupPluginRemote } from './plugin-remote';
27
27
  import { WebSocketConnection } from './plugin-remote-websocket';
28
28
  import { ensurePluginVolume, getScryptedVolume } from './plugin-volume';
29
29
  import { createClusterForkWorker } from './runtime/cluster-fork-worker';
@@ -210,7 +210,7 @@ export class PluginHost {
210
210
 
211
211
  const { runtime } = this.packageJson.scrypted;
212
212
  const mediaManager = runtime && runtime !== 'node'
213
- ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id))
213
+ ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true)
214
214
  : undefined;
215
215
 
216
216
  this.api = new PluginHostAPI(scrypted, this.pluginId, this, mediaManager!);
@@ -498,8 +498,18 @@ export class PluginHost {
498
498
  serializer.setupRpcPeer(rpcPeer);
499
499
 
500
500
  // wrap the host api with a connection specific api that can be torn down on disconnect
501
- const createMediaManager = await this.peer.getParam('createMediaManager');
502
- const api = new PluginAPIProxy(this.api, await createMediaManager());
501
+ const pluginDeviceId = this.scrypted.findPluginDevice(this.pluginId)!._id;
502
+ const getSystemState = accessControls
503
+ ? () => getAccessControlSystemState(accessControls, () => this.scrypted.stateManager.getSystemState())
504
+ : () => this.scrypted.stateManager.getSystemState();
505
+ const mediaManager = new MediaManagerHostImpl(
506
+ pluginDeviceId,
507
+ getSystemState,
508
+ console,
509
+ id => this.scrypted.getDevice(id),
510
+ !accessControls,
511
+ );
512
+ const api = new PluginAPIProxy(this.api, mediaManager);
503
513
  api.acl = accessControls;
504
514
  const kill = () => {
505
515
  serializer.onDisconnected();
@@ -77,7 +77,7 @@ export function startPluginRemote(mainFilename: string, pluginId: string, peerSe
77
77
  attachPluginRemote(peer, {
78
78
  createMediaManager: async (sm, dm) => {
79
79
  systemManager = sm;
80
- deviceManager = dm
80
+ deviceManager = dm;
81
81
  return new MediaManagerImpl(systemManager, dm);
82
82
  },
83
83
  onGetRemote: async (_api, _pluginId) => {