212 lines
11 KiB
JavaScript
212 lines
11 KiB
JavaScript
/* D10 character exchange for Roll20 Mod. Commands:
|
|
* !d10-export (selected token's character)
|
|
* !d10-export --id CHARACTER_ID
|
|
* !d10-import {"format":"d10-roll20-character",...}
|
|
* !d10-import --handout HANDOUT_ID
|
|
* !d10-import --replace [--id CHARACTER_ID] --handout HANDOUT_ID
|
|
* Players may export and replace characters they control. New-character import is GM-only.
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
var FORMAT = 'd10-roll20-character';
|
|
var VERSION = 1;
|
|
|
|
function whisper(playerId, message) {
|
|
if (playerIsGM(playerId)) return sendChat('D10 IO', '/w gm ' + message);
|
|
var player = getObj('player', playerId);
|
|
var name = String(player && player.get('_displayname') || 'player').replace(/"/g, '');
|
|
sendChat('D10 IO', '/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 validText(value) { return typeof value === 'string' && value.length <= 200000; }
|
|
function validPayload(data) {
|
|
if (!data || Array.isArray(data) || typeof data !== 'object' ||
|
|
data.format !== FORMAT || data.version !== VERSION ||
|
|
typeof data.name !== 'string' || !data.name.trim() || data.name.length > 100 ||
|
|
!Array.isArray(data.attributes) || data.attributes.length > 5000 ||
|
|
(data.abilities !== undefined && (!Array.isArray(data.abilities) || data.abilities.length > 1000)) ||
|
|
!validText(data.bio || '') || !validText(data.gmnotes || '') ||
|
|
!validText(data.controlledby || '') || !validText(data.inplayerjournals || '')) return false;
|
|
return data.attributes.every(function (item) {
|
|
return item && !Array.isArray(item) && typeof item === 'object' &&
|
|
typeof item.name === 'string' && item.name.trim() && item.name.length <= 150 &&
|
|
validText(item.current) && validText(item.max);
|
|
}) && (data.abilities || []).every(function (item) {
|
|
return item && typeof item.name === 'string' && item.name.length <= 150 &&
|
|
validText(item.action) && typeof item.istokenaction === 'boolean';
|
|
});
|
|
}
|
|
function decodeHandout(raw) {
|
|
var text = String(raw || '').trim();
|
|
if (/^(?:%7B|%3C)/i.test(text)) {
|
|
try { text = decodeURIComponent(text); }
|
|
catch (error) { /* Continue with the original Notes value. */ }
|
|
}
|
|
text = text.replace(/<br\s*\/?\s*>/gi, '\n').replace(/<\/(?:p|div)>/gi, '\n')
|
|
.replace(/<[^>]*>/g, '').replace(/"/g, '"').replace(/'/g, "'")
|
|
.replace(/</g, '<').replace(/>/g, '>')
|
|
.replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, decimal) {
|
|
return String.fromCodePoint(parseInt(hex || decimal, hex ? 16 : 10));
|
|
}).replace(/&/g, '&').replace(/ /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 populateCharacter(character, data, replace, isGM, playerId) {
|
|
if (replace) {
|
|
findObjs({ type: 'attribute', characterid: character.id }).forEach(function (item) { item.remove(); });
|
|
findObjs({ type: 'ability', characterid: character.id }).forEach(function (item) { item.remove(); });
|
|
}
|
|
character.set('name', data.name.trim());
|
|
character.set('bio', data.bio || '');
|
|
if (isGM) {
|
|
character.set('gmnotes', data.gmnotes || '');
|
|
character.set('controlledby', data.controlledby || '');
|
|
character.set('inplayerjournals', data.inplayerjournals || '');
|
|
}
|
|
data.attributes.forEach(function (item) {
|
|
createObj('attribute', { characterid: character.id, name: item.name,
|
|
current: item.current, max: item.max });
|
|
});
|
|
(data.abilities || []).forEach(function (item) {
|
|
createObj('ability', { characterid: character.id, name: item.name,
|
|
action: item.action, istokenaction: item.istokenaction });
|
|
});
|
|
whisper(playerId, (replace ? 'Replaced ' : 'Imported ') + data.attributes.length +
|
|
' attributes in character ' + character.id + '.');
|
|
}
|
|
function importCharacter(data, playerId, targetId) {
|
|
if (!validPayload(data)) return whisper(playerId, 'Invalid or unsupported D10 character JSON.');
|
|
if (targetId) {
|
|
var target = getObj('character', targetId);
|
|
if (!target) return whisper(playerId, 'Character not found.');
|
|
if (!canControl(target, playerId)) return whisper(playerId, 'Permission denied for that character.');
|
|
return populateCharacter(target, data, true, playerIsGM(playerId), playerId);
|
|
}
|
|
if (!playerIsGM(playerId)) return whisper(playerId,
|
|
'Only a GM can create a new character. Use --replace on a character you control.');
|
|
var character = createObj('character', { name: data.name.trim(),
|
|
controlledby: data.controlledby || '', inplayerjournals: data.inplayerjournals || '' });
|
|
if (!character) return whisper(playerId, 'Roll20 could not create the character.');
|
|
populateCharacter(character, data, false, true, playerId);
|
|
}
|
|
function exportCharacter(id, playerId) {
|
|
var character = getObj('character', id);
|
|
if (!character) return whisper(playerId, 'Character not found. Use its Roll20 character ID.');
|
|
if (!canControl(character, playerId)) return whisper(playerId, 'Permission denied for that character.');
|
|
var isGM = playerIsGM(playerId);
|
|
character.get('bio', function (bio) {
|
|
character.get('gmnotes', function (gmnotes) {
|
|
var attributes = findObjs({ type: 'attribute', characterid: id }).map(function (item) {
|
|
var current = item.get('current');
|
|
var max = item.get('max');
|
|
return { name: item.get('name'), current: current == null ? '' : String(current),
|
|
max: max == null ? '' : String(max) };
|
|
}).sort(function (a, b) { return a.name.localeCompare(b.name); });
|
|
var abilities = findObjs({ type: 'ability', characterid: id }).map(function (item) {
|
|
return { name: item.get('name'), action: item.get('action') || '',
|
|
istokenaction: item.get('istokenaction') === true || item.get('istokenaction') === 'true' };
|
|
});
|
|
var data = { format: FORMAT, version: VERSION, name: character.get('name'),
|
|
controlledby: character.get('controlledby') || '',
|
|
inplayerjournals: character.get('inplayerjournals') || '', bio: bio || '',
|
|
gmnotes: isGM ? gmnotes || '' : '', attributes: attributes, abilities: abilities };
|
|
var handout = createObj('handout', { name: 'D10 export - ' + data.name,
|
|
inplayerjournals: isGM ? '' : playerId, controlledby: isGM ? '' : playerId });
|
|
if (!handout) return whisper(playerId, 'Roll20 could not create the export handout.');
|
|
var readable = JSON.stringify(data, null, 2).replace(/&/g, '&')
|
|
.replace(/</g, '<').replace(/>/g, '>');
|
|
handout.set(isGM ? 'gmnotes' : 'notes', '<pre>' + readable + '</pre>');
|
|
whisper(playerId, 'Exported ' + attributes.length + ' attributes to handout ' + handout.id + '.');
|
|
});
|
|
});
|
|
}
|
|
function selectedCharacterId(message) {
|
|
var selected = message.selected || [];
|
|
if (selected.length !== 1 || selected[0]._type !== 'graphic') {
|
|
whisper(message.playerid, 'Select one token representing a character, or use --id CHARACTER_ID.');
|
|
return '';
|
|
}
|
|
var token = getObj('graphic', selected[0]._id);
|
|
var id = token && token.get('represents');
|
|
if (!id) whisper(message.playerid, 'The selected token does not represent a character.');
|
|
return id || '';
|
|
}
|
|
function importArguments(input) {
|
|
var result = { replace: false, id: '', handout: '', json: '' };
|
|
var rest = input.trim();
|
|
while (rest.indexOf('--') === 0) {
|
|
var flag = rest.match(/^--replace(?:\s+|$)/);
|
|
if (flag) {
|
|
if (result.replace) return null;
|
|
result.replace = true;
|
|
rest = rest.slice(flag[0].length);
|
|
continue;
|
|
}
|
|
var option = rest.match(/^--(id|handout)\s+(\S+)\s*/);
|
|
if (!option || result[option[1]]) return null;
|
|
result[option[1]] = option[2];
|
|
rest = rest.slice(option[0].length);
|
|
}
|
|
result.json = rest;
|
|
if (!!result.handout === !!result.json || (!result.replace && result.id)) return null;
|
|
return result;
|
|
}
|
|
on('chat:message', function (message) {
|
|
if (message.type !== 'api') return;
|
|
var content = message.content.trim();
|
|
if (content === '!d10-export') {
|
|
var selectedId = selectedCharacterId(message);
|
|
if (selectedId) return exportCharacter(selectedId, message.playerid);
|
|
return;
|
|
}
|
|
if (content.indexOf('!d10-export ') === 0) {
|
|
var argument = content.slice('!d10-export '.length).trim();
|
|
if (argument.indexOf('--id ') === 0) argument = argument.slice('--id '.length).trim();
|
|
return exportCharacter(argument, message.playerid);
|
|
}
|
|
if (content.indexOf('!d10-import ') !== 0) return;
|
|
var args = importArguments(content.slice('!d10-import '.length));
|
|
if (!args) return whisper(message.playerid, 'Invalid import command.');
|
|
if (!playerIsGM(message.playerid) && !args.replace)
|
|
return whisper(message.playerid, 'Only a GM can create a new character. Use --replace.');
|
|
var targetId = '';
|
|
if (args.replace) {
|
|
targetId = args.id || selectedCharacterId(message);
|
|
if (!targetId) return;
|
|
if (!canControl(getObj('character', targetId), message.playerid))
|
|
return whisper(message.playerid, 'Permission denied for that character.');
|
|
}
|
|
if (args.handout) {
|
|
var handout = getObj('handout', args.handout);
|
|
if (!handout) return whisper(message.playerid, 'Handout not found.');
|
|
if (!canReadHandout(handout, message.playerid))
|
|
return whisper(message.playerid, 'Permission denied for that handout.');
|
|
return readHandout(handout, playerIsGM(message.playerid), function (notes) {
|
|
var data;
|
|
try { data = decodeHandout(notes); }
|
|
catch (error) { return whisper(message.playerid, 'Handout does not contain valid D10 JSON.'); }
|
|
try { importCharacter(data, message.playerid, targetId); }
|
|
catch (error) { whisper(message.playerid,
|
|
'Character replacement failed: ' + String(error && error.message || error)); }
|
|
});
|
|
}
|
|
try { importCharacter(JSON.parse(args.json), message.playerid, targetId); }
|
|
catch (error) { whisper(message.playerid, 'Invalid JSON.'); }
|
|
});
|
|
}());
|