Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

317 lines
9.6KB

  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. const requestFullscreen = (el.requestFullscreen || el.webkitRequestFullscreen).bind(el)
  120. document.fullscreenElement ? document.exitFullscreen() : requestFullscreen()
  121. }
  122. const prettyTime = (ts) => {
  123. const dt = new Date(ts)
  124. const H = `0${dt.getHours()}`.slice(-2)
  125. const M = `0${dt.getMinutes()}`.slice(-2)
  126. const S = `0${dt.getSeconds()}`.slice(-2)
  127. return `${H}:${M}:${S}`
  128. }
  129. const hotKey = (e) => {
  130. // if isDesktop, Enter posts, unless Shift+Enter
  131. // use isLandscape as proxy for isDesktop
  132. if(e.key === 'Enter' && isLandscape && !e.shiftKey) {
  133. e.preventDefault()
  134. Chat.sendPost()
  135. }
  136. }
  137. const Video = {
  138. appendStream: ({username, stream}) => ({dom}) => {
  139. dom.autoplay = true
  140. dom.muted = (username === State.username)
  141. dom.srcObject = stream
  142. dom.ondblclick = toggleFullscreen(dom)
  143. },
  144. view({attrs}) {
  145. const rpc = State.rpcs[attrs.username] || {iceConnectionState: m.trust(' ')}
  146. return m('.video-container',
  147. m('.video-source', attrs.username),
  148. m('.video-state', rpc.iceConnectionState),
  149. m('video.mirrored', {playsinline: true, oncreate: Video.appendStream(attrs)}),
  150. )
  151. },
  152. }
  153. const Media = {
  154. audioDefaults: {
  155. noiseSuppresion: true,
  156. echoCancellation: true,
  157. },
  158. videoOptions: {
  159. camera: {width: {ideal: 320}, facingMode: 'user', frameRate: 26},
  160. screen: {mediaSource: 'screen', frameRate: 26},
  161. none: false,
  162. },
  163. getSelectedConstraints: () => {
  164. const videoChoice = document.querySelector('#media-source').value
  165. const muted = document.querySelector('#mute-check').checked
  166. return {
  167. video: Media.videoOptions[videoChoice],
  168. audio: muted ? false : Media.audioDefaults,
  169. }
  170. },
  171. turnOn: async () => {
  172. const constraints = Media.getSelectedConstraints()
  173. const media = await navigator.mediaDevices.getUserMedia(constraints)
  174. State.media[State.username] = media
  175. wire({kind: 'peerInfo', value: {type: 'request'}})
  176. m.redraw()
  177. },
  178. turnOff: () => {
  179. wire({kind: 'peerInfo', value: {type: 'stop'}})
  180. State.online.forEach(signalPeerStop)
  181. },
  182. view() {
  183. if(!State.media[State.username]) {
  184. return m('.media',
  185. m('button', {onclick: Media.turnOn}, 'turn on'),
  186. m('select#media-source',
  187. Object.keys(Media.videoOptions).map(description => m('option', description)),
  188. ),
  189. m('label', m('input#mute-check', {type: 'checkbox'}), 'mute'),
  190. )
  191. }
  192. else {
  193. return m('.media',
  194. m('button', {onclick: Media.turnOff}, 'turn off'),
  195. m('.videos',
  196. Object.entries(State.media).map(([username, stream]) =>
  197. m(Video, {username, stream})
  198. ),
  199. ),
  200. )
  201. }
  202. }
  203. }
  204. const Login = {
  205. sendLogin: (e) => {
  206. e.preventDefault()
  207. const username = e.target.username.value
  208. localStorage.username = username
  209. connect(username)
  210. },
  211. sendLogout: (e) => {
  212. Media.turnOff()
  213. wire({kind: 'logout'})
  214. State.posts = []
  215. },
  216. view() {
  217. const attrs = {
  218. oncreate: autoFocus,
  219. name: 'username',
  220. autocomplete: 'off',
  221. value: localStorage.username,
  222. }
  223. return m('.login',
  224. m('form', {onsubmit: Login.sendLogin},
  225. m('input', attrs),
  226. m('button', 'Login'),
  227. ),
  228. m('.error', State.info),
  229. )
  230. },
  231. }
  232. const Chat = {
  233. sendPost: () => {
  234. if(textbox.value) {
  235. wire({kind: 'post', value: textbox.value})
  236. textbox.value = ''
  237. }
  238. },
  239. view() {
  240. return m('.chat',
  241. m('.posts',
  242. State.posts.map(post => m('.post', {oncreate: scrollIntoView},
  243. m('.ts', prettyTime(post.ts)),
  244. m('.source', post.source || '~'),
  245. m('.text', m.trust(DOMPurify.sanitize(marked(post.value)))),
  246. )),
  247. ),
  248. m('.actions',
  249. m('textarea#textbox', {oncreate: autoFocus, onkeydown: hotKey}),
  250. m('button', {onclick: Chat.sendPost}, 'Send'),
  251. ),
  252. m('.online',
  253. m('button', {onclick: Login.sendLogout}, 'Logout'),
  254. m('ul.user-list', State.online.map(username => m('li', username))),
  255. ),
  256. m(Media),
  257. )
  258. },
  259. }
  260. const Main = {
  261. view() {
  262. const connected = State.websocket && State.websocket.readyState === 1
  263. return connected ? m(Chat) : m(Login)
  264. },
  265. }
  266. m.mount(document.body, Main)
  267. /*
  268. *
  269. * WEBSOCKETS
  270. *
  271. */
  272. const connect = (username) => {
  273. const wsUrl = location.href.replace('http', 'ws')
  274. State.websocket = new WebSocket(wsUrl)
  275. State.websocket.onopen = (e) => {
  276. wire({kind: 'login', value: username})
  277. }
  278. State.websocket.onmessage = (e) => {
  279. const message = JSON.parse(e.data)
  280. if(message.online) {
  281. const difference = (l1, l2) => l1.filter(u => !l2.includes(u))
  282. difference(message.online, State.online).forEach(username =>
  283. State.posts.push({ts: message.ts, value: `${username} joined`}))
  284. difference(State.online, message.online).forEach(username =>
  285. State.posts.push({ts: message.ts, value: `${username} left`}))
  286. }
  287. if(!doNotLog.has(message.kind)) {
  288. console.log(message)
  289. }
  290. signal(message)
  291. m.redraw()
  292. }
  293. State.websocket.onclose = (e) => {
  294. State.online.forEach(signalPeerStop)
  295. if(!e.wasClean) {
  296. setTimeout(connect, 1000, username)
  297. }
  298. m.redraw()
  299. }
  300. }
  301. if(localStorage.username) {
  302. connect(localStorage.username)
  303. }
  304. addEventListener('pagehide', Media.turnOff)