All files / stream obsControl.ts

0% Statements 0/38
0% Branches 0/13
0% Functions 0/11
0% Lines 0/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                             
const STREAM_TIME_ZONE = 'Europe/Berlin'
const RESTART_HOUR = 4
const RESTART_MINUTE = 0
const CHECK_INTERVAL_MS = 10000
const FULL_CONTROL_LEVEL = 5
 
interface ObsStudio {
  getControlLevel: (callback: (level: number) => void) => void
  getStatus: (callback: (status: { streaming: boolean }) => void) => void
  startStreaming: () => void
  stopStreaming: () => void
}
 
declare global {
  interface Window {
    obsstudio?: ObsStudio
  }
}
 
const clock = new Intl.DateTimeFormat('en-CA', {
  timeZone: STREAM_TIME_ZONE,
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  hourCycle: 'h23',
})
 
const localTime = () => {
  const parts = Object.fromEntries(clock.formatToParts(new Date()).map(({ type, value }) => [type, value]))
  return { day: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), minute: Number(parts.minute) }
}
 
export const createObsControl = () => {
  const obs = window.obsstudio
  let restartedOn: string | null = null
  let timer: number | undefined
 
  const restartDue = () => {
    const { day, hour, minute } = localTime()
    if (hour !== RESTART_HOUR || minute !== RESTART_MINUTE || day === restartedOn) return false
    restartedOn = day
    return true
  }
  const keepStreaming = (studio: ObsStudio) => {
    const restart = restartDue()
    studio.getStatus((status) => {
      if (!status.streaming) studio.startStreaming()
      else if (restart) studio.stopStreaming()
    })
  }
  const schedule = (studio: ObsStudio, level: number) => {
    if (level < FULL_CONTROL_LEVEL) {
      console.error('Keeping the OBS stream alive needs the browser source permission "Full access to OBS"')
      return
    }
    keepStreaming(studio)
    timer = window.setInterval(() => keepStreaming(studio), CHECK_INTERVAL_MS)
  }
 
  return {
    start() {
      if (obs) obs.getControlLevel((level) => schedule(obs, level))
    },
    stop() {
      window.clearInterval(timer)
    },
  }
}