Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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