added translated chat

This commit is contained in:
Beatrice Olivera 2018-09-05 14:59:39 +01:00
parent f5be2763ec
commit cf71cee5d7
5 changed files with 114 additions and 74 deletions

View File

@ -55,6 +55,35 @@ class PagesController < ApplicationController
head :ok
end
def translate_message
require 'google/cloud/translate'
keyfile = ENV["TRANSLATION_CREDENTIALS"]
creds = Google::Cloud::Translate::Credentials.new(keyfile)
translate = Google::Cloud::Translate.new(
project_id: ENV["PROJECT_ID"],
credentials: creds
)
target = params[:target]
message = params[:message]
userId = params[:userId]
detection = translate.detect(message)
original = detection.language
translated_message = message
unless original == target
translation = translate.translate(message, { from: original, to: target })
translated_message = translation.text.gsub("&#39;", "'")
end
ActionCable.server.broadcast "chat_room_#{params[:chat_room_id]}", {
translated_message: translated_message,
userId: userId
}
end
def send_message
puts params
@ -72,7 +101,9 @@ class PagesController < ApplicationController
chat_message: {
message: params[:message],
user_info: user_info,
time_stamp: Time.now.strftime("%H:%M") }
time_stamp: Time.now.strftime("%H:%M"),
userId: current_user.id
}
})
head :ok
end

View File

