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.

469 lines
15KB

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