Merge pull request #60 from beatriceo/translation-chat

Translation chat
This commit is contained in:
Beatrice Olivera 2018-09-05 15:02:38 +01:00 committed by GitHub
commit f3d8397b5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 143 additions and 122 deletions

View File

@ -55,6 +55,35 @@ class PagesController < ApplicationController
head :ok head :ok
end 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 def send_message
puts params puts params
@ -72,7 +101,9 @@ class PagesController < ApplicationController
chat_message: { chat_message: {
message: params[:message], message: params[:message],
user_info: user_info, user_info: user_info,
time_stamp: Time.now.strftime("%H:%M") } time_stamp: Time.now.strftime("%H:%M"),
userId: current_user.id
}
}) })
head :ok head :ok
end end

View File

@ -28,9 +28,26 @@ class UsersController < ApplicationController
def setting def setting
@user = current_user @user = current_user
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
)
@languages = translate.languages("en")
end end
def update_setting
current_user.update(user_params)
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
puts current_user.language
current_user.save
redirect_to setting_path
end
private private

View File

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

View File

@ -1,24 +1,5 @@
<!-- <button id="test-btn" class="btn btn-primary">Test Connection</button> --> <!-- <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="join-btn" data-room="<%= @chat_room.id %>"></div>
<div id="chatroom-hook" data-chatroom-id='<%= @chat_room.id %>'></div> <div id="chatroom-hook" data-chatroom-id='<%= @chat_room.id %>'></div>
@ -40,6 +21,11 @@
</div> </div>
<div class="input-group mb-3"> <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"> <input type="text" class="form-control" name="chat-input" id="chat-input" value="" aria-describedby="basic-addon2">
<div class="input-group-append"> <div class="input-group-append">
<button class="btn btn-primary" id="send-btn" type="submit" remote: true>Send</button> <button class="btn btn-primary" id="send-btn" type="submit" remote: true>Send</button>

View File

