Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* globals getObj findObjs */
- const fixDuplicates = (() => { //eslint-disable-line
- let env = 'api';
- if (!this.on) env = 'console';
- const myOn = this.on ? this.on : () =>{}
- const hlog = (msg) => {
- if (env === 'console') console.log(msg);
- else (this.log||console.log)(msg);
- }
- const rx = { id: /(-[A-Za-z0-9_-]{19})(\b|$)/, rowId: /_(-[A-Za-z0-9-]{19})_/ }
- const sheetData = {
- repSecs: {
- traits: { keyAttrs: ['name', 'description'] },
- proficiencies: { keyAttrs: ['name', 'prof_type'] },
- tool: { keyAttrs: ['toolname', 'toolattr_base'] },
- inventory: { keyAttrs: ['itemname', 'itemcount'] },
- attack: { keyAttrs: ['atkname', 'atkrange'] },
- 'spell-cantrip': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-1': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-2': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-3': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-4': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-5': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-6': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-7': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-8': { keyAttrs: ['spellname', 'spellschool'] },
- 'spell-9': { keyAttrs: ['spellname', 'spellschool'] },
- }
- }
- const helpers = {
- api: {
- getAllAttrs: (charId, section) => {
- const rxSection = new RegExp(`repeating_${section}`, 'i'),
- allAttrs = findObjs({ type: 'attribute', characterid: charId });
- return allAttrs.length ? allAttrs.filter(a => rxSection.test(a.get('name'))) : [];
- },
- getChar: (charId) => {
- return getObj('character', charId);
- },
- getAllChars: () => {
- return findObjs({ type: 'character' });
- },
- findCharFromName: (charName) => {
- const chars = helpers.api.getAllChars(),
- rxName = new RegExp(`^\\s*${charName}\\s*$`, 'i');
- return chars.filter(c => rxName.test(c.get('name')));
- },
- filterNpcs: (c) => {
- let flag = findObjs({ type: 'attribute', characterid: c.id, name: 'npc' })[0];
- if (!flag || flag.get('current') != 1) return 1;
- },
- deleteAttr: (attribute) => attribute.remove(),
- toChat: (msg) => this.sendChat('fixDupeBot', `/w gm ${msg}`)
- },
- console: {
- getAllAttrs: (charId, section) => {
- const rxSection = new RegExp(`repeating_${section}`, 'i'),
- allAttrs = window.Campaign.characters.get(charId).attribs.models;
- return allAttrs.length ? allAttrs.filter(a => rxSection.test(a.get('name'))) : [];
- },
- getChar: (charId) => {
- return window.Campaign.characters.get(charId);
- },
- getAllChars: () => {
- return window.Campaign.characters.models;
- },
- findCharFromName: (charName) => {
- const chars = helpers.console.getAllChars(),
- rxName = new RegExp(`^\\s*${charName}\\s*$`, 'i');
- return chars.filter(c => rxName.test(c.get('name')));
- },
- filterNpcs: (c) => {
- let flag = c.attribs.models.find(a => a.get('name') === 'npc');
- if (flag && flag.get('current') == 1) return null;
- else return 1;
- },
- deleteAttr: (attribute) => attribute.destroy(),
- toChat: () => {},
- }
- }
- const deleteDuplicates = (delQueue, charId) => {
- let deletedAttrs = 0;
- for (let section in delQueue) {
- const allAttrs = helpers[env].getAllAttrs(charId, section);
- delQueue[section].forEach(row => {
- // hlog(`Checking ${row}...`)
- const rowAttrs = allAttrs.filter(a => a.get('name').indexOf(row) > -1);
- if (rowAttrs.length) {
- // hlog(`Found ${rowAttrs.length} attributes in row to delete`);
- rowAttrs.forEach(a => {
- helpers[env].deleteAttr(a);
- deletedAttrs ++;
- });
- }
- });
- }
- return deletedAttrs;
- }
- const findDuplicates = (charId) => {
- // hlog(`Fixing sheet ${charId}`);
- const deleteQueue = {},
- dupeNamesLog = [];
- const sections = Object.keys(sheetData.repSecs),
- char = helpers[env].getChar(charId)
- if (!char) return new Error(`Couldn't find character`);
- sections.forEach(section => {
- const sectionQueue = [];
- const rxKeyAttr1 = new RegExp(`repeating_${section}.*_${sheetData.repSecs[section].keyAttrs[0]}$`, 'i'),
- rxKeyAttr2 = new RegExp(`repeating_${section}.*_${sheetData.repSecs[section].keyAttrs[1]}$`, 'i'),
- processedNames = [],
- attrs = helpers[env].getAllAttrs(charId, section);
- const attrs1 = attrs.filter(a => rxKeyAttr1.test(a.get('name'))),
- attrs2 = attrs.filter(a => rxKeyAttr2.test(a.get('name')));
- attrs1.forEach(attr => {
- if (!processedNames.includes(attr.get('current'))) {
- const masterRow = (attr.get('name').match(rx.rowId)||[])[1];
- if (!masterRow) return hlog(`Bad rowid`);
- // hlog(`Comparing ${masterRow}...`);
- const duplicates = attrs1.filter(a => a.get('current') === attr.get('current'));
- if (duplicates.length > 1) {
- // hlog(`Duplicates found: ${duplicates.length-1}`);
- duplicates.forEach(dupe => {
- const dupeRow = (dupe.get('name').match(rx.rowId)||[])[1];
- if (!dupeRow) return hlog(`Bad rowId`);
- const master2 = attrs2.find(a => a.get('name').indexOf(masterRow) > -1),
- compare2 = attrs2.find(a => a.get('name').indexOf(dupeRow) > -1);
- if (!flags.secondCheck || ((master2 && compare2) && (master2.get('current') === compare2.get('current')) && (dupeRow !== masterRow))) {
- // hlog(`Duplicate verified at row: ${dupeRow}`);
- sectionQueue.push(`${dupeRow}`);
- dupeNamesLog.push(dupe.get('current'));
- }
- });
- }
- } //else hlog(`Skipping ${attr.get('current')}, already processed`);
- processedNames.push(attr.get('current'));
- });
- // hlog(`Duplicates found in ${section}: ${sectionQueue.length}`);
- deleteQueue[section] = sectionQueue;
- });
- const total = Object.entries(deleteQueue).reduce((a,v) => a += v[1].length, 0);
- // hlog(`Finished all sections, deleteQueue has ${total} entries`);
- if (flags.deleteDupes) {
- let deleted = total > 0 ? deleteDuplicates(deleteQueue, charId) : 0;
- return deleted ? (`{{**${helpers[env].getChar(charId).get('name')}**: ${total} duplicate(s) deleted}}`) : null;
- } else {
- return dupeNamesLog.length ? `{{** ${helpers[env].getChar(charId).get('name')} ** - ${dupeNamesLog.join(', ')}}}` : null;
- }
- }
- const getCharIds = (includeNpc, charId, charName) => {
- let idArray = []
- if (charName) {
- let char = helpers[env].findCharFromName(charName);
- if (!char || !char.length) return helpers[env].toChat(`Error: couldn't look up character from "${charName}"`);
- if (char.length > 1) return helpers[env].thChat(`Error: found multiple character from supplied name: ${char.map(c=>c.get('name')).join(', ')}`);
- else if (!char[0] || !char[0].id) return helpers[env].thChat(`Error: something went wrong, bad character data`);
- else idArray.push(char[0].id);
- }
- else if (charId) {
- let char = helpers[env].getChar(charId);
- if (char) idArray.push(char.id);
- else return helpers[env].toChat(`Error: couldn't look up character from "${charId}"`);
- }
- else {
- let allChars = helpers[env].getAllChars();
- allChars = includeNpc ? allChars : allChars.filter(helpers[env].filterNpcs);
- idArray = allChars.map(c=>c.id);
- // hlog(idArray.length);
- }
- // hlog(idArray);
- return idArray;
- }
- const flags = { deleteDupes: false, chatReport: false, secondCheck: true }
- const handleCli = async (msgContent) => {
- let charIdArray = [];
- flags.deleteDupes = /--del/i.test(msgContent) ? true : false;
- flags.chatReport = /--rep/i.test(msgContent) ? true : false;
- flags.secondCheck = /--single/.test(msgContent) ? false : true;
- if (/--all/.test(msgContent)) charIdArray = getCharIds(true);
- else if (/--pc/.test(msgContent)) charIdArray = getCharIds();
- else if (/--char/.test(msgContent)) {
- let charId = (msgContent.match(rx.id)||[])[1];
- if (!charId) {
- let charNameMatch = msgContent.match(/--char[\w]*\s+((.+?)\s*--|(.+)$)/);
- let charName = charNameMatch ? charNameMatch[2] || charNameMatch[3] : null;
- if (!charName) {
- helpers[env].toChat(`Error: invalid charId or charName`);
- return;
- } else charIdArray = getCharIds(null, null, charName);
- } else {
- if (helpers[env].getChar(charId)) charIdArray.push(charId);
- }
- } else {
- helpers[env].toChat(`Error: invalid command line. Use --char --all or --pcs`);
- }
- if (charIdArray.length) {
- hlog(`cycling through ${charIdArray.join(', ')}...`);
- let reportLog = [];
- await Promise.all(charIdArray.map(async (id) => {
- const result = findDuplicates(id, flags.deleteDupes);
- if (result) reportLog.push(result);
- }));
- if (flags.chatReport) {
- let chatTemplate = `&{template:default}{{name=fixDupes Report}}`;
- chatTemplate += reportLog.length ? reportLog.join(' ') : `{{No duplicates found. These aren't the droids you're looking for. Move along.}}`;
- helpers[env].toChat(chatTemplate);
- }
- }
- }
- const consoleHandleChatMsg = (msg) => {
- console.log(msg);
- if (/^!fixdup(e|licate)/i.test(msg)) handleCli(msg)
- }
- myOn('ready', () => {
- setTimeout(() => hlog(`<< fixDuplicates finished loading - running in environment: ${env.toUpperCase()} >>`), 500);
- myOn('chat:message', (msg) => {
- if (msg.type === 'api' && /^!fixdup(e|licate)/i.test(msg.content)) handleCli(msg.content);
- });
- });
- const watchChat = (() => { //eslint-disable-line
- if (env === 'api') return;
- const chat = document.querySelector('#textchat-input textarea'),
- sendbutton = $('#textchat-input button.btn'),
- send = () => sendbutton.trigger('click');
- helpers.console.toChat = (msg) => {
- chat.value = `${msg}`;
- send();
- };
- if (chat) {
- chat.addEventListener('change', (ev) => consoleHandleChatMsg(ev.target.value));
- chat.addEventListener('input', (ev) => window.chatCache = ev.target.value );
- chat.addEventListener('keyup', (ev) => { if (ev.key === 'Enter') consoleHandleChatMsg(window.chatCache||'') });
- }
- })();
- setTimeout(() => console.log(`<< fixDuplicates finished loading - running in environment: ${env.toUpperCase()} >>`), 1500);
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement