Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring Code for src/messaging/data.js #155

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 100 additions & 89 deletions public/src/client/account/edit.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// used Chat GPT to update the code to address both warnings

'use strict';

define('forum/account/edit', [
Expand All @@ -9,12 +11,20 @@ define('forum/account/edit', [
'bootbox',
'alerts',
'admin/modules/change-email',
], function (header, picture, translator, api, hooks, bootbox, alerts, changeEmail) {
], function (dependencies) {
const {
header, picture, translator, api, hooks, bootbox, alerts, changeEmail,
} = dependencies;

const AccountEdit = {};

AccountEdit.init = function () {
header.init();
setupEventHandlers();
handleEmailChange();
};

function setupEventHandlers() {
$('#submitBtn').on('click', updateProfile);

if (ajaxify.data.groupTitleArray.length === 1 && ajaxify.data.groupTitleArray[0] === '') {
Expand All @@ -23,97 +33,98 @@ define('forum/account/edit', [

handleAccountDelete();
handleEmailConfirm();
updateSignature();
updateAboutMe();
setupCharCountHandlers();
handleGroupControls();
}

function handleEmailChange() {
if (!ajaxify.data.isSelf && ajaxify.data.canEdit) {
$(`a[href="${config.relative_path}/user/${ajaxify.data.userslug}/edit/email"]`).on('click', () => {
changeEmail.init({
uid: ajaxify.data.uid,
email: ajaxify.data.email,
onSuccess: function () {
alerts.success('[[user:email-updated]]');
},
onSuccess: () => alerts.success('[[user:email-updated]]'),
});
return false;
});
}
};
}

function updateProfile() {
function getGroupSelection() {
const els = $('[component="group/badge/list"] [component="group/badge/item"][data-selected="true"]');
return els.map((i, el) => $(el).attr('data-value')).get();
}
const userData = gatherProfileData();
updateUserProfile(userData);
return false;
}

function gatherProfileData() {
const userData = $('form[component="profile/edit/form"]').serializeObject();
userData.uid = ajaxify.data.uid;
userData.groupTitle = userData.groupTitle || '';
userData.groupTitle = JSON.stringify(getGroupSelection());
return userData;
}

function getGroupSelection() {
return $('[component="group/badge/list"] [component="group/badge/item"][data-selected="true"]')
.map((i, el) => $(el).attr('data-value')).get();
}

function updateUserProfile(userData) {
hooks.fire('action:profile.update', userData);

api.put('/users/' + userData.uid, userData).then((res) => {
api.put(`/users/${userData.uid}`, userData).then((res) => {
alerts.success('[[user:profile-update-success]]');

if (res.picture) {
$('#user-current-picture').attr('src', res.picture);
picture.updateHeader(res.picture);
}

picture.updateHeader(res.picture);
}).catch(alerts.error);
}

return false;
function handleAccountDelete() {
$('#deleteAccountBtn').on('click', () => {
translator.translate('[[user:delete-account-confirm]]', (translated) => {
showDeleteAccountModal(translated);
});
return false;
});
}

function showDeleteAccountModal(translated) {
const modal = bootbox.confirm(translated + '<p><input type="password" class="form-control" id="confirm-password" /></p>', (confirm) => {
if (!confirm) return;

const confirmBtn = modal.find('.btn-primary');
confirmBtn.html('<i class="fa fa-spinner fa-spin"></i>').prop('disabled', true);

function handleAccountDelete() {
$('#deleteAccountBtn').on('click', function () {
translator.translate('[[user:delete-account-confirm]]', function (translated) {
const modal = bootbox.confirm(translated + '<p><input type="password" class="form-control" id="confirm-password" /></p>', function (confirm) {
if (!confirm) {
return;
}

const confirmBtn = modal.find('.btn-primary');
confirmBtn.html('<i class="fa fa-spinner fa-spin"></i>');
confirmBtn.prop('disabled', true);
api.del(`/users/${ajaxify.data.uid}/account`, {
password: $('#confirm-password').val(),
}, function (err) {
function restoreButton() {
translator.translate('[[modules:bootbox.confirm]]', function (confirmText) {
confirmBtn.text(confirmText);
confirmBtn.prop('disabled', false);
});
}

if (err) {
restoreButton();
return alerts.error(err);
}

confirmBtn.html('<i class="fa fa-check"></i>');
window.location.href = `${config.relative_path}/`;
});

return false;
});
api.del(`/users/${ajaxify.data.uid}/account`, {
password: $('#confirm-password').val(),
}, (err) => {
if (err) {
restoreDeleteButton(confirmBtn);
return alerts.error(err);
}

modal.on('shown.bs.modal', function () {
modal.find('input').focus();
});
confirmBtn.html('<i class="fa fa-check"></i>');
window.location.href = `${config.relative_path}/`;
});
return false;
});

modal.on('shown.bs.modal', () => {
modal.find('input').focus();
});
}

function restoreDeleteButton(confirmBtn) {
translator.translate('[[modules:bootbox.confirm]]', (confirmText) => {
confirmBtn.text(confirmText).prop('disabled', false);
});
}

function handleEmailConfirm() {
$('#confirm-email').on('click', function () {
const btn = $(this).attr('disabled', true);
socket.emit('user.emailConfirm', {}, function (err) {
$('#confirm-email').on('click', () => {
const btn = $('#confirm-email').attr('disabled', true);
socket.emit('user.emailConfirm', {}, (err) => {
btn.removeAttr('disabled');
if (err) {
return alerts.error(err);
Expand All @@ -123,56 +134,56 @@ define('forum/account/edit', [
});
}

function getCharsLeft(el, max) {
return el.length ? '(' + el.val().length + '/' + max + ')' : '';
function setupCharCountHandlers() {
setupCharCount('#signature', '#signatureCharCountLeft', ajaxify.data.maximumSignatureLength);
setupCharCount('#aboutme', '#aboutMeCharCountLeft', ajaxify.data.maximumAboutMeLength);
}

function updateSignature() {
const el = $('#signature');
$('#signatureCharCountLeft').html(getCharsLeft(el, ajaxify.data.maximumSignatureLength));
function setupCharCount(inputSelector, countSelector, maxLength) {
const el = $(inputSelector);
$(countSelector).html(getCharsLeft(el, maxLength));

el.on('keyup change', function () {
$('#signatureCharCountLeft').html(getCharsLeft(el, ajaxify.data.maximumSignatureLength));
el.on('keyup change', () => {
$(countSelector).html(getCharsLeft(el, maxLength));
});
}

function updateAboutMe() {
const el = $('#aboutme');
$('#aboutMeCharCountLeft').html(getCharsLeft(el, ajaxify.data.maximumAboutMeLength));

el.on('keyup change', function () {
$('#aboutMeCharCountLeft').html(getCharsLeft(el, ajaxify.data.maximumAboutMeLength));
});
function getCharsLeft(el, max) {
return el.length ? `(${el.val().length}/${max})` : '';
}

function handleGroupControls() {
const { allowMultipleBadges } = ajaxify.data;
$('[component="group/toggle/hide"]').on('click', function () {
const groupEl = $(this).parents('[component="group/badge/item"]');
groupEl.attr('data-selected', 'false');
$(this).addClass('hidden');
groupEl.find('[component="group/toggle/show"]').removeClass('hidden');
});

$('[component="group/toggle/show"]').on('click', function () {
if (!allowMultipleBadges) {
$('[component="group/badge/list"] [component="group/toggle/show"]').removeClass('hidden');
$('[component="group/badge/list"] [component="group/toggle/hide"]').addClass('hidden');
$('[component="group/badge/list"] [component="group/badge/item"]').attr('data-selected', 'false');
setupGroupToggle('[component="group/toggle/hide"]', 'false', true);
setupGroupToggle('[component="group/toggle/show"]', 'true', false, allowMultipleBadges);

setupGroupReordering('[component="group/order/up"]', 'before');
setupGroupReordering('[component="group/order/down"]', 'after');
}

function setupGroupToggle(selector, dataSelected, hidden, allowMultipleBadges = true) {
$(selector).on('click', function () {
if (!allowMultipleBadges && dataSelected === 'true') {
resetGroupSelection();
}
const groupEl = $(this).parents('[component="group/badge/item"]');
groupEl.attr('data-selected', 'true');
$(this).addClass('hidden');
groupEl.find('[component="group/toggle/hide"]').removeClass('hidden');
groupEl.attr('data-selected', dataSelected);
$(this).toggleClass('hidden', hidden);
groupEl.find(selector === '[component="group/toggle/hide"]' ? '[component="group/toggle/show"]' : '[component="group/toggle/hide"]').toggleClass('hidden', !hidden);
});
}

$('[component="group/order/up"]').on('click', function () {
const el = $(this).parents('[component="group/badge/item"]');
el.insertBefore(el.prev());
});
$('[component="group/order/down"]').on('click', function () {
function resetGroupSelection() {
$('[component="group/badge/list"] [component="group/toggle/show"]').removeClass('hidden');
$('[component="group/badge/list"] [component="group/toggle/hide"]').addClass('hidden');
$('[component="group/badge/list"] [component="group/badge/item"]').attr('data-selected', 'false');
}

function setupGroupReordering(selector, position) {
$(selector).on('click', function () {
const el = $(this).parents('[component="group/badge/item"]');
el.insertAfter(el.next());
el[`insert${position.charAt(0).toUpperCase() + position.slice(1)}`](el[position]());
});
}

Expand Down
33 changes: 16 additions & 17 deletions src/messaging/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ module.exports = function (Messaging) {
return msg;
})
.filter(Boolean);

messages = await user.blocks.filter(uid, 'fromuid', messages);
const users = await user.getUsersFields(
messages.map(msg => msg && msg.fromuid),
Expand All @@ -77,34 +78,21 @@ module.exports = function (Messaging) {
await parseMessages(messages, uid, roomId, isNew);

if (messages.length > 1) {
// Add a spacer in between messages with time gaps between them
console.log('**********Riya Kinny**********');
messages = messages.map((message, index) => {
// Compare timestamps with the previous message, and check if a spacer needs to be added
if (index > 0 && message.timestamp > messages[index - 1].timestamp + Messaging.newMessageCutoff) {
// If it's been 5 minutes, this is a new set of messages
message.newSet = true;
} else if (index > 0 && message.fromuid !== messages[index - 1].fromuid) {
// If the previous message was from the other person, this is also a new set
message.newSet = true;
} else if (index > 0 && messages[index - 1].system) {
message.newSet = true;
} else if (index === 0 || message.toMid) {
if (index > 0 && shouldCreateNewSet(message, messages[index - 1])) {
message.newSet = true;
}

return message;
});
} else if (messages.length === 1) {
// For single messages, we don't know the context, so look up the previous message and compare
console.log('**********Riya Kinny**********');
const key = `chat:room:${roomId}:mids`;
const index = await db.sortedSetRank(key, messages[0].messageId);
if (index > 0) {
const mid = await db.getSortedSetRange(key, index - 1, index - 1);
const fields = await Messaging.getMessageFields(mid, ['fromuid', 'timestamp']);
if ((messages[0].timestamp > fields.timestamp + Messaging.newMessageCutoff) ||
(messages[0].fromuid !== fields.fromuid) ||
messages[0].system || messages[0].toMid) {
// If it's been 5 minutes, this is a new set of messages
if (shouldCreateNewSet(messages[0], fields)) {
messages[0].newSet = true;
}
} else {
Expand All @@ -125,6 +113,16 @@ module.exports = function (Messaging) {
return data && data.messages;
};

function shouldCreateNewSet(current, previous) {
console.log('**********Riya Kinny**********');
return (
current.timestamp > previous.timestamp + Messaging.newMessageCutoff ||
current.fromuid !== previous.fromuid ||
previous.system ||
current.toMid
);
}

async function addParentMessages(messages, uid, roomId) {
let parentMids = messages.map(msg => (msg && msg.hasOwnProperty('toMid') ? parseInt(msg.toMid, 10) : null)).filter(Boolean);

Expand Down Expand Up @@ -182,6 +180,7 @@ module.exports = function (Messaging) {
msg.content = await parseMessage(msg, uid, roomId, isNew);
}));
}

async function parseMessage(message, uid, roomId, isNew) {
if (message.system) {
return validator.escape(String(message.content));
Expand Down
Loading