Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

308 lines
9.2KB

  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. }
  10. const markedOptions = {
  11. breaks: true,
  12. }
  13. marked.setOptions(markedOptions)
  14. /*
  15. *
  16. * SIGNALING
  17. *
  18. */
  19. const wire = (message) => State.websocket.send(JSON.stringify(message))
  20. const signal = (message) => dispatchEvent(new CustomEvent(message.kind, {detail: message}))
  21. const signalPeerStop = (username) => signal({kind: 'peerInfo', value: {type: 'stop'}, source: username})
  22. const listen = (kind, handler) => addEventListener(kind, handler)
  23. listen('login', ({detail}) => State.username = detail.value)
  24. listen('state', ({detail}) => Object.assign(State, detail))
  25. listen('post', ({detail}) => State.posts.push(detail))
  26. listen('peerInfo', (e) => onPeerInfo(e))
  27. const doNotLog = new Set(['login', 'state', 'post', 'peerInfo'])
  28. /*
  29. *
  30. * ALERTS
  31. *
  32. */
  33. State.unseen = 0
  34. listen('post', () => {State.unseen += !document.hasFocus(); updateTitle()})
  35. listen('focus', () => {State.unseen = 0; updateTitle()})
  36. const updateTitle = () => {
  37. document.title = `Pico.Chat` + (State.unseen ? ` (${State.unseen})` : ``)
  38. }
  39. /*
  40. *
  41. * WEBRTC
  42. *
  43. */
  44. const getOrCreateRpc = (username) => {
  45. if(State.username === username) {
  46. return
  47. }
  48. const myStream = State.media[State.username]
  49. if(!State.rpcs[username] && myStream) {
  50. const rpc = new RTCPeerConnection({iceServers: [{urls: 'stun:stun.sipgate.net:3478'}]})
  51. myStream.getTracks().forEach(track => rpc.addTrack(track, myStream))
  52. rpc.onicecandidate = ({candidate}) => {
  53. if(candidate) {
  54. wire({kind: 'peerInfo', value: {type: 'candidate', candidate}})
  55. }
  56. }
  57. rpc.ontrack = (e) => {
  58. State.media[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 onPeerInfo = async ({detail: message}) => {
  72. const rpc = getOrCreateRpc(message.source)
  73. if(rpc && message.value.type === 'request') {
  74. const localOffer = await rpc.createOffer()
  75. await rpc.setLocalDescription(localOffer)
  76. wire({kind: 'peerInfo', value: localOffer, target: message.source})
  77. }
  78. else if(rpc && message.value.type === 'offer') {
  79. const remoteOffer = new RTCSessionDescription(message.value)
  80. await rpc.setRemoteDescription(remoteOffer)
  81. const localAnswer = await rpc.createAnswer()
  82. await rpc.setLocalDescription(localAnswer)
  83. wire({kind: 'peerInfo', value: localAnswer, target: message.source})
  84. }
  85. else if(rpc && message.value.type === 'answer') {
  86. const remoteAnswer = new RTCSessionDescription(message.value)
  87. await rpc.setRemoteDescription(remoteAnswer)
  88. }
  89. else if(rpc && message.value.type === 'candidate') {
  90. const candidate = new RTCIceCandidate(message.value.candidate)
  91. rpc.addIceCandidate(candidate)
  92. }
  93. else if(message.value.type === 'stop') {
  94. if(State.media[message.source]) {
  95. State.media[message.source].getTracks().map(track => track.stop())
  96. delete State.media[message.source]
  97. }
  98. if(State.rpcs[message.source]) {
  99. State.rpcs[message.source].close()
  100. delete State.rpcs[message.source]
  101. }
  102. }
  103. else if(rpc) {
  104. console.log('uncaught', message)
  105. }
  106. }
  107. /*
  108. *
  109. * GUI
  110. *
  111. */
  112. const autoFocus = (vnode) => {
  113. vnode.dom.focus()
  114. }
  115. const scrollIntoView = (vnode) => {
  116. vnode.dom.scrollIntoView()
  117. }
  118. const toggleFullscreen = (el) => (event) => {
  119. document.fullscreenElement ? document.exitFullscreen() : el.requestFullscreen()
  120. }
  121. const prettyTime = (ts) => {
  122. const dt = new Date(ts)
  123. const H = `0${dt.getHours()}`.slice(-2)
  124. const M = `0${dt.getMinutes()}`.slice(-2)
  125. const S = `0${dt.getSeconds()}`.slice(-2)
  126. return `${H}:${M}:${S}`
  127. }
  128. const hotKey = (e) => {
  129. // if isDesktop, Enter posts, unless Shift+Enter
  130. // use isLandscape as proxy for isDesktop
  131. if(e.key === 'Enter' && isLandscape && !e.shiftKey) {
  132. e.preventDefault()
  133. Chat.sendPost()
  134. }
  135. }
  136. const Video = {
  137. appendStream: ({username, stream}) => ({dom}) => {
  138. dom.autoplay = true
  139. dom.muted = (username === State.username)
  140. dom.srcObject = stream
  141. dom.ondblclick = toggleFullscreen(dom)
  142. },
  143. view({attrs}) {
  144. const rpc = State.rpcs[attrs.username] || {iceConnectionState: m.trust(' ')}
  145. return m('.video-container',
  146. m('.video-source', attrs.username),
  147. m('.video-state', rpc.iceConnectionState),
  148. m('video.mirrored', {playsinline: true, oncreate: Video.appendStream(attrs)}),
  149. )
  150. },
  151. }
  152. const audio = {
  153. noiseSuppresion: true,
  154. echoCancellation: true,
  155. }
  156. const Media = {
  157. options: {
  158. video: {audio, video: {width: {ideal: 320}, facingMode: 'user'}},
  159. audio: {audio, video: false},
  160. screen: {audio, video: {mediaSource: 'screen'}},
  161. none: {audio: false, video: false},
  162. },
  163. turnOn: async () => {
  164. const constraints = Media.options[document.querySelector('#media-source').value]
  165. const media = await navigator.mediaDevices.getUserMedia(constraints)
  166. State.media[State.username] = media
  167. wire({kind: 'peerInfo', value: {type: 'request'}})
  168. m.redraw()
  169. },
  170. turnOff: () => {
  171. wire({kind: 'peerInfo', value: {type: 'stop'}})
  172. State.online.forEach(signalPeerStop)
  173. },
  174. view() {
  175. if(!State.media[State.username]) {
  176. return m('.media',
  177. m('button', {onclick: Media.turnOn}, 'turn on'),
  178. m('select#media-source',
  179. Object.keys(Media.options).map(description => m('option', description)),
  180. ),
  181. )
  182. }
  183. else {
  184. return m('.media',
  185. m('button', {onclick: Media.turnOff}, 'turn off'),
  186. m('.videos',
  187. Object.entries(State.media).map(([username, stream]) =>
  188. m(Video, {username, stream})
  189. ),
  190. ),
  191. )
  192. }
  193. }
  194. }
  195. const Login = {
  196. sendLogin: (e) => {
  197. e.preventDefault()
  198. const username = e.target.username.value
  199. localStorage.username = username
  200. connect(username)
  201. },
  202. sendLogout: (e) => {
  203. Media.turnOff()
  204. wire({kind: 'logout'})
  205. State.posts = []
  206. },
  207. view() {
  208. const attrs = {
  209. oncreate: autoFocus,
  210. name: 'username',
  211. autocomplete: 'off',
  212. value: localStorage.username,
  213. }
  214. return m('.login',
  215. m('form', {onsubmit: Login.sendLogin},
  216. m('input', attrs),
  217. m('button', 'Login'),
  218. ),
  219. m('.error', State.info),
  220. )
  221. },
  222. }
  223. const Chat = {
  224. sendPost: () => {
  225. if(textbox.value) {
  226. wire({kind: 'post', value: textbox.value})
  227. textbox.value = ''
  228. }
  229. },
  230. view() {
  231. return m('.chat',
  232. m('.posts',
  233. State.posts.map(post => m('.post', {oncreate: scrollIntoView},
  234. m('.ts', prettyTime(post.ts)),
  235. m('.source', post.source || '~'),
  236. m('.text', m.trust(DOMPurify.sanitize(marked(post.value)))),
  237. )),
  238. ),
  239. m('.actions',
  240. m('textarea#textbox', {oncreate: autoFocus, onkeydown: hotKey}),
  241. m('button', {onclick: Chat.sendPost}, 'Send'),
  242. ),
  243. m('.online',
  244. m('button', {onclick: Login.sendLogout}, 'Logout'),
  245. m('ul.user-list', State.online.map(username => m('li', username))),
  246. ),
  247. m(Media),
  248. )
  249. },
  250. }
  251. const Main = {
  252. view() {
  253. const connected = State.websocket && State.websocket.readyState === 1
  254. return connected ? m(Chat) : m(Login)
  255. },
  256. }
  257. m.mount(document.body, Main)
  258. /*
  259. *
  260. * WEBSOCKETS
  261. *
  262. */
  263. const connect = (username) => {
  264. const wsUrl = location.href.replace('http', 'ws')
  265. State.websocket = new WebSocket(wsUrl)
  266. State.websocket.onopen = (e) => {
  267. wire({kind: 'login', value: username})
  268. }
  269. State.websocket.onmessage = (e) => {
  270. const message = JSON.parse(e.data)
  271. if(message.online) {
  272. const difference = (l1, l2) => l1.filter(u => !l2.includes(u))
  273. difference(message.online, State.online).forEach(username =>
  274. State.posts.push({ts: message.ts, value: `${username} joined`}))
  275. difference(State.online, message.online).forEach(username =>
  276. State.posts.push({ts: message.ts, value: `${username} left`}))
  277. }
  278. if(!doNotLog.has(message.kind)) {
  279. console.log(message)
  280. }
  281. signal(message)
  282. m.redraw()
  283. }
  284. State.websocket.onclose = (e) => {
  285. State.online.forEach(signalPeerStop)
  286. if(!e.wasClean) {
  287. setTimeout(connect, 1000, username)
  288. }
  289. m.redraw()
  290. }
  291. }
  292. if(localStorage.username) {
  293. connect(localStorage.username)
  294. }
  295. addEventListener('pagehide', Media.turnOff)