選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

418 行
13KB

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