@ -11,6 +11,7 @@ import ActionCable from 'actioncable'
// find chatroom id
const chatroomId = document.getElementById('chatroom-hook').dataset["chatroomId"]
const userId = document.getElementById('current-user').innerText
console.log(userId)
// create subsciptions
App['chatroom' + chatroomId] = App.cable.subscriptions.create({
@ -19,18 +20,40 @@ App['chatroom' + chatroomId] = App.cable.subscriptions.create({
}, {
connected: () => {},
received: data => {
if (data["chat_message"]) {
if (data["chat_message"] && data["chat_message"]["userId"] == userId) {
const chatMessage = data["chat_message"]
const message = `${chatMessage["message"]}`
const messagesContainer = document.getElementById('messages-container')
const message = document.createElement("p")
message.innerText = `${chatMessage["time_stamp"]} ${chatMessage["user_info"]["name"]}: ${chatMessage["message"]}`
messagesContainer.appendChild(message)
const messageElement = document.createElement("p")
messageElement.innerText = message
messagesContainer.appendChild(messageElement)
}
else if (data["chat_message"] && data["chat_message"]["userId"] != userId) {
const chatMessage = data["chat_message"]
const target = document.getElementById('language-1').value
const message = `${chatMessage["message"]}`
fetch(`/chat_rooms/${chatroomId}/translate_message` , {
method: 'POST',
body: JSON.stringify({
message: message,
target: target,
userId: userId
}),
headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
})
} else if (data["translation"] && data["userId"] == userId) {
if (data["input"] == 1) {
document.getElementById('language-2-input').value = data["translation"].text
} else {
document.getElementById('language-1-input').value = data["translation"].text
}
} else if (data["translated_message"] && data["userId"] == userId) {
const messagesContainer = document.getElementById('messages-container')
const message = document.createElement("p")
message.innerText = data["translated_message"]
messagesContainer.appendChild(message)
} else {
// console.log(data)
}
@ -68,10 +91,9 @@ const sendBtn = document.getElementById('send-btn')
sendBtn.addEventListener('click', event => {
const chatInput = document.getElementById('chat-input')
if (chatInput && chatInput.value != chatInput.value.match(/^\s*$/g)) {
console.log(chatInput.value)
fetch(`/chat_rooms/${chatroomId}/send_message` , {
method: 'POST',
body: JSON.stringify({message: chatInput.value}),
body: JSON.stringify({message: chatInput.value, userId: userId}),
headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
})
}

View File

@ -1,51 +1,51 @@
const userId = document.getElementById('current-user').innerText
const languageForm1 = document.getElementById('lang-1')
const languageForm2 = document.getElementById('lang-2')
const chatroomId = document.getElementById('chatroom-hook').dataset["chatroomId"]
// const userId = document.getElementById('current-user').innerText
// const languageForm1 = document.getElementById('lang-1')
// const languageForm2 = document.getElementById('lang-2')
// const chatroomId = document.getElementById('chatroom-hook').dataset["chatroomId"]
languageForm1.addEventListener('submit', event => {
event.preventDefault()
const original = document.getElementById('language-1').value
const target = document.getElementById('language-2').value
const text = document.getElementById('language-1-input').value
// languageForm1.addEventListener('submit', event => {
// event.preventDefault()
// const original = document.getElementById('language-1').value
// const target = document.getElementById('language-2').value
// const text = document.getElementById('language-1-input').value
if (original !== target) {
fetch(`/chat_rooms/${chatroomId}/translate` , {
method: 'POST',
body: JSON.stringify({
original,
target,
text,
input: 1,
userId
}),
headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
})
} else {
document.getElementById('language-2-input').value = text
}
// post request and change form 1
})
// if (original !== target) {
// fetch(`/chat_rooms/${chatroomId}/translate` , {
// method: 'POST',
// body: JSON.stringify({
// original,
// target,
// text,
// input: 1,
// userId
// }),
// headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
// })
// } else {
// document.getElementById('language-2-input').value = text
// }
// // post request and change form 1
// })
languageForm2.addEventListener('submit', event => {
event.preventDefault()
const original = document.getElementById('language-2').value
const target = document.getElementById('language-1').value
const text = document.getElementById('language-2-input').value
// post request and change form 2
if (original !== target) {
fetch(`/chat_rooms/${chatroomId}/translate` , {
method: 'POST',
body: JSON.stringify({
original: original,
target: target,
text: text,
input: 2,
userId
}),
headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
})
} else {
document.getElementById('language-1-input').value = text
}
})
// languageForm2.addEventListener('submit', event => {
// event.preventDefault()
// const original = document.getElementById('language-2').value
// const target = document.getElementById('language-1').value
// const text = document.getElementById('language-2-input').value
// // post request and change form 2
// if (original !== target) {
// fetch(`/chat_rooms/${chatroomId}/translate` , {
// method: 'POST',
// body: JSON.stringify({
// original: original,
// target: target,
// text: text,
// input: 2,
// userId
// }),
// headers: { "content-type": "application/json", "X-CSRF-Token": document.querySelector('meta[name=csrf-token]').content }
// })
// } else {
// document.getElementById('language-1-input').value = text
// }
// })

View File

@ -1,24 +1,5 @@
<!-- <button id="test-btn" class="btn btn-primary">Test Connection</button> -->
<div>
<select id="language-1" class="input-field-text-black input-dropdown form-control">
<% @languages.each do |language| %>
<option value="<%= language.code %>"><%= language.name %></option>
<% end %>
</select>
<form id="lang-1">
<input type="text" class="form-control" name="language-1-input" id="language-1-input" value="" aria-describedby="basic-addon2">
</form>
<select id="language-2" class="input-field-text-black input-dropdown form-control">
<% @languages.each do |language| %>
<option value="<%= language.code %>"><%= language.name %></option>
<% end %>
</select>
<form id="lang-2">
<input type="text" class="form-control" name="language-2-input" id="language-2-input" value="" aria-describedby="basic-addon2">
</form>
</div>
<div id="join-btn" data-room="<%= @chat_room.id %>"></div>
<div id="chatroom-hook" data-chatroom-id='<%= @chat_room.id %>'></div>
@ -40,6 +21,11 @@
</div>
<div class="input-group mb-3">
<select id="language-1" class="input-field-text-black input-dropdown form-control">
<% @languages.each do |language| %>
<option value="<%= language.code %>"><%= language.name %></option>
<% end %>
</select>
<input type="text" class="form-control" name="chat-input" id="chat-input" value="" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" id="send-btn" type="submit" remote: true>Send</button>

View File

@ -33,6 +33,7 @@ Rails.application.routes.draw do
post '/cable_testing', to: 'pages#cable_testing'
post '/send_message', to: 'pages#send_message'
post '/translate', to: 'pages#translate'
post '/translate_message', to: 'pages#translate_message'
end
mount ActionCable.server, at: '/cable'