OverviewFilesCommitsIssuesDocsReleasesPeers

hypercore-kb / hyper-social / bridge-matrix / lib / adapter.js

82 lines · javascript ref:
import { createEnvelope, TYPES, PLATFORMS } from 'bridge-envelope'

// Strip HTML tags (for Matrix formatted_body)
function stripHtml (html) {
  return html
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/p>\s*<p>/gi, '\n\n')
    .replace(/<[^>]+>/g, '')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .trim()
}

// Convert Matrix message to bridge envelope
function matrixToEnvelope (sender, roomId, text) {
  return createEnvelope({
    type: TYPES.TEXT,
    platform: PLATFORMS.MATRIX,
    author: sender,
    content: text,
    channel: roomId
  })
}

// Format a Matrix message for sending to Keet
function matrixToKeetText (sender, text) {
  return `[Matrix] <${sender}> ${text}`
}

// Convert a Keet message to text for Matrix, filtering out bridge echo
function keetToMatrixText (keetMsg, bridgeUserId) {
  if (!keetMsg) return null

  // Skip messages from bridge identity (prevents echo)
  if (keetMsg.memberId === bridgeUserId) return null

  // Skip system messages
  if (keetMsg.system) return null

  const text = keetMsg.text || ''
  if (!text.trim()) return null

  // Skip messages already bridged from Matrix
  if (text.startsWith('[Matrix]')) return null

  const name = keetMsg.name || keetMsg.username || 'anonymous'
  return { sender: name, text }
}

// Format a Keet message for display in Matrix
function keetToMatrixDisplayText (sender, text) {
  return `<${sender}> ${text}`
}

// Format envelope for Matrix posting
function envelopeToMatrixText (envelope) {
  if (!envelope) return ''

  const platformName = {
    [PLATFORMS.KEET]: 'Keet',
    [PLATFORMS.IRC]: 'IRC',
    [PLATFORMS.DISCORD]: 'Discord',
    [PLATFORMS.MASTODON]: 'Mastodon',
    [PLATFORMS.EMAIL]: 'Email'
  }

  const source = platformName[envelope.platform] || 'P2P'
  return `[${source}] <${envelope.author}> ${envelope.content}`
}

export {
  matrixToEnvelope,
  matrixToKeetText,
  keetToMatrixText,
  keetToMatrixDisplayText,
  envelopeToMatrixText,
  stripHtml
}