OverviewFilesCommitsIssuesDocsReleasesPeers

keet-cli / keet-core-4.14.4-pretty / workers / push.js

87 lines · javascript ref:
const e = require("hypercore-id-encoding"),
  o = require("hypercore-proof-queue"),
  s = require("fs-native-lock"),
  i = require("b4a"),
  {
    getNotificationBody: n,
    getNotificationTitle: t,
    ROOM_TYPE: a,
    MESSAGE_TYPE: r,
  } = require("./utils/notification.js"),
  l = require("../lib/push"),
  u = Bare.argv[0],
  p = Bare.argv[1],
  c = JSON.parse(i.toString(i.from(p, "base64"), "utf8")),
  g = (...e) => console.log("[keet-push]", ...e)
BareKit.on("push", async (p, f) => {
  const d = new s(`${u}/lock`)
  try {
    await d.lock()
  } catch {
    return (g("skipping push cause lock can not be acquired (app is running)"), f(null, null))
  }
  g("running push handler")
  try {
    const s = JSON.parse(p.toString()),
      d = s.data ? s.data.payload : s.payload,
      m = await l(u, Buffer.from(d, "base64"), { log: g })
    if ((g("result", m), null === m)) return (g("skipping push cause no result"), f(null, null))
    if (m.proof) {
      g("processing proof queue")
      const e = new o(`${u}/notifications`)
      ;(e.push(m.proof), await e.close(), g("done processing proof queue"))
    }
    const {
        sender: y,
        room: { key: h, title: k, type: b },
      } = m,
      q = e.encode(h),
      { type: S } = m.message,
      w = { title: k, roomType: b },
      v = b === a.DM,
      B = b === a.BROADCAST,
      N = v && S === r.CALL_JOINED
    if ((y.self && !N) || y.blocked || !m.message)
      return (
        g(
          "skipping push, self=" + !!y.self + " blocked=" + !!y.blocked + " message=" + !!m.message,
        ),
        f(null, null)
      )
    y.self &&
      N &&
      g(
        "not skipping self push because message type is call_joined, to hangup call on this linked device",
      )
    const O = t({ sender: y, config: w }),
      T = n({ ...m, config: w, strings: c }),
      A = m?.room?.roomAvatar?.small?.pointer?.inlined,
      E = A ? i.toString(A, "base64") : ""
    ;(g("replying with push, title=" + O + " body=" + T),
      f(
        null,
        JSON.stringify({
          id: m.id,
          title: O,
          body: T,
          type: m.message.type,
          timestamp: m.message.timestamp,
          threadIdentifier: q,
          avatar: E,
          userInfo: {
            roomKey: q,
            isDmRoom: v,
            isBroadcast: B,
            messageType: S,
            profileName: y.name,
          },
          sound: { type: "named", name: "notif_default.wav" },
        }),
      ))
  } catch (e) {
    ;(g("error", e.message), f(e, null))
  } finally {
    await d.unlock()
  }
})