OverviewFilesCommitsIssuesDocsReleasesPeers

keet-deobfuscated / @holepunchto / keet-call / lib / common.js

82 lines · javascript ref:
const e = require("safety-catch"),
  n = require("b4a")
function t() {}
;((module.exports.TRACKER_EVENTS = { HAVE: "have-track", UNHAVE: "unhave-track" }),
  (module.exports.MEDIA_EVENTS = {
    WANT: "want-track",
    UNWANT: "unwant-track",
    SIGNAL: "media-signal",
    PROXY_OPEN: "proxy-open",
    PROXY_CLOSE: "proxy-close",
  }),
  (module.exports.PRESENCE_EVENTS = {
    PEER_PRESENT: "present",
    PEER_NOT_PRESENT: "not-present",
    STREAM_AVAILABLE: "stream-available",
    STREAM_UNAVAILABLE: "stream-unavailable",
    STREAM_STATUS_CHANGED: "stream-status-changed",
  }),
  (module.exports.encodeTrackId = function (e, n) {
    return `${e}:${n}`
  }),
  (module.exports.decodeTrackId = function (e) {
    const [n, t] = e.split(":")
    return { streamId: n, trackKind: t }
  }),
  (module.exports.getConnection = function (e, t) {
    for (const r of e.connections) if (n.equals(r.remotePublicKey, t)) return r
    return null
  }),
  (module.exports.createResourceManager = function (n, r = t) {
    const o = new Map()
    return {
      collection: o,
      open: c,
      release: u,
      subscription: function (n) {
        return (t, ...r) => {
          const o = c(t),
            a = n(o, ...r)
          return (
            a.once("close", () => {
              u(t)
            }),
            a.on("error", e),
            a
          )
        }
      },
      method: function (e) {
        return (n, ...t) => {
          const r = c(n)
          try {
            return e(r, ...t)
          } finally {
            u(n)
          }
        }
      },
      asyncMethod: function (e) {
        return async (n, ...t) => {
          const r = c(n)
          try {
            return await e(r, ...t)
          } finally {
            u(n)
          }
        }
      },
    }
    function c(e) {
      const t = o.get(e)
      if (t) return (t.refs++, t.value)
      const c = n(e)
      return (o.set(e, { value: c, refs: 1 }), r(e, !0), c)
    }
    function u(e) {
      const n = o.get(e)
      if (!n) throw new Error("Releasing an unopened resource")
      --n.refs > 0 || (n.value.close(), o.delete(e), r(e, !1))
    }
  }))