ravenous_roll20/roll20_mod/ravenous_effects_import.js

208 lines
12 KiB
JavaScript

/* Ravenous reusable-effects importer for Roll20 Mod. Commands:
* !ravenous-import-effects JSON
* !ravenous-import-effects --id CHARACTER_ID JSON
* !ravenous-import-effects --handout HANDOUT_ID
* !ravenous-import-effects --id CHARACTER_ID --handout HANDOUT_ID
* !ravenous-export-effects --id CHARACTER_ID
*
* Without --id, exactly one token representing the destination character must
* be selected. Players may only use characters they control and handouts they
* can read.
*/
(function () {
'use strict';
var COMMAND = '!ravenous-import-effects';
var EXPORT_COMMAND = '!ravenous-export-effects';
var FORMAT = 'ravenous-roll20-effects';
var VERSION = 1;
var LIMITS = { effects: 100, id: 80, name: 120, duration: 120, description: 1000, reminder: 500 };
var TYPES = ['alteration', 'dot', 'hot', 'bonus', 'malus', 'other'];
var DURATION_TYPES = ['manual', 'turns', 'until_start', 'until_end', 'combat'];
var PHASES = ['start', 'end'];
var FIELDS = ['enabled', 'effect_id', 'type', 'name', 'duration', 'description', 'duration_type',
'remaining', 'countdown_phase', 'start_reminder', 'end_reminder', 'apply_reminder', 'removal_reminder'];
var TOP_LEVEL_FIELDS = ['format', 'version', 'name', 'catalog', 'effects'];
var TEXT_LIMITS = {
effect_id: LIMITS.id, name: LIMITS.name, duration: LIMITS.duration,
description: LIMITS.description, start_reminder: LIMITS.reminder,
end_reminder: LIMITS.reminder, apply_reminder: LIMITS.reminder,
removal_reminder: LIMITS.reminder
};
function whisper(message, playerId) {
if (!playerId || playerIsGM(playerId)) return sendChat('Ravenous Effects', '/w gm ' + message);
var player = getObj('player', playerId);
var name = String(player && player.get('_displayname') || 'player').replace(/"/g, '');
sendChat('Ravenous Effects', '/w "' + name + '" ' + message);
}
function grantsAccess(list, playerId) {
return String(list || '').split(',').some(function (id) { return id === 'all' || id === playerId; });
}
function canControl(character, playerId) {
return playerIsGM(playerId) || grantsAccess(character && character.get('controlledby'), playerId);
}
function canReadHandout(handout, playerId) {
return playerIsGM(playerId) || grantsAccess(handout && handout.get('controlledby'), playerId) ||
grantsAccess(handout && handout.get('inplayerjournals'), playerId);
}
function plainObject(value) {
return value && !Array.isArray(value) && typeof value === 'object';
}
function validText(effect, field) {
return effect[field] === undefined ||
(typeof effect[field] === 'string' && effect[field].length <= TEXT_LIMITS[field]);
}
function validEffect(effect) {
if (!plainObject(effect) || Object.keys(effect).some(function (key) { return FIELDS.indexOf(key) < 0; })) return false;
if (typeof effect.effect_id !== 'string' || !effect.effect_id.trim() || effect.effect_id.length > LIMITS.id ||
typeof effect.name !== 'string' || !effect.name.trim() || effect.name.length > LIMITS.name ||
TYPES.indexOf(effect.type) < 0 ||
(effect.enabled !== undefined && typeof effect.enabled !== 'boolean') ||
(effect.duration_type !== undefined && DURATION_TYPES.indexOf(effect.duration_type) < 0) ||
(effect.countdown_phase !== undefined && PHASES.indexOf(effect.countdown_phase) < 0) ||
(effect.remaining !== undefined && (!Number.isInteger(effect.remaining) || effect.remaining < 0 || effect.remaining > 999))) return false;
return Object.keys(TEXT_LIMITS).every(function (field) { return validText(effect, field); });
}
function validPayload(data) {
return plainObject(data) && data.format === FORMAT && data.version === VERSION &&
!Object.keys(data).some(function (key) { return TOP_LEVEL_FIELDS.indexOf(key) < 0; }) &&
(data.name === undefined || (typeof data.name === 'string' && data.name.length <= 150)) &&
(data.catalog === undefined || (typeof data.catalog === 'string' && data.catalog.length <= 64)) &&
Array.isArray(data.effects) && data.effects.length > 0 && data.effects.length <= LIMITS.effects &&
data.effects.every(validEffect);
}
function decodeHandout(raw) {
var text = String(raw || '');
text = text.replace(/<br\s*\/?\s*>/gi, '\n').replace(/<\/(?:p|div)>/gi, '\n')
.replace(/<[^>]*>/g, '').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
.replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, decimal) {
return String.fromCodePoint(parseInt(hex || decimal, hex ? 16 : 10));
}).replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ').trim();
return JSON.parse(text);
}
function readHandout(handout, isGM, callback) {
if (!isGM) return handout.get('notes', callback);
handout.get('gmnotes', function (gmnotes) {
if (String(gmnotes || '').trim()) return callback(gmnotes);
handout.get('notes', callback);
});
}
function rowId(index) {
return 'effect' + Date.now().toString(36) + index.toString(36) +
Math.floor(Math.random() * 1679616).toString(36);
}
function valuesFor(effect) {
return {
enabled: effect.enabled === false ? '0' : '1', effect_id: effect.effect_id.trim(), type: effect.type,
name: effect.name.trim(), duration: effect.duration || '', description: effect.description || '',
duration_type: effect.duration_type || 'manual', remaining: String(effect.remaining || 0),
countdown_phase: effect.countdown_phase || 'end', start_reminder: effect.start_reminder || '',
end_reminder: effect.end_reminder || '', apply_reminder: effect.apply_reminder || '',
removal_reminder: effect.removal_reminder || ''
};
}
function importEffects(characterId, data, playerId) {
if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous effects JSON.', playerId);
var character = getObj('character', characterId);
if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.', playerId);
data.effects.forEach(function (effect, index) {
var prefix = 'repeating_sharedeffects_' + rowId(index) + '_';
var values = valuesFor(effect);
FIELDS.forEach(function (field) {
createObj('attribute', { characterid: characterId, name: prefix + field, current: values[field], max: '' });
});
});
whisper('Imported ' + data.effects.length + ' reusable effect(s) into ' + character.get('name') + '.', playerId);
}
function exportEffects(characterId, playerId) {
var character = getObj('character', characterId);
if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.', playerId);
if (!canControl(character, playerId)) return whisper('Permission denied: the player does not control that character.', playerId);
var rows = {};
findObjs({ type: 'attribute', characterid: characterId }).forEach(function (attribute) {
var match = String(attribute.get('name') || '').match(/^repeating_sharedeffects_([^_]+)_(.+)$/);
if (!match || FIELDS.indexOf(match[2]) < 0) return;
rows[match[1]] = rows[match[1]] || {};
rows[match[1]][match[2]] = attribute.get('current');
});
var effects = Object.keys(rows).sort().map(function (id) {
var row = rows[id];
return {
enabled: row.enabled !== '0', effect_id: row.effect_id || id, type: TYPES.indexOf(row.type) >= 0 ? row.type : 'other',
name: row.name || row.effect_id || 'Effet', duration: row.duration || '', description: row.description || '',
duration_type: DURATION_TYPES.indexOf(row.duration_type) >= 0 ? row.duration_type : 'manual',
remaining: Math.max(0, Math.min(999, Math.floor(Number(row.remaining) || 0))),
countdown_phase: PHASES.indexOf(row.countdown_phase) >= 0 ? row.countdown_phase : 'end',
start_reminder: row.start_reminder || '', end_reminder: row.end_reminder || '',
apply_reminder: row.apply_reminder || '', removal_reminder: row.removal_reminder || ''
};
}).filter(validEffect);
if (!effects.length) return whisper('No reusable effects found on that character.', playerId);
var data = { format: FORMAT, version: VERSION, name: character.get('name') + ' — effets', effects: effects };
var isGM = playerIsGM(playerId);
var handout = createObj('handout', { name: 'Ravenous effects - ' + character.get('name'),
inplayerjournals: isGM ? '' : playerId, controlledby: isGM ? '' : playerId });
if (!handout) return whisper('Roll20 could not create the effects handout.', playerId);
var readable = JSON.stringify(data, null, 2).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
handout.set(isGM ? 'gmnotes' : 'notes', '<pre>' + readable + '</pre>');
whisper('Exported ' + effects.length + ' reusable effect(s) to handout ' + handout.id + '.', playerId);
}
function selectedCharacterId(message) {
var selected = message.selected || [];
if (selected.length !== 1 || selected[0]._type !== 'graphic') {
whisper('Select one token representing the destination character, or use --id CHARACTER_ID.', message.playerid);
return '';
}
var token = getObj('graphic', selected[0]._id);
var id = token && token.get('represents');
if (!id) whisper('The selected token does not represent a character.', message.playerid);
return id || '';
}
function argumentsFrom(input) {
var result = { id: '', handout: '', json: '' };
var rest = input.trim();
while (rest.indexOf('--') === 0) {
var match = rest.match(/^--(id|handout)\s+(\S+)\s*/);
if (!match || result[match[1]]) return null;
result[match[1]] = match[2];
rest = rest.slice(match[0].length);
}
result.json = rest;
if (!!result.handout === !!result.json) return null;
return result;
}
on('chat:message', function (message) {
if (message.type !== 'api') return;
var content = message.content.trim();
if (content === EXPORT_COMMAND || content.indexOf(EXPORT_COMMAND + ' ') === 0) {
var exportArgument = content.slice(EXPORT_COMMAND.length).trim();
var exportId = '';
if (exportArgument.indexOf('--id ') === 0) exportId = exportArgument.slice('--id '.length).trim();
else if (exportArgument) return whisper('Usage: ' + EXPORT_COMMAND + ' [--id CHARACTER_ID].', message.playerid);
exportId = exportId || selectedCharacterId(message);
if (exportId) return exportEffects(exportId, message.playerid);
return;
}
if (content !== COMMAND && content.indexOf(COMMAND + ' ') !== 0) return;
var args = argumentsFrom(content.slice(COMMAND.length));
if (!args) return whisper('Usage: ' + COMMAND + ' [--id CHARACTER_ID] JSON or --handout HANDOUT_ID.', message.playerid);
var characterId = args.id || selectedCharacterId(message);
if (!characterId) return;
if (!canControl(getObj('character', characterId), message.playerid))
return whisper('Permission denied: the player does not control the destination character.', message.playerid);
if (args.handout) {
var handout = getObj('handout', args.handout);
if (!handout) return whisper('Handout not found.', message.playerid);
if (!canReadHandout(handout, message.playerid)) return whisper('Permission denied for that handout.', message.playerid);
return readHandout(handout, playerIsGM(message.playerid), function (notes) {
try { importEffects(characterId, decodeHandout(notes), message.playerid); }
catch (error) { whisper('Handout does not contain valid Ravenous effects JSON.', message.playerid); }
});
}
try { importEffects(characterId, JSON.parse(args.json), message.playerid); }
catch (error) { whisper('Invalid JSON.', message.playerid); }
});
}());