Skip to content

Commit

Permalink
Merge pull request #12 from fulldecent/cweagans-main
Browse files Browse the repository at this point in the history
Add configurable URL
  • Loading branch information
fulldecent authored Apr 4, 2024
2 parents 39a08ca + fa7057f commit 739c02f
Show file tree
Hide file tree
Showing 16 changed files with 396 additions and 79 deletions.
123 changes: 123 additions & 0 deletions Http/Controllers/SidebarWebhookController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

namespace Modules\SidebarWebhook\Http\Controllers;

use App\Mailbox;
use App\Conversation;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;

class SidebarWebhookController extends Controller
{
/**
* Edit ratings.
* @return Response
*/
public function mailboxSettings($id)
{
$mailbox = Mailbox::findOrFail($id);

return view('sidebarwebhook::mailbox_settings', [
'settings' => [
'sidebarwebhook.url' => \Option::get('sidebarwebhook.url')[(string)$id] ?? '',
'sidebarwebhook.secret' => \Option::get('sidebarwebhook.secret')[(string)$id] ?? '',
],
'mailbox' => $mailbox
]);
}

public function mailboxSettingsSave($id, Request $request)
{
$mailbox = Mailbox::findOrFail($id);

$settings = $request->settings ?: [];

$urls = \Option::get('sidebarwebhook.url') ?: [];
$secrets = \Option::get('sidebarwebhook.secret') ?: [];

$urls[(string)$id] = $settings['sidebarwebhook.url'] ?? '';
$secrets[(string)$id] = $settings['sidebarwebhook.secret'] ?? '';

\Option::set('sidebarwebhook.url', $urls);
\Option::set('sidebarwebhook.secret', $secrets);

\Session::flash('flash_success_floating', __('Settings updated'));

return redirect()->route('mailboxes.sidebarwebhook', ['id' => $id]);
}

/**
* Ajax controller.
*/
public function ajax(Request $request)
{
$response = [
'status' => 'error',
'msg' => '', // this is error message
];

switch ($request->action) {

case 'loadSidebar':
// mailbox_id and customer_id are required.
if (!$request->mailbox_id || !$request->conversation_id) {
$response['msg'] = 'Missing required parameters';
break;
}

try {
$mailbox = Mailbox::findOrFail($request->mailbox_id);
$conversation = Conversation::findOrFail($request->conversation_id);
$customer = $conversation->customer;
} catch (\Exception $e) {
$response['msg'] = 'Invalid mailbox or customer';
break;
}

$url = \Option::get('sidebarwebhook.url')[(string)$mailbox->id] ?? '';
$secret = \Option::get('sidebarwebhook.secret')[(string)$mailbox->id] ?? '';
if (!$url) {
$response['msg'] = 'Webhook URL is not set';
break;
}

$payload = [
'customerEmail' => $customer->getMainEmail(),
'customerPhones' => $customer->getPhones(),
'conversationSubject' => $conversation->getSubject(),
'conversationType' => $conversation->getTypeName(),
'mailboxId' => $mailbox->id,
'secret' => empty($secret) ? '' : $secret,
];

try {
$client = new \GuzzleHttp\Client();
$result = $client->post($url, [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'text/html',
],
'body' => json_encode($payload),
]);
$response['html'] = $result->getBody()->getContents();
$response['status'] = 'success';
} catch (\Exception $e) {
$response['msg'] = 'Webhook error: ' . $e->getMessage();
break;
}

break;

default:
$response['msg'] = 'Unknown action';
break;
}

if ($response['status'] == 'error' && empty($response['msg'])) {
$response['msg'] = 'Unknown error occured';
}

return \Response::json($response);
}
}
8 changes: 8 additions & 0 deletions Http/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

Route::group(['middleware' => 'web', 'prefix' => \Helper::getSubdirectory(), 'namespace' => 'Modules\SidebarWebhook\Http\Controllers'], function () {
Route::post('/sidebarwebhook/ajax', ['uses' => 'SidebarWebhookController@ajax', 'laroute' => true])->name('sidebarwebhook.ajax');

Route::get('/mailbox/sidebarwebhook/{id}', ['uses' => 'SidebarWebhookController@mailboxSettings', 'middleware' => ['auth', 'roles'], 'roles' => ['admin']])->name('mailboxes.sidebarwebhook');
Route::post('/mailbox/sidebarwebhook/{id}', ['uses' => 'SidebarWebhookController@mailboxSettingsSave', 'middleware' => ['auth', 'roles'], 'roles' => ['admin']])->name('mailboxes.sidebarwebhook.save');
});
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021–2022 William Entriken
Copyright (c) 2021–2024 William Entriken

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
70 changes: 50 additions & 20 deletions Providers/SidebarWebhookServiceProvider.php
Original file line number Diff line number Diff line change
@@ -1,36 +1,66 @@
<?php

