您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

370 行
12KB

  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 blockIndent = (text, iStart, iEnd, nLevels) => {
  130. // prop
  131. const startLine = text.slice(0, iStart).split('\n').length - 1
  132. const endLine = text.slice(0, iEnd).split('\n').length - 1
  133. const newText = text
  134. .split('\n')
  135. .map((line, i) => {
  136. if(i < startLine || i > endLine || nLevels === 0) {
  137. newLine = line
  138. }
  139. else if(nLevels > 0) {
  140. newLine = line.replace(/^/, ' ')
  141. }
  142. else if(nLevels < 0) {
  143. newLine = line.replace(/^ /, '')
  144. }
  145. if(i === startLine) {
  146. iStart = iStart + newLine.length - line.length
  147. }
  148. iEnd = iEnd + newLine.length - line.length
  149. return newLine
  150. })
  151. .join('\n')
  152. return [newText, Math.max(0, iStart), Math.max(0, iEnd)]
  153. }
  154. const hotKey = (e) => {
  155. // if isDesktop, Enter posts, unless Shift+Enter
  156. // use isLandscape as proxy for isDesktop
  157. if(e.key === 'Enter' && isLandscape && !e.shiftKey) {
  158. e.preventDefault()
  159. Chat.sendPost()
  160. }
  161. // indent and dedent
  162. const modKey = e.ctrlKey || e.metaKey
  163. const {value: text, selectionStart: A, selectionEnd: B} = textbox
  164. if(e.key === 'Tab') {
  165. e.preventDefault()
  166. const regex = new RegExp(`([\\s\\S]{${A}})([\\s\\S]{${B - A}})`)
  167. textbox.value = text.replace(regex, (m, a, b) => a + ' '.repeat(4))
  168. textbox.setSelectionRange(A + 4, A + 4)
  169. }
  170. if(']['.includes(e.key) && modKey) {
  171. e.preventDefault()
  172. const nLevels = {']': 1, '[': -1}[e.key]
  173. const [newText, newA, newB] = blockIndent(text, A, B, nLevels)
  174. textbox.value = newText
  175. textbox.setSelectionRange(newA, newB)
  176. }
  177. }
  178. const Video = {
  179. appendStream: ({username, stream}) => ({dom}) => {
  180. dom.autoplay = true
  181. dom.muted = (username === State.username)
  182. dom.srcObject = stream
  183. dom.ondblclick = toggleFullscreen(dom)
  184. },
  185. view({attrs}) {
  186. const rpc = State.rpcs[attrs.username] || {iceConnectionState: m.trust('&nbsp;')}
  187. return m('.video-container',
  188. m('.video-source', attrs.username),
  189. m('.video-state', rpc.iceConnectionState),
  190. m('video.mirrored', {playsinline: true, oncreate: Video.appendStream(attrs)}),
  191. )
  192. },
  193. }
  194. const Media = {
  195. audioDefaults: {
  196. noiseSuppresion: true,
  197. echoCancellation: true,
  198. },
  199. getSelectedMedia: async () => {
  200. const stream = new MediaStream()
  201. const muted = document.querySelector('#mute-check').checked
  202. if(!muted) {
  203. const audio = Media.audioDefaults
  204. const audioStream = await navigator.mediaDevices.getUserMedia({audio})
  205. audioStream.getAudioTracks().forEach(track => stream.addTrack(track))
  206. }
  207. const source = document.querySelector('#media-source').value
  208. if(source === 'camera') {
  209. const video = {width: {ideal: 320}, facingMode: 'user', frameRate: 26}
  210. const videoStream = await navigator.mediaDevices.getUserMedia({video})
  211. videoStream.getVideoTracks().forEach(track => stream.addTrack(track))
  212. }
  213. if(source === 'screen' && navigator.mediaDevices.getDisplayMedia) {
  214. const videoStream = await navigator.mediaDevices.getDisplayMedia()
  215. videoStream.getVideoTracks().forEach(track => stream.addTrack(track))
  216. }
  217. return stream
  218. },
  219. turnOn: async () => {
  220. const media = await Media.getSelectedMedia()
  221. State.media[State.username] = media
  222. wire({kind: 'peerInfo', value: {type: 'request'}})
  223. m.redraw()
  224. },
  225. turnOff: () => {
  226. wire({kind: 'peerInfo', value: {type: 'stop'}})
  227. State.online.forEach(signalPeerStop)
  228. },
  229. view() {
  230. if(!State.media[State.username]) {
  231. return m('.media',
  232. m('button', {onclick: Media.turnOn}, 'turn on'),
  233. m('select#media-source',
  234. m('option', 'camera'),
  235. m('option', 'screen'),
  236. m('option', 'none'),
  237. ),
  238. m('label', m('input#mute-check', {type: 'checkbox'}), 'mute'),
  239. )
  240. }
  241. else {
  242. return m('.media',
  243. m('button', {onclick: Media.turnOff}, 'turn off'),
  244. m('.videos',
  245. Object.entries(State.media).map(([username, stream]) =>
  246. m(Video, {username, stream})
  247. ),
  248. ),
  249. )
  250. }
  251. }
  252. }
  253. const Login = {
  254. sendLogin: (e) => {
  255. e.preventDefault()
  256. const username = e.target.username.value
  257. localStorage.username = username
  258. connect(username)
  259. },
  260. sendLogout: (e) => {
  261. Media.turnOff()
  262. wire({kind: 'logout'})
  263. State.posts = []
  264. },
  265. view() {
  266. const attrs = {
  267. oncreate: autoFocus,
  268. name: 'username',
  269. autocomplete: 'off',
  270. value: localStorage.username,
  271. }
  272. return m('.login',
  273. m('form', {onsubmit: Login.sendLogin},
  274. m('input', attrs),
  275. m('button', 'Login'),
  276. ),
  277. m('.error', State.info),
  278. )
  279. },
  280. }
  281. const Chat = {
  282. sendPost: () => {
  283. if(textbox.value) {
  284. wire({kind: 'post', value: textbox.value})
  285. textbox.value = ''
  286. }
  287. },
  288. view() {
  289. return m('.chat',
  290. m('.posts',
  291. State.posts.map(post => m('.post', {oncreate: scrollIntoView},
  292. m('.ts', prettyTime(post.ts)),
  293. m('.source', post.source || '~'),
  294. m('.text', m.trust(DOMPurify.sanitize(marked(post.value)))),
  295. )),
  296. ),
  297. m('.actions',
  298. m('textarea#textbox', {oncreate: autoFocus, onkeydown: hotKey}),
  299. m('button', {onclick: Chat.sendPost}, 'Send'),
  300. ),
  301. m('.online',
  302. m('button', {onclick: Login.sendLogout}, 'Logout'),
  303. m('ul.user-list', State.online.map(username => m('li', username))),
  304. ),
  305. m(Media),
  306. )
  307. },
  308. }
  309. const Main = {
  310. view() {
  311. const connected = State.websocket && State.websocket.readyState === 1
  312. return connected ? m(Chat) : m(Login)
  313. },
  314. }
  315. m.mount(document.body, Main)
  316. /*
  317. *
  318. * WEBSOCKETS
  319. *
  320. */
  321. const connect = (username) => {
  322. const wsUrl = location.href.replace('http', 'ws')
  323. State.websocket = new WebSocket(wsUrl)
  324. State.websocket.onopen = (e) => {
  325. wire({kind: 'login', value: username})
  326. }
  327. State.websocket.onmessage = (e) => {
  328. const message = JSON.parse(e.data)
  329. if(message.online) {
  330. const difference = (l1, l2) => l1.filter(u => !l2.includes(u))
  331. difference(message.online, State.online).forEach(username =>
  332. State.posts.push({ts: message.ts, value: `${username} joined`}))
  333. difference(State.online, message.online).forEach(username =>
  334. State.posts.push({ts: message.ts, value: `${username} left`}))
  335. }
  336. if(!doNotLog.has(message.kind)) {
  337. console.log(message)
  338. }
  339. signal(message)
  340. m.redraw()
  341. }
  342. State.websocket.onclose = (e) => {
  343. State.online.forEach(signalPeerStop)
  344. if(!e.wasClean) {
  345. setTimeout(connect, 1000, username)
  346. }
  347. m.redraw()
  348. }
  349. }
  350. if(localStorage.username) {
  351. connect(localStorage.username)
  352. }
  353. addEventListener('pagehide', Media.turnOff)