Skip to content

Commit

Permalink
Move message_replacement_patterns to ChatGeneral Settings
Browse files Browse the repository at this point in the history
  • Loading branch information
smpallen99 committed Apr 8, 2018
1 parent 5ac24c1 commit 91c9a1e
Show file tree
Hide file tree
Showing 19 changed files with 342 additions and 44 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* Add site avatar to admin for customizing the desktop app icon
* Add site_client_name to admin for customizing the desktop app tooltip
* Add support for @@username and @@@username live status and status-message messages
* Move message_replacement_patterns to ChatGeneral Settings
* Optimize message_replacement_patterns processing with a run-time compiled module

### Bug Fixes

Expand Down
2 changes: 1 addition & 1 deletion assets/_scss/theme/imports/color_consts.scss
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ $component-color: #EAEAEA;
$success-color: #4dff4d;
$pending-color: #1ec7f1;
// $pending-color: #FCB316;
$error-color: #BC2031;
$error-color: rgb(244, 67, 54);
$selection-color: #02ACEC;
$attention-color: #9C27B0;
$content-background-color: #FFFFFF;
Expand Down
18 changes: 18 additions & 0 deletions assets/css/admin.scss
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,21 @@ form.backup {
.reset-settings {
margin-left: 20px;
}

label.message-pattern {
font-weight: bold;
}
input.message-pattern.cmd {
display: inline-block;
width: 50%
}
.input-line.double-col.message-pattern {
position: relative;
button.reset-settings {
display: none;
}
}
a.delete-pattern {
position: absolute;
bottom: 10px;
}
30 changes: 30 additions & 0 deletions assets/js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ class Admin {
})
.on('click', '.admin-settings button.save', function(e) {
//console.log('saving form....', $('form').data('id'))
$('input.error').removeClass('error');
$('.help-block').remove();
e.preventDefault()
OneChat.userchan.push('admin:save:' + $('form').data('id'), $('form').serializeArray())
.receive("ok", resp => {
Expand Down Expand Up @@ -132,6 +134,7 @@ class Admin {
})
.on('click', '#showPassword', e => {
let prefix = "";

if ($('#user_password').length > 0) {
prefix = "user_";
}
Expand Down Expand Up @@ -240,6 +243,33 @@ class Admin {
.on('change', 'section.page-container input.check', e => {
this.enable_disable_batch_delete();
})
.on('click', '.delete-pattern', e => {
let id = $(e.currentTarget).attr('data-id');
let target = $(`.input-line.message-pattern[data-id="${id}"]`);
$(`input.pattern-deleted`).val("true");
target.hide('slow', () => {
target.remove();
this.enable_save_button();
this.adjust_pattern_indexes();
});
});
}

adjust_pattern_indexes() {
// adjust pattern numbers and indexes
$.each($('.input-line.message-pattern'), (cnt, item) => {
let $item = $(item);
if (parseInt($item.attr('data-id')) !== cnt) {
$item.attr('data-id', cnt);
$item.find('[data-id]').attr('data-id', cnt);
$.each($item.find('[name]'), (_, item) => {
let $elem = $(item);
$elem.attr('name', $elem.attr('name').replace(/\[\d+\]/, `[${cnt}]`));
});
let label = $item.find('label.setting-label');
label.text(label.text().replace(/[0-9]+/, cnt + 1));
}
});
}

enable_disable_batch_delete() {
Expand Down
7 changes: 7 additions & 0 deletions assets/js/chan_user.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ OneChat.on_connect(function(one_chat, socket) {
console.log('userchan connect')
let ucxchat = one_chat.ucxchat
let chan = window.Rebel.channels.user.channel

// TODO: This is a temporary work around to stop the duplicate messages.
// It however does not stop the duplicate channels on the server.
if (one_chat.userchan) {
console.warn('found an existing user channel', one_chat.userchan, chan);
return;
}
one_chat.userchan = chan
console.log('ucxchat', ucxchat)
console.log('one_chat', one_chat)
Expand Down
1 change: 0 additions & 1 deletion lib/infinity_one_web/controllers/site_avatar_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ defmodule InfinityOneWeb.SiteAvatarController do
"""
use InfinityOneWeb, :controller

alias InfinityOne.Accounts
alias InfinityOne.Settings.General
alias InfinityOne.SiteAvatar

Expand Down
12 changes: 7 additions & 5 deletions plugins/one_admin/lib/one_admin/services/admin_service.ex
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,13 @@ defmodule OneAdmin.AdminService do
|> case do
{:ok, _} ->
{:ok, %{success: ~g"General settings updated successfully"}}
{:error, cs} ->
Logger.error "problem updating general: #{inspect cs}"
{:error, %{errors: errors} = cs} ->
Logger.debug fn -> "problem updating general: #{inspect cs.errors}" end
Enum.each(errors, fn {name, {error, _}} ->
error = String.replace(error, "'", "\\'")
js = ~s|$('input[name="#{name}"]').addClass('error').after('<div class="help-block">#{error}</div>')|
Rebel.Core.exec_js(socket, js);
end)
{:ok, %{error: ~g"There a problem updating your settings."}}
end
{:reply, resp, socket}
Expand Down Expand Up @@ -317,22 +322,19 @@ defmodule OneAdmin.AdminService do

def handle_in(ev = "permissions:role:new", _params, socket) do
debug ev, ""
# Logger.warn "new role"
Rebel.Core.async_js socket, ~s/$('.admin-link[data-id="admin_role"]').click();/
{:noreply, socket}
end

def handle_in(ev = "permissions:role:edit", params, socket) do
debug ev, params
# Logger.warn "new role params: " <> inspect(params)

AdminChannel.admin_link("admin_role", socket, Map.put(%{}, "edit-name", params["name"]))
# {:noreply, socket}
end

def handle_in(ev = "permissions:role:delete", params, socket) do
debug ev, params
# Logger.warn "new role params: " <> inspect(params)
role_name = params["name"]
if role = InfinityOne.Accounts.get_by_role(name: role_name) do
changeset = InfinityOne.Accounts.change_role(role)
Expand Down
15 changes: 15 additions & 0 deletions plugins/one_admin/lib/one_admin_web/channels/admin_channel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -482,4 +482,19 @@ defmodule OneAdminWeb.AdminChannel do
async_js socket, ~s/$('.-autocomplete-container.rooms').removeClass('hidden')/
end

def admin_new_pattern(socket, sender) do
last_id_string = Rebel.Core.exec_js!(socket, ~s/$('.input-line.message-pattern').last().attr('data-id')/)
index =
case is_binary(last_id_string) && Integer.parse(last_id_string) do
{int, ""} -> int + 1
_ -> 0
end

html = Phoenix.View.render_to_string(OneChatWeb.AdminView, "replacement_pattern.html", bindings: [hidden: true, index: index])

socket
|> Rebel.Query.insert(html, before: ~s/a.new-message-pattern/)
|> async_js(~s/$('a.new-message-pattern').prev().show('slow')/)
end

end
5 changes: 5 additions & 0 deletions plugins/one_chat/lib/one_chat/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ defmodule OneChat.Application do
def start(_type, _args) do
OneChatWeb.FlexBar.Defaults.add_buttons()
OneChatWeb.RoomChannel.KeyStore.initialize()
spawn fn ->
# Need time for the app to fully load before compiling the Message Patterns
Process.sleep(1000)
OneChat.MessageReplacementPatterns.compile()
end
end

end
78 changes: 78 additions & 0 deletions plugins/one_chat/lib/one_chat/message_replacement_patterns.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
defmodule OneChat.MessageReplacementPatterns do
require Logger

def compile do
compile_patterns()
|> compile_regex()
|> create_module()
|> compile_module()
end

defp compile_patterns do
try do
{res, _} = Code.eval_string OneSettings.message_replacement_patterns()
res
rescue
_ -> []
end
end

defp compile_regex(patterns) do
Enum.reduce(patterns, [], fn tuple, acc ->
command = elem(tuple, 3)
command =
cond do
is_tuple(command) -> command
is_binary(command) && command =~ "." ->
case String.split(command, ".", trim: true) do
[_] -> ""
list when is_list(list) ->
[fun | modules] = Enum.reverse list
mod = modules |> Enum.reverse() |> Module.concat()
{mod, String.to_existing_atom(fun)}
_ -> ""
end
true -> ""
end
case Regex.compile(elem(tuple, 1)) do
{:ok, re} ->
[{re, elem(tuple, 2), command} | acc]
_ ->
Logger.warn "Failed to compile #{elem(tuple, 1)} for name: #{elem(tuple, 0)}"
acc
end
end)
end

def create_module(patterns) do
"""
defmodule OneChat.RunPatterns do
require Logger
@patterns #{inspect patterns}
def get do
@patterns
end
def run(body) do
Enum.reduce(@patterns, body, fn {re, sub, command}, body ->
case command do
{mod, fun} ->
apply(mod, fun, [Regex.scan(re, body)])
_ -> :ok
end
Regex.replace(re, body, sub)
end)
end
end
"""
end

defp compile_module(module) do
try do
Code.eval_string(module)
rescue
e ->
Logger.warn "error: " <> inspect(e)
Logger.warn "Could not compile module: #{inspect module}"
end
end
end
4 changes: 3 additions & 1 deletion plugins/one_chat/lib/one_chat/models/schema/channel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ defmodule OneChat.Schema.Channel do
@fields ~w(archived name type topic read_only blocked default user_id description active nway)a

def model, do: OneChat.Channel

def validate_name_re, do: ~r/^[a-z0-9\.\-_]+$/i
@doc """
Builds a changeset based on the `struct` and `params`.
"""
Expand Down Expand Up @@ -68,7 +70,7 @@ defmodule OneChat.Schema.Channel do
def validate(changeset, params \\ %{}) do
changeset
|> validate_required([:name, :user_id])
|> validate_format(:name, ~r/^[a-z0-9\.\-_]+$/i)
|> validate_format(:name, validate_name_re())
|> validate_length(:name, min: 2, max: 55)
|> handle_virtual_private(params)
end
Expand Down
Loading

0 comments on commit 91c9a1e

Please sign in to comment.