index.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // chatV1()
  2. function chatV1() {
  3. async function jsonPost(url, data) {
  4. return new Promise((resolve, reject) => {
  5. let x = new XMLHttpRequest()
  6. x.onerror = () => reject(new Error('jsonPost failed'))
  7. x.open("POST", url, true)
  8. // x.setRequestHeader('Content-Type', 'application/json')
  9. x.send(JSON.stringify(data))
  10. x.onreadystatechange = () => {
  11. if (x.readyState == XMLHttpRequest.DONE && x.status == 200){
  12. resolve(JSON.parse(x.responseText))
  13. }
  14. else if (x.status != 200){
  15. reject(new Error('status is not 200'))
  16. }
  17. }
  18. })
  19. }
  20. // jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: "ууу", message: 'УУУУУУУ'})
  21. function sendMessage(nick, message) {
  22. let data = {func: "addMessage", nick: nick, message: message, author: 'chat'}
  23. jsonPost("http://students.a-level.com.ua:10012", data).then(res => console.log(res))
  24. }
  25. function cleanUp(text) {
  26. if (typeof text !== 'string')
  27. return text
  28. if (text.match(/<script/i)){
  29. let el = document.createElement('div')
  30. el.innerText = text
  31. return `<h1>НАС ЛОМАЮТ!!</h1><pre>${el.innerHTML}</pre>`
  32. }
  33. return text
  34. }
  35. let nextMessageId = 0
  36. function getMessages() {
  37. let data = {func: "getMessages", messageId: nextMessageId, author: 'chat'}
  38. jsonPost("http://students.a-level.com.ua:10012", data).then(result => {
  39. // console.log(result.data)
  40. for (const msg of result.data) {
  41. const msgDiv = document.createElement('div')
  42. msgDiv.innerHTML = `<b>${cleanUp(msg.nick)}</b>:${cleanUp(msg.message)}`
  43. area.prepend(msgDiv)
  44. }
  45. nextMessageId = result.nextMessageId
  46. // console.log(nextMessageId)
  47. })
  48. }
  49. getMessages()
  50. btn.addEventListener("click", () => {
  51. sendMessage(user.value, msg.value)
  52. getMessages()
  53. })
  54. setInterval(getMessages, 2000)
  55. }
  56. chatV2()
  57. function chatV2() {
  58. async function jsonPost(url, data) {
  59. try {
  60. let response = await fetch(url, {
  61. method: 'POST',
  62. // headers: {
  63. // 'Content-Type': 'application/json'
  64. // },
  65. body: JSON.stringify(data)
  66. })
  67. if (response.status === 200) {
  68. return await response.json()
  69. } else if (response.status != 200) {
  70. return new Error('status is not 200')
  71. }
  72. } catch (err) {
  73. return new Error('jsonPost failed')
  74. }
  75. }
  76. async function sendMessage(nick, message) {
  77. let data = {func: "addMessage", nick: nick, message: message, author: 'chat'}
  78. try {
  79. let res = await jsonPost("http://students.a-level.com.ua:10012", data)
  80. console.log(res)
  81. } catch (err) {
  82. console.log(err)
  83. }
  84. }
  85. function cleanUp(text) {
  86. if (typeof text !== 'string') {
  87. return String(text)
  88. }
  89. if (text.match(/<script/i)){
  90. let el = document.createElement('div')
  91. el.innerText = text
  92. return `<h1>НАС ЛОМАЮТ!!</h1><pre>${el.innerHTML}</pre>`
  93. }
  94. return text
  95. }
  96. function decorateLinks(text) {
  97. const linkRegEx = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
  98. const youtubeRegEx = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/
  99. let matchLink = text.match(linkRegEx)
  100. let matchYoutube = text.match(youtubeRegEx)
  101. // console.log(matchLink)
  102. if (matchLink) {
  103. let [link] = matchLink
  104. if (link) {
  105. let newLink = `<a href="${link}" style="color:blue">${link}</a>`
  106. let newText = null
  107. newText = text.replace(link, newLink)
  108. if (matchYoutube) {
  109. let [, youtubeKey] = matchYoutube
  110. if (youtubeKey) {
  111. return `${newText} <br/> <iframe width="560" height="315"
  112. src="https://www.youtube.com/embed/${youtubeKey}" title="YouTube video player"
  113. frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope;
  114. picture-in-picture" allowfullscreen></iframe>`
  115. }
  116. } else {
  117. return newText
  118. }
  119. }
  120. } else {
  121. return text
  122. }
  123. }
  124. let nextMessageId = 0
  125. async function getMessages() {
  126. let data = {func: "getMessages", messageId: nextMessageId, author: 'chat'}
  127. try {
  128. let result = await jsonPost("http://students.a-level.com.ua:10012", data)
  129. for (const msg of result.data) {
  130. const msgDiv = document.createElement('div')
  131. msgDiv.className = 'input_message'
  132. msgDiv.innerHTML = `<div class="message_content"><b>${cleanUp(msg.nick)}</b>:<br/> ${decorateLinks(cleanUp(msg.message))}</div>`
  133. const timeDiv = document.createElement('div')
  134. timeDiv.className = 'message_time'
  135. let msgDate = new Date(msg.timestamp)
  136. function addZero(str) {
  137. let string = String(str)
  138. if (string.length === 1) {
  139. let newStr = '0' + string
  140. return newStr
  141. } else {
  142. return string
  143. }
  144. }
  145. timeDiv.innerText = `${addZero(msgDate.getHours())}:${addZero(msgDate.getMinutes())} ${addZero(msgDate.getDate())}.${addZero(msgDate.getMonth())}`
  146. msgDiv.append(timeDiv)
  147. area.prepend(msgDiv)
  148. }
  149. nextMessageId = result.nextMessageId
  150. } catch (err) {
  151. console.log(err)
  152. }
  153. }
  154. async function sendAndCheck() {
  155. await Promise.all([
  156. sendMessage(user.value, msg.value),
  157. getMessages()
  158. ])
  159. }
  160. btn.addEventListener("click", () => {
  161. sendAndCheck()
  162. })
  163. getMessages()
  164. async function checkLoop() {
  165. let delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  166. let inf = true
  167. while (inf) {
  168. await delay(2000)
  169. getMessages()
  170. }
  171. }
  172. checkLoop()
  173. }