script.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. //Chat Homework http://chat.serg15577330.fe.a-level.com.ua/
  2. function dataToDataTimeLocal(date) {
  3. let timeStamp = date.getTime();
  4. let timeZoneoffset = -date.getTimezoneOffset() * 60 * 1000;
  5. let localTime = timeStamp + timeZoneoffset;
  6. return new Date(localTime).toISOString().slice(0, -1);
  7. }
  8. let message = document.querySelector('#message');
  9. let nick = document.querySelector('#nickname');
  10. let btn = document.querySelector('.btn');
  11. btn.addEventListener('click',async () => {
  12. nickName = nickname.value;
  13. userMessage = message.value;
  14. await sendMessage(nickName, userMessage);
  15. getMasseges();
  16. message.value = '';
  17. });
  18. btn.disabled = 'true';
  19. message.addEventListener('input', () => {
  20. if (nick.value && message.value) {
  21. btn.disabled = '';
  22. } else if (nick.value == '' || message.value == '') btn.disabled = 'true';
  23. })
  24. function jsonPost(url, data) {
  25. return new Promise((resolve, reject) => {
  26. var x = new XMLHttpRequest();
  27. x.onerror = () => reject(new Error('jsonPost failed'))
  28. //x.setRequestHeader('Content-Type', 'application/json');
  29. x.open("POST", url, true);
  30. x.send(JSON.stringify(data))
  31. x.onreadystatechange = () => {
  32. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  33. resolve(JSON.parse(x.responseText))
  34. } else if (x.status != 200) {
  35. reject(new Error('status is not 200'))
  36. }
  37. }
  38. })
  39. }
  40. function getMasseges(messageId = 0) {
  41. jsonPost("http://students.a-level.com.ua:10012", {
  42. func: "getMessages",
  43. messageId: messageId
  44. })
  45. .then(res => {
  46. res.data.forEach(el => {
  47. readMessage(el)
  48. });
  49. let prevId = res.nextMessageId;
  50. let currentId = messageId;
  51. let messageInterval = setInterval((id) => {
  52. if (currentId < prevId) {
  53. console.log('step')
  54. soundClick();
  55. jsonPost("http://students.a-level.com.ua:10012", {
  56. func: "getMessages",
  57. messageId: currentId + 1
  58. }).then(res => res.nextMessageId, res.data.forEach(el => {
  59. readMessage(el)
  60. }))
  61. currentId = res.nextMessageId;
  62. }
  63. }, 2000);
  64. });
  65. }
  66. getMasseges();
  67. function soundClick() {
  68. const audio = new Audio();
  69. audio.src = '7.mp3';
  70. audio.play();
  71. }
  72. function sendMessage(nick, message) {
  73. jsonPost("http://students.a-level.com.ua:10012", {
  74. func: "addMessage",
  75. nick: nick,
  76. message: message
  77. })
  78. .then(res => getMasseges(res.nextMessageId));
  79. message.value = '';
  80. }
  81. let regYoutube = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/; //regExp for YouTube video
  82. function readMessage(msg) {
  83. let div = document.createElement('div');
  84. let spanUserName = document.createElement('span');
  85. let spanMessages = document.createElement('span');
  86. let timeSpan = document.createElement('span');
  87. let idMsg = document.createElement('span');
  88. div.style.marginBottom = '10px';
  89. spanUserName.style.backgroundColor = '#a7cbf8';
  90. spanUserName.style.marginBottom = '10px';
  91. spanMessages.style.backgroundColor = '#94f094';
  92. spanMessages.style.textAlign = 'rigth';
  93. spanUserName.innerHTML += `${msg.nick || 'NONAME'}`;
  94. timeSpan.style.backgroundColor = '#afafc2';
  95. timeSpan.style.marginLeft = '10px';
  96. timeSpan.innerText = dataToDataTimeLocal(new Date(msg.timestamp)).slice(0, 19);
  97. console.log(dataToDataTimeLocal(new Date(msg.timestamp)).slice(0, 19));
  98. //idMsg.innerText = nextMessageId;
  99. /* if (msg.message.match(regYoutube)) {
  100. console.log(`https://www.youtube.com/embed/${msg.message.match(regYoutube)[1]}`) // get youtube key
  101. spanMessages.innerHTML += `<iframe width="560" height="315" src="https://www.youtube.com/embed/${msg.message.match(regYoutube)[1]}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
  102. } else {
  103. spanMessages.innerHTML += ` Write: ${msg.message}`;
  104. } */
  105. spanMessages.innerHTML += msg.message || 'Send empty message'; //*** */
  106. div.prepend(spanMessages, timeSpan);
  107. div.prepend(spanUserName, idMsg);
  108. answer.prepend(div)
  109. }
  110. //Stage 6
  111. //Прогуглить и разобраться с fetch и заменить внутренности jsonPost на код, использующий fetch вместо XMLHttpRequest.
  112. /* async function jsonPost(url, data) {
  113. let response = await fetch(url, {
  114. method: "POST",
  115. headers: {
  116. 'Content-Type': 'application/json'
  117. },
  118. body: JSON.stringify(data)
  119. });
  120. console.log(response);
  121. if (response.ok) {
  122. let json = response.json();
  123. return json;
  124. } else {
  125. return new Error('jsonPost failed'+ response.status);
  126. }
  127. } */