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.

285 lines
8.3KB

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