You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

434 line
14KB

  1. const isLandscape = screen.width > screen.height
  2. const State = {
  3. username: null,
  4. websocket: null,
  5. online: [],
  6. posts: [],
  7. rpcs: {},
  8. media: {},
  9. options: {},
  10. }
  11. const markedOptions = {
  12. breaks: true,
  13. }
  14. marked.setOptions(markedOptions)
  15. /*
  16. *
  17. * SIGNALING
  18. *
  19. */
  20. const wire = (message) => State.websocket.send(JSON.stringify(message))
  21. const signal = (message) => dispatchEvent(new CustomEvent(message.kind, {detail: message}))
  22. const signalPeerStop = (username) => signal({kind: 'peerInfo', value: {type: 'stop'}, source: username})
  23. const listen = (kind, handler) => addEventListener(kind, handler)
  24. listen('login', ({detail}) => State.username = detail.value)
  25. listen('state', ({detail}) => Object.assign(State, detail))
  26. listen('post', ({detail}) => State.posts.push(detail))
  27. listen('peerInfo', (e) => onPeerInfo(e))
  28. const doNotLog = new Set(['login', 'state', 'post', 'peerInfo'])
  29. /*
  30. *
  31. * ALERTS
  32. *
  33. */
  34. State.unseen = 0
  35. listen('post', () => {State.unseen += !document.hasFocus(); updateTitle()})
  36. listen('focus', () => {State.unseen = 0; updateTitle()})
  37. const updateTitle = () => {
  38. document.title = `pico.chat` + (State.unseen ? ` (${State.unseen})` : ``)
  39. }
  40. /*
  41. *
  42. * WEBRTC
  43. *
  44. */
  45. const getOrCreateRpc = (username) => {
  46. if(State.username === username) {
  47. return
  48. }
  49. const myStream = State.media[State.username]
  50. if(!State.rpcs[username] && myStream) {
  51. const rpc = new RTCPeerConnection({iceServers: [{urls: 'stun:stun.sipgate.net:3478'}]})
  52. myStream.getTracks().forEach(track => rpc.addTrack(track, myStream))
  53. rpc.onicecandidate = ({candidate}) => {
  54. if(candidate) {
  55. wire({kind: 'peerInfo', value: {type: 'candidate', candidate}})
  56. }
  57. }
  58. rpc.ontrack = (e) => {
  59. State.media[username] = e.streams[0]
  60. m.redraw()
  61. }
  62. rpc.onclose = (e) => {
  63. console.log(username, e)
  64. }
  65. rpc.oniceconnectionstatechange = (e) => {
  66. m.redraw()
  67. }
  68. State.rpcs[username] = rpc
  69. }
  70. return State.rpcs[username]
  71. }
  72. const onPeerInfo = async ({detail: message}) => {
  73. const rpc = getOrCreateRpc(message.source)
  74. if(rpc && message.value.type === 'request') {
  75. const localOffer = await rpc.createOffer()
  76. await rpc.setLocalDescription(localOffer)
  77. wire({kind: 'peerInfo', value: localOffer, target: message.source})
  78. }
  79. else if(rpc && message.value.type === 'offer') {
  80. const remoteOffer = new RTCSessionDescription(message.value)
  81. await rpc.setRemoteDescription(remoteOffer)
  82. const localAnswer = await rpc.createAnswer()
  83. await rpc.setLocalDescription(localAnswer)
  84. wire({kind: 'peerInfo', value: localAnswer, target: message.source})
  85. }
  86. else if(rpc && message.value.type === 'answer') {
  87. const remoteAnswer = new RTCSessionDescription(message.value)
  88. await rpc.setRemoteDescription(remoteAnswer)
  89. }
  90. else if(rpc && message.value.type === 'candidate') {
  91. const candidate = new RTCIceCandidate(message.value.candidate)
  92. rpc.addIceCandidate(candidate)
  93. }
  94. else if(message.value.type === 'stop') {
  95. if(State.media[message.source]) {
  96. State.media[message.source].getTracks().map(track => track.stop())
  97. delete State.media[message.source]
  98. }
  99. if(State.rpcs[message.source]) {
  100. State.rpcs[message.source].close()
  101. delete State.rpcs[message.source]
  102. }
  103. }
  104. else if(rpc) {
  105. console.log('uncaught', message)
  106. }
  107. }
  108. /*
  109. *
  110. * GUI
  111. *
  112. */
  113. const autoFocus = (vnode) => {
  114. vnode.dom.focus()
  115. }
  116. const scrollIntoView = (vnode) => {
  117. vnode.dom.scrollIntoView()
  118. }
  119. const TextBox = {
  120. autoSize: () => {
  121. textbox.rows = textbox.value.split('\n').length
  122. },
  123. sendPost: () => {
  124. if(textbox.value) {
  125. wire({kind: 'post', value: textbox.value})
  126. textbox.value = ''
  127. textbox.focus()
  128. }
  129. },
  130. blockIndent: (text, iStart, iEnd, nLevels) => {
  131. const startLine = text.slice(0, iStart).split('\n').length - 1
  132. const endLine = text.slice(0, iEnd).split('\n').length - 1
  133. const newText = text
  134. .split('\n')
  135. .map((line, i) => {
  136. if(i < startLine || i > endLine || nLevels === 0) {
  137. newLine = line
  138. }
  139. else if(nLevels > 0) {
  140. newLine = line.replace(/^/, ' ')
  141. }
  142. else if(nLevels < 0) {
  143. newLine = line.replace(/^ /, '')
  144. }
  145. if(i === startLine) {
  146. iStart = iStart + newLine.length - line.length
  147. }
  148. iEnd = iEnd + newLine.length - line.length
  149. return newLine
  150. })
  151. .join('\n')
  152. return [newText, Math.max(0, iStart), Math.max(0, iEnd)]
  153. },
  154. hotKey: (e) => {
  155. // if isDesktop, Enter posts, unless Shift+Enter
  156. // use isLandscape as proxy for isDesktop
  157. if(e.key === 'Enter' && isLandscape && !e.shiftKey) {
  158. e.preventDefault()
  159. TextBox.sendPost()
  160. }
  161. // indent and dedent
  162. const modKey = e.ctrlKey || e.metaKey
  163. const {value: text, selectionStart: A, selectionEnd: B} = textbox
  164. if(e.key === 'Tab') {
  165. e.preventDefault()
  166. const regex = new RegExp(`([\\s\\S]{${A}})([\\s\\S]{${B - A}})`)
  167. textbox.value = text.replace(regex, (m, a, b) => a + ' '.repeat(4))
  168. textbox.setSelectionRange(A + 4, A + 4)
  169. }
  170. if(']['.includes(e.key) && modKey) {
  171. e.preventDefault()
  172. const nLevels = {']': 1, '[': -1}[e.key]
  173. const [newText, newA, newB] = TextBox.blockIndent(text, A, B, nLevels)
  174. textbox.value = newText
  175. textbox.setSelectionRange(newA, newB)
  176. }
  177. },
  178. view() {
  179. return m('.actions',
  180. m('textarea#textbox', {
  181. oncreate: (vnode) => {
  182. TextBox.autoSize()
  183. autoFocus(vnode)
  184. },
  185. onkeydown: TextBox.hotKey,
  186. onkeyup: TextBox.autoSize,
  187. }),
  188. m('button', {
  189. onclick: ({target}) => {
  190. TextBox.sendPost()
  191. TextBox.autoSize()
  192. },
  193. },
  194. 'Send'),
  195. )
  196. },
  197. }
  198. const VideoOptions = {
  199. available: ['mirror', 'square', 'full-screen'],
  200. getFor: (username) => {
  201. if(!State.options[username]) {
  202. State.options[username] = new Set(['mirror', 'square'])
  203. }
  204. return State.options[username]
  205. },
  206. getClassListFor: (username) => {
  207. return [...VideoOptions.getFor(username)].join(' ')
  208. },
  209. toggle: (options, string) => () => options.has(string)
  210. ? options.delete(string)
  211. : options.add(string),
  212. view({attrs: {username}}) {
  213. const options = VideoOptions.getFor(username)
  214. return VideoOptions.available.map((string) =>
  215. m('label.video-option',
  216. m('input', {
  217. type: 'checkbox',
  218. checked: options.has(string),
  219. onchange: VideoOptions.toggle(options, string),
  220. }),
  221. string,
  222. )
  223. )
  224. }
  225. }
  226. const Video = {
  227. keepRatio: {observe: () => {}},
  228. appendStream: ({username, stream}) => ({dom}) => {
  229. dom.autoplay = true
  230. dom.muted = (username === State.username)
  231. dom.srcObject = stream
  232. },
  233. view({attrs}) {
  234. const classList = VideoOptions.getClassListFor(attrs.username)
  235. const rpc = State.rpcs[attrs.username] || {iceConnectionState: null}
  236. return m('.video-container', {class: classList, oncreate: ({dom}) => Video.keepRatio.observe(dom)},
  237. m('.video-meta',
  238. m('span.video-source', attrs.username),
  239. m('.video-state', rpc.iceConnectionState),
  240. ),
  241. m('video', {playsinline: true, oncreate: Video.appendStream(attrs)}),
  242. )
  243. },
  244. }
  245. if(window.ResizeObserver) {
  246. const doOne = ({target}) => target.style.setProperty('--height', `${target.clientHeight}px`)
  247. const doAll = (entries) => entries.forEach(doOne)
  248. Video.keepRatio = new ResizeObserver(doAll)
  249. }
  250. const Media = {
  251. videoSources: ['camera', 'screen', 'none'],
  252. audioDefaults: {
  253. noiseSuppresion: true,
  254. echoCancellation: true,
  255. },
  256. getSelectedMedia: async () => {
  257. const stream = new MediaStream()
  258. const addTrack = stream.addTrack.bind(stream)
  259. const muted = document.querySelector('#mute-check').checked
  260. if(!muted) {
  261. const audio = Media.audioDefaults
  262. await navigator.mediaDevices.getUserMedia({audio})
  263. .then(s => s.getAudioTracks().forEach(addTrack))
  264. .catch(e => console.error(e))
  265. }
  266. const source = document.querySelector('#media-source').value
  267. if(source === 'camera') {
  268. const video = {width: {ideal: 320}, facingMode: 'user', frameRate: 26}
  269. await navigator.mediaDevices.getUserMedia({video})
  270. .then(s => s.getVideoTracks().forEach(addTrack))
  271. .catch(e => console.error(e))
  272. }
  273. if(source === 'screen' && navigator.mediaDevices.getDisplayMedia) {
  274. await navigator.mediaDevices.getDisplayMedia()
  275. .then(s => s.getVideoTracks().forEach(addTrack))
  276. .catch(e => console.error(e))
  277. }
  278. return stream
  279. },
  280. turnOn: async () => {
  281. const media = await Media.getSelectedMedia()
  282. State.media[State.username] = media
  283. wire({kind: 'peerInfo', value: {type: 'request'}})
  284. m.redraw()
  285. },
  286. turnOff: () => {
  287. wire({kind: 'peerInfo', value: {type: 'stop'}})
  288. State.online.forEach(signalPeerStop)
  289. },
  290. view() {
  291. if(!State.media[State.username]) {
  292. return m('.media',
  293. m('.media-settings',
  294. m('button', {onclick: Media.turnOn}, 'turn on'),
  295. m('select#media-source', Media.videoSources.map(option => m('option', option))),
  296. m('label', m('input#mute-check', {type: 'checkbox'}), 'mute'),
  297. ),
  298. )
  299. }
  300. else {
  301. return m('.media',
  302. m('.media-settings',
  303. m('button', {onclick: Media.turnOff}, 'turn off'),
  304. ),
  305. m('.videos',
  306. Object.entries(State.media).map(([username, stream]) =>
  307. m(Video, {username, stream})
  308. ),
  309. ),
  310. )
  311. }
  312. }
  313. }
  314. const Login = {
  315. sendLogin: (e) => {
  316. e.preventDefault()
  317. const username = e.target.username.value
  318. localStorage.username = username
  319. connect(username)
  320. },
  321. sendLogout: (e) => {
  322. Media.turnOff()
  323. wire({kind: 'logout'})
  324. State.posts = []
  325. },
  326. view() {
  327. const attrs = {
  328. oncreate: autoFocus,
  329. name: 'username',
  330. autocomplete: 'off',
  331. value: localStorage.username,
  332. }
  333. return m('.login',
  334. m('form', {onsubmit: Login.sendLogin},
  335. m('input', attrs),
  336. m('button', 'Login'),
  337. ),
  338. m('.error', State.info),
  339. )
  340. },
  341. }
  342. const Chat = {
  343. prettifyTime: (ts) => {
  344. const dt = new Date(ts)
  345. const H = `0${dt.getHours()}`.slice(-2)
  346. const M = `0${dt.getMinutes()}`.slice(-2)
  347. const S = `0${dt.getSeconds()}`.slice(-2)
  348. return `${H}:${M}:${S}`
  349. },
  350. view() {
  351. return m('.chat',
  352. m('.posts',
  353. State.posts.map(post => m('.post', {oncreate: scrollIntoView},
  354. m('.ts', Chat.prettifyTime(post.ts)),
  355. m('.source', post.source || '~'),
  356. m('.text', m.trust(DOMPurify.sanitize(marked(post.value)))),
  357. )),
  358. ),
  359. m(TextBox),
  360. m('.online',
  361. m('button', {onclick: Login.sendLogout}, 'Logout'),
  362. m('.user-list', State.online.map(username =>
  363. m('details',
  364. m('summary', username),
  365. m(VideoOptions, {username}),
  366. ),
  367. )),
  368. ),
  369. m(Media),
  370. )
  371. },
  372. }
  373. const Main = {
  374. view() {
  375. const connected = State.websocket && State.websocket.readyState === 1
  376. return connected ? m(Chat) : m(Login)
  377. },
  378. }
  379. m.mount(document.body, Main)
  380. /*
  381. *
  382. * WEBSOCKETS
  383. *
  384. */
  385. const connect = (username) => {
  386. const wsUrl = location.href.replace('http', 'ws')
  387. State.websocket = new WebSocket(wsUrl)
  388. State.websocket.onopen = (e) => {
  389. wire({kind: 'login', value: username})
  390. }
  391. State.websocket.onmessage = (e) => {
  392. const message = JSON.parse(e.data)
  393. if(message.online) {
  394. const difference = (l1, l2) => l1.filter(u => !l2.includes(u))
  395. difference(message.online, State.online).forEach(username =>
  396. State.posts.push({ts: message.ts, value: `${username} joined`}))
  397. difference(State.online, message.online).forEach(username =>
  398. State.posts.push({ts: message.ts, value: `${username} left`}))
  399. }
  400. if(!doNotLog.has(message.kind)) {
  401. console.log(message)
  402. }
  403. signal(message)
  404. m.redraw()
  405. }
  406. State.websocket.onclose = (e) => {
  407. State.online.forEach(signalPeerStop)
  408. if(!e.wasClean) {
  409. setTimeout(connect, 1000, username)
  410. }
  411. m.redraw()
  412. }
  413. }
  414. if(localStorage.username) {
  415. connect(localStorage.username)
  416. }
  417. addEventListener('pagehide', Media.turnOff)