namespace Modules\SidebarWebhook\Providers;

use Illuminate\Support\ServiceProvider;

class SidebarWebhookServiceProvider extends ServiceProvider
{
private const MODULE_NAME = 'sidebarwebhook';
private const WEBHOOK_URL = 'https://example.com/';

public function boot()
{
$this->loadViewsFrom(__DIR__.'/../Resources/views', self::MODULE_NAME);

\Eventy::addAction('conversation.after_prev_convs', function($customer, $conversation, $mailbox) {
// Skip if no customer (e.g. a draft email)
if (empty($customer)) {
return;
$this->loadViewsFrom(__DIR__ . '/../Resources/views', self::MODULE_NAME);
$this->hooks();
}

public function registerViews()
{
$viewPath = resource_path('views/modules/sidebarwebhook');

$sourcePath = __DIR__ . '/../Resources/views';

$this->publishes([
$sourcePath => $viewPath
], 'views');

$this->loadViewsFrom(array_merge(array_map(function ($path) {
return $path . '/modules/sidebarwebhook';
}, \Config::get('view.paths')), [$sourcePath]), 'sidebarwebhook');
}

/**
* Module hooks.
*/
public function hooks()
{
\Eventy::addFilter('javascripts', function ($javascripts) {
$javascripts[] = \Module::getPublicPath('sidebarwebhook') . '/js/laroute.js';
$javascripts[] = \Module::getPublicPath('sidebarwebhook') . '/js/module.js';
return $javascripts;
});

\Eventy::addAction('mailboxes.settings.menu', function ($mailbox) {
if (auth()->user()->isAdmin()) {
echo \View::make('sidebarwebhook::partials/settings_menu', ['mailbox' => $mailbox])->render();
}
}, 34);

$payload = [
'customerEmail' => $customer->getMainEmail(),
'customerPhones' => $customer->getPhones(),
'conversationSubject' => $conversation->getSubject(),
'conversationType' => $conversation->getTypeName(),
'mailboxId' => $mailbox->id,
'csrfToken' => csrf_token(),
];

echo \View::make(self::MODULE_NAME . '::partials/sidebar', [
'webhookUrlJson' => json_encode(self::WEBHOOK_URL),
'payloadJson' => json_encode($payload),
])->render();
// Settings view.
\Eventy::addFilter('settings.view', function ($view, $section) {
if ($section != 'sidebarwebhook') {
return $view;
} else {
return 'sidebarwebhook::settings';
}
}, 20, 2);

\Eventy::addAction('conversation.after_prev_convs', function ($customer, $conversation, $mailbox) {
$url = \Option::get('sidebarwebhook.url')[(string)$mailbox->id] ?? '';

if ($url != '') {
echo \View::make(self::MODULE_NAME . '::partials/sidebar', [])->render();
}
}, -1, 3);
}
}
14 changes: 14 additions & 0 deletions Public/js/laroute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(function () {
var module_routes = [{
"uri": "sidebarwebhook\/ajax",
"name": "sidebarwebhook.ajax"
}];

if (typeof(laroute) != "undefined") {
laroute.add_routes(module_routes);
} else {
contole.log('laroute not initialized, can not add module routes:');
contole.log(module_routes);
}
})();

51 changes: 51 additions & 0 deletions Public/js/module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
function swh_load_content() {
$('#swh-title').html('');
$('#swh-title').parent().addClass('hide');
$('#swh-content').addClass('hide');
$('#swh-loader').removeClass('hide');

fsAjax({
action: 'loadSidebar',
mailbox_id: getGlobalAttr('mailbox_id'),
conversation_id: getGlobalAttr('conversation_id')
},
laroute.route('sidebarwebhook.ajax'),
function(response) {
if (typeof(response.status) != "undefined" && response.status == 'success' && typeof(response.html) != "undefined" && response.html) {
$('#swh-content').html(response.html);

// Find a <title> element inside the response and display it
title = $('#swh-content').find('title').first().text();

if (title) {
$('#swh-title').html(title);
$('#swh-title').parent().removeClass('hide');
}

$('#swh-loader').addClass('hide');
$('#swh-content').removeClass('hide');
} else {
showAjaxError(response);
}
}, true
);
}

$(document).ready(function() {
// If we're not actually viewing a conversation, don't try to do anything.
if (typeof(getGlobalAttr('mailbox_id')) == "undefined" || typeof(getGlobalAttr('conversation_id')) == "undefined") {
return;
}

// If we don't have the #swh-content element, the server doesn't have a configured webhook URL.
if ($('#swh-content').length == 0) {
return;
}

swh_load_content();

$('.swh-refresh').click(function(e) {
e.preventDefault();
swh_load_content();
});
});
Loading

0 comments on commit 739c02f

Please sign in to comment.