@ -1,47 +1,10 @@
<div id="settings-page"></div> <div id="settings-page"></div>
<% languages = [ <% language_names = [] %>
"Afrikaans (South Africa)", "Amharic (Ethiopia)", "Armenian (Armenia)",
"Azerbaijani (Azerbaijan)", "Indonesian (Indonesia)", "Malay (Malaysia)", <% @languages.each do |language| %>
"Bengali (Bangladesh)", "Bengali (India)", "Catalan (Spain)", <% language_names << language.name %>
"Czech (Czech Republic)", "Danish (Denmark)", "German (Germany)", <% end %>
"English (Australia)", "English (Canada)", "English (Ghana)",
"English (United Kingdom)", "English (India)", "English (Ireland)",
"English (Kenya)", "English (New Zealand)", "English (Nigeria)",
"English (Philippines)", "English (South Africa)", "English (Tanzania)",
"English (United States)", "Spanish (Argentina)", "Spanish (Bolivia)",
"Spanish (Chile)", "Spanish (Colombia)", "Spanish (Costa Rica)",
"Spanish (Ecuador)", "Spanish (El Salvador)", "Spanish (Spain)",
"Spanish (United States)", "Spanish (Guatemala)", "Spanish (Honduras)",
"Spanish (Mexico)", "Spanish (Nicaragua)", "Spanish (Panama)",
"Spanish (Paraguay)", "Spanish (Peru)", "Spanish (Puerto Rico)",
"Spanish (Dominican Republic)", "Spanish (Uruguay)", "Spanish (Venezuela)",
"Basque (Spain)", "Filipino (Philippines)", "French (Canada)",
"French (France)", "Galician (Spain)", "Georgian (Georgia)",
"Gujarati (India)", "Croatian (Croatia)", "Zulu (South Africa)",
"Icelandic (Iceland)", "Italian (Italy)", "Javanese (Indonesia)",
"Kannada (India)", "Khmer (Cambodia)", "Lao (Laos)",
"Latvian (Latvia)", "Lithuanian (Lithuania)", "Hungarian (Hungary)",
"Malayalam (India)", "Marathi (India)", "Dutch (Netherlands)",
"Nepali (Nepal)", "Norwegian Bokmål (Norway)", "Polish (Poland)",
"Portuguese (Brazil)", "Portuguese (Portugal)", "Romanian (Romania)",
"Sinhala (Sri Lanka)", "Slovak (Slovakia)", "Slovenian (Slovenia)",
"Sundanese (Indonesia)", "Swahili (Tanzania)", "Swahili (Kenya)",
"Finnish (Finland)", "Swedish (Sweden)", "Tamil (India)",
"Tamil (Singapore)", "Tamil (Sri Lanka)", "Tamil (Malaysia)",
"Telugu (India)", "Vietnamese (Vietnam)", "Turkish (Turkey)",
"Urdu (Pakistan)", "Urdu (India)", "Greek (Greece)",
"Bulgarian (Bulgaria)", "Russian (Russia)", "Serbian (Serbia)",
"Ukrainian (Ukraine)", "Hebrew (Israel)", "Arabic (Israel)",
"Arabic (Jordan)", "Arabic (United Arab Emirates)", "Arabic (Bahrain)",
"Arabic (Algeria)", "Arabic (Saudi Arabia)", "Arabic (Iraq)",
"Arabic (Kuwait)", "Arabic (Morocco)", "Arabic (Tunisia)",
"Arabic (Oman)", "Arabic (Qatar)", "Arabic (Lebanon)",
"Arabic (Egypt)", "Persian (Iran)", "Hindi (India)",
"Thai (Thailand)", "Korean (South Korea)", "Chinese, Mandarin (Traditional, Taiwan)",
"Chinese, Cantonese (Traditional, Hong Kong)", "Japanese (Japan)",
"Chinese, Mandarin (Simplified, Hong Kong)",
"Chinese, Mandarin (Simplified, China)" ]%>
<% fonts = [ <% fonts = [
"Arial", "Arial",
@ -56,11 +19,11 @@
<div class="settings"> <div class="settings">
<h2>Settings</h2> <h2>Settings</h2>
<div> <div>
<%= simple_form_for(@user) do |t| %> <%= simple_form_for(current_user, url: update_setting_path) do |t| %>
<div> <div>
<div class="card card-form card-form-no-hover"> <div class="card card-form card-form-no-hover">
<%= t.label :language, class:'padding-right no-margin font-weight-normal' %> <%= t.label :language, class:'padding-right no-margin font-weight-normal' %>
<%= t.input_field :language, collection: languages.sort, class:'input-field-text-black input-dropdown form-control' %> <%= t.input_field :language, collection: language_names, class:'input-field-text-black input-dropdown form-control', include_blank: false %>
</div> </div>
<div class="card card-form card-form-no-hover"> <div class="card card-form card-form-no-hover">
<%= t.label :caption_font, class:'padding-right no-margin font-weight-normal' %> <%= t.label :caption_font, class:'padding-right no-margin font-weight-normal' %>
@ -77,11 +40,11 @@
<span class="slider round"></span> <span class="slider round"></span>
</label> </label>
</div> </div>
<%= t.button :submit, value: 'Save', class: "btn btn-primary save-btn form-control" %>
<%= link_to "Save", contacts_path, class: "btn btn-primary save-btn form-control" %>
<p></p> <p></p>
</div> </div>
<% end %> <% end %>
<%#= link_to "Save", update_setting_path, method: :patch, class: "btn btn-primary save-btn form-control" %>
</div> </div>
</div> </div>
</div> </div>

View File

@ -23,6 +23,7 @@ Rails.application.routes.draw do
get '/contacts', to: 'pages#index' get '/contacts', to: 'pages#index'
get '/setting', to: 'users#setting' get '/setting', to: 'users#setting'
patch '/setting', to: 'users#update_setting', as: 'update_setting'
post '/sessions', to: 'video_sessions#create' post '/sessions', to: 'video_sessions#create'
post '/chat_rooms/chat_room_sessions', to: 'chat_rooms#create' post '/chat_rooms/chat_room_sessions', to: 'chat_rooms#create'
@ -32,6 +33,7 @@ Rails.application.routes.draw do
post '/cable_testing', to: 'pages#cable_testing' post '/cable_testing', to: 'pages#cable_testing'
post '/send_message', to: 'pages#send_message' post '/send_message', to: 'pages#send_message'
post '/translate', to: 'pages#translate' post '/translate', to: 'pages#translate'
post '/translate_message', to: 'pages#translate_message'
end end
mount ActionCable.server, at: '/cable' mount ActionCable.server, at: '/cable'