{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n"},"max_stars_repo_name":{"kind":"string","value":"fredrikaverpil/fredrikaverpil.github.io"}}},{"rowIdx":223,"cells":{"content":{"kind":"string","value":"<|start_filename|>lib/helpers/chunk-string.coffee<|end_filename|>\nmodule.exports = chunkString = (str, len) ->\n _size = Math.ceil(str.length / len)\n _ret = new Array(_size)\n _offset = undefined\n _i = 0\n\n while _i < _size\n _offset = _i * len\n _ret[_i] = str.substring(_offset, _offset + len)\n _i++\n _ret\n\n\n<|start_filename|>lib/helpers/colour-list.coffee<|end_filename|>\nmodule.exports = [\n \"red\"\n \"blue\"\n \"pink\"\n \"yellow\"\n \"orange\"\n \"purple\"\n \"green\"\n \"brown\"\n \"skyblue\"\n \"olive\"\n \"salmon\"\n \"white\"\n \"lime\"\n \"maroon\"\n \"beige\"\n \"darkgoldenrod\"\n \"blanchedalmond\"\n \"tan\"\n \"violet\"\n \"navy\"\n \"gold\"\n \"black\"\n]\n"},"max_stars_repo_name":{"kind":"string","value":"mingsai/atom-supercopair"}}},{"rowIdx":224,"cells":{"content":{"kind":"string","value":"<|start_filename|>codehandler/Makefile<|end_filename|>\n\nPATH := $(DEVKITPPC)/bin:$(PATH)\n\nPREFIX ?= powerpc-eabi-\nLD := $(PREFIX)ld\nAS := $(PREFIX)as\nCC := $(PREFIX)gcc\nOBJDUMP ?= $(PREFIX)objdump\nOBJCOPY ?= $(PREFIX)objcopy\n\nSFLAGS := -mgekko -mregnames\n\n# -O2: optimise lots\n# -Wall: generate lots of warnings\n# -x c: compile as C code\n# -std=gnu99: use the C99 standard with GNU extensions\n# -ffreestanding: we don't have libc; don't expect we do\n# -mrvl: enable wii/gamecube compilation\n# -mcpu=750: enable processor specific compilation\n# -meabi: enable eabi specific compilation\n# -mhard-float: enable hardware floating point instructions\n# -fshort-wchar: use 16 bit whcar_t type in keeping with Wii executables\n# -msdata-none: do not use r2 or r13 as small data areas\n# -memb: enable embedded application specific compilation\n# -ffunction-sections: split up functions so linker can garbage collect\n# -fdata-sections: split up data so linker can garbage collect\nCFLAGS := -O2 -Wall -x c -std=gnu99 \\\n -ffreestanding \\\n -mrvl -mcpu=750 -meabi -mhard-float -fshort-wchar \\\n -msdata=none -memb -ffunction-sections -fdata-sections \\\n -Wno-unknown-pragmas -Wno-strict-aliasing\n\nSRC := $(wildcard *.S) $(wildcard *.c)\nOBJ := $(patsubst %.S,build/%.o,$(patsubst %.c,build/%.o,$(SRC)))\n\n# Simulate an order only dependency\nBUILD_REQ := $(filter-out $(wildcard build),build)\nBIN_REQ := $(filter-out $(wildcard bin),bin)\n\nall: bin/codehandler310.h bin/codehandler400.h bin/codehandler410.h bin/codehandler500.h bin/codehandler532.h bin/codehandler550.h\n\nbin/codehandler%.h: build/codehandler%.text.bin $(BIN_REQ)\n\txxd -i $< | sed \"s/unsigned/static const unsigned/g;s/ler$*/ler/g;s/build_//g\" > $@\n\nbuild/codehandler%.text.bin: build/codehandler%.elf $(BUILD_REQ)\n\t$(OBJCOPY) -j .text -O binary $< $@\n\nbuild/codehandler%.elf: codehandler%.ld $(OBJ) $(BUILD_REQ)\n\t$(LD) -T $< $(OBJ)\n\nbuild/%.o: %.c $(BUILD_REQ)\n\t$(CC) -c $(CFLAGS) -o $@ $<\nbuild/%.o: %.S $(BUILD_REQ)\n\t$(AS) $(SFLAGS) -o $@ $<\n\nbin:\n\tmkdir $@\nbuild:\n\tmkdir $@\n\nclean:\n\trm -rf $(wildcard build) $(wildcard bin)\n\n\n<|start_filename|>installer/src/codehandler400.h<|end_filename|>\nstatic const unsigned char codehandler_text_bin[] = {\n 0x94, 0x21, 0xff, 0xe8, 0x7c, 0x08, 0x02, 0xa6, 0x3d, 0x20, 0x10, 0x05,\n 0x81, 0x29, 0x9c, 0x1c, 0x93, 0x81, 0x00, 0x08, 0x7c, 0x7c, 0x1b, 0x78,\n 0x38, 0x60, 0x00, 0x00, 0x93, 0xa1, 0x00, 0x0c, 0x93, 0xe1, 0x00, 0x14,\n 0x7c, 0x9d, 0x23, 0x78, 0x90, 0x01, 0x00, 0x1c, 0x60, 0x63, 0x86, 0xa8,\n 0x93, 0xc1, 0x00, 0x10, 0x38, 0x80, 0x00, 0x40, 0x7d, 0x29, 0x03, 0xa6,\n 0x4e, 0x80, 0x04, 0x21, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x82, 0x00, 0x50,\n 0x38, 0xa0, 0x00, 0x00, 0x38, 0x80, 0x00, 0x00, 0x60, 0xa5, 0x86, 0xa8,\n 0x3b, 0xdf, 0x00, 0x08, 0x4b, 0xe5, 0x3e, 0x2d, 0x3c, 0xff, 0x00, 0x01,\n 0x3c, 0x80, 0x01, 0x1e, 0x39, 0x00, 0x00, 0x00, 0x7f, 0xc3, 0xf3, 0x78,\n 0x38, 0x84, 0xdb, 0x28, 0x38, 0xa0, 0x00, 0x00, 0x7f, 0xe6, 0xfb, 0x78,\n 0x38, 0xe7, 0x86, 0xa8, 0x61, 0x08, 0x80, 0x00, 0x39, 0x20, 0x00, 0x00,\n 0x39, 0x40, 0x00, 0x0c, 0x4b, 0xe5, 0xe5, 0x49, 0x7f, 0xc3, 0xf3, 0x78,\n 0x4b, 0xe5, 0xea, 0x25, 0x3d, 0x20, 0x10, 0x06, 0x80, 0x01, 0x00, 0x1c,\n 0x81, 0x29, 0xa6, 0x00, 0x7f, 0x83, 0xe3, 0x78, 0x83, 0xc1, 0x00, 0x10,\n 0x7f, 0xa4, 0xeb, 0x78, 0x83, 0x81, 0x00, 0x08, 0x7d, 0x29, 0x03, 0xa6,\n 0x83, 0xa1, 0x00, 0x0c, 0x83, 0xe1, 0x00, 0x14, 0x7c, 0x08, 0x03, 0xa6,\n 0x38, 0x21, 0x00, 0x18, 0x4e, 0x80, 0x04, 0x20, 0x94, 0x21, 0xff, 0xe8,\n 0x7c, 0x08, 0x02, 0xa6, 0x38, 0xa0, 0x00, 0x01, 0x38, 0xc0, 0x00, 0x20,\n 0x38, 0x81, 0x00, 0x08, 0x90, 0x01, 0x00, 0x1c, 0x4b, 0xed, 0x7b, 0xe1,\n 0x2c, 0x03, 0x00, 0x00, 0x41, 0x80, 0x00, 0x0c, 0x41, 0x82, 0x00, 0x18,\n 0x88, 0x61, 0x00, 0x08, 0x80, 0x01, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x18,\n 0x7c, 0x08, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x38, 0x60, 0xff, 0xff,\n 0x4b, 0xff, 0xff, 0xec, 0x94, 0x21, 0xff, 0xe0, 0x7c, 0x08, 0x02, 0xa6,\n 0x93, 0xe1, 0x00, 0x1c, 0x7c, 0xff, 0x3b, 0x79, 0x93, 0x61, 0x00, 0x0c,\n 0x7c, 0x9b, 0x23, 0x78, 0x93, 0x81, 0x00, 0x10, 0x7c, 0x7c, 0x1b, 0x78,\n 0x93, 0xa1, 0x00, 0x14, 0x7c, 0xbd, 0x2b, 0x78, 0x93, 0xc1, 0x00, 0x18,\n 0x7c, 0xde, 0x33, 0x78, 0x90, 0x01, 0x00, 0x24, 0x41, 0xa1, 0x00, 0x0c,\n 0x48, 0x00, 0x00, 0x64, 0x40, 0x9d, 0x00, 0x60, 0x7f, 0xc4, 0xf3, 0x78,\n 0x7f, 0xe5, 0xfb, 0x78, 0x7f, 0xa3, 0xeb, 0x78, 0x38, 0xc0, 0x00, 0x00,\n 0x4b, 0xed, 0x7b, 0x65, 0x7c, 0x69, 0x1b, 0x79, 0x7f, 0xe9, 0xf8, 0x50,\n 0x7f, 0xde, 0x4a, 0x14, 0x2f, 0x9f, 0x00, 0x00, 0x40, 0x80, 0xff, 0xd8,\n 0x80, 0x01, 0x00, 0x24, 0x39, 0x40, 0x01, 0x5c, 0x91, 0x5b, 0x00, 0x00,\n 0x7d, 0x23, 0x4b, 0x78, 0x7c, 0x08, 0x03, 0xa6, 0x91, 0x3c, 0x00, 0x00,\n 0x83, 0x61, 0x00, 0x0c, 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14,\n 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20,\n 0x4e, 0x80, 0x00, 0x20, 0x80, 0x01, 0x00, 0x24, 0x38, 0x60, 0x00, 0x00,\n 0x83, 0x61, 0x00, 0x0c, 0x7c, 0x08, 0x03, 0xa6, 0x83, 0x81, 0x00, 0x10,\n 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c,\n 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x94, 0x21, 0xff, 0xe0,\n 0x7c, 0x08, 0x02, 0xa6, 0x93, 0xe1, 0x00, 0x1c, 0x7c, 0xff, 0x3b, 0x79,\n 0x93, 0x61, 0x00, 0x0c, 0x7c, 0x9b, 0x23, 0x78, 0x93, 0x81, 0x00, 0x10,\n 0x7c, 0x7c, 0x1b, 0x78, 0x93, 0xa1, 0x00, 0x14, 0x7c, 0xbd, 0x2b, 0x78,\n 0x93, 0xc1, 0x00, 0x18, 0x7c, 0xde, 0x33, 0x78, 0x90, 0x01, 0x00, 0x24,\n 0x41, 0xa1, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x64, 0x40, 0x9d, 0x00, 0x60,\n 0x7f, 0xc4, 0xf3, 0x78, 0x7f, 0xe5, 0xfb, 0x78, 0x7f, 0xa3, 0xeb, 0x78,\n 0x38, 0xc0, 0x00, 0x00, 0x4b, 0xed, 0x83, 0x09, 0x7c, 0x69, 0x1b, 0x79,\n 0x7f, 0xe9, 0xf8, 0x50, 0x7f, 0xde, 0x4a, 0x14, 0x2f, 0x9f, 0x00, 0x00,\n 0x40, 0x80, 0xff, 0xd8, 0x80, 0x01, 0x00, 0x24, 0x39, 0x40, 0x01, 0x7d,\n 0x91, 0x5b, 0x00, 0x00, 0x7d, 0x23, 0x4b, 0x78, 0x7c, 0x08, 0x03, 0xa6,\n 0x91, 0x3c, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x83, 0x81, 0x00, 0x10,\n 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c,\n 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x80, 0x01, 0x00, 0x24,\n 0x38, 0x60, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x7c, 0x08, 0x03, 0xa6,\n 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18,\n 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20,\n 0x7c, 0x08, 0x02, 0xa6, 0x94, 0x21, 0xfb, 0x90, 0x92, 0xe1, 0x04, 0x4c,\n 0x3e, 0xe0, 0x00, 0x00, 0x90, 0x01, 0x04, 0x74, 0x3a, 0xf7, 0x01, 0x90,\n 0x92, 0x41, 0x04, 0x38, 0x92, 0x61, 0x04, 0x3c, 0x92, 0x81, 0x04, 0x40,\n 0x93, 0x61, 0x04, 0x5c, 0x93, 0xc1, 0x04, 0x68, 0x93, 0xe1, 0x04, 0x6c,\n 0x92, 0xa1, 0x04, 0x44, 0x3a, 0xa0, 0xff, 0xaa, 0x92, 0xc1, 0x04, 0x48,\n 0x3a, 0xc0, 0xff, 0x82, 0x93, 0x01, 0x04, 0x50, 0x3f, 0x00, 0x40, 0x00,\n 0x93, 0x21, 0x04, 0x54, 0x3b, 0x21, 0x00, 0x28, 0x93, 0x41, 0x04, 0x58,\n 0x3b, 0x43, 0x00, 0x04, 0x93, 0x81, 0x04, 0x60, 0x7c, 0x7c, 0x1b, 0x78,\n 0x93, 0xa1, 0x04, 0x64, 0x7c, 0x9d, 0x23, 0x78, 0x7f, 0xa3, 0xeb, 0x78,\n 0x4b, 0xff, 0xfd, 0xc9, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0x68,\n 0x2f, 0x9f, 0x00, 0x41, 0x41, 0x9e, 0x06, 0x88, 0x40, 0x9d, 0x00, 0x58,\n 0x2f, 0x9f, 0x00, 0x72, 0x41, 0x9e, 0x05, 0xbc, 0x41, 0x9d, 0x01, 0x78,\n 0x2f, 0x9f, 0x00, 0x70, 0x41, 0x9e, 0x02, 0xfc, 0x41, 0x9d, 0x04, 0xe8,\n 0x2f, 0x9f, 0x00, 0x50, 0x40, 0xbe, 0xff, 0xc8, 0x39, 0x20, 0x00, 0x01,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x99, 0x21, 0x04, 0x2c,\n 0x4b, 0xff, 0xfe, 0x7d, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xff, 0xa0,\n 0x39, 0x20, 0x00, 0xd1, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x02, 0x20,\n 0x2f, 0x9f, 0x00, 0x03, 0x41, 0x9e, 0x05, 0xec, 0x40, 0x9d, 0x02, 0x64,\n 0x2f, 0x9f, 0x00, 0x0b, 0x41, 0x9e, 0x03, 0x58, 0x2f, 0x9f, 0x00, 0x0c,\n 0x41, 0x9e, 0x03, 0xdc, 0x2f, 0x9f, 0x00, 0x04, 0x40, 0x9e, 0xff, 0x70,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfd, 0x69,\n 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x07, 0x64, 0x83, 0xc1, 0x00, 0x28,\n 0x3a, 0x40, 0xff, 0xb0, 0x82, 0x81, 0x00, 0x2c, 0x3a, 0x60, 0xff, 0xbd,\n 0x7f, 0x9e, 0xa0, 0x40, 0x41, 0xbe, 0xff, 0x38, 0x7f, 0x7e, 0xa0, 0x50,\n 0x2f, 0x9b, 0x04, 0x00, 0x40, 0x9d, 0x00, 0x7c, 0x3b, 0x60, 0x04, 0x00,\n 0x89, 0x3e, 0x00, 0x00, 0x2f, 0x89, 0x00, 0x00, 0x40, 0x9e, 0x00, 0x78,\n 0x7f, 0x69, 0x03, 0xa6, 0x48, 0x00, 0x00, 0x10, 0x7d, 0x5e, 0x48, 0xae,\n 0x2f, 0x8a, 0x00, 0x00, 0x40, 0x9e, 0x00, 0x64, 0x39, 0x29, 0x00, 0x01,\n 0x42, 0x00, 0xff, 0xf0, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01,\n 0x9a, 0x41, 0x04, 0x2c, 0x4b, 0xff, 0xfd, 0xb9, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x06, 0xfc, 0x7f, 0xa3, 0xeb, 0x78, 0x4b, 0xff, 0xfc, 0xa1,\n 0x2f, 0x83, 0x00, 0xcc, 0x41, 0xbe, 0xfe, 0xcc, 0x7f, 0xde, 0xda, 0x14,\n 0x7f, 0x94, 0xf0, 0x40, 0x41, 0xbe, 0xfe, 0xc0, 0x7f, 0x7e, 0xa0, 0x50,\n 0x2f, 0x9b, 0x04, 0x00, 0x41, 0xbd, 0xff, 0x8c, 0x2f, 0x9b, 0x00, 0x00,\n 0x41, 0x9d, 0xff, 0x88, 0x41, 0xbe, 0xff, 0xac, 0x7f, 0xc4, 0xf3, 0x78,\n 0x7f, 0x65, 0xdb, 0x78, 0x38, 0x61, 0x00, 0x29, 0x4b, 0xe5, 0x3a, 0x35,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xfb, 0x00, 0x01, 0x9a, 0x61, 0x00, 0x28,\n 0x4b, 0xff, 0xfd, 0x51, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xff, 0x9c,\n 0x39, 0x20, 0x00, 0x8f, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x00, 0xf4,\n 0x2f, 0x9f, 0x00, 0x99, 0x41, 0x9e, 0x02, 0x08, 0x2f, 0x9f, 0x00, 0x9a,\n 0x41, 0x9e, 0x02, 0x8c, 0x2f, 0x9f, 0x00, 0x80, 0x40, 0x9e, 0xfe, 0x50,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x44, 0x4b, 0xff, 0xfc, 0x49,\n 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x06, 0x38, 0x80, 0x81, 0x00, 0x4c,\n 0x81, 0x61, 0x00, 0x28, 0x90, 0x81, 0x00, 0x08, 0x80, 0x81, 0x00, 0x50,\n 0x7d, 0x69, 0x03, 0xa6, 0x80, 0xa1, 0x00, 0x34, 0x90, 0x81, 0x00, 0x0c,\n 0x80, 0x81, 0x00, 0x54, 0x80, 0xc1, 0x00, 0x38, 0x90, 0x81, 0x00, 0x10,\n 0x80, 0x81, 0x00, 0x58, 0x80, 0xe1, 0x00, 0x3c, 0x90, 0x81, 0x00, 0x14,\n 0x80, 0x81, 0x00, 0x5c, 0x81, 0x01, 0x00, 0x40, 0x90, 0x81, 0x00, 0x18,\n 0x80, 0x81, 0x00, 0x60, 0x81, 0x21, 0x00, 0x44, 0x90, 0x81, 0x00, 0x1c,\n 0x80, 0x81, 0x00, 0x64, 0x81, 0x41, 0x00, 0x48, 0x90, 0x81, 0x00, 0x20,\n 0x80, 0x81, 0x00, 0x68, 0x80, 0x61, 0x00, 0x2c, 0x90, 0x81, 0x00, 0x24,\n 0x80, 0x81, 0x00, 0x30, 0x4e, 0x80, 0x04, 0x21, 0x7f, 0xa5, 0xeb, 0x78,\n 0x90, 0x61, 0x00, 0x28, 0x7f, 0x26, 0xcb, 0x78, 0x90, 0x81, 0x00, 0x2c,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x38, 0xe0, 0x00, 0x08,\n 0x4b, 0xff, 0xfc, 0x79, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfd, 0x9c,\n 0x39, 0x20, 0x01, 0x36, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x00, 0x1c,\n 0x4b, 0xe5, 0xce, 0xc5, 0x81, 0x23, 0x00, 0x00, 0x2f, 0x89, 0x00, 0x06,\n 0x41, 0x9e, 0x04, 0xf8, 0x39, 0x20, 0x00, 0x54, 0x91, 0x3c, 0x00, 0x04,\n 0x80, 0x01, 0x04, 0x74, 0x38, 0x60, 0x00, 0x00, 0x93, 0xfc, 0x00, 0x00,\n 0x7c, 0x08, 0x03, 0xa6, 0x82, 0x41, 0x04, 0x38, 0x82, 0x61, 0x04, 0x3c,\n 0x82, 0x81, 0x04, 0x40, 0x82, 0xa1, 0x04, 0x44, 0x82, 0xc1, 0x04, 0x48,\n 0x82, 0xe1, 0x04, 0x4c, 0x83, 0x01, 0x04, 0x50, 0x83, 0x21, 0x04, 0x54,\n 0x83, 0x41, 0x04, 0x58, 0x83, 0x61, 0x04, 0x5c, 0x83, 0x81, 0x04, 0x60,\n 0x83, 0xa1, 0x04, 0x64, 0x83, 0xc1, 0x04, 0x68, 0x83, 0xe1, 0x04, 0x6c,\n 0x38, 0x21, 0x04, 0x70, 0x4e, 0x80, 0x00, 0x20, 0x2f, 0x9f, 0x00, 0x01,\n 0x41, 0x9e, 0x01, 0xfc, 0x2f, 0x9f, 0x00, 0x02, 0x40, 0xbe, 0xfd, 0x18,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfb, 0x11,\n 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x04, 0x90, 0x81, 0x21, 0x00, 0x28,\n 0x38, 0x80, 0x00, 0x02, 0xa1, 0x41, 0x00, 0x2e, 0x7d, 0x23, 0x4b, 0x78,\n 0xb1, 0x49, 0x00, 0x00, 0x4b, 0xe4, 0x38, 0x91, 0x4b, 0xff, 0xfc, 0xdc,\n 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78,\n 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x24, 0x4b, 0xff, 0xfa, 0xd5,\n 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x04, 0xa0, 0x81, 0x61, 0x00, 0x28,\n 0x80, 0xa1, 0x00, 0x34, 0x80, 0xc1, 0x00, 0x38, 0x7d, 0x69, 0x03, 0xa6,\n 0x80, 0xe1, 0x00, 0x3c, 0x81, 0x01, 0x00, 0x40, 0x81, 0x21, 0x00, 0x44,\n 0x81, 0x41, 0x00, 0x48, 0x80, 0x61, 0x00, 0x2c, 0x80, 0x81, 0x00, 0x30,\n 0x4e, 0x80, 0x04, 0x21, 0x7f, 0xa5, 0xeb, 0x78, 0x90, 0x61, 0x00, 0x28,\n 0x7f, 0x26, 0xcb, 0x78, 0x90, 0x81, 0x00, 0x2c, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfb, 0x45,\n 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfc, 0x68, 0x39, 0x20, 0x00, 0xea,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfe, 0xe8, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c,\n 0x38, 0xe0, 0x00, 0x01, 0x9a, 0xc1, 0x04, 0x2c, 0x4b, 0xff, 0xfb, 0x15,\n 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfc, 0x38, 0x39, 0x20, 0x01, 0x3b,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfe, 0xb8, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfa, 0x25, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x03, 0xd0, 0x83, 0xc1, 0x00, 0x2c, 0x83, 0xe1, 0x00, 0x28,\n 0x38, 0x60, 0x00, 0x01, 0x38, 0x80, 0x00, 0x00, 0x7f, 0xc5, 0xf3, 0x78,\n 0x38, 0xc0, 0x00, 0x00, 0x38, 0xe0, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x01,\n 0x7f, 0xe9, 0xfb, 0x78, 0x7c, 0x3e, 0x0b, 0x78, 0x38, 0x00, 0x35, 0x00,\n 0x44, 0x00, 0x00, 0x02, 0x60, 0x00, 0x00, 0x00, 0x7f, 0xc1, 0xf3, 0x78,\n 0x4b, 0xff, 0xfb, 0xd0, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04,\n 0x92, 0xe1, 0x00, 0x28, 0x4b, 0xff, 0xfa, 0x89, 0x7c, 0x7f, 0x1b, 0x79,\n 0x40, 0x80, 0xfb, 0xac, 0x39, 0x20, 0x01, 0x44, 0x91, 0x3c, 0x00, 0x04,\n 0x4b, 0xff, 0xfe, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04,\n 0x4b, 0xff, 0xf9, 0x99, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x03, 0x0c,\n 0x83, 0xe1, 0x00, 0x28, 0x38, 0x60, 0x00, 0x01, 0x38, 0x80, 0x00, 0x00,\n 0x38, 0xa0, 0x00, 0x00, 0x38, 0xc0, 0x00, 0x00, 0x38, 0xe0, 0x00, 0x00,\n 0x3d, 0x00, 0x00, 0x01, 0x7f, 0xe9, 0xfb, 0x78, 0x38, 0x00, 0x34, 0x00,\n 0x7c, 0x3f, 0x0b, 0x78, 0x44, 0x00, 0x00, 0x02, 0x60, 0x00, 0x00, 0x00,\n 0x7f, 0xe1, 0xfb, 0x78, 0x7c, 0x7f, 0x1b, 0x78, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x04, 0x93, 0xe1, 0x00, 0x28, 0x4b, 0xff, 0xfa, 0x01,\n 0x4b, 0xff, 0xfb, 0x28, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08,\n 0x4b, 0xff, 0xf9, 0x21, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0xac,\n 0x81, 0x21, 0x00, 0x28, 0x38, 0x80, 0x00, 0x01, 0x89, 0x41, 0x00, 0x2f,\n 0x7d, 0x23, 0x4b, 0x78, 0x99, 0x49, 0x00, 0x00, 0x4b, 0xe4, 0x36, 0xa1,\n 0x4b, 0xff, 0xfa, 0xec, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01,\n 0x4b, 0xff, 0xf8, 0xe5, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x80, 0x02, 0x88,\n 0x88, 0xe1, 0x04, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x54, 0xe7, 0x06, 0x3e,\n 0x4b, 0xff, 0xf8, 0xc1, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0x80,\n 0x38, 0x81, 0x04, 0x30, 0x38, 0x61, 0x00, 0x30, 0x83, 0xe1, 0x00, 0x2c,\n 0x4b, 0xe4, 0x95, 0xfd, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01,\n 0x7f, 0xf9, 0xfa, 0x14, 0x4b, 0xff, 0xf8, 0x8d, 0x2c, 0x03, 0x00, 0x00,\n 0x41, 0x80, 0x02, 0x44, 0x88, 0x81, 0x04, 0x2c, 0x80, 0x61, 0x04, 0x30,\n 0x7f, 0xe5, 0xfb, 0x78, 0x54, 0x84, 0x06, 0x3e, 0x38, 0xc1, 0x04, 0x2c,\n 0x4b, 0xe4, 0xab, 0xc1, 0x81, 0x21, 0x04, 0x2c, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x04, 0x91, 0x21, 0x00, 0x28, 0x4b, 0xff, 0xf9, 0x11,\n 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfa, 0x34, 0x39, 0x20, 0x01, 0x00,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xb4, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x0c, 0x4b, 0xff, 0xf8, 0x21, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x02, 0x04, 0x81, 0x21, 0x00, 0x28, 0x81, 0x01, 0x00, 0x30,\n 0x80, 0xe1, 0x00, 0x2c, 0x7d, 0x09, 0x42, 0x14, 0x7f, 0x89, 0x40, 0x00,\n 0x41, 0xbc, 0x00, 0x14, 0x48, 0x00, 0x01, 0x5c, 0x39, 0x29, 0x00, 0x04,\n 0x7f, 0x89, 0x40, 0x00, 0x40, 0x9c, 0x01, 0x50, 0x81, 0x49, 0x00, 0x00,\n 0x7f, 0x8a, 0x38, 0x00, 0x40, 0x9e, 0xff, 0xec, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x04, 0x91, 0x21, 0x00, 0x28, 0x4b, 0xff, 0xf8, 0x8d,\n 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xf9, 0xb0, 0x39, 0x20, 0x01, 0x15,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0x30, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xf7, 0x9d, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x01, 0x34, 0x81, 0x21, 0x00, 0x28, 0x38, 0x80, 0x00, 0x04,\n 0x81, 0x41, 0x00, 0x2c, 0x7d, 0x23, 0x4b, 0x78, 0x91, 0x49, 0x00, 0x00,\n 0x4b, 0xe4, 0x35, 0x1d, 0x4b, 0xff, 0xf9, 0x68, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78,\n 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xf7, 0x61, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x01, 0x38, 0x83, 0xc1, 0x00, 0x28, 0x82, 0x81, 0x00, 0x2c,\n 0x7f, 0x9e, 0xa0, 0x40, 0x41, 0x9e, 0x00, 0x88, 0x7f, 0x7e, 0xa0, 0x50,\n 0x3d, 0x3e, 0xf0, 0x00, 0x2f, 0x9b, 0x04, 0x00, 0x7f, 0xc6, 0xf3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x09, 0xc0, 0x40, 0x40, 0x9d, 0x00, 0x08, 0x3b, 0x60, 0x04, 0x00,\n 0x7f, 0x67, 0xdb, 0x78, 0x40, 0x99, 0x00, 0x38, 0x7f, 0x44, 0xd3, 0x78,\n 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x7f, 0x67, 0xdb, 0x78,\n 0x7f, 0x83, 0xe3, 0x78, 0x4b, 0xff, 0xf7, 0x01, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x00, 0x68, 0x7f, 0xc3, 0xf3, 0x78, 0x7f, 0x24, 0xcb, 0x78,\n 0x7f, 0x65, 0xdb, 0x78, 0x4b, 0xe5, 0x34, 0x75, 0x48, 0x00, 0x00, 0x18,\n 0x4b, 0xff, 0xf6, 0xe1, 0x7f, 0x99, 0xf0, 0x00, 0x7c, 0x7f, 0x1b, 0x79,\n 0x41, 0x80, 0x00, 0x44, 0x41, 0xbe, 0xff, 0xdc, 0x7f, 0xde, 0xda, 0x14,\n 0x7f, 0x94, 0xf0, 0x40, 0x40, 0x9e, 0xff, 0x80, 0x7f, 0x83, 0xe3, 0x78,\n 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c,\n 0x38, 0xe0, 0x00, 0x01, 0x9a, 0xa1, 0x04, 0x2c, 0x4b, 0xff, 0xf7, 0x6d,\n 0x4b, 0xff, 0xf8, 0x94, 0x39, 0x20, 0x00, 0x00, 0x4b, 0xff, 0xfe, 0xbc,\n 0x4b, 0xf6, 0x7a, 0x49, 0x4b, 0xff, 0xf8, 0x84, 0x39, 0x20, 0x00, 0xc4,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfb, 0x04, 0x39, 0x20, 0x00, 0xa7,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xf8, 0x39, 0x20, 0x00, 0x67,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xec, 0x39, 0x20, 0x00, 0x5d,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xe0, 0x39, 0x20, 0x00, 0x71,\n 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xd4, 0x7c, 0x67, 0x1b, 0x78,\n 0x4b, 0xff, 0xfd, 0x7c, 0x39, 0x20, 0x00, 0x9c, 0x91, 0x3c, 0x00, 0x04,\n 0x4b, 0xff, 0xfa, 0xc0, 0x7c, 0x64, 0x1b, 0x78, 0x4b, 0xff, 0xfd, 0xc0,\n 0x39, 0x20, 0x00, 0xf1, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xac,\n 0x39, 0x20, 0x00, 0xda, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xa0,\n 0x39, 0x20, 0x00, 0xb4, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x94,\n 0x39, 0x20, 0x01, 0x05, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x88,\n 0x39, 0x20, 0x01, 0x1e, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x7c,\n 0x39, 0x20, 0x00, 0x7b, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x70,\n 0x39, 0x20, 0x00, 0x8a, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x64,\n 0x94, 0x21, 0xff, 0xa0, 0x7c, 0x08, 0x02, 0xa6, 0x7d, 0x80, 0x00, 0x26,\n 0x93, 0x81, 0x00, 0x50, 0x3b, 0x80, 0xff, 0xff, 0x2d, 0x9c, 0xff, 0xff,\n 0x92, 0x81, 0x00, 0x30, 0x92, 0xa1, 0x00, 0x34, 0x3a, 0x80, 0x00, 0x3e,\n 0x92, 0xc1, 0x00, 0x38, 0x3a, 0xa0, 0x00, 0x3a, 0x92, 0xe1, 0x00, 0x3c,\n 0x3a, 0xc0, 0x00, 0x37, 0x93, 0x01, 0x00, 0x40, 0x3a, 0xe0, 0x00, 0x35,\n 0x93, 0x21, 0x00, 0x44, 0x3b, 0x00, 0x00, 0x33, 0x93, 0x41, 0x00, 0x48,\n 0x3b, 0x20, 0x00, 0x02, 0x93, 0x61, 0x00, 0x4c, 0x3b, 0x40, 0x1c, 0xa3,\n 0x93, 0xa1, 0x00, 0x54, 0x3b, 0x60, 0x00, 0x00, 0x90, 0x01, 0x00, 0x64,\n 0x7c, 0x9d, 0x23, 0x78, 0x93, 0xc1, 0x00, 0x58, 0x93, 0xe1, 0x00, 0x5c,\n 0x91, 0x81, 0x00, 0x2c, 0x4b, 0xed, 0x69, 0x3d, 0x38, 0x60, 0x00, 0x02,\n 0x38, 0x80, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x06, 0xb3, 0x21, 0x00, 0x08,\n 0xb3, 0x41, 0x00, 0x0a, 0x93, 0x61, 0x00, 0x0c, 0x4b, 0xed, 0x81, 0xed,\n 0x2e, 0x03, 0xff, 0xff, 0x7c, 0x7f, 0x1b, 0x78, 0x40, 0x92, 0x00, 0x4c,\n 0x93, 0x1d, 0x00, 0x04, 0x3b, 0xc0, 0xff, 0xff, 0x2f, 0x9c, 0xff, 0xff,\n 0x41, 0x9e, 0x00, 0x0c, 0x7f, 0x83, 0xe3, 0x78, 0x4b, 0xed, 0x83, 0x15,\n 0x40, 0x92, 0x00, 0x84, 0x93, 0xdd, 0x00, 0x00, 0x38, 0x60, 0x00, 0x02,\n 0x38, 0x80, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x06, 0xb3, 0x21, 0x00, 0x08,\n 0xb3, 0x41, 0x00, 0x0a, 0x93, 0x61, 0x00, 0x0c, 0x4b, 0xed, 0x81, 0xa5,\n 0x2e, 0x03, 0xff, 0xff, 0x7c, 0x7f, 0x1b, 0x78, 0x41, 0xb2, 0xff, 0xbc,\n 0x38, 0x81, 0x00, 0x08, 0x38, 0xa0, 0x00, 0x10, 0x4b, 0xed, 0x6c, 0x8d,\n 0x7c, 0x7e, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x54, 0x7f, 0xe3, 0xfb, 0x78,\n 0x38, 0x80, 0x00, 0x01, 0x4b, 0xed, 0x6f, 0x79, 0x7c, 0x7e, 0x1b, 0x79,\n 0x41, 0x80, 0x00, 0x48, 0x39, 0x20, 0x00, 0x10, 0x7f, 0xe3, 0xfb, 0x78,\n 0x38, 0x81, 0x00, 0x08, 0x38, 0xa1, 0x00, 0x18, 0x91, 0x21, 0x00, 0x18,\n 0x4b, 0xed, 0x6a, 0xd9, 0x2f, 0x83, 0xff, 0xff, 0x7c, 0x7c, 0x1b, 0x78,\n 0x40, 0x9e, 0x00, 0x2c, 0x92, 0xbd, 0x00, 0x04, 0x3b, 0xc0, 0xff, 0xff,\n 0x7f, 0xe3, 0xfb, 0x78, 0x4b, 0xed, 0x82, 0x89, 0x93, 0xdd, 0x00, 0x00,\n 0x4b, 0xff, 0xff, 0x78, 0x92, 0xfd, 0x00, 0x04, 0x4b, 0xff, 0xff, 0x58,\n 0x92, 0xdd, 0x00, 0x04, 0x4b, 0xff, 0xff, 0x50, 0x7f, 0xe3, 0xfb, 0x78,\n 0x4b, 0xed, 0x82, 0x69, 0x7f, 0xa3, 0xeb, 0x78, 0x7f, 0x84, 0xe3, 0x78,\n 0x4b, 0xff, 0xf6, 0x05, 0x7c, 0x7e, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x14,\n 0x7f, 0x83, 0xe3, 0x78, 0x3b, 0x80, 0xff, 0xff, 0x4b, 0xed, 0x82, 0x49,\n 0x4b, 0xff, 0xfe, 0xf4, 0x92, 0x9d, 0x00, 0x04, 0x3b, 0xe0, 0xff, 0xff,\n 0x4e, 0x0c, 0x00, 0x00, 0x4b, 0xff, 0xff, 0x1c\n};\nstatic const unsigned int codehandler_text_bin_len = 3260;\n\n\n<|start_filename|>installer/src/loader.c<|end_filename|>\n#include \"loader.h\"\n\n#define RW_MEM_MAP 0xA0000000\n#if VER == 300\n\t#include \"codehandler310.h\" //TODO ???\n\t#define INSTALL_ADDR 0x011D3000\n\t#define MAIN_JMP_ADDR 0x0101894C\n#elif VER == 310\n\t#include \"codehandler310.h\"\n\t#define INSTALL_ADDR 0x011D3000\n\t#define MAIN_JMP_ADDR 0x0101894C\n#elif VER == 400\n\t#include \"codehandler400.h\"\n\t#define INSTALL_ADDR 0x011DD000\n\t#define MAIN_JMP_ADDR 0x0101BD4C\n#elif VER == 410\n\t#include \"codehandler410.h\"\n\t#define INSTALL_ADDR 0x011DD000\n\t#define MAIN_JMP_ADDR 0x0101C55C\n#elif VER == 500\n\t#include \"codehandler500.h\"\n\t#define INSTALL_ADDR 0x011DD000\n\t#define MAIN_JMP_ADDR 0x0101C55C\n#elif VER == 532\n\t#include \"codehandler532.h\"\n\t#define INSTALL_ADDR 0x011DD000\n\t#define MAIN_JMP_ADDR 0x0101C55C\n#elif VER == 550\n\t#include \"codehandler550.h\"\n\t#define INSTALL_ADDR 0x011DD000\n\t#define MAIN_JMP_ADDR 0x0101C56C\n#endif\n\n#define assert(x) \\\n\tdo { \\\n\t\tif (!(x)) \\\n\t\t\tOSFatal(\"Assertion failed \" #x \".\\n\"); \\\n\t} while (0)\n\n#define ALIGN_BACKWARD(x,align) \\\n\t((typeof(x))(((unsigned int)(x)) & (~(align-1))))\n\nint doBL( unsigned int dst, unsigned int src );\nvoid doOSScreenInit(unsigned int coreinit_handle);\ninline void doOSScreenClear();\nvoid doOSScreenPrintPos(char *buf, int pos);\nvoid doVPADWait();\n\nvoid _main(){\n\t/* Get a handle to coreinit.rpl. */\n\tunsigned int coreinit_handle;\n\tOSDynLoad_Acquire(\"coreinit.rpl\", &coreinit_handle);\n\t\n\t/* Get for later socket patch */\n\tunsigned int nsysnet_handle;\n\tOSDynLoad_Acquire(\"nsysnet.rpl\", &nsysnet_handle);\n\t\n\t/* Get for IP address print */\n\tunsigned int nn_ac_handle;\n\tOSDynLoad_Acquire(\"nn_ac.rpl\", &nn_ac_handle);\n\t\n\t/* Load a few useful symbols. */\n\tvoid*(*OSEffectiveToPhysical)(const void *);\n\tvoid*(*OSAllocFromSystem)(uint32_t size, int align);\n\tvoid (*OSFreeToSystem)(void *ptr);\n\tvoid (*DCFlushRange)(const void *, int);\n\tvoid (*ICInvalidateRange)(const void *, int);\n\tvoid (*_Exit)(void) __attribute__ ((noreturn));\n\t\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSEffectiveToPhysical\", &OSEffectiveToPhysical);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSAllocFromSystem\", &OSAllocFromSystem);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSFreeToSystem\", &OSFreeToSystem);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"DCFlushRange\", &DCFlushRange);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"ICInvalidateRange\", &ICInvalidateRange);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"_Exit\", &_Exit);\n\t\n\tassert(OSEffectiveToPhysical);\n\tassert(OSAllocFromSystem);\n\tassert(OSFreeToSystem);\n\tassert(DCFlushRange);\n\tassert(ICInvalidateRange);\n\tassert(_Exit);\n\t\n\t/* Socket functions */\n\tunsigned int *socket_lib_finish;\n\tOSDynLoad_FindExport(nsysnet_handle, 0, \"socket_lib_finish\", &socket_lib_finish);\n\tassert(socket_lib_finish);\n\t\n\t/* AC functions */\n\tint(*ACGetAssignedAddress)(unsigned int *addr);\n\tOSDynLoad_FindExport(nn_ac_handle, 0, \"ACGetAssignedAddress\", &ACGetAssignedAddress);\n\tassert(ACGetAssignedAddress);\n\t\n\t/* IM functions */\n\tint(*IM_SetDeviceState)(int fd, void *mem, int state, int a, int b);\n\tint(*IM_Close)(int fd);\n\tint(*IM_Open)();\n\t\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"IM_SetDeviceState\", &IM_SetDeviceState);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"IM_Close\", &IM_Close);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"IM_Open\", &IM_Open);\n\t\n\tassert(IM_SetDeviceState);\n\tassert(IM_Close);\n\tassert(IM_Open);\n\t\n\t/* Restart system to get lib access */\n\tint fd = IM_Open();\n\tvoid *mem = OSAllocFromSystem(0x100, 64);\n\tmemset(mem, 0, 0x100);\n\t\n\t/* set restart flag to force quit browser */\n\tIM_SetDeviceState(fd, mem, 3, 0, 0);\n\tIM_Close(fd);\n\tOSFreeToSystem(mem);\n\t\n\t/* wait a bit for browser end */\n\tunsigned int t1 = 0x1FFFFFFF;\n\twhile(t1--){};\n\t\n\tdoOSScreenInit(coreinit_handle);\n\tdoOSScreenClear();\n\tdoOSScreenPrintPos(\"TCPGecko Installer\", 0);\n\t\n\t/* Make sure the kernel exploit has been run */\n\tif (OSEffectiveToPhysical((void *)0xA0000000) == (void *)0){\n\t\tdoOSScreenPrintPos(\"You must execute the kernel exploit before installing TCPGecko.\", 1);\n\t\tdoOSScreenPrintPos(\"Returning to the home menu...\",2);\n\t\tt1 = 0x3FFFFFFF;\n\t\twhile(t1--) ;\n\t\tdoOSScreenClear();\n\t\t_Exit();\n\t}else{\n\t\tdoOSScreenPrintPos(\"Trying to install TCPGecko...\", 1);\n\t\t\n\t\t// Make sure everything has kern I/O\n\t\tkern_write((void*)KERN_SYSCALL_TBL_1 + (0x34 * 4), KERN_CODE_READ);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_2 + (0x34 * 4), KERN_CODE_READ);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_3 + (0x34 * 4), KERN_CODE_READ);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_4 + (0x34 * 4), KERN_CODE_READ);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_5 + (0x34 * 4), KERN_CODE_READ);\n\t\t\n\t\tkern_write((void*)KERN_SYSCALL_TBL_1 + (0x35 * 4), KERN_CODE_WRITE);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_2 + (0x35 * 4), KERN_CODE_WRITE);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_3 + (0x35 * 4), KERN_CODE_WRITE);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_4 + (0x35 * 4), KERN_CODE_WRITE);\n\t\tkern_write((void*)KERN_SYSCALL_TBL_5 + (0x35 * 4), KERN_CODE_WRITE);\n\t\t\n\t\t/* Our main writable area */\n\t\tunsigned int physWriteLoc = (unsigned int)OSEffectiveToPhysical((void*)RW_MEM_MAP);\n\t\t\n\t\t/* Install codehandler */\n\t\tunsigned int phys_codehandler_loc = (unsigned int)OSEffectiveToPhysical((void*)INSTALL_ADDR);\n\t\tvoid *codehandler_loc = (unsigned int*)(RW_MEM_MAP + (phys_codehandler_loc - physWriteLoc));\n\t\t\n\t\tmemcpy(codehandler_loc, codehandler_text_bin, codehandler_text_bin_len);\n\t\tDCFlushRange(codehandler_loc, codehandler_text_bin_len);\n\t\tICInvalidateRange(codehandler_loc, codehandler_text_bin_len);\n\t\t\n\t\t/* Patch coreinit jump */\n\t\tunsigned int phys_main_jmp_loc = (unsigned int)OSEffectiveToPhysical((void*)MAIN_JMP_ADDR);\n\t\tunsigned int *main_jmp_loc = (unsigned int*)(RW_MEM_MAP + (phys_main_jmp_loc - physWriteLoc));\n\t\t\n\t\t*main_jmp_loc = doBL(INSTALL_ADDR, MAIN_JMP_ADDR);\n\t\tDCFlushRange(ALIGN_BACKWARD(main_jmp_loc, 32), 0x20);\n\t\tICInvalidateRange(ALIGN_BACKWARD(main_jmp_loc, 32), 0x20);\n\t\t\n\t\t/* Patch Socket Function */\n\t\tunsigned int phys_socket_loc = (unsigned int)OSEffectiveToPhysical(socket_lib_finish);\n\t\tunsigned int *socket_loc = (unsigned int*)(RW_MEM_MAP + (phys_socket_loc - physWriteLoc));\n\t\t\n\t\tsocket_loc[0] = 0x38600000;\n\t\tsocket_loc[1] = 0x4E800020;\n\t\tDCFlushRange(ALIGN_BACKWARD(socket_loc, 32), 0x40);\n\t\tICInvalidateRange(ALIGN_BACKWARD(socket_loc, 32), 0x40);\n\t\t\n\t\t/* The fix for Splatoon and such */\n\t\tkern_write((void*)(KERN_ADDRESS_TBL + (0x12 * 4)), 0x00000000);\n\t\tkern_write((void*)(KERN_ADDRESS_TBL + (0x13 * 4)), 0x14000000);\n\t\t\n\t\t/* All good! */\n\t\tunsigned int addr;\n\t\tACGetAssignedAddress(&addr);\n\t\tchar buf[64];\n\t\t__os_snprintf(buf,64,\"Success! Your Gecko IP is %i.%i.%i.%i.\", (addr>>24)&0xFF,(addr>>16)&0xFF,(addr>>8)&0xFF,addr&0xFF);\n\t\tdoOSScreenPrintPos(buf, 2);\n\t\t\n\t\tdoOSScreenPrintPos(\"Press any button to return to the home menu.\", 3);\n\t\tdoVPADWait();\n\t}\n\tdoOSScreenClear();\n\t_Exit();\n}\n\nint doBL( unsigned int dst, unsigned int src ){\n\tunsigned int newval = (dst - src);\n\tnewval &= 0x03FFFFFC;\n\tnewval |= 0x48000001;\n\treturn newval;\n}\n\n/* for internal and gcc usage */\nvoid* memset(void* dst, const uint8_t val, uint32_t size){\n\tuint32_t i;\n\tfor (i = 0; i < size; i++){\n\t\t((uint8_t*) dst)[i] = val;\n\t}\n\treturn dst;\n}\n\nvoid* memcpy(void* dst, const void* src, uint32_t size){\n\tuint32_t i;\n\tfor (i = 0; i < size; i++){\n\t\t((uint8_t*) dst)[i] = ((const uint8_t*) src)[i];\n\t}\n\treturn dst;\n}\n\n/* Write a 32-bit word with kernel permissions */\nvoid kern_write(void *addr, uint32_t value){\n\tasm(\n\t\t\"li 3,1\\n\"\n\t\t\"li 4,0\\n\"\n\t\t\"mr 5,%1\\n\"\n\t\t\"li 6,0\\n\"\n\t\t\"li 7,0\\n\"\n\t\t\"lis 8,1\\n\"\n\t\t\"mr 9,%0\\n\"\n\t\t\"mr %1,1\\n\"\n\t\t\"li 0,0x3500\\n\"\n\t\t\"sc\\n\"\n\t\t\"nop\\n\"\n\t\t\"mr 1,%1\\n\"\n\t\t:\n\t\t:\t\"r\"(addr), \"r\"(value)\n\t\t:\t\"memory\", \"ctr\", \"lr\", \"0\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\",\n\t\t\t\"11\", \"12\"\n\t\t);\n}\n\n/* OSScreen helper functions */\nvoid doOSScreenInit(unsigned int coreinit_handle){\n\t/* OSScreen functions */\n\tvoid(*OSScreenInit)();\n\tunsigned int(*OSScreenGetBufferSizeEx)(unsigned int bufferNum);\n\tunsigned int(*OSScreenSetBufferEx)(unsigned int bufferNum, void * addr);\n\t\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSScreenInit\", &OSScreenInit);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSScreenGetBufferSizeEx\", &OSScreenGetBufferSizeEx);\n\tOSDynLoad_FindExport(coreinit_handle, 0, \"OSScreenSetBufferEx\", &OSScreenSetBufferEx);\n\t\n\tassert(OSScreenInit);\n\tassert(OSScreenGetBufferSizeEx);\n\tassert(OSScreenSetBufferEx);\n\t\n\t/* Call the Screen initilzation function */\n\tOSScreenInit();\n\t\n\t/* Grab the buffer size for each screen (TV and gamepad) */\n\tint buf0_size = OSScreenGetBufferSizeEx(0);\n\tint buf1_size = OSScreenGetBufferSizeEx(1);\n\t\n\t/* Set the buffer area */\n\tOSScreenSetBufferEx(0, (void *)0xF4000000);\n\tOSScreenSetBufferEx(1, (void *)0xF4000000 + buf0_size);\n}\n\ninline void doOSScreenClear(){\n\t/* Clear both framebuffers */\n\tint ii;\n\tfor (ii = 0; ii < 2; ii++){\n\t\tfillScreen(0,0,0,0);\n\t\tflipBuffers();\n\t}\n}\n\nvoid doOSScreenPrintPos(char *buf, int pos){\n\tint i;\n\tfor(i=0;i<2;i++){\n\t\tdrawString(0,pos,buf);\n\t\tflipBuffers();\n\t}\n}\n\nvoid doVPADWait(){\n\tunsigned int vpad_handle;\n\tOSDynLoad_Acquire(\"vpad.rpl\", &vpad_handle);\n\t\n\t/* VPAD functions */\n\tint(*VPADRead)(int controller, VPADData *buffer, unsigned int num, int *error);\n\tOSDynLoad_FindExport(vpad_handle, 0, \"VPADRead\", &VPADRead);\n\tassert(VPADRead);\n\t\n\tint error;\n\tVPADData vpad_data;\n\t\n\t/* Read initial vpad status */\n\tVPADRead(0, &vpad_data, 1, &error);\n\twhile(1){\n\t\tVPADRead(0, &vpad_data, 1, &error);\n\t\tif(vpad_data.btn_hold){\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n<|start_filename|>installer/Makefile<|end_filename|>\nroot := .\nproject := $(root)/src\nbuild := $(root)/bin\nlibs := $(root)/../../libwiiu/bin\nwww := $(root)/../../www\nframework := $(root)/../../framework\nAS=powerpc-eabi-as\nCC=powerpc-eabi-gcc\nCFLAGS=-nostdinc -fno-builtin -c\nLDFLAGS=-T $(project)/link.ld -nostartfiles -nostdlib -s\nall: clean setup main550 main532 main500 main410 main400 main310 main300\nsetup:\n\tmkdir -p $(root)/bin/\nmain550:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=550 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code550.bin $(libs)/550/draw.o $(build)/*.o\nmain532:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=532 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code532.bin $(libs)/532/draw.o $(build)/*.o\nmain500:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=500 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code500.bin $(libs)/500/draw.o $(build)/*.o\nmain410:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=410 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code410.bin $(libs)/410/draw.o $(build)/*.o\nmain400:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=400 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code400.bin $(libs)/400/draw.o $(build)/*.o\nmain310:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=400 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code310.bin $(libs)/310/draw.o $(build)/*.o\nmain300:\n\t$(AS) $(project)/asm.s -o $(root)/asm.o\n\t$(CC) $(CFLAGS) -DVER=300 $(project)/*.c\n\t#-Wa,-a,-ad\n\tmv -f $(root)/*.o $(build)\n\t$(CC) $(LDFLAGS) -o $(build)/code300.bin $(libs)/300/draw.o $(build)/*.o\nclean:\n\trm -f -r $(build)/*\n\n\n<|start_filename|>installer/src/loader.h<|end_filename|>\n#ifndef LOADER_H\n#define LOADER_H\n\n#include \"../../../libwiiu/src/coreinit.h\"\n#include \"../../../libwiiu/src/draw.h\"\n#include \"../../../libwiiu/src/socket.h\"\n#include \"../../../libwiiu/src/types.h\"\n#include \"../../../libwiiu/src/vpad.h\"\n\n/* Kernel address table */\n#if VER == 300\n\t#define KERN_ADDRESS_TBL\t\t0xFFEB66E4\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84D50\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85150\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85D50\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFE85550\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFE85950\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF02214\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02234\n#elif VER == 310\n\t#define KERN_ADDRESS_TBL\t\t0xFFEB66E4\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84D50\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85150\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85D50\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFE85550\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFE85950\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF02214\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02234\n#elif VER == 400\n\t#define KERN_ADDRESS_TBL\t\t0xFFEB7E5C\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84C90\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85090\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85C90\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFE85490\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFE85890\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF02214\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02234\n#elif VER == 410\n\t#define KERN_ADDRESS_TBL\t\t0xFFEB902C\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84C90\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85090\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85C90\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFE85490\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFE85890\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF02214\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02234\n#elif VER == 500\n\t#define KERN_ADDRESS_TBL\t\t0xFFEA9E4C\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84C70\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85070\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85470\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFEA9120\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFEA9520\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF021f4\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02214\n#elif VER == 532\n\t#define KERN_ADDRESS_TBL\t\t0xFFEAAA10\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84C70\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85070\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85470\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFEA9CE0\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFEAA0E0\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF02274\n\t#define KERN_CODE_WRITE\t\t\t0xFFF02294\n#elif VER == 550\n\t#define KERN_ADDRESS_TBL\t\t0xFFEAB7A0\n\t\n\t#define KERN_SYSCALL_TBL_1\t\t0xFFE84C70\n\t#define KERN_SYSCALL_TBL_2\t\t0xFFE85070\n\t#define KERN_SYSCALL_TBL_3\t\t0xFFE85470\n\t#define KERN_SYSCALL_TBL_4\t\t0xFFEAAA60\n\t#define KERN_SYSCALL_TBL_5\t\t0xFFEAAE60\n\t\n\t#define KERN_CODE_READ\t\t\t0xFFF023D4\n\t#define KERN_CODE_WRITE\t\t\t0xFFF023F4\n#else\n#error \"Unsupported Wii U software version\"\n#endif\n\nvoid _main();\nvoid kern_write(void *addr, uint32_t value);\nvoid* memset(void* dst, const uint8_t val, uint32_t size);\nvoid* memcpy(void* dst, const void* src, uint32_t size);\n\n#endif /* LOADER_H */\n\n<|start_filename|>codehandler/main.c<|end_filename|>\n#include \"main.h\"\n\nstatic void start(int argc, void *argv);\nstatic int rungecko(struct bss_t *bss, int clientfd);\nstatic int recvwait(struct bss_t *bss, int sock, void *buffer, int len);\nstatic int recvbyte(struct bss_t *bss, int sock);\nstatic int checkbyte(struct bss_t *bss, int sock);\nstatic int sendwait(struct bss_t *bss, int sock, const void *buffer, int len);\nstatic int sendbyte(struct bss_t *bss, int sock, unsigned char byte);\nstatic void *kern_read(const void *addr);\nstatic void kern_write(void *addr, void *value);\n\nint _start(int argc, char *argv[]) {\n\tstruct bss_t *bss;\n\n\tbss = memalign(sizeof(struct bss_t), 0x40);\n\tif (bss == 0)\n\t\tgoto error;\n\tmemset(bss, 0, sizeof(struct bss_t));\n\tOSCreateThread(\n\t\t&bss->thread,\n\t\tstart,\n\t\t0,\n\t\tbss,\n\t\tbss->stack + sizeof(bss->stack),\n\t\tsizeof(bss->stack),\n\t\t0,\n\t\t0xc\n\t);\n\tOSResumeThread(&bss->thread);\n\nerror:\n\treturn main(argc, argv);\n}\n\n#define CHECK_ERROR(cond) if (cond) { bss->line = __LINE__; goto error; }\n\nstatic void start(int argc, void *argv) {\n\tint sockfd = -1, clientfd = -1, ret, len;\n\tstruct sockaddr_in addr;\n\tstruct bss_t *bss = argv;\n\n\tsocket_lib_init();\n\n\twhile (1) {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 7331;\n\t\taddr.sin_addr.s_addr = 0;\n\n\t\tsockfd = ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\t\tCHECK_ERROR(ret == -1);\n\t\tret = bind(sockfd, (void *)&addr, 16);\n\t\tCHECK_ERROR(ret < 0);\n\t\tret = listen(sockfd, 1);\n\t\tCHECK_ERROR(ret < 0);\n\t\tlen = 16;\n\t\tclientfd = ret = accept(sockfd, (void *)&addr, &len);\n\t\tCHECK_ERROR(ret == -1);\n\t\tsocketclose(sockfd);\n\t\tsockfd = -1;\n\t\tret = rungecko(bss, clientfd);\n\t\tCHECK_ERROR(ret < 0);\n\t\tsocketclose(clientfd);\n\t\tclientfd = -1;\n\n\t\tcontinue;\nerror:\n\t\tif (clientfd != -1)\n\t\t\tsocketclose(clientfd);\n\t\tif (sockfd != -1)\n\t\t\tsocketclose(sockfd);\n\t\tbss->error = ret;\n\t}\n}\n\nstatic int rungecko(struct bss_t *bss, int clientfd) {\n\tint ret;\n\tunsigned char buffer[0x401];\n\n\twhile (1) {\n\t\tret = checkbyte(bss, clientfd);\n\n\t\tif (ret < 0) {\n\t\t\tCHECK_ERROR(errno != EWOULDBLOCK);\n\t\t\tGX2WaitForVsync();\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (ret) {\n\t\tcase 0x01: { /* cmd_poke08 */\n\t\t\tchar *ptr;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tptr = ((char **)buffer)[0];\n\t\t\t*ptr = buffer[7];\n\t\t\tDCFlushRange(ptr, 1);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x02: { /* cmd_poke16 */\n\t\t\tshort *ptr;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tptr = ((short **)buffer)[0];\n\t\t\t*ptr = ((short *)buffer)[3];\n\t\t\tDCFlushRange(ptr, 2);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x03: { /* cmd_pokemem */\n\t\t\tint *ptr;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tptr = ((int **)buffer)[0];\n\t\t\t*ptr = ((int *)buffer)[1];\n\t\t\tDCFlushRange(ptr, 4);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x04: { /* cmd_readmem */\n\t\t\tconst unsigned char *ptr, *end;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tptr = ((const unsigned char **)buffer)[0];\n\t\t\tend = ((const unsigned char **)buffer)[1];\n\n\t\t\twhile (ptr != end) {\n\t\t\t\tint len, i;\n\n\t\t\t\tlen = end - ptr;\n\t\t\t\tif (len > 0x400)\n\t\t\t\t\tlen = 0x400;\n\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\tif (ptr[i] != 0) break;\n\n\t\t\t\tif (i == len) { // all zero!\n\t\t\t\t\tret = sendbyte(bss, clientfd, 0xb0);\n\t\t\t\t\tCHECK_ERROR(ret < 0);\n\t\t\t\t} else {\n\t\t\t\t\tmemcpy(buffer + 1, ptr, len);\n\t\t\t\t\tbuffer[0] = 0xbd;\n\t\t\t\t\tret = sendwait(bss, clientfd, buffer, len + 1);\n\t\t\t\t\tCHECK_ERROR(ret < 0);\n\t\t\t\t}\n\n\t\t\t\tret = checkbyte(bss, clientfd);\n\t\t\t\tif (ret == 0xcc) /* GCFAIL */\n\t\t\t\t\tgoto next_cmd;\n\t\t\t\tptr += len;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x0b: { /* cmd_writekern */\n\t\t\tvoid *ptr, * value;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tptr = ((void **)buffer)[0];\n\t\t\tvalue = ((void **)buffer)[1];\n\n\t\t\tkern_write(ptr, value);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x0c: { /* cmd_readkern */\n\t\t\tvoid *ptr, *value;\n\t\t\tret = recvwait(bss, clientfd, buffer, 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tptr = ((void **)buffer)[0];\n\n\t\t\tvalue = kern_read(ptr);\n\n\t\t\t*(void **)buffer = value;\n\t\t\tsendwait(bss, clientfd, buffer, 4);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x41: { /* cmd_upload */\n\t\t\tunsigned char *ptr, *end, *dst;\n\t\t\tret = recvwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tptr = ((unsigned char **)buffer)[0];\n\t\t\tend = ((unsigned char **)buffer)[1];\n\n\t\t\twhile (ptr != end) {\n\t\t\t\tint len;\n\n\t\t\t\tlen = end - ptr;\n\t\t\t\tif (len > 0x400)\n\t\t\t\t\tlen = 0x400;\n\t\t\t\tif ((int)ptr >= 0x10000000 && (int)ptr <= 0x50000000) {\n\t\t\t\t\tdst = ptr;\n\t\t\t\t} else {\n\t\t\t\t\tdst = buffer;\n\t\t\t\t}\n\t\t\t\tret = recvwait(bss, clientfd, dst, len);\n\t\t\t\tCHECK_ERROR(ret < 0);\n\t\t\t\tif (dst == buffer) {\n\t\t\t\t\tmemcpy(ptr, buffer, len);\n\t\t\t\t}\n\n\t\t\t\tptr += len;\n\t\t\t}\n\n\t\t\tsendbyte(bss, clientfd, 0xaa); /* GCACK */\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x50: { /* cmd_status */\n\t\t\tret = sendbyte(bss, clientfd, 1); /* running */\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x70: { /* cmd_rpc */\n\t\t\tlong long (*fun)(int, int, int, int, int, int, int, int);\n\t\t\tint r3, r4, r5, r6, r7, r8, r9, r10;\n\t\t\tlong long result;\n\n\t\t\tret = recvwait(bss, clientfd, buffer, 4 + 8 * 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tfun = ((void **)buffer)[0];\n\t\t\tr3 = ((int *)buffer)[1];\n\t\t\tr4 = ((int *)buffer)[2];\n\t\t\tr5 = ((int *)buffer)[3];\n\t\t\tr6 = ((int *)buffer)[4];\n\t\t\tr7 = ((int *)buffer)[5];\n\t\t\tr8 = ((int *)buffer)[6];\n\t\t\tr9 = ((int *)buffer)[7];\n\t\t\tr10 = ((int *)buffer)[8];\n\n\t\t\tresult = fun(r3, r4, r5, r6, r7, r8, r9, r10);\n\n\t\t\t((long long *)buffer)[0] = result;\n\t\t\tret = sendwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x71: { /* cmd_getsymbol */\n\t\t\tchar size = recvbyte(bss, clientfd);\n\t\t\tCHECK_ERROR(size < 0);\n\t\t\tret = recvwait(bss, clientfd, buffer, size);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\t/* Identify the RPL name and symbol name */\n\t\t\tchar *rplname = (char*) &((int*)buffer)[2];\n\t\t\tchar *symname = (char*) (&buffer[0] + ((int*)buffer)[1]);\n\n\t\t\t/* Get the symbol and store it in the buffer */\n\t\t\tunsigned int module_handle, function_address;\n\t\t\tOSDynLoad_Acquire(rplname, &module_handle);\n\n\t\t\tchar data = recvbyte(bss, clientfd);\n\t\t\tOSDynLoad_FindExport(module_handle, data, symname, &function_address);\n\t\t\t\n\t\t\t((int*)buffer)[0] = (int)function_address;\n\t\t\tret = sendwait(bss, clientfd, buffer, 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x72: { /* cmd_search32 */\n\t\t\tret = recvwait(bss, clientfd, buffer, 12);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tint addr = ((int *) buffer)[0];\n\t\t\tint val = ((int *) buffer)[1];\n\t\t\tint size = ((int *) buffer)[2];\n\t\t\tint i;\n\t\t\tint resaddr = 0;\n\t\t\tfor(i = addr; i < (addr+size); i+=4)\n\t\t\t{\n\t\t\t\tif(*(int*)i == val)\n\t\t\t\t{\n\t\t\t\t\tresaddr = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((int *)buffer)[0] = resaddr;\n\t\t\tret = sendwait(bss, clientfd, buffer, 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x80: { /* cmd_rpc_big */\n\t\t\tlong long (*fun)(int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int);\n\t\t\tint r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18;\n\t\t\tlong long result;\n\n\t\t\tret = recvwait(bss, clientfd, buffer, 4 + 16 * 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\n\t\t\tfun = ((void **)buffer)[0];\n\t\t\tr3 = ((int *)buffer)[1];\n\t\t\tr4 = ((int *)buffer)[2];\n\t\t\tr5 = ((int *)buffer)[3];\n\t\t\tr6 = ((int *)buffer)[4];\n\t\t\tr7 = ((int *)buffer)[5];\n\t\t\tr8 = ((int *)buffer)[6];\n\t\t\tr9 = ((int *)buffer)[7];\n\t\t\tr10 = ((int *)buffer)[8];\n\t\t\tr11 = ((int *)buffer)[9];\n\t\t\tr12 = ((int *)buffer)[10];\n\t\t\tr13 = ((int *)buffer)[11];\n\t\t\tr14 = ((int *)buffer)[12];\n\t\t\tr15 = ((int *)buffer)[13];\n\t\t\tr16 = ((int *)buffer)[14];\n\t\t\tr17 = ((int *)buffer)[15];\n\t\t\tr18 = ((int *)buffer)[16];\n\n\t\t\tresult = fun(r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18);\n\n\t\t\t((long long *)buffer)[0] = result;\n\t\t\tret = sendwait(bss, clientfd, buffer, 8);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x99: { /* cmd_version */\n\t\t\tret = sendbyte(bss, clientfd, 0x82); /* WiiU */\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0x9A: { /* cmd_os_version */\n\t\t\t/* Little bit of a hack here, the linker script will define the\n\t\t\t * symbol ver to have address of the version number! */\n\t\t\textern char ver[];\n\t\t\t((int *)buffer)[0] = (int)ver;\n\t\t\tret = sendwait(bss, clientfd, buffer, 4);\n\t\t\tCHECK_ERROR(ret < 0);\n\t\t\tbreak;\n\t\t}\n\t\tcase 0xcc: { /* GCFAIL */\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tret = -1;\n\t\t\tCHECK_ERROR(0);\n\t\t\tbreak;\n\t\t}\nnext_cmd:\n\t\tcontinue;\n\t}\n\treturn 0;\nerror:\n\tbss->error = ret;\n\treturn 0;\n}\n\nstatic int recvwait(struct bss_t *bss, int sock, void *buffer, int len) {\n\tint ret;\n\twhile (len > 0) {\n\t\tret = recv(sock, buffer, len, 0);\n\t\tCHECK_ERROR(ret < 0);\n\t\tlen -= ret;\n\t\tbuffer += ret;\n\t}\n\treturn 0;\nerror:\n\tbss->error = ret;\n\treturn ret;\n}\n\nstatic int recvbyte(struct bss_t *bss, int sock) {\n\tunsigned char buffer[1];\n\tint ret;\n\n\tret = recvwait(bss, sock, buffer, 1);\n\tif (ret < 0) return ret;\n\treturn buffer[0];\n}\n\nstatic int checkbyte(struct bss_t *bss, int sock) {\n\tunsigned char buffer[1];\n\tint ret;\n\n\tret = recv(sock, buffer, 1, MSG_DONTWAIT);\n\tif (ret < 0) return ret;\n\tif (ret == 0) return -1;\n\treturn buffer[0];\n}\n\nstatic int sendwait(struct bss_t *bss, int sock, const void *buffer, int len) {\n\tint ret;\n\twhile (len > 0) {\n\t\tret = send(sock, buffer, len, 0);\n\t\tCHECK_ERROR(ret < 0);\n\t\tlen -= ret;\n\t\tbuffer += ret;\n\t}\n\treturn 0;\nerror:\n\tbss->error = ret;\n\treturn ret;\n}\n\nstatic int sendbyte(struct bss_t *bss, int sock, unsigned char byte) {\n\tunsigned char buffer[1];\n\n\tbuffer[0] = byte;\n\treturn sendwait(bss, sock, buffer, 1);\n}\n\n/* Naughty syscall which we installed to allow arbitrary kernel mode reading.\n * This syscall actually branches part way into __OSReadRegister32Ex after the\n * address validation has already occurred. */\nstatic void *kern_read(const void *addr) {\n\tvoid *result;\n\tasm(\n\t\t\"li 3,1\\n\"\n\t\t\"li 4,0\\n\"\n\t\t\"li 5,0\\n\"\n\t\t\"li 6,0\\n\"\n\t\t\"li 7,0\\n\"\n\t\t\"lis 8,1\\n\"\n\t\t\"mr 9,%1\\n\"\n\t\t\"li 0,0x3400\\n\"\n\t\t\"mr %0,1\\n\"\n\t\t\"sc\\n\"\n\t\t\"nop\\n\" /* sometimes on return it skips an instruction */\n\t\t\"mr 1,%0\\n\"\n\t\t\"mr %0,3\\n\"\n\t\t: \"=r\"(result)\n\t\t: \"b\"(addr)\n\t\t: \"memory\", \"ctr\", \"lr\", \"0\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\",\n\t\t\t\"11\", \"12\"\n\t);\n\n\treturn result;\n}\n\n/* Naughty syscall which we installed to allow arbitrary kernel mode writing.\n * This syscall actually branches part way into __OSWriteRegister32Ex after the\n * address validation has already occurred. */\nstatic void kern_write(void *addr, void *value) {\n\tasm(\n\t\t\"li 3,1\\n\"\n\t\t\"li 4,0\\n\"\n\t\t\"mr 5,%1\\n\"\n\t\t\"li 6,0\\n\"\n\t\t\"li 7,0\\n\"\n\t\t\"lis 8,1\\n\"\n\t\t\"mr 9,%0\\n\"\n\t\t\"mr %1,1\\n\"\n\t\t\"li 0,0x3500\\n\"\n\t\t\"sc\\n\"\n\t\t\"nop\\n\" /* sometimes on return it skips an instruction */\n\t\t\"mr 1,%1\\n\"\n\t\t:\n\t\t: \"r\"(addr), \"r\"(value)\n\t\t: \"memory\", \"ctr\", \"lr\", \"0\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\",\n\t\t\t\"11\", \"12\"\n\t);\n}\n\n\n<|start_filename|>codehandler/main.h<|end_filename|>\n/* string.h */\n#define NULL ((void *)0)\n\nextern void *memcpy(void *dst, const void *src, int bytes);\nextern void *memset(void *dst, int val, int bytes);\n\n/* errno.h */\nextern int *__gh_errno_ptr(void);\n#define errno (*__gh_errno_ptr())\n\n#define EWOULDBLOCK 6\n\n/* malloc.h */\nextern void *(* const MEMAllocFromDefaultHeapEx)(int size, int align);\nextern void *(* const MEMAllocFromDefaultHeap)(int size);\nextern void *(* const MEMFreeToDefaultHeap)(void *ptr);\n\n#define memalign (*MEMAllocFromDefaultHeapEx)\n#define malloc (*MEMAllocFromDefaultHeap)\n#define free (*MEMFreeToDefaultHeap)\n\n/* socket.h */\n#define AF_INET 2\n#define SOCK_STREAM 1\n#define IPPROTO_TCP 6\n\n#define MSG_DONTWAIT 32\n\nextern void socket_lib_init();\nextern int socket(int domain, int type, int protocol);\nextern int socketclose(int socket);\nextern int connect(int socket, void *addr, int addrlen);\nextern int send(int socket, const void *buffer, int size, int flags);\nextern int recv(int socket, void *buffer, int size, int flags);\n\nstruct in_addr {\n\tunsigned int s_addr;\n};\nstruct sockaddr_in {\n\tshort sin_family;\n\tunsigned short sin_port;\n\tstruct in_addr sin_addr;\n\tchar sin_zero[8];\n};\n\nextern int bind(int socket, void *addr, int size);\nextern int listen(int socket, int backlog);\nextern int accept(int socket, void *addr, int *size);\n\n/* coreinit.rpl */\n#include \n#include \n#include \n\ntypedef struct {\n\tchar tag[8]; /* 0x000 \"OSContxt\" */\n\tint32_t gpr[32]; /* 0x008 from OSDumpContext */\n\tuint32_t cr; /* 0x088 from OSDumpContext */\n\tuint32_t lr; /* 0x08c from OSDumpContext */\n\tuint32_t ctr; /* 0x090 from context switch code */\n\tuint32_t xer; /* 0x094 from context switch code */\n\tuint32_t srr0; /* 0x098 from OSDumpContext */\n\tuint32_t srr1; /* 0x09c from OSDumpContext */\n\tchar _unknowna0[0xb8 - 0xa0];\n\tuint64_t fpr[32]; /* 0x0b8 from OSDumpContext */\n\tint16_t spinLockCount; /* 0x1b8 from OSDumpContext */\n\tchar _unknown1ba[0x1bc - 0x1ba]; /* 0x1ba could genuinely be padding? */\n\tuint32_t gqr[8]; /* 0x1bc from OSDumpContext */\n\tchar _unknown1dc[0x1e0 - 0x1dc];\n\tuint64_t psf[32]; /* 0x1e0 from OSDumpContext */\n\tint64_t coretime[3]; /* 0x2e0 from OSDumpContext */\n\tint64_t starttime; /* 0x2f8 from OSDumpContext */\n\tint32_t error; /* 0x300 from OSDumpContext */\n\tchar _unknown304[0x6a0 - 0x304];\n} OSThread; /* 0x6a0 total length from RAM dumps */\n\nextern bool OSCreateThread(OSThread *thread, void (*entry)(int,void*), int argc, void *args, void *stack, size_t stack_size, int32_t priority, int16_t affinity);\nextern void OSResumeThread(OSThread *thread);\n\nextern void DCFlushRange(const void *addr, size_t length);\n\nextern int OSDynLoad_Acquire(char* rpl, unsigned int *handle);\nextern int OSDynLoad_FindExport(unsigned int handle, int isdata, char *symbol, void *address);\n\n/* gx */\nextern void GX2WaitForVsync(void);\n\n/* main */\nextern int (* const entry_point)(int argc, char *argv[]);\n\n#define main (*entry_point)\n\n/* BSS section */\nstruct bss_t {\n\tint error, line;\n\tOSThread thread;\n\tchar stack[0x8000];\n};"},"max_stars_repo_name":{"kind":"string","value":"pablingalas/hacks"}}},{"rowIdx":225,"cells":{"content":{"kind":"string","value":"<|start_filename|>components/github/actions/get-repo/get-repo.js<|end_filename|>\nconst github = require('../../github.app.js')\nconst { Octokit } = require('@octokit/rest')\n\nmodule.exports = {\n key: \"github-get-repo\",\n name: \"Get Repo\",\n description: \"Get details for a repo including the owner, description, metrics (e.g., forks, stars, watchers, issues) and more.\",\n version: \"0.0.2\",\n type: \"action\",\n props: {\n github,\n repoFullName: { propDefinition: [github, \"repoFullName\"] },\n },\n async run() {\n const octokit = new Octokit({\n auth: this.github.$auth.oauth_access_token\n })\n \n return (await octokit.repos.get({\n owner: this.repoFullName.split(\"/\")[0],\n repo: this.repoFullName.split(\"/\")[1],\n })).data\n },\n}\n\n<|start_filename|>components/firebase_admin_sdk/sources/common.js<|end_filename|>\nconst firebase = require(\"../firebase_admin_sdk.app.js\");\n\nmodule.exports = {\n props: {\n firebase,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n processEvent() {\n throw new Error(\"processEvent is not implemented\");\n },\n },\n async run(event) {\n try {\n await this.firebase.initializeApp();\n await this.processEvent(event);\n } catch (err) {\n console.log(\"CHECK HERE FOR ERROR: \", err.response);\n throw new Error(err);\n } finally {\n this.firebase.deleteApp();\n }\n },\n};\n\n\n<|start_filename|>components/ahrefs/actions/get-backlinks-one-per-domain/get-backlinks-one-per-domain.js<|end_filename|>\nconst ahrefs = require('../../ahrefs.app.js')\nconst axios = require('axios')\n\nmodule.exports = {\n name: 'Get Backlinks One Per Domain',\n key: \"ahrefs-get-backlinks-one-per-domain\",\n description: \"Get one backlink with the highest `ahrefs_rank` per referring domain for a target URL or domain (with details for the referring pages including anchor and page title).\",\n version: '0.0.4',\n type: \"action\",\n props: {\n ahrefs,\n target: { propDefinition: [ahrefs, \"target\"] },\n mode: { propDefinition: [ahrefs, \"mode\"] },\n limit: { propDefinition: [ahrefs, \"limit\"] },\n },\n async run() {\n return (await axios({\n url: `https://apiv2.ahrefs.com`,\n params: {\n token: this.ahrefs.$auth.oauth_access_token,\n from: \"backlinks_one_per_domain\",\n target: this.target,\n mode: this.mode,\n limit: this.limit,\n order_by: \"ahrefs_rank:desc\",\n output: \"json\"\n },\n })).data\n },\n}\n\n<|start_filename|>components/asana/asana.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst crypto = require(\"crypto\");\n\nmodule.exports = {\n type: \"app\",\n app: \"asana\",\n propDefinitions: {\n workspaceId: {\n type: \"string\",\n label: \"Workspace\",\n optional: false,\n async options(opts) {\n const workspaces = await this.getWorkspaces();\n return workspaces.map((workspace) => {\n return {\n label: workspace.name,\n value: workspace.gid,\n };\n });\n },\n },\n projectId: {\n type: \"string\",\n label: \"Project\",\n optional: false,\n async options(opts) {\n const projects = await this.getProjects(opts.workspaceId);\n return projects.map((project) => {\n return {\n label: project.name,\n value: project.gid,\n };\n });\n },\n },\n taskIds: {\n type: \"string[]\",\n label: \"Tasks\",\n async options(opts) {\n const tasks = await this.getTasks(opts.projectId);\n return tasks.map((task) => {\n return { label: task.name, value: task.gid };\n });\n },\n },\n organizationId: {\n type: \"string\",\n label: \"Organization\",\n optional: false,\n async options(opts) {\n const organizations = await this.getOrganizations();\n return organizations.map((organization) => {\n return {\n label: organization.name,\n value: organization.gid,\n };\n });\n },\n },\n },\n methods: {\n async _getBaseUrl() {\n return \"https://app.asana.com/api/1.0\"\n },\n async _getHeaders() {\n return {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n };\n },\n async _makeRequest(endpoint) {\n config = {\n url: `${await this._getBaseUrl()}/${endpoint}`,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n }\n };\n try {\n return await axios(config);\n } catch (err) {\n console.log(err);\n }\n }, \n async _getAuthorizationHeader({ data, method, url, headers }) {\n return await axios({\n method: \"POST\",\n url: `${await this._getBaseUrl()}/webhooks`,\n data: data.body,\n headers,\n });\n },\n async createHook(body) {\n const config = {\n method: \"post\",\n url: `${await this._getBaseUrl()}/webhooks`,\n headers: {\n \"Content-Type\": \"applicaton/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n },\n data: {\n body,\n },\n };\n const authorization = await this._getAuthorizationHeader(config);\n config.headers.authorization = authorization;\n try {\n await axios(config);\n } catch (err) {\n console.log(err);\n }\n return authorization.data;\n },\n async deleteHook(hookId) {\n const config = {\n method: \"delete\",\n url: `${await this._getBaseUrl()}/webhooks/${hookId}`,\n headers: await this._getHeaders(),\n };\n try {\n await axios(config);\n } catch (err) {\n console.log(err);\n }\n },\n async verifyAsanaWebhookRequest(request) {\n let secret = this.$auth.oauth_refresh_token;\n var base64Digest = function (s) {\n return crypto.createHmac(\"sha1\", secret).update(s).digest(\"base64\");\n };\n var content = JSON.stringify(request.body);\n var doubleHash = base64Digest(content);\n var headerHash = request.headers[\"x-hook-secret\"];\n return doubleHash === headerHash;\n },\n async getWorkspace(workspaceId) {\n return (await this._makeRequest(`workspaces/${workspaceId}`)).data.data;\n },\n async getWorkspaces() {\n return (await this._makeRequest(\"workspaces\")).data.data;\n },\n async getOrganizations() {\n const organizations = [];\n const workspaces = await this.getWorkspaces();\n for (const workspace of workspaces) {\n let w = await this.getWorkspace(workspace.gid);\n if (w.is_organization) organizations.push(w);\n }\n return organizations;\n },\n async getProject(projectId) {\n return (await this._makeRequest(`projects/${projectId}`)).data.data;\n },\n async getProjects(workspaceId) {\n return (await this._makeRequest(`projects?workspace=${workspaceId}`)).data.data;\n },\n async getStory(storyId) {\n return (await this._makeRequest(`stories/${storyId}`)).data.data;\n },\n async getTask(taskId) {\n return (await this._makeRequest(`tasks/${taskId}`)).data.data;\n },\n async getTasks(projectId) {\n let incompleteTasks = [];\n const tasks = (await this._makeRequest(`projects/${projectId}/tasks`)).data.data;\n for (const task of tasks) {\n let t = await this.getTask(task.gid);\n if (t.completed == false) incompleteTasks.push(task);\n }\n return incompleteTasks;\n },\n async getTag(tagId) {\n return (await this._makeRequest(`tags/${tagId}`)).data.data;\n },\n async getTeam(teamId) {\n return (await this._makeRequest(`teams/${teamId}`)).data.data;\n },\n async getTeams(organizationId) {\n return (await this._makeRequest(`organizations/${organizationId}/teams`)).data.data;\n },\n async getUser(userId) {\n\n return (await this._makeRequest(`users/${userId}`)).data.data;\n },\n async getUsers(workspaceId) {\n return (await this._makeRequest(`workspaces/${workspaceId}/users`)).data.data;\n },\n },\n};\n\n<|start_filename|>interfaces/timer/examples/example-cron-component.js<|end_filename|>\n// Example component that runs a console.log() statement once a minute\n// Run `pd logs ` to see these logs in the CLI\nmodule.exports = {\n name: \"cronjob\",\n version: \"0.0.1\",\n props: {\n timer: {\n type: \"$.interface.timer\",\n default: {\n cron: \"0 0 * * *\",\n },\n },\n },\n async run() {\n console.log(\"Run any Node.js code here\");\n },\n};\n\n\n<|start_filename|>components/bitbucket/sources/new-repo-event/new-repo-event.js<|end_filename|>\nconst common = require(\"../../common\");\nconst { bitbucket } = common.props;\n\nconst EVENT_SOURCE_NAME = \"New Repository Event (Instant)\";\n\nmodule.exports = {\n ...common,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-repo-event\",\n description: \"Emits an event when a repository-wide event occurs.\",\n version: \"0.0.2\",\n props: {\n ...common.props,\n repositoryId: {\n propDefinition: [\n bitbucket,\n \"repositoryId\",\n c => ({ workspaceId: c.workspaceId }),\n ],\n },\n eventTypes: {\n propDefinition: [\n bitbucket,\n \"eventTypes\",\n c => ({ subjectType: \"repository\" }),\n ],\n },\n },\n methods: {\n ...common.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return this.eventTypes;\n },\n getHookPathProps() {\n return {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n };\n },\n generateMeta(data) {\n const {\n \"x-request-uuid\": id,\n \"x-event-key\": eventType,\n \"x-event-time\": eventDate,\n } = data.headers;\n const summary = `New repository event: ${eventType}`;\n const ts = +new Date(eventDate);\n return {\n id,\n summary,\n ts,\n };\n },\n async processEvent(event) {\n const data = {\n headers: event.headers,\n body: event.body,\n };\n const meta = this.generateMeta(data);\n this.$emit(data, meta);\n },\n },\n};\n\n\n<|start_filename|>components/shopify/sources/new-paid-order/new-paid-order.js<|end_filename|>\nconst shopify = require(\"../../shopify.app.js\");\nconst { dateToISOStringWithoutMs } = require(\"../common/utils\");\n\n/**\n * The component's run timer.\n * @constant {number}\n * @default 300 (5 minutes)\n */\nconst DEFAULT_TIMER_INTERVAL_SECONDS = 60 * 5;\n\n/**\n * The minimum time interval from Order Transaction to Order update where the\n * Order update will be considered the result of the Transaction.\n * Note: From testing, an Order (`financial_status:=PAID`) seems to be updated\n * within 15s of the Transaction.\n * @constant {number}\n * @default 30000 (30 seconds)\n */\nconst MIN_ALLOWED_TRANSACT_TO_ORDER_UPDATE_MS = 1000 * 30 * 1;\n\n/**\n * Uses Shopify GraphQL API to get Order Transactions (`created_at`) in the same\n * request as Orders (`updated_at`). Order Transaction `created_at` dates are\n * used to determine if a `PAID` Order's update was from being paid - to avoid\n * duped orders if there are more than 100 orders between updates of a `PAID`\n * Order.\n *\n * Data from GraphQL request is used to generate list of relevant Order IDs.\n * Relevent Orders are requested via Shopify REST API using list of relevant\n * Order IDs.\n */\nmodule.exports = {\n key: \"shopify-new-paid-order\",\n name: \"New Paid Order\",\n description: \"Emits an event each time a new order is paid.\",\n version: \"0.0.3\",\n dedupe: \"unique\",\n props: {\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: DEFAULT_TIMER_INTERVAL_SECONDS,\n },\n },\n shopify,\n },\n methods: {\n _getPrevCursor() {\n return this.db.get(\"prevCursor\") || null;\n },\n _setPrevCursor(prevCursor) {\n this.db.set(\"prevCursor\", prevCursor);\n },\n /**\n * Returns the allowed time interval between Order Transaction and Order\n * update where the Order update can still be considered the result of\n * becoming 'paid'.\n *\n * @returns {number} The number of milliseconds after a Transaction is created\n */\n _getAllowedTransactToOrderUpdateMs() {\n return Math.max(\n MIN_ALLOWED_TRANSACT_TO_ORDER_UPDATE_MS,\n 2 * DEFAULT_TIMER_INTERVAL_SECONDS * 1000,\n );\n },\n /**\n * Gets the fields to include in a GraphQL query.\n *\n * To get the query fields for an Orders query like this,\n * @example\n * {\n * orders {\n * edges {\n * node {\n * updatedAt\n * name\n * legacyResourceId\n * transactions {\n * createdAt\n * }\n * }\n * }\n * }\n * }\n * the function would look like this:\n * @example\n * function getQueryFields() {\n * return [\n * \"updatedAt\",\n * \"name\",\n * \"legacyResourceId\",\n * \"transactions.createdAt\",\n * ];\n * }\n *\n * @returns {string[]} The GraphQL query fields\n */\n getQueryFields() {\n // See https://shopify.dev/docs/admin-api/graphql/reference/orders/order\n // With these fields and a limit of 100, queries cost up to 202 points\n return [\n \"updatedAt\",\n \"name\",\n \"legacyResourceId\", // The ID of the corresponding resource (Order) in the REST Admin API.\n \"transactions.createdAt\",\n ];\n },\n /**\n * Gets the filter string to be used in a GraphQL query.\n * @param {object} opts Options for creating the query filter\n * @param {string} [opts.updatedAt=null] The minimum `updated_at` time to\n * allow in queried resources\n * @returns The query filter string\n */\n getQueryFilter({ updatedAt = null }) {\n return `financial_status:paid updated_at:>${updatedAt}`;\n },\n isRelevant(order) {\n // Don't emit if Order was updated long after last Transaction (update not\n // caused by order being paid)\n let lastTransactionDate = null;\n // Iterate over Order Transactions to get date of most recent Transaction\n for (const transaction of order.transactions) {\n const transactionDate = Date.parse(transaction.createdAt);\n if (!lastTransactionDate || transactionDate - lastTransactionDate > 0) {\n lastTransactionDate = transactionDate;\n }\n }\n if (!lastTransactionDate) {\n return false;\n }\n const timeFromTransactToOrderUpdate =\n Date.parse(order.updatedAt) - lastTransactionDate;\n // - If the Order was updated long after the last Transaction, assume\n // becoming 'paid' was not the cause of update.\n // - Allow at least 2x the timer interval (2 * 5min) after an Order\n // Transaction for Order updates to be considered 'paid' updates.\n // - If 2x the timer interval isn't allowed, some Orders that are updated\n // from a Transaction and then one or more times between polling requests\n // could be considered not 'paid' by the update (because time from Order\n // Transaction `created_at` to Order `updated_at` would be too large).\n // - The larger interval could cause Orders updated multiple times within\n // the interval to be considered 'paid' twice, but those Order events\n // would be deduped if there are fewer than 100 paid Orders in 2x timer\n // inverval.\n return (\n timeFromTransactToOrderUpdate <\n this._getAllowedTransactToOrderUpdateMs()\n );\n },\n\n generateMeta(order) {\n return {\n id: order.id,\n summary: `Order paid: ${order.name}`,\n ts: Date.parse(order.updated_at),\n };\n },\n },\n\n async run() {\n const prevCursor = this._getPrevCursor();\n const queryOrderOpts = {\n fields: this.getQueryFields(),\n filter: this.getQueryFilter({\n // If there is no cursor yet, get orders updated_at after 1 day ago\n // The Shopify GraphQL Admin API does not accept date ISO strings that include milliseconds\n updatedAt: prevCursor\n ? null\n : dateToISOStringWithoutMs(this.shopify.dayAgo()),\n }),\n prevCursor,\n };\n const orderStream = this.shopify.queryOrders(queryOrderOpts);\n const relevantOrderIds = [];\n for await (const orderInfo of orderStream) {\n const {\n order,\n cursor,\n } = orderInfo;\n\n if (this.isRelevant(order)) {\n relevantOrderIds.push(order.legacyResourceId);\n }\n\n this._setPrevCursor(cursor);\n }\n\n const relevantOrders = await this.shopify.getOrdersById(relevantOrderIds);\n\n relevantOrders.forEach((order) => {\n const meta = this.generateMeta(order);\n this.$emit(order, meta);\n });\n },\n};\n\n\n<|start_filename|>components/twitch/actions/search-channels/search-channels.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Search Channels\",\n key: \"twitch-search-channels\",\n description: `Returns a list of channels (users who have streamed within the past 6 months)\n that match the query via channel name or description either entirely or partially. Results \n include both live and offline channels.`,\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of channels to return\",\n },\n query: {\n type: \"string\",\n label: \"Query\",\n description: \"The search query\",\n },\n liveOnly: {\n type: \"boolean\",\n label: \"Live Only\",\n description: \"Filter results for live streams only\",\n default: false,\n },\n },\n async run() {\n const params = {\n query: this.query,\n live_only: this.liveOnly,\n };\n const searchResults = await this.paginate(\n this.twitch.searchChannels.bind(this),\n params,\n this.max,\n );\n return await this.getPaginatedResults(searchResults);\n },\n};\n\n\n<|start_filename|>components/datadog/sources/payload-format.js<|end_filename|>\n/**\n * This object specifies the fields to include as part of every webhook call\n * payload, and their mappings to Datadog webhook variables.\n *\n * See https://docs.datadoghq.com/integrations/webhooks/#usage for further\n * details.\n */\nmodule.exports = {\n aggregKey: \"$AGGREG_KEY\",\n alertCycleKey: \"$ALERT_CYCLE_KEY\",\n alertId: \"$ALERT_ID\",\n alertMetric: \"$ALERT_METRIC\",\n alertPriority: \"$ALERT_PRIORITY\",\n alertQuery: \"$ALERT_QUERY\",\n alertScope: \"$ALERT_SCOPE\",\n alertStatus: \"$ALERT_STATUS\",\n alertTitle: \"$ALERT_TITLE\",\n alertTransition: \"$ALERT_TRANSITION\",\n alertType: \"$ALERT_TYPE\",\n date: \"$DATE\",\n email: \"$EMAIL\",\n eventMsg: \"$EVENT_MSG\",\n eventTitle: \"$EVENT_TITLE\",\n eventType: \"$EVENT_TYPE\",\n hostname: \"$HOSTNAME\",\n id: \"$ID\",\n lastUpdated: \"$LAST_UPDATED\",\n link: \"$LINK\",\n logsSample: \"$LOGS_SAMPLE\",\n metricNamespace: \"$METRIC_NAMESPACE\",\n orgId: \"$ORG_ID\",\n orgName: \"$ORG_NAME\",\n priority: \"$PRIORITY\",\n snapshot: \"$SNAPSHOT\",\n tags: \"$TAGS\",\n textOnlyMsg: \"$TEXT_ONLY_MSG\",\n user: \"$USER\",\n username: \"$USERNAME\",\n};\n\n\n<|start_filename|>components/pipedream/pipedream.app.js<|end_filename|>\n// Pipedream API app file\nconst axios = require(\"axios\");\nconst { convertArrayToCSV } = require(\"convert-array-to-csv\");\n\nconst PIPEDREAM_SQL_BASE_URL = \"https://rt.pipedream.com/sql\";\n\nmodule.exports = {\n type: \"app\",\n app: \"pipedream\",\n methods: {\n async _makeAPIRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers[\"Authorization\"] = `Bearer ${this.$auth.api_key}`;\n opts.headers[\"Content-Type\"] = \"application/json\";\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n const { path } = opts;\n delete opts.path;\n opts.url = `https://api.pipedream.com/v1${\n path[0] === \"/\" ? \"\" : \"/\"\n }${path}`;\n return await axios(opts);\n },\n async subscribe(emitter_id, listener_id, channel) {\n let params = {\n emitter_id,\n listener_id,\n };\n if (channel) {\n params.event_name = channel;\n }\n return await this._makeAPIRequest({\n method: \"POST\",\n path: \"/subscriptions\",\n params,\n });\n },\n async listEvents(dcID, event_name) {\n return (\n await this._makeAPIRequest({\n path: `/sources/${dcID}/event_summaries`,\n params: {\n event_name,\n },\n })\n ).data;\n },\n async deleteEvent(dcID, eventID, event_name) {\n return (\n await this._makeAPIRequest({\n method: \"DELETE\",\n path: `/sources/${dcID}/events`,\n params: {\n start_id: eventID,\n end_id: eventID,\n event_name,\n },\n })\n ).data;\n },\n // Runs a query againt the Pipedream SQL service\n // https://docs.pipedream.com/destinations/sql/\n async runSQLQuery(query, format) {\n const { data } = await axios({\n url: PIPEDREAM_SQL_BASE_URL,\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.$auth.api_key}`,\n },\n data: { query },\n });\n\n const { error, queryExecutionId, resultSet, resultsFilename } = data;\n\n if (error && error.toDisplay) {\n throw new Error(error.toDisplay);\n }\n\n // Parse raw results\n const results = {\n columnInfo: resultSet.ResultSetMetadata.ColumnInfo,\n queryExecutionId,\n csvLocation: `https://rt.pipedream.com/sql/csv/${resultsFilename}`,\n };\n\n let formattedResults = [];\n\n // We can return results as an object, CSV, or array (default)\n if (format === \"object\") {\n // The SQL service returns headers as the first row of results\n let headers = resultSet.Rows.shift();\n for (const row of resultSet.Rows) {\n let obj = {};\n for (let j = 0; j < row.Data.length; j++) {\n // Column name : row value\n obj[headers.Data[j].VarCharValue] = row.Data[j].VarCharValue;\n }\n formattedResults.push(obj);\n }\n } else {\n for (const row of resultSet.Rows) {\n formattedResults.push(row.Data.map((data) => data.VarCharValue));\n }\n }\n\n if (format === \"csv\") {\n formattedResults = convertArrayToCSV(formattedResults);\n }\n\n results.results = formattedResults;\n\n return results;\n },\n },\n};\n\n\n<|start_filename|>components/twilio/sources/common-polling.js<|end_filename|>\nconst twilio = require(\"../twilio.app.js\");\n\nmodule.exports = {\n props: {\n twilio,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n _getCreatedAfter() {\n return this.db.get(\"createdAfter\");\n },\n _setCreatedAfter(createdAfter) {\n this.db.set(\"createdAfter\", createdAfter);\n },\n emitEvent(result) {\n const meta = this.generateMeta(result);\n this.$emit(result, meta);\n },\n },\n async run(event) {\n let dateCreatedAfter = this._getCreatedAfter();\n const params = {\n dateCreatedAfter,\n };\n const results = await this.listResults(params);\n for (const result of results) {\n this.emitEvent(result);\n if (\n !dateCreatedAfter ||\n Date.parse(result.dateCreated) > Date.parse(dateCreatedAfter)\n )\n dateCreatedAfter = result.dateCreated;\n }\n this._setCreatedAfter(dateCreatedAfter);\n },\n};\n\n<|start_filename|>components/twitch/actions/common.js<|end_filename|>\nconst common = require(\"../sources/common.js\");\n\nmodule.exports = {\n ...common,\n methods: {\n ...common.methods,\n async getUserId() {\n const { data: authenticatedUserData } = await this.twitch.getUsers();\n const { id } = authenticatedUserData[0];\n return id;\n },\n async getPaginatedResults(paginated) {\n const results = [];\n for await (const result of paginated) {\n results.push(result);\n }\n return results;\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/sources/new-attendee-registered/new-attendee-registered.js<|end_filename|>\nconst common = require(\"../common/webhook.js\");\n\nmodule.exports = {\n ...common,\n key: \"eventbrite-new-attendee-registered\",\n name: \" Registered (Instant)\",\n description: \"Emits an event when an attendee registers for an event\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getActions() {\n return \"order.placed\";\n },\n async getData(order) {\n const { id: orderId, event_id: eventId } = order;\n const attendeeStream = await this.resourceStream(\n this.eventbrite.getOrderAttendees.bind(this),\n \"attendees\",\n orderId\n );\n const attendees = [];\n for await (const attendee of attendeeStream) {\n attendees.push(attendee);\n }\n const event = await this.eventbrite.getEvent(eventId, {\n expand: \"ticket_classes\",\n });\n return {\n order,\n attendees,\n event,\n };\n },\n generateMeta({ order }) {\n const { id, name: summary, created } = order;\n return {\n id,\n summary,\n ts: Date.parse(created),\n };\n },\n },\n};\n\n<|start_filename|>components/pipefy/sources/card-overdue/card-overdue.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n name: \"Card Overdue\",\n key: \"pipefy-card-overdue\",\n description: \"Emits an event each time a card becomes overdue in a Pipe.\",\n version: \"0.0.1\",\n methods: {\n isCardRelevant({ node, event }) {\n const { timestamp: eventTimestamp } = event;\n const eventDate = eventTimestamp * 1000;\n const { due_date: dueDateIso } = node;\n const dueDate = Date.parse(dueDateIso);\n return (\n dueDate < eventDate &&\n !node.done\n );\n },\n getMeta({ node, event }) {\n const {\n id,\n title: summary,\n due_date: dueDate,\n } = node;\n const { timestamp: eventTimestamp } = event;\n const ts = Date.parse(dueDate) || eventTimestamp;\n return {\n id,\n summary,\n ts,\n };\n }\n },\n};\n\n<|start_filename|>components/slack/actions/list_reminders/list_reminders.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-list-reminders\",\n name: \"List Reminders\",\n description: \"List all reminders for a given user\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n team_id: {\n propDefinition: [\n slack,\n \"team_id\",\n ],\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().reminders.list({\n team_id: this.team_id,\n });\n },\n};\n\n\n<|start_filename|>components/formstack/sources/new-form-submission/new-form-submission.js<|end_filename|>\nconst formstack = require(\"../../formstack.app.js\");\nconst get = require(\"lodash.get\");\n\nmodule.exports = {\n key: \"formstack-new-form-submission\",\n name: \"New Form Submission (Instant)\",\n description: \"Emits an event for each new form submission.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n formstack,\n db: \"$.service.db\",\n http: \"$.interface.http\",\n formId: { propDefinition: [formstack, \"formId\"] },\n },\n hooks: {\n async activate() {\n const { id } = await this.formstack.createHook({\n id: this.formId,\n url: this.http.endpoint,\n });\n this.db.set(\"hookId\", id);\n },\n async deactivate() {\n await this.formstack.deleteHook({\n hookId: this.db.get(\"hookId\"),\n });\n },\n },\n async run(event) {\n const body = get(event, \"body\");\n if (!body) {\n return;\n }\n\n // verify incoming request\n if (\n this.formstack.$auth.oauth_refresh_token !== get(body, \"HandshakeKey\")\n ) {\n console.log(\"HandshakeKey mismatch. Exiting.\");\n return;\n }\n\n const uniqueID = get(body, \"UniqueID\");\n if (!uniqueID) return;\n delete body.HandshakeKey;\n this.$emit(body, {\n id: body.UniqueID,\n summary: `New Form Submission ${body.UniqueID}`,\n ts: Date.now(),\n });\n },\n};\n\n<|start_filename|>components/twitch/actions/get-channel-information/get-channel-information.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Channel Information\",\n key: \"twitch-get-channel-information\",\n description: \"Retrieves information about a particular broadcaster's channel\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n broadcaster: {\n propDefinition: [\n common.props.twitch,\n \"broadcaster\",\n ],\n description: \"ID of the user/channel to get information about\",\n },\n },\n async run() {\n const params = {\n broadcaster_id: this.broadcaster,\n };\n return (await this.twitch.getChannelInformation(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/here/here.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"here\",\n propDefinitions: {\n zipCode: {\n type: \"integer\",\n label: \"ZIP code\",\n description:\n \"The ZIP code you'd like to pull weather stats for (only supported for locations in the United States)\",\n },\n },\n methods: {\n _apiUrl() {\n return \"https://weather.ls.hereapi.com/weather/1.0\";\n },\n _apiKey() {\n return this.$auth.apikey;\n },\n async returnReportForZIP(zipCode) {\n const baseUrl = this._apiUrl();\n return await require(\"@pipedreamhq/platform\").axios(this, {\n url: `${baseUrl}/report.json?apiKey=${this._apiKey()}&product=observation&zipcode=${zipCode}`,\n });\n },\n },\n};\n\n\n<|start_filename|>components/airtable/actions/list-records/list-records.js<|end_filename|>\nconst common = require(\"../common.js\");\nconst commonList = require(\"../common-list.js\");\n\nmodule.exports = {\n key: \"airtable-list-records\",\n name: \"List Records\",\n description: \"Retrieve records from a table with automatic pagination. Optionally sort and filter results.\",\n type: \"action\",\n version: \"0.1.0\",\n ...commonList,\n props: {\n ...common.props,\n ...commonList.props,\n },\n};\n\n\n<|start_filename|>components/textlocal/textlocal.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"textlocal\",\n methods: {\n _apiUrl() {\n return \"https://api.txtlocal.com\";\n },\n _apiKey() {\n return this.$auth.api_key;\n },\n _apiMessageHistoryUrl() {\n // API docs: https://api.txtlocal.com/docs/messagereporting/getapimessagehistory\n const baseUrl = this._apiUrl();\n return `${baseUrl}/get_history_api`;\n },\n _contactGroupsUrl() {\n // API docs: https://api.txtlocal.com/docs/contactmanagement/getgroups\n const baseUrl = this._apiUrl();\n return `${baseUrl}/get_groups`;\n },\n _contactsUrl() {\n // API docs: https://api.txtlocal.com/docs/contactmanagement/getcontacts\n const baseUrl = this._apiUrl();\n return `${baseUrl}/get_contacts`;\n },\n _baseRequestParams() {\n return {\n apikey: this._apiKey(),\n };\n },\n async _getApiMessageHistory({\n limit = 100,\n sortOrder = \"desc\",\n start = 0,\n }) {\n const url = this._apiMessageHistoryUrl();\n const params = {\n ...this._baseRequestParams(),\n limit,\n sort_order: sortOrder,\n start,\n };\n const { data } = await axios.get(url, { params });\n return data;\n },\n /**\n * Get the ID of the latest message sent via the [Send\n * SMS](https://api.txtlocal.com/docs/sendsms) API.\n *\n * @return {string} The message ID\n */\n async getLatestMessageId() {\n const { messages } = await this._getApiMessageHistory({\n limit: 1,\n });\n if (messages.length === 0) {\n console.log(\"No messages sent so far\");\n return;\n }\n\n const { id } = messages.shift();\n return id;\n },\n /**\n * This generator function scans the history of messages sent via the [Send\n * SMS](https://api.txtlocal.com/docs/sendsms) API and yields each message\n * separately.\n *\n * It accepts optional parameter `lowerBoundMessageId` that will stop the\n * scan whenever it reaches a message with ID equal to the provided value of\n * the parameter.\n *\n * @param {object} options Options to customize the operation\n * @param {string} options.lowerBoundMessageId The ID of the message at\n * which the scan should stop\n * @yield {object} The next message in the message history\n */\n async *scanApiMessageHistory({ lowerBoundMessageId }) {\n let start = 0;\n let prevTotal;\n do {\n const {\n messages,\n total,\n } = await this._getApiMessageHistory({\n start,\n });\n prevTotal = prevTotal ? prevTotal : total;\n\n for (const message of messages) {\n if (message.id === lowerBoundMessageId) {\n return;\n }\n\n yield message;\n }\n\n start += messages.length + (total - prevTotal);\n prevTotal = total;\n } while (start < prevTotal);\n },\n /**\n * Retrieves the list of Contact Groups in the user's account, as provided\n * by the [Get\n * Groups](https://api.txtlocal.com/docs/contactmanagement/getgroups) API.\n *\n * @return {object} The response of the call to the Get Groups API\n */\n async getContactGroups() {\n const url = this._contactGroupsUrl();\n const params = this._baseRequestParams();\n const { data } = await axios.get(url, { params });\n return data;\n },\n async _getContactsInGroup({\n groupId,\n limit = 100,\n start = 0,\n }) {\n const url = this._contactsUrl();\n const params = {\n ...this._baseRequestParams(),\n group_id: groupId,\n limit,\n start,\n };\n const { data } = await axios.get(url, { params });\n return data;\n },\n /**\n * This generator function scans a specific contact group and yields each\n * contact in such group separately.\n *\n * It requires a parameter `groupId` that identifies the contact group to\n * scan.\n *\n * @param {object} options Options to customize the operation\n * @param {string} options.groupId The ID of the contact group to scan for\n * contacts\n * @yield {object} The next contact in the contact group\n */\n async *scanContactGroup({ groupId }) {\n let start = 0;\n let prevNumContacts;\n do {\n const {\n contacts,\n num_contacts: numContacts,\n } = await this._getContactsInGroup({\n groupId,\n });\n prevNumContacts = prevNumContacts ? prevNumContacts : numContacts;\n\n for (const contact of contacts) {\n yield contact;\n }\n\n start += contacts.length + (numContacts - prevNumContacts);\n prevNumContacts = numContacts;\n } while (start < prevNumContacts);\n },\n },\n};\n\n\n<|start_filename|>components/twitch/actions/get-followers/get-followers.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Followers\",\n key: \"twitch-get-followers\",\n description: \"Retrieves a list of users who follow the specified user\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n user: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"User ID of the user to get followers of\",\n },\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of followers to return\",\n },\n },\n async run() {\n const params = {\n to_id: this.user,\n };\n // get the users who follow the specified user\n const follows = await this.paginate(\n this.twitch.getUserFollows.bind(this),\n params,\n this.max,\n );\n return await this.getPaginatedResults(follows);\n },\n};\n\n\n<|start_filename|>components/mysql/sources/new-table/new-table.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"mysql-new-table\",\n name: \"New Table\",\n description: \"Emits an event when a new table is added to a database\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n db: \"$.service.db\",\n },\n hooks: {\n async deploy() {\n const connection = await this.mysql.getConnection();\n const tables = await this.mysql.listTopTables(connection);\n this.iterateAndEmitEvents(tables);\n this._setLastResult(tables, \"CREATE_TIME\");\n await this.mysql.closeConnection(connection);\n },\n },\n methods: {\n ...common.methods,\n async listResults(connection) {\n const lastResult = this._getLastResult();\n const tables = await this.mysql.listBaseTables(connection, lastResult);\n this.iterateAndEmitEvents(tables);\n this._setLastResult(tables, \"CREATE_TIME\");\n },\n generateMeta({ TABLE_NAME: tableName, CREATE_TIME: createTime }) {\n return {\n id: tableName,\n summary: tableName,\n ts: Date.parse(createTime),\n };\n },\n },\n};\n\n<|start_filename|>components/shopify/sources/common/utils.js<|end_filename|>\nmodule.exports.dateToISOStringWithoutMs = (date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n};\n\n\n<|start_filename|>components/pipefy/pipefy.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"pipefy\",\n methods: {\n _getBaseUrl() {\n return \"https://app.pipefy.com\";\n },\n _getHeaders() {\n return {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.$auth.token}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n },\n async _makeRequest(data, endpoint) {\n const config = {\n method: \"POST\",\n url: `${this._getBaseUrl()}/${endpoint}`,\n headers: this._getHeaders(),\n data,\n };\n return (await axios(config)).data;\n },\n async _makeQueriesRequest(data = null) {\n return await this._makeRequest(data, \"queries\");\n },\n async _makeGraphQlRequest(data = null) {\n return await this._makeRequest(data, \"graphql\");\n },\n async createHook({ pipe_id, name, url, actions }) {\n const data = {\n query: `\n mutation { \n createWebhook(input: { \n pipe_id: ${pipe_id} \n name: \"${name}\" \n url: \"${url}\" \n actions: [\"${actions}\"] \n headers: \\\"{\\\\\\\"token\\\\\\\": \\\\\\\"${this.$auth.token}\\\\\\\"}\\\" \n }) \n { \n webhook { \n id \n name \n } \n } \n }\n `,\n };\n return (await this._makeQueriesRequest(data)).data.createWebhook;\n },\n async deleteHook(hookId) {\n const data = {\n query: `\n mutation { \n deleteWebhook(input: { \n id: ${hookId} \n }) \n { \n success \n } \n }\n `,\n };\n await this._makeQueriesRequest(data);\n },\n async getCard(id) {\n const data = {\n query: `\n { \n card(id: ${id}) { \n id \n title \n url \n comments{text} \n createdAt \n createdBy{name} \n due_date \n } \n }\n `,\n };\n return await this._makeGraphQlRequest(data);\n },\n async listCards(pipe_id) {\n const data = {\n query: `\n { \n cards(pipe_id: ${pipe_id}, first: 100) { \n edges { \n node { \n id \n title \n assignees { \n id \n } \n comments { \n text \n } \n comments_count \n current_phase { \n name \n id \n } \n done \n late \n expired \n due_date \n fields { \n name \n value \n } \n labels { \n name \n } \n phases_history { \n phase { \n name \n } \n firstTimeIn \n lastTimeOut \n } \n url \n } \n } \n } \n }\n `,\n };\n return (await this._makeQueriesRequest(data)).data.cards;\n },\n },\n};\n\n<|start_filename|>components/snowflake/sources/query-results/query-results.js<|end_filename|>\nconst { v4: uuidv4 } = require(\"uuid\");\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"snowflake-query-results\",\n name: \"Query Results\",\n description: \"Emit an event with the results of an arbitrary query\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n sqlQuery: {\n type: \"string\",\n label: \"SQL Query\",\n description: \"Your SQL query\",\n },\n dedupeKey: {\n type: \"string\",\n label: \"De-duplication Key\",\n description: \"The name of a column in the table to use for de-duplication\",\n optional: true,\n },\n },\n methods: {\n ...common.methods,\n generateMeta(data) {\n const {\n row: {\n [this.dedupeKey]: id = uuidv4(),\n },\n timestamp: ts,\n } = data;\n const summary = `New event (ID: ${id})`;\n return {\n id,\n summary,\n ts,\n };\n },\n generateMetaForCollection(data) {\n const {\n timestamp: ts,\n } = data;\n const id = uuidv4();\n const summary = `New event (ID: ${id})`;\n return {\n id,\n summary,\n ts,\n };\n },\n getStatement() {\n return {\n sqlText: this.sqlQuery,\n };\n },\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/new-campaign-unsubscribe/new-campaign-unsubscribe.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-campaign.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Campaign Unsubscribe (Instant)\",\n key: \"activecampaign-new-campaign-unsubscribe\",\n description:\n \"Emits an event when a contact unsubscribes as a result of a campaign email sent to them.\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"unsubscribe\"];\n },\n },\n};\n\n<|start_filename|>components/slack/actions/find-message/find-message.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-find-message\",\n name: \"Find Message\",\n description: \"Find a Slack message\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n query: {\n propDefinition: [\n slack,\n \"query\",\n ],\n },\n count: {\n propDefinition: [\n slack,\n \"count\",\n ],\n optional: true,\n },\n team_id: {\n propDefinition: [\n slack,\n \"team_id\",\n ],\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().search.messages({\n query: this.query,\n count: this.count,\n });\n },\n};\n\n\n<|start_filename|>components/mysql/sources/new-or-updated-row/new-or-updated-row.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"mysql-new-or-updated-row\",\n name: \"New or Updated Row\",\n description: \"Emits an event when you add or modify a new row in a table\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n db: \"$.service.db\",\n table: { propDefinition: [common.props.mysql, \"table\"] },\n column: {\n propDefinition: [\n common.props.mysql,\n \"column\",\n (c) => ({ table: c.table }),\n ],\n label: \"Order By\",\n description:\n \"A datetime column, such as 'date_updated' or 'last_modified' that is set to the current datetime when a row is updated.\",\n },\n },\n hooks: {\n async deploy() {\n const connection = await this.mysql.getConnection();\n await this.listTopRows(connection, this.column);\n await this.mysql.closeConnection(connection);\n },\n },\n methods: {\n ...common.methods,\n async listResults(connection) {\n await this.listRowResults(connection, this.column);\n },\n generateMeta(row) {\n return {\n id: JSON.stringify(row),\n summary: `New Row Added/Updated ${row[this.column]}`,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/formstack/sources/new-form/new-form.js<|end_filename|>\nconst formstack = require(\"../../formstack.app.js\");\n\nmodule.exports = {\n key: \"formstack-new-form\",\n name: \"New Form\",\n description: \"Emits an event for each new form added.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n formstack,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run() {\n const largestPreviousFormId = this.db.get(\"largestPreviousFormId\") || 0;\n let largestFormId = 0;\n let forms = [];\n let page = 1;\n const per_page = 100;\n let total = per_page;\n while (total === per_page) {\n const results = await this.formstack.getForms(page, per_page);\n total = results.length;\n forms = forms.concat(results);\n page++;\n }\n for (const form of forms) {\n if (form.id > largestPreviousFormId) {\n this.$emit(form, {\n id: form.id,\n summary: form.name,\n ts: Date.now(),\n });\n largestFormId = form.id;\n }\n }\n if (largestFormId > 0) this.db.set(\"largestPreviousFormId\", largestFormId);\n },\n};\n\n<|start_filename|>components/twist/event-types.js<|end_filename|>\n// The Twist event types that can be subscribed to via webhook.\n// The lines commented out are for event types listed in Twist's documentation,\n// but not yet available. Coming Soon!\n\nmodule.exports = [\n { label: \"Workspace Added\", value: `workspace_added` },\n { label: \"Workspace Updated\", value: `workspace_updated` },\n // { label: \"Workspace Deleted\", value: `workspace_deleted` },\n { label: \"Workspace User Added\", value: `workspace_user_added` },\n { label: \"Workspace User Updated\", value: `workspace_user_updated` },\n { label: \"Workspace User Removed\", value: `workspace_user_removed` },\n { label: \"Channel Added\", value: `channel_added` },\n { label: \"Channel Updated\", value: `channel_updated` },\n { label: \"Channel Deleted\", value: `channel_deleted` },\n { label: \"Channel User Added\", value: `channel_user_added` },\n // { label: \"Channel User Updated\", value: `channel_user_updated` },\n { label: \"Channel User Removed\", value: `channel_user_removed` },\n { label: \"Thread Added\", value: `thread_added` },\n { label: \"Thread Updated\", value: `thread_updated` },\n { label: \"Thread Deleted\", value: `thread_deleted` },\n { label: \"Comment Added\", value: `comment_added` },\n { label: \"Comment Updated\", value: `comment_updated` },\n { label: \"Comment Deleted\", value: `comment_deleted` },\n { label: \"Message Added\", value: `message_added` },\n { label: \"Message Updated\", value: `message_updated` },\n // { label: \"Message Deleted\", value: `message_deleted` },\n // { label: \"Group Added\", value: `group_added` },\n // { label: \"Group Updated\", value: `group_updated` },\n // { label: \"Group Deleted\", value: `group_deleted` },\n // { label: \"Group User Added\", value: `group_user_added` },\n // { label: \"Group User Removed\", value: `group_user_removed` },\n];\n\n<|start_filename|>components/twitch/actions/get-stream-by-user/get-stream-by-user.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Stream By User\",\n key: \"twitch-get-stream-by-user\",\n description: \"Gets stream information (the stream object) for a specified user\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n user: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"User ID of the user whose stream to get information about\",\n },\n },\n async run() {\n // get live streams for the specified streamer\n const streams = await this.paginate(this.twitch.getStreams.bind(this), {\n user_id: this.user,\n });\n return await this.getPaginatedResults(streams);\n },\n};\n\n\n<|start_filename|>components/faunadb/faunadb.app.js<|end_filename|>\n// FaunaDB app file\nconst faunadb = require(\"faunadb\");\nconst q = faunadb.query;\n\nmodule.exports = {\n type: \"app\",\n app: \"faunadb\",\n propDefinitions: {\n collection: {\n type: \"string\",\n label: \"Collection\",\n description: \"The collection you'd like to watch for changes\",\n async options() {\n return await this.getCollections();\n },\n },\n },\n methods: {\n // Fetches events (changes) for all documents in a collection\n // made after a specific epoch timestamp\n getClient() {\n return new faunadb.Client({ secret: this.$auth.secret });\n },\n async getCollections() {\n const client = this.getClient();\n\n const collections = [];\n const collectionsPaginator = await client.paginate(q.Collections());\n\n await collectionsPaginator.each((page) => {\n for (const collection of page) {\n collections.push({\n label: collection.id,\n value: collection.id,\n });\n }\n });\n\n return collections;\n },\n async getEventsInCollectionAfterTs(collection, after) {\n const client = this.getClient();\n\n // Fetch pages of all changes (events) for a particular collection\n // since the given timestamp cursor. See docs on Events / Pagination\n // https://docs.fauna.com/fauna/current/api/fql/functions/events\n // https://docs.fauna.com/fauna/current/api/fql/functions/paginate\n const paginationHelper = await client.paginate(\n q.Documents(q.Collection(collection)),\n { after, events: true }\n );\n\n const events = [];\n await paginationHelper.each((page) => {\n for (const event of page) {\n events.push(event);\n }\n });\n\n return events;\n },\n },\n};\n\n\n<|start_filename|>components/calendly/sources/invitee-canceled/invitee-canceled.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n key: \"calendly-invitee-cancelled\",\n name: \"Invitee Cancelled (Instant)\",\n description: \"Emits an event when an invitee cancels a scheduled event\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"invitee.canceled\"];\n },\n generateMeta(body) {\n return this.generateInviteeMeta(body);\n },\n },\n};\n\n<|start_filename|>components/google_drive/utils.js<|end_filename|>\nconst { MY_DRIVE_VALUE } = require(\"./constants\");\n\n/**\n * Returns whether the specified drive ID corresponds to the authenticated\n * user's My Drive or not\n *\n * @param {String} drive the ID value of a Google Drive\n * @returns `true` only when the specified drive is the user's 'My Drive'\n */\nfunction isMyDrive(drive) {\n return drive === MY_DRIVE_VALUE;\n}\n\n/**\n * Returns a valid Google Drive ID to be used in Google Drive API calls\n *\n * @param {String} drive the ID value of a Google Drive, as provided by the\n * `drive` prop definition of this app\n * @returns the proper Google Drive ID to be used in Google Drive API calls\n */\nfunction getDriveId(drive) {\n return isMyDrive(drive)\n ? null\n : drive;\n}\n\nmodule.exports = {\n MY_DRIVE_VALUE,\n isMyDrive,\n getDriveId,\n};\n\n\n<|start_filename|>components/uservoice/uservoice.app.js<|end_filename|>\n/* \nAPI docs: https://developer.uservoice.com/docs/api/v2/reference/\nGetting Started Guide: https://developer.uservoice.com/docs/api/v2/getting-started/\n*/\n\nmodule.exports = {\n type: \"app\",\n app: \"uservoice\",\n methods: {\n _accessToken() {\n return this.$auth.access_token;\n },\n _apiUrl() {\n return `https://${this._subdomain()}.uservoice.com/api/v2`;\n },\n async _makeRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers.authorization = `Bearer ${this._accessToken()}`;\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n const { path } = opts;\n delete opts.path;\n opts.url = `${this._apiUrl()}${path[0] === \"/\" ? \"\" : \"/\"}${path}`;\n return await require(\"@pipedreamhq/platform\").axios(this, opts);\n },\n _subdomain() {\n return this.$auth.subdomain;\n },\n // https://developer.uservoice.com/docs/api/v2/reference/#operation/ListNpsRatings\n async listNPSRatings({ updated_after, numSampleResults }) {\n const npsRatings = [];\n let cursor;\n do {\n const { nps_ratings, pagination } = await this._makeRequest({\n path: \"/admin/nps_ratings\",\n params: {\n per_page: 100, // max allowed by API\n cursor,\n updated_after,\n },\n });\n npsRatings.push(...(nps_ratings || []));\n // When retrieving sample data, return early once we've fetched numSampleResults\n if (numSampleResults && npsRatings.length >= numSampleResults) {\n return npsRatings.slice(0, numSampleResults);\n }\n cursor = pagination.cursor;\n } while (cursor);\n\n // Calculate the ISO 8601 timestamp of the most recent record, if available\n let maxUpdatedAt;\n if (npsRatings.length) {\n const dates = npsRatings.map((r) => new Date(r.updated_at));\n maxUpdatedAt = new Date(Math.max.apply(null, dates)).toISOString();\n }\n\n return { npsRatings, maxUpdatedAt };\n },\n },\n};\n\n\n<|start_filename|>components/mysql/sources/common.js<|end_filename|>\nconst mysql = require(\"../mysql.app.js\");\n\nmodule.exports = {\n props: {\n mysql,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n _getLastResult() {\n return this.db.get(\"lastResult\");\n },\n /**\n * Sets lastResult in db. Since results are ordered by the specified column, we can assume the maximum\n * result for that column is in the first row returned.\n * @param {object} rows - The rows returned to be emitted.\n * @param {string} column - Name of the table column to order by\n */\n _setLastResult(rows, column) {\n if (rows.length) this.db.set(\"lastResult\", rows[0][column]);\n },\n iterateAndEmitEvents(results) {\n for (const result of results) {\n const meta = this.generateMeta(result);\n this.$emit(result, meta);\n }\n },\n /**\n * Used by components that call listRows(). Gets lastResult, gets rows, sets lastResult, and returns rows.\n * @param {object} connection - The database connection.\n * @param {string} column - Name of the table column to order by\n */\n async listRowResults(connection, column) {\n let lastResult = this._getLastResult();\n const rows = await this.mysql.listRows(\n connection,\n this.table,\n column,\n lastResult\n );\n this._setLastResult(rows, column);\n this.iterateAndEmitEvents(rows);\n },\n async listTopRows(connection, column, maxCount = 10) {\n const rows = await this.mysql.listMaxRows(\n connection,\n this.table,\n column,\n maxCount\n );\n this._setLastResult(rows, column);\n this.iterateAndEmitEvents(rows);\n },\n },\n async run(event) {\n const connection = await this.mysql.getConnection();\n\n try {\n await this.listResults(connection);\n } catch (err) {\n console.log(err);\n } finally {\n await this.mysql.closeConnection(connection);\n }\n },\n};\n\n<|start_filename|>components/github/sources/new-security-alert/new-security-alert.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n key: \"github-new-security-alert\",\n name: \"New Security Alert\",\n description:\n \"Emit new events when GitHub discovers a security vulnerability in one of your repositories\",\n version: \"0.0.4\",\n type: \"source\",\n dedupe: \"greatest\",\n methods: {\n ...common.methods,\n generateMeta(data) {\n const ts = new Date(data.updated_at).getTime();\n return {\n id: data.updated_at,\n summary: data.subject.title,\n ts,\n };\n },\n },\n async run() {\n const since = this.db.get(\"since\");\n\n const notifications = await this.getFilteredNotifications(\n {\n participating: false,\n since,\n },\n \"security_alert\",\n );\n\n let maxDate = since;\n for (const notification of notifications) {\n if (!maxDate || new Date(notification.updated_at) > new Date(maxDate)) {\n maxDate = notification.updated_at;\n }\n const meta = this.generateMeta(notification);\n this.$emit(notification, meta);\n }\n\n if (maxDate !== since) {\n this.db.set(\"since\", maxDate);\n }\n },\n};\n\n\n<|start_filename|>components/threads/actions/delete-thread/delete-thread.js<|end_filename|>\nconst threads = require(\"../../threads.app.js\");\n\nmodule.exports = {\n key: \"threads-delete-thread\",\n name: \"Delete a Thread\",\n description: \"Delete a thread\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n threads,\n threadID: {\n propDefinition: [\n threads,\n \"threadID\",\n ],\n },\n },\n async run() {\n return await this.threads.deleteThread({\n threadID: this.threadID,\n });\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-contact-in-list/new-contact-in-list.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-contact-in-list\",\n name: \"New Contact in List\",\n description: \"Emits an event for each new contact in a list.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n lists: { propDefinition: [common.props.hubspot, \"lists\"] },\n },\n methods: {\n ...common.methods,\n generateMeta(contact, list) {\n const { vid, properties } = contact;\n const { value, label } = list;\n return {\n id: `${vid}${value}`,\n summary: `${properties.firstname.value} ${properties.lastname.value} added to ${label}`,\n ts: Date.now(),\n };\n },\n async emitEvent(contact, properties, list) {\n const contactInfo = await this.hubspot.getContact(\n contact.vid,\n properties\n );\n const meta = this.generateMeta(contact, list);\n this.$emit({ contact, contactInfo }, meta);\n },\n },\n async run(event) {\n const properties = this.db.get(\"properties\");\n for (let list of this.lists) {\n list = JSON.parse(list);\n const params = {\n count: 100,\n };\n let hasMore = true;\n while (hasMore) {\n const results = await this.hubspot.getListContacts(params, list.value);\n hasMore = results[\"has-more\"];\n if (hasMore) params.vidOffset = results[\"vid-offset\"];\n for (const contact of results.contacts) {\n await this.emitEvent(contact, properties, list);\n }\n }\n }\n },\n};\n\n<|start_filename|>components/clickup/actions/common.js<|end_filename|>\nconst clickup = require(\"../clickup.app.js\");\n\nmodule.exports = {\n props: {\n clickup,\n workspace: {\n propDefinition: [\n clickup,\n \"workspace\",\n ],\n },\n space: {\n propDefinition: [\n clickup,\n \"space\",\n (c) => ({\n workspace: c.workspace,\n }),\n ],\n },\n folder: {\n propDefinition: [\n clickup,\n \"folder\",\n (c) => ({\n space: c.space,\n }),\n ],\n },\n priority: {\n propDefinition: [\n clickup,\n \"priority\",\n ],\n },\n },\n};\n\n\n<|start_filename|>components/google_drive/actions/language-codes.js<|end_filename|>\nmodule.exports = [\n {\n label: \"Undetected\",\n value: \"und\",\n },\n {\n label: \"Abkhazian\",\n value: \"ab\",\n },\n {\n label: \"Afar\",\n value: \"aa\",\n },\n {\n label: \"Afrikaans\",\n value: \"af\",\n },\n {\n label: \"Akan\",\n value: \"ak\",\n },\n {\n label: \"Albanian\",\n value: \"sq\",\n },\n {\n label: \"Amharic\",\n value: \"am\",\n },\n {\n label: \"Arabic\",\n value: \"ar\",\n },\n {\n label: \"Aragonese\",\n value: \"an\",\n },\n {\n label: \"Armenian\",\n value: \"hy\",\n },\n {\n label: \"Assamese\",\n value: \"as\",\n },\n {\n label: \"Avaric\",\n value: \"av\",\n },\n {\n label: \"Avestan\",\n value: \"ae\",\n },\n {\n label: \"Aymara\",\n value: \"ay\",\n },\n {\n label: \"Azerbaijani\",\n value: \"az\",\n },\n {\n label: \"Bambara\",\n value: \"bm\",\n },\n {\n label: \"Bashkir\",\n value: \"ba\",\n },\n {\n label: \"Basque\",\n value: \"eu\",\n },\n {\n label: \"Belarusian\",\n value: \"be\",\n },\n {\n label: \"Bengali\",\n value: \"bn\",\n },\n {\n label: \"Bihari languages\",\n value: \"bh\",\n },\n {\n label: \"Bislama\",\n value: \"bi\",\n },\n {\n label: \"Bokmål, Norwegian; Norwegian Bokmål\",\n value: \"nb\",\n },\n {\n label: \"Bosnian\",\n value: \"bs\",\n },\n {\n label: \"Breton\",\n value: \"br\",\n },\n {\n label: \"Bulgarian\",\n value: \"bg\",\n },\n {\n label: \"Burmese\",\n value: \"my\",\n },\n {\n label: \"Catalan; Valencian\",\n value: \"ca\",\n },\n {\n label: \"Central Khmer\",\n value: \"km\",\n },\n {\n label: \"Chamorro\",\n value: \"ch\",\n },\n {\n label: \"Chechen\",\n value: \"ce\",\n },\n {\n label: \"Chichewa; Chewa; Nyanja\",\n value: \"ny\",\n },\n {\n label: \"Chinese\",\n value: \"zh\",\n },\n {\n label: \"Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic\",\n value: \"cu\",\n },\n {\n label: \"Chuvash\",\n value: \"cv\",\n },\n {\n label: \"Cornish\",\n value: \"kw\",\n },\n {\n label: \"Corsican\",\n value: \"co\",\n },\n {\n label: \"Cree\",\n value: \"cr\",\n },\n {\n label: \"Croatian\",\n value: \"hr\",\n },\n {\n label: \"Czech\",\n value: \"cs\",\n },\n {\n label: \"Danish\",\n value: \"da\",\n },\n {\n label: \"Divehi; Dhivehi; Maldivian\",\n value: \"dv\",\n },\n {\n label: \"Dutch; Flemish\",\n value: \"nl\",\n },\n {\n label: \"Dzongkha\",\n value: \"dz\",\n },\n {\n label: \"English\",\n value: \"en\",\n },\n {\n label: \"Esperanto\",\n value: \"eo\",\n },\n {\n label: \"Estonian\",\n value: \"et\",\n },\n {\n label: \"Ewe\",\n value: \"ee\",\n },\n {\n label: \"Faroese\",\n value: \"fo\",\n },\n {\n label: \"Fijian\",\n value: \"fj\",\n },\n {\n label: \"Finnish\",\n value: \"fi\",\n },\n {\n label: \"French\",\n value: \"fr\",\n },\n {\n label: \"Fulah\",\n value: \"ff\",\n },\n {\n label: \"Gaelic; Scottish Gaelic\",\n value: \"gd\",\n },\n {\n label: \"Galician\",\n value: \"gl\",\n },\n {\n label: \"Ganda\",\n value: \"lg\",\n },\n {\n label: \"Georgian\",\n value: \"ka\",\n },\n {\n label: \"German\",\n value: \"de\",\n },\n {\n label: \"Greek, Modern (1453-)\",\n value: \"el\",\n },\n {\n label: \"Guarani\",\n value: \"gn\",\n },\n {\n label: \"Gujarati\",\n value: \"gu\",\n },\n {\n label: \"Haitian; Haitian Creole\",\n value: \"ht\",\n },\n {\n label: \"Hausa\",\n value: \"ha\",\n },\n {\n label: \"Hebrew\",\n value: \"he\",\n },\n {\n label: \"Herero\",\n value: \"hz\",\n },\n {\n label: \"Hindi\",\n value: \"hi\",\n },\n {\n label: \"\",\n value: \"ho\",\n },\n {\n label: \"Hungarian\",\n value: \"hu\",\n },\n {\n label: \"Icelandic\",\n value: \"is\",\n },\n {\n label: \"Ido\",\n value: \"io\",\n },\n {\n label: \"Igbo\",\n value: \"ig\",\n },\n {\n label: \"Indonesian\",\n value: \"id\",\n },\n {\n label: \"Interlingua (International Auxiliary Language Association)\",\n value: \"ia\",\n },\n {\n label: \"Interlingue; Occidental\",\n value: \"ie\",\n },\n {\n label: \"Inuktitut\",\n value: \"iu\",\n },\n {\n label: \"Inupiaq\",\n value: \"ik\",\n },\n {\n label: \"Irish\",\n value: \"ga\",\n },\n {\n label: \"Italian\",\n value: \"it\",\n },\n {\n label: \"Japanese\",\n value: \"ja\",\n },\n {\n label: \"Javanese\",\n value: \"jv\",\n },\n {\n label: \"Kalaallisut; Greenlandic\",\n value: \"kl\",\n },\n {\n label: \"Kannada\",\n value: \"kn\",\n },\n {\n label: \"Kanuri\",\n value: \"kr\",\n },\n {\n label: \"Kashmiri\",\n value: \"ks\",\n },\n {\n label: \"Kazakh\",\n value: \"kk\",\n },\n {\n label: \"Kikuyu; Gikuyu\",\n value: \"ki\",\n },\n {\n label: \"Kinyarwanda\",\n value: \"rw\",\n },\n {\n label: \"Kirghiz; Kyrgyz\",\n value: \"ky\",\n },\n {\n label: \"Komi\",\n value: \"kv\",\n },\n {\n label: \"Kongo\",\n value: \"kg\",\n },\n {\n label: \"Korean\",\n value: \"ko\",\n },\n {\n label: \"Kuanyama; Kwanyama\",\n value: \"kj\",\n },\n {\n label: \"Kurdish\",\n value: \"ku\",\n },\n {\n label: \"Lao\",\n value: \"lo\",\n },\n {\n label: \"Latin\",\n value: \"la\",\n },\n {\n label: \"Latvian\",\n value: \"lv\",\n },\n {\n label: \"Limburgan; Limburger; Limburgish\",\n value: \"li\",\n },\n {\n label: \"Lingala\",\n value: \"ln\",\n },\n {\n label: \"Lithuanian\",\n value: \"lt\",\n },\n {\n label: \"Luba-Katanga\",\n value: \"lu\",\n },\n {\n label: \"Luxembourgish; Letzeburgesch\",\n value: \"lb\",\n },\n {\n label: \"Macedonian\",\n value: \"mk\",\n },\n {\n label: \"Malagasy\",\n value: \"mg\",\n },\n {\n label: \"Malay\",\n value: \"ms\",\n },\n {\n label: \"Malayalam\",\n value: \"ml\",\n },\n {\n label: \"Maltese\",\n value: \"mt\",\n },\n {\n label: \"Manx\",\n value: \"gv\",\n },\n {\n label: \"Maori\",\n value: \"mi\",\n },\n {\n label: \"Marathi\",\n value: \"mr\",\n },\n {\n label: \"Marshallese\",\n value: \"mh\",\n },\n {\n label: \"Mongolian\",\n value: \"mn\",\n },\n {\n label: \"Nauru\",\n value: \"na\",\n },\n {\n label: \"Navajo; Navaho\",\n value: \"nv\",\n },\n {\n label: \"Ndebele, North; North Ndebele\",\n value: \"nd\",\n },\n {\n label: \"Ndebele, South; South Ndebele\",\n value: \"nr\",\n },\n {\n label: \"Ndonga\",\n value: \"ng\",\n },\n {\n label: \"Nepali\",\n value: \"ne\",\n },\n {\n label: \"Northern Sami\",\n value: \"se\",\n },\n {\n label: \"Norwegian\",\n value: \"no\",\n },\n {\n label: \"Norwegian Nynorsk; Nynorsk, Norwegian\",\n value: \"nn\",\n },\n {\n label: \"Occitan (post 1500)\",\n value: \"oc\",\n },\n {\n label: \"Ojibwa\",\n value: \"oj\",\n },\n {\n label: \"Oriya\",\n value: \"or\",\n },\n {\n label: \"Oromo\",\n value: \"om\",\n },\n {\n label: \"Ossetian; Ossetic\",\n value: \"os\",\n },\n {\n label: \"Pali\",\n value: \"pi\",\n },\n {\n label: \"Panjabi; Punjabi\",\n value: \"pa\",\n },\n {\n label: \"Persian\",\n value: \"fa\",\n },\n {\n label: \"Polish\",\n value: \"pl\",\n },\n {\n label: \"Portuguese\",\n value: \"pt\",\n },\n {\n label: \"Pushto; Pashto\",\n value: \"ps\",\n },\n {\n label: \"Quechua\",\n value: \"qu\",\n },\n {\n label: \"Romanian; Moldavian; Moldovan\",\n value: \"ro\",\n },\n {\n label: \"Romansh\",\n value: \"rm\",\n },\n {\n label: \"Rundi\",\n value: \"rn\",\n },\n {\n label: \"Russian\",\n value: \"ru\",\n },\n {\n label: \"Samoan\",\n value: \"sm\",\n },\n {\n label: \"Sango\",\n value: \"sg\",\n },\n {\n label: \"Sanskrit\",\n value: \"sa\",\n },\n {\n label: \"Sardinian\",\n value: \"sc\",\n },\n {\n label: \"Serbian\",\n value: \"sr\",\n },\n {\n label: \"Shona\",\n value: \"sn\",\n },\n {\n label: \"; Nuosu\",\n value: \"ii\",\n },\n {\n label: \"Sindhi\",\n value: \"sd\",\n },\n {\n label: \"Sinhala; Sinhalese\",\n value: \"si\",\n },\n {\n label: \"Slovak\",\n value: \"sk\",\n },\n {\n label: \"Slovenian\",\n value: \"sl\",\n },\n {\n label: \"Somali\",\n value: \"so\",\n },\n {\n label: \"Sotho, Southern\",\n value: \"st\",\n },\n {\n label: \"Spanish; Castilian\",\n value: \"es\",\n },\n {\n label: \"Sundanese\",\n value: \"su\",\n },\n {\n label: \"Swahili\",\n value: \"sw\",\n },\n {\n label: \"Swati\",\n value: \"ss\",\n },\n {\n label: \"Swedish\",\n value: \"sv\",\n },\n {\n label: \"Tagalog\",\n value: \"tl\",\n },\n {\n label: \"Tahitian\",\n value: \"ty\",\n },\n {\n label: \"Tajik\",\n value: \"tg\",\n },\n {\n label: \"Tamil\",\n value: \"ta\",\n },\n {\n label: \"Tatar\",\n value: \"tt\",\n },\n {\n label: \"Telugu\",\n value: \"te\",\n },\n {\n label: \"Thai\",\n value: \"th\",\n },\n {\n label: \"Tibetan\",\n value: \"bo\",\n },\n {\n label: \"Tigrinya\",\n value: \"ti\",\n },\n {\n label: \"Tonga (Tonga Islands)\",\n value: \"to\",\n },\n {\n label: \"Tsonga\",\n value: \"ts\",\n },\n {\n label: \"Tswana\",\n value: \"tn\",\n },\n {\n label: \"Turkish\",\n value: \"tr\",\n },\n {\n label: \"Turkmen\",\n value: \"tk\",\n },\n {\n label: \"Twi\",\n value: \"tw\",\n },\n {\n label: \"Uighur; Uyghur\",\n value: \"ug\",\n },\n {\n label: \"Ukrainian\",\n value: \"uk\",\n },\n {\n label: \"Urdu\",\n value: \"ur\",\n },\n {\n label: \"Uzbek\",\n value: \"uz\",\n },\n {\n label: \"Venda\",\n value: \"ve\",\n },\n {\n label: \"Vietnamese\",\n value: \"vi\",\n },\n {\n label: \"Volapük\",\n value: \"vo\",\n },\n {\n label: \"Walloon\",\n value: \"wa\",\n },\n {\n label: \"Welsh\",\n value: \"cy\",\n },\n {\n label: \"Western Frisian\",\n value: \"fy\",\n },\n {\n label: \"Wolof\",\n value: \"wo\",\n },\n {\n label: \"Xhosa\",\n value: \"xh\",\n },\n {\n label: \"Yiddish\",\n value: \"yi\",\n },\n {\n label: \"Yoruba\",\n value: \"yo\",\n },\n {\n label: \"Zhuang; Chuang\",\n value: \"za\",\n },\n {\n label: \"Zulu\",\n value: \"zu\",\n },\n];\n\n\n<|start_filename|>components/textlocal/sources/new-contact/new-contact.js<|end_filename|>\nconst common = require(\"../common/timer-based\");\n\nmodule.exports = {\n ...common,\n key: \"textlocal-new-contact\",\n name: \"New Contact\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n groupId: {\n type: \"string\",\n label: \"Contact Group\",\n description: \"The contact group to monitor for new contacts\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return [];\n }\n\n const { groups } = await this.textlocal.getContactGroups();\n const options = groups.map((group) => ({\n label: group.name,\n value: group.id,\n }));\n return {\n options,\n };\n },\n },\n },\n hooks: {\n ...common.hooks,\n deactivate() {\n this.db.set(\"isInitialized\", false);\n },\n },\n methods: {\n ...common.methods,\n _isContactProcessed(contact) {\n const { number } = contact;\n return Boolean(this.db.get(number));\n },\n _markContactAsProcessed(contact) {\n const { number } = contact;\n this.db.set(number, true);\n },\n async takeContactGroupSnapshot() {\n const contactScan = await this.textlocal.scanContactGroup({\n groupId: this.groupId,\n });\n\n for await (const contact of contactScan) {\n this._markContactAsProcessed(contact);\n }\n },\n generateMeta({\n contact,\n ts,\n }) {\n const {\n number,\n first_name: firstName,\n last_name: lastName,\n } = contact;\n const maskedName = this.getMaskedName({\n firstName,\n lastName,\n });\n const maskedNumber = this.getMaskedNumber(number);\n const summary = `New contact: ${maskedName} (${maskedNumber})`;\n return {\n id: number,\n summary,\n ts,\n };\n },\n async processEvent(event) {\n const isInitialized = this.db.get(\"isInitialized\");\n if (!isInitialized) {\n await this.takeContactGroupSnapshot();\n this.db.set(\"isInitialized\", true);\n return;\n }\n\n const { timestamp: ts } = event;\n const contactScan = await this.textlocal.scanContactGroup({\n groupId: this.groupId,\n });\n\n for await (const contact of contactScan) {\n if (this._isContactProcessed(contact)) {\n continue;\n }\n\n const meta = this.generateMeta({\n contact,\n ts,\n });\n this.$emit(contact, meta);\n this._markContactAsProcessed(contact);\n }\n },\n },\n};\n\n\n<|start_filename|>components/ahrefs/ahrefs.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"ahrefs\",\n propDefinitions: {\n limit: {\n type: \"integer\",\n description: \"Number of results to return.\",\n default: 1000,\n optional: true,\n },\n mode: {\n type: \"string\",\n description: \"Select a mode of operation (defaults to `Domain`).\",\n options: [\n { label: 'Exact', value: 'exact' },\n { label: 'Domain', value: 'domain' }, \n { label: 'Subdomain', value: 'subdomains' },\n { label: 'Prefix', value: 'prefix' },\n ],\n default: 'domain',\n optional: true,\n },\n target: {\n type: \"string\",\n description: \"Enter a domain or URL.\",\n },\n }\n}\n\n\n<|start_filename|>components/bitbucket/sources/new-repository/new-repository.js<|end_filename|>\nconst common = require(\"../../common\");\nconst watchWorkspace = require(\"../new-workspace-event/new-workspace-event\");\n\nconst EVENT_SOURCE_NAME = \"New Repository (Instant)\";\n\nmodule.exports = {\n ...watchWorkspace,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-repository\",\n description: \"Emits an event when a repository is created.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n },\n methods: {\n ...watchWorkspace.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return [\n \"repo:created\",\n ];\n },\n generateMeta(data) {\n const { headers, body } = data;\n const {\n \"x-request-uuid\": id,\n \"x-event-time\": eventDate,\n } = headers;\n const {\n full_name: repositoryName,\n } = body.repository;\n const summary = `New repository created: ${repositoryName}`;\n const ts = +new Date(eventDate);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/ongage/ongage.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst Ongage = require(\"ongage\");\n\nmodule.exports = {\n type: \"app\",\n app: \"ongage\",\n methods: {\n _ongage (client) {\n return new Ongage[client](\n this.$auth.x_username,\n this.$auth.x_password,\n this.$auth.x_account_code,\n );\n },\n async _execute ({\n body, ...config\n }) {\n if (body) config.data = body;\n const res = await axios(config);\n return res.data;\n },\n async getLists (page) {\n const api = this._ongage(\"ListsApi\");\n const req = api.getAll({\n sort: \"name\",\n order: \"ASC\",\n limit: 50,\n offset: 50 * page,\n });\n return await this._execute(req);\n },\n async subscribe (listId, email, fields = {}, overwrite = false) {\n const api = this._ongage(\"ContactsApi\");\n const req = api.create({\n email,\n overwrite,\n fields,\n }, listId);\n return await this._execute(req);\n },\n async updateSubscriber (listId, email, fields = {}) {\n const api = this._ongage(\"ContactsApi\");\n const req = api.update({\n email,\n fields,\n }, listId);\n return await this._execute(req);\n },\n async findSubscriber (email) {\n const api = this._ongage(\"ContactsApi\");\n const req = api.getListsByEmail(email);\n return await this._execute(req);\n },\n },\n propDefinitions: {\n listId: {\n type: \"string\",\n label: \"List ID\",\n async options ({ page }) {\n const { payload } = await this.getLists(page);\n return payload.map(list => ({\n label: list.name,\n value: list.id,\n }));\n },\n },\n overwrite: {\n type: \"boolean\",\n label: \"Overwrite?\",\n default: false,\n description: \"Whether to overwrite the specified fields if the subscriber already exists. Only the fields specified will be overwritten. For more information, see the [Ongage API documentation](https://ongage.atlassian.net/wiki/spaces/HELP/pages/1004175381/Contacts+API+Methods#ContactsAPIMethods-Description.3)\",\n },\n haltOnError: {\n type: \"boolean\",\n label: \"Halt on error?\",\n default: true,\n },\n email: {\n type: \"string\",\n label: \"Email Address\",\n },\n fields: {\n type: \"object\",\n label: \"List Fields\",\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/sources/common/event.js<|end_filename|>\nconst common = require(\"./webhook.js\");\n\nmodule.exports = {\n ...common,\n methods: {\n ...common.methods,\n generateMeta({ id, name, created }) {\n return {\n id,\n summary: name.text,\n ts: Date.parse(created),\n };\n },\n },\n};\n\n<|start_filename|>components/firebase_admin_sdk/sources/new-child-object/new-child-object.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"firebase_admin_sdk-new-child-object\",\n name: \"New Child Object in a Realtime Database\",\n description:\n \"Emits an event when a new child object is discovered within a specific path\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n path: {\n propDefinition: [\n common.props.firebase,\n \"path\",\n ],\n },\n },\n methods: {\n ...common.methods,\n async processEvent(event) {\n const { timestamp } = event;\n const ref = this.firebase.getApp().database()\n .ref(this.path);\n const snapshot = await ref.get();\n const children = snapshot.val() || {};\n for (const [\n key,\n value,\n ] of Object.entries(children)) {\n const meta = this.generateMeta(key, timestamp);\n const child = {\n [key]: value,\n };\n this.$emit(child, meta);\n }\n },\n generateMeta(key, timestamp) {\n return {\n id: key,\n summary: `New child object: ${key}`,\n ts: timestamp,\n };\n },\n },\n};\n\n\n<|start_filename|>components/twitch/twitch.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst crypto = require(\"crypto\");\nconst qs = require(\"qs\");\n\nmodule.exports = {\n type: \"app\",\n app: \"twitch\",\n propDefinitions: {\n streamerLoginNames: {\n type: \"string[]\",\n label: \"Streamer Login Names\",\n description:\n \"Enter the login names of the streamers whose streams you want to watch.\",\n },\n game: {\n type: \"string\",\n label: \"Game Title\",\n description: \"Watch for live streams about the specified game.\",\n },\n language: {\n type: \"string\",\n label: \"Stream Language\",\n description:\n \"Watch for games streamed in the specified language. A language value must be either the ISO 639-1 two-letter code for a supported stream language or \\\"other\\\".\",\n },\n max: {\n type: \"integer\",\n label: \"Max Items\",\n description:\n \"The maximum number of items to return at one time. Streams are returned sorted by number of viewers, in descending order. Videos and Clips are returned sorted by publish date.\",\n min: 1,\n },\n user: {\n type: \"string\",\n label: \"User ID\",\n },\n broadcaster: {\n type: \"string\",\n label: \"Broadcaster Id\",\n },\n },\n methods: {\n _getBaseUrl() {\n return \"https://api.twitch.tv/helix\";\n },\n _getHeaders() {\n return {\n \"Authorization\": `Bearer ${this.$auth.oauth_access_token}`,\n \"client-id\": this.$auth.oauth_client_id,\n \"Content-Type\": \"application/json\",\n };\n },\n _getParamsSerializer() {\n return (p) =>\n qs.stringify(p, {\n arrayFormat: \"repeat\",\n });\n },\n async _makeRequest(method, endpoint, params = {}) {\n const config = {\n method,\n url: `${this._getBaseUrl()}/${endpoint}`,\n headers: this._getHeaders(),\n params,\n paramsSerializer: this._getParamsSerializer(params),\n };\n return await axios(config);\n },\n // Uses Twitch API to create or delete webhook subscriptions.\n // Set mode to \"subscribe\" to create a webhook and \"unsubscribe\" to delete it.\n async manageHook(mode, url, topic, leaseSeconds, secretToken) {\n const data = {\n \"hub.callback\": url,\n \"hub.mode\": mode,\n \"hub.topic\": `${this._getBaseUrl()}/${topic}`,\n \"hub.lease_seconds\": leaseSeconds,\n \"hub.secret\": secretToken,\n };\n return await this._makeRequest(\"POST\", \"webhooks/hub\", data);\n },\n verifyWebhookRequest(headers, bodyRaw, secretToken) {\n const [\n algorithm,\n expectedHash,\n ] = headers[\"x-hub-signature\"].split(\"=\");\n const hash = crypto\n .createHmac(algorithm, secretToken)\n .update(bodyRaw)\n .digest(\"hex\");\n return expectedHash == hash;\n },\n async blockUser(params) {\n return await this._makeRequest(\"PUT\", \"users/blocks\", params);\n },\n async checkUserSubscription(params) {\n return await this._makeRequest(\"GET\", \"subscriptions/user\", params);\n },\n async deleteVideo(params) {\n return await this._makeRequest(\"DELETE\", \"videos\", params);\n },\n async getBroadcasterSubscriptions(params) {\n return await this._makeRequest(\"GET\", \"subscriptions\", params);\n },\n async getChannelEditors(params) {\n return await this._makeRequest(\"GET\", \"channels/editors\", params);\n },\n async getChannelInformation(params) {\n return await this._makeRequest(\"GET\", \"channels\", params);\n },\n async getChannelTeams(params) {\n return await this._makeRequest(\"GET\", \"teams/channel\", params);\n },\n async getClips(params) {\n return await this._makeRequest(\"GET\", \"clips\", params);\n },\n async getEmoteSets(params) {\n return await this._makeRequest(\"GET\", \"chat/emotes/set\", params);\n },\n async getGames(name = []) {\n let endpoint = \"games\";\n const params = {\n name,\n };\n return (await this._makeRequest(\"GET\", encodeURI(endpoint), params)).data;\n },\n async getMultipleUsers(params) {\n return await this._makeRequest(\"GET\", \"users\", params);\n },\n // gets all live streams that match the given parameters\n async getStreams(params) {\n return await this._makeRequest(\"GET\", \"streams\", params);\n },\n async getTopGames() {\n return await this._makeRequest(\"GET\", \"games/top\");\n },\n async getUsers(login = []) {\n let endpoint = \"users\";\n const params = {\n login,\n };\n return (await this._makeRequest(\"GET\", encodeURI(endpoint), params)).data;\n },\n async getUserFollows(params) {\n return await this._makeRequest(\"GET\", \"users/follows\", params);\n },\n async getVideos(params) {\n return await this._makeRequest(\"GET\", \"videos\", params);\n },\n async searchChannels(params) {\n return await this._makeRequest(\"GET\", \"search/channels\", params);\n },\n async searchGames(params) {\n return await this._makeRequest(\"GET\", \"search/categories\", params);\n },\n async unblockUser(params) {\n return await this._makeRequest(\"DELETE\", \"users/blocks\", params);\n },\n async updateChannel(params) {\n return await this._makeRequest(\"PATCH\", \"channels\", params);\n },\n },\n};\n\n\n<|start_filename|>components/airtable/actions/common.js<|end_filename|>\nconst airtable = require(\"../airtable.app.js\");\n\nmodule.exports = {\n props: {\n airtable,\n baseId: {\n type: \"$.airtable.baseId\",\n appProp: \"airtable\",\n },\n tableId: {\n type: \"$.airtable.tableId\",\n baseIdProp: \"baseId\",\n },\n },\n};\n\n\n<|start_filename|>components/slack/actions/complete-reminder/complete-reminder.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-complete-reminder\",\n name: \"Complete Reminder\",\n description: \"Complete a reminder\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n reminder: {\n propDefinition: [\n slack,\n \"reminder\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().reminders.complete({\n reminder: this.reminder,\n });\n },\n};\n\n\n<|start_filename|>components/twitch/actions/get-videos/get-videos.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Videos\",\n key: \"twitch-get-videos\",\n description: \"Gets video information by video ID, user ID, or game ID\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n id: {\n type: \"string\",\n label: \"Video ID\",\n description: `ID of the video being queried. If this is specified, you cannot use any of the optional query parameters below.\n Each request must specify one video id, one user_id, or one game_id.`,\n optional: true,\n },\n userId: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"ID of the user who owns the video. Each request must specify one video id, one user_id, or one game_id\",\n optional: true,\n },\n gameId: {\n type: \"string\",\n label: \"Game ID\",\n description: \"ID of the game the video is of. Each request must specify one video id, one user_id, or one game_id.\",\n optional: true,\n },\n language: {\n propDefinition: [\n common.props.twitch,\n \"language\",\n ],\n description: \"Language of the video being queried. A language value must be either the ISO 639-1 two-letter code for a supported stream language or “other”.\",\n optional: true,\n },\n period: {\n type: \"string\",\n label: \"Period\",\n description: \"Period during which the video was created. Defaults to “all” if left blank\",\n options: [\n \"all\",\n \"day\",\n \"week\",\n \"month\",\n ],\n optional: true,\n },\n sort: {\n type: \"string\",\n label: \"Sort\",\n description: \"Sort order of the videos. Defaults to “time” if left blank\",\n options: [\n \"time\",\n \"trending\",\n \"views\",\n ],\n optional: true,\n },\n type: {\n type: \"string\",\n label: \"Type\",\n description: \"Type of video. Defaults to “all” if left blank\",\n options: [\n \"all\",\n \"upload\",\n \"archive\",\n \"highlight\",\n ],\n optional: true,\n },\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of videos to return\",\n },\n },\n async run() {\n let params = {\n id: this.id,\n user_id: this.userId,\n game_id: this.gameId,\n language: this.language,\n period: this.period,\n sort: this.sort,\n type: this.type,\n };\n // remove empty values from params\n Object.keys(params).forEach((k) => (params[k] == null || params[k] == \"\") && delete params[k]);\n const videos = await this.paginate(\n this.twitch.getVideos.bind(this),\n params,\n this.max,\n );\n return await this.getPaginatedResults(videos);\n },\n};\n\n\n<|start_filename|>components/stack_exchange/sources/new-answers-for-questions/new-answers-for-questions.js<|end_filename|>\nconst stack_exchange = require('../../stack_exchange.app');\n\nmodule.exports = {\n key: \"stack_exchange-new-answers-for-questions\",\n name: \"New Answers for Specific Questions\",\n description: \"Emits an event when a new answer is posted in one of the specified questions\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n stack_exchange,\n db: \"$.service.db\",\n siteId: { propDefinition: [stack_exchange, \"siteId\"] },\n questionIds: {\n propDefinition: [\n stack_exchange,\n \"questionIds\",\n c => ({ siteId: c.siteId }),\n ],\n },\n timer: {\n type: '$.interface.timer',\n default: {\n intervalSeconds: 60 * 15, // 15 minutes\n },\n },\n },\n hooks: {\n async activate() {\n const fromDate = this._getCurrentEpoch();\n this.db.set(\"fromDate\", fromDate);\n },\n },\n methods: {\n _getCurrentEpoch() {\n // The StackExchange API works with Unix epochs in seconds.\n return Math.floor(Date.now() / 1000);\n },\n generateMeta(data) {\n const {\n answer_id: id,\n question_id: questionId,\n creation_date: ts,\n } = data;\n const summary = `New answer for question ID ${questionId}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n const fromDate = this.db.get(\"fromDate\");\n const toDate = this._getCurrentEpoch();\n const filter = '!SWKA(ozr4ec2cHE9JK'; // See https://api.stackexchange.com/docs/filters\n const searchParams = {\n fromDate,\n toDate,\n filter,\n sort: 'creation',\n order: 'asc',\n site: this.siteId,\n }\n\n const items = this.stack_exchange.answersForQuestions(this.questionIds, searchParams);\n for await (const item of items) {\n const meta = this.generateMeta(item);\n this.$emit(item, meta);\n }\n\n this.db.set(\"fromDate\", toDate);\n },\n};\n\n\n<|start_filename|>components/snowflake/sources/common-table-scan.js<|end_filename|>\nconst isString = require(\"lodash/isString\");\nconst common = require(\"./common\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n tableName: {\n type: \"string\",\n label: \"Table Name\",\n description: \"The name of the table to watch for new rows\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return [];\n }\n\n const options = await this.snowflake.listTables();\n return options.map(i => i.name);\n },\n },\n uniqueKey: {\n type: \"string\",\n label: \"Unique Key\",\n description: \"The name of a column in the table to use for deduplication. Defaults to `ID`\",\n default: \"ID\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return [];\n }\n\n const options = await this.snowflake.listFieldsForTable(this.tableName);\n return options.map(i => i.name);\n },\n },\n },\n hooks: {\n ...common.hooks,\n async activate() {\n await this.validateColumn(this.uniqueKey);\n\n let lastResultId = this.db.get(\"lastResultId\");\n if (lastResultId === undefined) {\n lastResultId = await this._getLastId();\n this.db.set(\"lastResultId\", lastResultId);\n }\n\n console.log(`\n Starting scan of table \"${this.tableName}\" from ${this.uniqueKey}=${lastResultId}\n `);\n },\n },\n methods: {\n ...common.methods,\n /**\n * Utility method to make sure that a certain column exists in the target\n * table. Useful for SQL query sanitizing.\n *\n * @param {string} columnNameToValidate The name of the column to validate\n * for existence\n */\n async validateColumn(columnNameToValidate) {\n if (!isString(columnNameToValidate)) {\n throw new Error(\"columnNameToValidate must be a string\");\n }\n\n const columns = await this.snowflake.listFieldsForTable(this.tableName);\n const columnNames = columns.map(i => i.name);\n if (!columnNames.includes(columnNameToValidate)) {\n throw new Error(`Inexistent column: ${columnNameToValidate}`);\n }\n },\n generateMeta(data) {\n const {\n row: {\n [this.uniqueKey]: id,\n },\n timestamp: ts,\n } = data;\n const summary = `New row: ${id}`;\n return {\n id,\n summary,\n ts,\n };\n },\n generateMetaForCollection(data) {\n const {\n lastResultId: id,\n rowCount,\n timestamp: ts,\n } = data;\n const entity = rowCount === 1 ? \"row\" : \"rows\";\n const summary = `${rowCount} new ${entity}`;\n return {\n id,\n summary,\n ts,\n };\n },\n async _getLastId() {\n const sqlText = `\n SELECT ${this.uniqueKey}\n FROM IDENTIFIER(:1)\n ORDER BY ${this.uniqueKey} DESC\n LIMIT 1\n `;\n const binds = [\n this.tableName,\n this.uniqueKey,\n ];\n const statement = {\n sqlText,\n binds,\n };\n const rowStream = await this.snowflake.getRows(statement);\n for await (const row of rowStream) {\n return row[this.uniqueKey];\n }\n return 0;\n },\n },\n async run(event) {\n const prevLastResultId = this.db.get(\"lastResultId\");\n const statement = await this.getStatement(prevLastResultId);\n\n const { timestamp } = event;\n const {\n lastResultId = prevLastResultId,\n } = (this.eventSize === 1) ?\n await this.processSingle(statement, timestamp) :\n await this.processCollection(statement, timestamp);\n this.db.set(\"lastResultId\", lastResultId);\n },\n};\n\n\n<|start_filename|>components/discord_webhook/actions/send-message-advanced/send-message-advanced.js<|end_filename|>\nconst discordWebhook = require(\"../../discord_webhook.app.js\");\n\nmodule.exports = {\n key: \"discord_webhook-send-message-advanced\",\n name: \"Send Message (Advanced)\",\n description: \"Send a simple or structured message (using embeds) to a Discord channel\",\n version: \"0.1.4\",\n type: \"action\",\n props: {\n discordWebhook,\n message: {\n propDefinition: [\n discordWebhook,\n \"message\",\n ],\n optional: true,\n },\n threadID: {\n propDefinition: [\n discordWebhook,\n \"threadID\",\n ],\n },\n embeds: {\n propDefinition: [\n discordWebhook,\n \"embeds\",\n ],\n },\n username: {\n propDefinition: [\n discordWebhook,\n \"username\",\n ],\n },\n avatarURL: {\n propDefinition: [\n discordWebhook,\n \"avatarURL\",\n ],\n },\n },\n async run() {\n const content = this.message;\n const {\n avatarURL,\n embeds,\n threadID,\n username,\n } = this;\n\n if (!content && !embeds) {\n throw new Error(\"This action requires at least 1 message OR embeds object. Please enter one or the other above.\");\n }\n\n // No interesting data is returned from Discord\n await this.discordWebhook.sendMessage({\n avatarURL,\n embeds,\n content,\n threadID,\n username,\n });\n },\n};\n\n\n<|start_filename|>interfaces/http/examples/http-hello-world.js<|end_filename|>\nmodule.exports = {\n name: \"http\",\n version: \"0.0.2\",\n props: {\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n async run(event) {\n this.http.respond({\n status: 200,\n body: \"Hello world!\",\n });\n // Emit the whole event, which contains\n // the HTTP payload, headers, and more\n this.$emit(event);\n },\n};\n\n\n<|start_filename|>components/airtable/actions/get-record/get-record.js<|end_filename|>\nconst airtable = require(\"../../airtable.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n key: \"airtable-get-record\",\n name: \"Get Record\",\n description: \"Get a record from a table by record ID.\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n ...common.props,\n recordId: {\n propDefinition: [\n airtable,\n \"recordId\",\n ],\n },\n },\n async run() {\n this.airtable.validateRecordID(this.recordId);\n const base = this.airtable.base(this.baseId);\n try {\n return await base(this.tableId).find(this.recordId);\n } catch (err) {\n this.airtable.throwFormattedError(err);\n }\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-deal-in-stage/new-deal-in-stage.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-deal-in-stage\",\n name: \"New Deal In Stage\",\n description: \"Emits an event for each new deal in a stage.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n props: {\n ...common.props,\n stages: { propDefinition: [common.props.hubspot, \"stages\"] },\n },\n methods: {\n ...common.methods,\n generateMeta(deal, stage) {\n const { id, properties, updatedAt } = deal;\n const { label } = stage;\n const ts = Date.parse(updatedAt);\n return {\n id: `${id}${properties.dealstage}`,\n summary: `${properties.dealname} ${label}`,\n ts,\n };\n },\n emitEvent(deal) {\n const stage = this.db.get(\"stage\");\n const meta = this.generateMeta(deal, stage);\n this.$emit(deal, meta);\n },\n isRelevant(deal, updatedAfter) {\n return Date.parse(deal.updatedAt) > updatedAfter;\n },\n },\n async run(event) {\n const updatedAfter = this._getAfter();\n\n for (let stage of this.stages) {\n stage = JSON.parse(stage);\n this.db.set(\"stage\", stage);\n const data = {\n limit: 100,\n filters: [\n {\n propertyName: \"dealstage\",\n operator: \"EQ\",\n value: stage.value,\n },\n ],\n sorts: [\n {\n propertyName: \"lastmodifieddate\",\n direction: \"DESCENDING\",\n },\n ],\n object: \"deals\",\n };\n\n await this.paginate(\n data,\n this.hubspot.searchCRM.bind(this),\n \"results\",\n updatedAfter\n );\n }\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/bitbucket/common.js<|end_filename|>\nconst bitbucket = require(\"./bitbucket.app\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n bitbucket,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n workspaceId: { propDefinition: [bitbucket, \"workspaceId\"] },\n },\n hooks: {\n async activate() {\n const hookParams = this._getHookParams();\n const hookPathProps = this.getHookPathProps();\n const opts = {\n hookParams,\n hookPathProps,\n };\n const { hookId } = await this.bitbucket.createHook(opts);\n console.log(\n `Created webhook for ${JSON.stringify(hookPathProps)}.\n Hook parameters: ${JSON.stringify(hookParams)}.\n (Hook ID: ${hookId}, endpoint: ${hookParams.url})`\n );\n this.db.set(\"hookId\", hookId);\n },\n async deactivate() {\n const hookId = this.db.get(\"hookId\");\n const hookPathProps = this.getHookPathProps();\n const opts = {\n hookId,\n hookPathProps,\n };\n await this.bitbucket.deleteHook(opts);\n console.log(\n `Deleted webhook for ${JSON.stringify(hookPathProps)}.\n (Hook ID: ${hookId})`\n );\n },\n },\n methods: {\n _isValidSource(headers, db) {\n const hookId = headers[\"x-hook-uuid\"];\n const expectedHookId = db.get(\"hookId\");\n return hookId === expectedHookId;\n },\n _getHookParams() {\n const eventSourceName = this.getEventSourceName();\n const hookDescription = `Pipedream - ${eventSourceName}`;\n const hookEvents = this.getHookEvents();\n return {\n description: hookDescription,\n url: this.http.endpoint,\n active: true,\n events: hookEvents,\n };\n },\n async processEvent(event) {\n const { body } = event;\n const meta = this.generateMeta(event);\n this.$emit(body, meta);\n },\n },\n async run(event) {\n const { headers } = event;\n\n // Reject any calls not made by the proper BitBucket webhook.\n if (!this._isValidSource(headers, this.db)) {\n this.http.respond({\n status: 404,\n });\n return;\n }\n\n // Acknowledge the event back to BitBucket.\n this.http.respond({\n status: 200,\n });\n\n return await this.processEvent(event);\n },\n};\n\n\n<|start_filename|>components/shopify/shopify.app.js<|end_filename|>\nconst get = require(\"lodash.get\");\nconst Shopify = require(\"shopify-api-node\");\nconst toPath = require(\"lodash/toPath\");\nconst retry = require(\"async-retry\");\n\nconst events = [\n {\n label: \"Article Created\",\n value: JSON.stringify({\n filter: \"Article\",\n verb: \"create\",\n }),\n },\n {\n label: \"Article Destroyed\",\n value: JSON.stringify({\n filter: \"Article\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Article Published\",\n value: JSON.stringify({\n filter: \"Article\",\n verb: \"published\",\n }),\n },\n {\n label: \"Article Unpublished\",\n value: JSON.stringify({\n filter: \"Article\",\n verb: \"unpublished\",\n }),\n },\n {\n label: \"Article Updated\",\n value: JSON.stringify({\n filter: \"Article\",\n verb: \"update\",\n }),\n },\n {\n label: \"Blog Created\",\n value: JSON.stringify({\n filter: \"Blog\",\n verb: \"create\",\n }),\n },\n {\n label: \"Blog Destroyed\",\n value: JSON.stringify({\n filter: \"Blog\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Collection Created\",\n value: JSON.stringify({\n filter: \"Collection\",\n verb: \"create\",\n }),\n },\n {\n label: \"Collection Destroyed\",\n value: JSON.stringify({\n filter: \"Collection\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Collection Published\",\n value: JSON.stringify({\n filter: \"Collection\",\n verb: \"published\",\n }),\n },\n {\n label: \"Collection Unpublished\",\n value: JSON.stringify({\n filter: \"Collection\",\n verb: \"unpublished\",\n }),\n },\n {\n label: \"Order Confirmed\",\n value: JSON.stringify({\n filter: \"Order\",\n verb: \"confirmed\",\n }),\n },\n {\n label: \"Page Created\",\n value: JSON.stringify({\n filter: \"Page\",\n verb: \"create\",\n }),\n },\n {\n label: \"Page Destroyed\",\n value: JSON.stringify({\n filter: \"Page\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Page Published\",\n value: JSON.stringify({\n filter: \"Page\",\n verb: \"published\",\n }),\n },\n {\n label: \"Page Unpublished\",\n value: JSON.stringify({\n filter: \"Page\",\n verb: \"unpublished\",\n }),\n },\n {\n label: \"Price Rule Created\",\n value: JSON.stringify({\n filter: \"PriceRule\",\n verb: \"create\",\n }),\n },\n {\n label: \"Price Rule Destroyed\",\n value: JSON.stringify({\n filter: \"PriceRule\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Price Rule Updated\",\n value: JSON.stringify({\n filter: \"PriceRule\",\n verb: \"update\",\n }),\n },\n {\n label: \"Product Created\",\n value: JSON.stringify({\n filter: \"Product\",\n verb: \"create\",\n }),\n },\n {\n label: \"Product Destroyed\",\n value: JSON.stringify({\n filter: \"Product\",\n verb: \"destroy\",\n }),\n },\n {\n label: \"Product Published\",\n value: JSON.stringify({\n filter: \"Product\",\n verb: \"published\",\n }),\n },\n {\n label: \"Product Unpublished\",\n value: JSON.stringify({\n filter: \"Product\",\n verb: \"unpublished\",\n }),\n },\n];\n\nmodule.exports = {\n type: \"app\",\n app: \"shopify\",\n propDefinitions: {\n eventTypes: {\n type: \"string[]\",\n label: \"Event Types\",\n optional: true,\n description: \"Only emit events for the selected event types.\",\n options: events,\n },\n },\n methods: {\n _getBaseURL() {\n return `https://${this.$auth.shop_id}.myshopify.com/admin/api/2020-10`;\n },\n _getAuthHeader() {\n return {\n \"x-shopify-access-token\": this.$auth.oauth_access_token,\n };\n },\n _monthAgo() {\n const now = new Date();\n const monthAgo = new Date(now.getTime());\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return monthAgo;\n },\n _jsonPathToGraphQl(path) {\n return toPath(path).reduceRight(\n (accum, item) => accum\n ? `${item} { ${accum} }`\n : item,\n );\n },\n /**\n * Returns if an error code represents a retriable error.\n * @callback isRetriableErrCode\n * @param {string} errCode The error code\n * @returns {boolean} If the error code is retriable\n */\n /**\n * Returns if a GraphQL error code represents a retriable error.\n * @type {isRetriableErrCode}\n */\n _isRetriableGraphQLErrCode(errCode) {\n return errCode === \"THROTTLED\";\n },\n /**\n * Options for handling error objects returned by API calls.\n * @typedef {Object} ErrorOptions\n * @property {(string|number)[]|string} errCodePath Path to the status/error\n * code in the error object\n * @property {(string|number)[]|string} errDataPath Path to the error data\n * in the error object\n * @property {isRetriableErrCode} isRetriableErrCode Function that returns if\n * the error code is retriable\n */\n /**\n * Returns options for handling GraphQL error objects.\n * @returns {ErrorOptions} The options\n */\n _graphQLErrOpts() {\n // Shopify GraphQL requests are throttled if queries exceed point limit.\n // See https://shopify.dev/concepts/about-apis/rate-limits\n // GraphQL err: { extensions: { code='THROTTLED' }, response: { body: { errors: [] } } }\n return {\n errCodePath: [\n \"extensions\",\n \"code\",\n ],\n errDataPath: [\n \"response\",\n \"body\",\n \"errors\",\n \"0\",\n ],\n isRetriableErrCode: this._isRetriableGraphQLErrCode,\n };\n },\n /**\n *\n * @param {function} apiCall The function that makes the API request\n * @param {object} opts Options for retrying the API call\n * @param {ErrorOptions} opts.errOpts Options for handling errors thrown by the API call\n * @param {object} opts.retryOpts Options for async-retry. See\n * https://www.npmjs.com/package/async-retry\n * @returns {Promise} A promise that resolves to the return value of the apiCall\n */\n async _withRetries(apiCall, opts = {}) {\n const {\n errOpts: {\n errCodePath,\n errDataPath,\n isRetriableErrCode,\n } = this._graphQLErrOpts(),\n retryOpts = {\n retries: 5,\n factor: 2,\n minTimeout: 2000, // In milliseconds\n },\n } = opts;\n return retry(async (bail, retryCount) => {\n try {\n return await apiCall();\n } catch (err) {\n const errCode = get(err, errCodePath);\n if (!isRetriableErrCode(errCode)) {\n const errData = get(err, errDataPath, {});\n return bail(new Error(`\n Unexpected error (error code: ${errCode}):\n ${JSON.stringify(errData, null, 2)}\n `));\n }\n\n console.log(`\n [Attempt #${retryCount}] Temporary error: ${err.message}\n `);\n throw err;\n }\n }, retryOpts);\n },\n _makeGraphQlRequest(query, variables = {}) {\n const shopifyClient = this.getShopifyInstance();\n return this._withRetries(\n () => shopifyClient.graphql(query, variables),\n );\n },\n dayAgo() {\n const dayAgo = new Date();\n dayAgo.setDate(dayAgo.getDate() - 1);\n return dayAgo;\n },\n getShopifyInstance() {\n return new Shopify({\n shopName: this.$auth.shop_id,\n accessToken: this.$auth.oauth_access_token,\n autoLimit: true,\n });\n },\n getSinceParams(sinceId = false, useCreatedAt = false, updatedAfter = null) {\n let params = {};\n if (sinceId) params = {\n ...params,\n since_id: sinceId,\n };\n if (updatedAfter) params = {\n ...params,\n updated_at_min: updatedAfter,\n };\n // If no sinceId or updatedAfter, get objects created within the last month\n if (!sinceId && !updatedAfter && useCreatedAt) return {\n created_at_min: this._monthAgo(),\n };\n return params;\n },\n async getObjects(objectType, params = {}, id = null) {\n const shopify = this.getShopifyInstance();\n let objects = [];\n do {\n const results = id\n ? await shopify[objectType].list(id, params)\n : await shopify[objectType].list(params);\n objects = objects.concat(results);\n params = results.nextPageParameters;\n } while (params !== undefined);\n return objects;\n },\n async getAbandonedCheckouts(sinceId) {\n let params = this.getSinceParams(sinceId, true);\n return await this.getObjects(\"checkout\", params);\n },\n async getArticles(blogId, sinceId) {\n let params = this.getSinceParams(sinceId, true);\n return await this.getObjects(\"article\", params, blogId);\n },\n async getBlogs() {\n return await this.getObjects(\"blog\");\n },\n async getCustomers(sinceId, updatedAfter) {\n let params = this.getSinceParams(sinceId, true, updatedAfter);\n return await this.getObjects(\"customer\", params);\n },\n async getEvents(sinceId, filter = null, verb = null) {\n let params = this.getSinceParams(sinceId, true);\n params.filter = filter;\n params.verb = verb;\n return await this.getObjects(\"event\", params);\n },\n async getOrders(fulfillmentStatus, useCreatedAt = false, sinceId = null, updatedAfter = null, status = \"any\") {\n let params = this.getSinceParams(sinceId, useCreatedAt, updatedAfter);\n params.status = status;\n params.fulfillment_status = fulfillmentStatus;\n return await this.getObjects(\"order\", params);\n },\n async getOrdersById(ids = []) {\n if (ids.length === 0) {\n return [];\n }\n const params = {\n ids: ids.join(\",\"),\n status: \"any\",\n limit: 100,\n };\n return await this.getObjects(\"order\", params);\n },\n async getPages(sinceId) {\n let params = this.getSinceParams(sinceId, true);\n return await this.getObjects(\"page\", params);\n },\n async getProducts(sinceId) {\n let params = this.getSinceParams(sinceId, true);\n return await this.getObjects(\"product\", params);\n },\n async *queryOrders(opts = {}) {\n const {\n sortKey = \"UPDATED_AT\",\n filter = \"\",\n fields = [],\n } = opts;\n const nodeFields = [\n \"id\",\n ...fields.map(this._jsonPathToGraphQl),\n ].join(\"\\n\");\n const query = `\n query orders($after: String, $filter: String, $sortKey: OrderSortKeys) {\n orders(after: $after, first: 100, query: $filter, sortKey: $sortKey) {\n pageInfo {\n hasNextPage\n }\n edges {\n cursor\n node {\n ${nodeFields}\n }\n }\n }\n }\n `;\n\n let { prevCursor: after = null } = opts;\n while (true) {\n const variables = {\n after,\n filter,\n sortKey,\n };\n const { orders } = await this._makeGraphQlRequest(query, variables);\n const { edges = [] } = orders;\n for (const edge of edges) {\n const {\n node: order,\n cursor,\n } = edge;\n yield {\n order,\n cursor,\n };\n after = cursor;\n }\n\n if (!orders.pageInfo.hasNextPage) {\n return;\n }\n }\n },\n },\n};\n\n\n<|start_filename|>components/ahrefs/actions/get-referring-domains/get-referring-domains.js<|end_filename|>\nconst ahrefs = require('../../ahrefs.app.js')\nconst axios = require('axios')\n\nmodule.exports = {\n name: 'Get Referring Domains',\n description: \"Get the referring domains that contain backlinks to the target URL or domain.\",\n key: \"ahrefs-get-referring-domains\",\n version: '0.0.16',\n type: \"action\",\n props: {\n ahrefs,\n target: { propDefinition: [ahrefs, \"target\"] },\n mode: { propDefinition: [ahrefs, \"mode\"] },\n limit: { propDefinition: [ahrefs, \"limit\"] },\n },\n async run() {\n return (await axios({\n url: `https://apiv2.ahrefs.com`,\n params: {\n token: this.ahrefs.$auth.oauth_access_token,\n from: \"refdomains\",\n target: this.target,\n mode: this.mode,\n limit: this.limit,\n order_by: \"domain_rating:desc\",\n output: \"json\"\n },\n })).data\n },\n}\n\n<|start_filename|>components/twilio/sources/new-incoming-sms/new-incoming-sms.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\nconst MessagingResponse = require(\"twilio\").twiml.MessagingResponse;\n\nmodule.exports = {\n ...common,\n key: \"twilio-new-incoming-sms\",\n name: \"New Incoming SMS (Instant)\",\n description:\n \"Configures a webhook in Twilio, tied to an incoming phone number, and emits an event each time an SMS is sent to that number\",\n version: \"0.0.5\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n responseMessage: {\n propDefinition: [common.props.twilio, \"responseMessage\"],\n },\n },\n methods: {\n ...common.methods,\n async setWebhook(...args) {\n return await this.twilio.setIncomingSMSWebhookURL(...args);\n },\n getResponseBody() {\n const twiml = new MessagingResponse();\n let responseBody = \"\";\n if (this.responseMessage) {\n twiml.message(this.responseMessage);\n responseBody = twiml.toString();\n }\n return responseBody;\n },\n generateMeta(body, headers) {\n return {\n /** if Twilio retries a message, but we've already emitted, dedupe */\n id: headers[\"i-twilio-idempotency-token\"],\n summary: body.Body,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/slack/actions/reply-to-a-message-thread/reply-to-a-message-thread.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-reply-to-a-message\",\n name: \"Reply to a Message Thread\",\n description: \"Send a message as a threaded reply\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n slack,\n thread_ts: {\n propDefinition: [\n slack,\n \"thread_ts\",\n ],\n optional: false,\n },\n reply_channel: {\n propDefinition: [\n slack,\n \"reply_channel\",\n ],\n optional: false,\n },\n text: {\n propDefinition: [\n slack,\n \"text\",\n ],\n optional: false,\n },\n as_user: {\n propDefinition: [\n slack,\n \"as_user\",\n ],\n },\n username: {\n propDefinition: [\n slack,\n \"username\",\n ],\n },\n icon_emoji: {\n propDefinition: [\n slack,\n \"icon_emoji\",\n ],\n },\n icon_url: {\n propDefinition: [\n slack,\n \"icon_url\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().chat.postMessage({\n text: this.text,\n channel: this.reply_channel,\n thread_ts: this.thread_ts,\n as_user: this.as_user,\n username: this.username,\n icon_emoji: this.icon_emoji,\n icon_url: this.icon_url,\n });\n },\n};\n\n\n<|start_filename|>components/twitter_developer_app/sources/common.js<|end_filename|>\nconst twitter_developer_app = require(\"../twitter_developer_app.app\");\n\nmodule.exports = {\n props: {\n twitter_developer_app,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 15 * 60, // 15 minutes\n },\n },\n },\n};\n\n\n<|start_filename|>components/textlocal/sources/new-sent-api-message/new-sent-api-message.js<|end_filename|>\nconst common = require(\"../common/timer-based\");\n\nmodule.exports = {\n...common,\n key: \"textlocal-new-sent-api-message\",\n name: \"New Sent API Message\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n hooks: {\n ...common.hooks,\n async activate() {\n let latestMessageId = this.db.get(\"latestMessageId\");\n if (!latestMessageId) {\n latestMessageId = await this.textlocal.getLatestMessageId();\n this.db.set(\"latestMessageId\", latestMessageId);\n }\n\n console.log(`Starting scanning from message ID: ${latestMessageId}`);\n },\n },\n methods: {\n ...common.methods,\n generateMeta(message) {\n const {\n id,\n datetime,\n number,\n sender,\n } = message;\n const maskedNumber = this.getMaskedNumber(number);\n const summary = `New message from ${sender} to ${maskedNumber}`;\n const ts = Date.parse(datetime);\n return {\n id,\n summary,\n ts,\n };\n },\n async processEvent() {\n const latestMessageId = this.db.get(\"latestMessageId\");\n const messageScan = await this.textlocal.scanApiMessageHistory({\n lowerBoundMessageId: latestMessageId,\n });\n\n const messages = [];\n for await (const message of messageScan) {\n messages.push(message);\n }\n\n if (messages.length === 0) {\n console.log(\"No new messages detected. Skipping...\");\n return;\n }\n\n messages.reverse().forEach((message) => {\n const meta = this.generateMeta(message);\n this.$emit(message, meta);\n });\n\n const newLatestMessageId = Math.max(\n ...messages.map(({ id }) => id)\n ).toString();\n this.db.set(\"latestMessageId\", newLatestMessageId);\n },\n },\n};\n\n\n<|start_filename|>components/supersaas/utils/makeEventSummary.js<|end_filename|>\nconst dayjs = require('dayjs');\n\n// See: https://www.supersaas.com/info/dev/webhooks\nmodule.exports = function makeEventSummary(ev) {\n const withUserEmail = x => {\n if (!ev.body.email) {\n return x;\n }\n\n return `${x} (${ev.body.email})`;\n };\n\n const withStartDateTime = x => {\n const start = ev.body.slot ? ev.body.slot.start : ev.body.start;\n\n if (!start) {\n return x;\n }\n\n return `${x} for ${dayjs(start).format('YYYY-MM-DD [at] HH:mm')}`;\n };\n\n switch (ev.body.event) {\n // User events:\n case 'new':\n return withUserEmail('New user');\n\n case 'change':\n if (ev.body.deleted) {\n return withUserEmail('Deleted user');\n }\n\n return withUserEmail('Changed user');\n\n case 'delete':\n return withUserEmail('Deleted user');\n\n case 'purchase':\n return withUserEmail('Purchased credit');\n\n // Appointment events:\n case 'create':\n return withStartDateTime('Created an appointment');\n break;\n\n case 'edit':\n return withStartDateTime(\n ev.body.deleted ? 'Deleted an appointment' : 'Changed an appointment',\n );\n\n case 'destroy':\n return withStartDateTime('Deleted an appointment');\n break;\n\n default:\n console.log('Unsupported event:', ev.body.event);\n return null;\n }\n};\n\n\n<|start_filename|>components/airtable/actions/update-record/update-record.js<|end_filename|>\nconst airtable = require(\"../../airtable.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n key: \"airtable-update-record\",\n name: \"Update record\",\n description: \"Update a single record in a table by Record ID.\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n ...common.props,\n recordId: {\n propDefinition: [\n airtable,\n \"recordId\",\n ],\n },\n record: {\n propDefinition: [\n airtable,\n \"record\",\n ],\n },\n },\n async run() {\n this.airtable.validateRecordID(this.recordId);\n const base = this.airtable.base(this.baseId);\n try {\n return (await base(this.tableId).update([\n {\n id: this.recordId,\n fields: this.record,\n },\n ]))[0];\n } catch (err) {\n this.airtable.throwFormattedError(err);\n }\n },\n};\n\n\n<|start_filename|>components/bandwidth/sources/new-outgoing-sms/new-outgoing-sms.js<|end_filename|>\nconst bandwidth = require('../../bandwidth.app');\n\nmodule.exports = {\n name: 'New Outgoing SMS',\n description:\n 'Emits an event each time an outbound message status event is received at the source url',\n key: 'bandwidth-new-ourgoing-sms',\n version: '1.1.1',\n props: {\n bandwidth,\n http: {\n type: '$.interface.http',\n customResponse: true,\n },\n },\n\n async run(event) {\n const messageBody = event.body[0];\n this.http.respond({\n status: 204,\n });\n\n if (messageBody.message.direction == 'out') {\n this.$emit(messageBody, {\n summary: messageBody.type,\n id: messageBody.message.id,\n ts: +new Date(messageBody.time),\n });\n }\n },\n};\n\n\n<|start_filename|>examples/user-input-prop.js<|end_filename|>\nmodule.exports = {\n name: \"User Input Prop Example\",\n version: \"0.1\",\n props: {\n msg: {\n type: \"string\",\n label: \"Message\",\n description: \"Enter a message to `console.log()`\",\n },\n },\n async run() {\n this.$emit(this.msg);\n },\n};\n\n\n<|start_filename|>components/webflow/sources/site-published/site-published.js<|end_filename|>\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-site-published\",\n name: \"Site Published (Instant)\",\n description: \"Emit an event when a site is published\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"site_publish\";\n },\n generateMeta(data) {\n const {\n site: siteId,\n publishTime: ts,\n } = data;\n const summary = `Site published: ${siteId}`;\n const id = `${siteId}-${ts}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/threads/actions/post-thread/post-thread.js<|end_filename|>\nconst threads = require(\"../../threads.app.js\");\n\nmodule.exports = {\n key: \"threads-post-thread\",\n name: \"Post a Thread\",\n description: \"Post a new thread to a specific forum\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n threads,\n forumID: {\n propDefinition: [\n threads,\n \"forumID\",\n ],\n },\n title: {\n propDefinition: [\n threads,\n \"title\",\n ],\n },\n body: {\n propDefinition: [\n threads,\n \"body\",\n ],\n },\n },\n async run() {\n const {\n forumID,\n title,\n body,\n } = this;\n return await this.threads.postThread({\n forumID,\n title,\n body,\n });\n },\n};\n\n\n<|start_filename|>components/sendgrid/sources/common/http-based.js<|end_filename|>\nconst {\n EventWebhook,\n EventWebhookHeader,\n} = require(\"@sendgrid/eventwebhook\");\nconst base = require(\"./base\");\n\nmodule.exports = {\n ...base,\n props: {\n ...base.props,\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n hooks: {\n ...base.hooks,\n async activate() {\n const { endpoint: endpointUrl } = this.http;\n const {\n enabled,\n url,\n } = await this.sendgrid.getWebhookSettings();\n if (enabled && endpointUrl !== url) {\n throw new Error(`\n Your account already has an active event webhook.\n Please verify and safely disable it before using this event source.\n `);\n }\n\n const newWebhookSettings = {\n ...this.baseWebhookSettings(),\n ...this.webhookEventFlags(),\n enabled: true,\n url: endpointUrl,\n };\n await this.sendgrid.setWebhookSettings(newWebhookSettings);\n\n const webhookPublicKey = await this.sendgrid.enableSignedWebhook();\n this.db.set(\"webhookPublicKey\", webhookPublicKey);\n },\n async deactivate() {\n const webhookSettings = {\n ...this.baseWebhookSettings(),\n enabled: false,\n url: null,\n };\n await this.sendgrid.setWebhookSettings(webhookSettings);\n await this.sendgrid.disableSignedWebhook();\n },\n },\n methods: {\n ...base.methods,\n _isValidSource(event) {\n const {\n [EventWebhookHeader.SIGNATURE().toLowerCase()]: signature,\n [EventWebhookHeader.TIMESTAMP().toLowerCase()]: timestamp,\n } = event.headers;\n const { bodyRaw: payload } = event;\n const webhookPublicKey = this.db.get(\"webhookPublicKey\");\n\n const webhookHelper = new EventWebhook();\n const ecdsaPublicKey = webhookHelper.convertPublicKeyToECDSA(webhookPublicKey);\n return webhookHelper.verifySignature(ecdsaPublicKey, payload, signature, timestamp);\n },\n processEvent(event) {\n if (!this._isValidSource(event)) {\n this.http.respond({\n status: 400,\n body: \"Signature check failed\",\n });\n return;\n }\n\n this.http.respond({\n status: 200,\n });\n\n const { body: events } = event;\n events.forEach((e) => {\n const meta = this.generateMeta(e);\n this.$emit(e, meta);\n });\n },\n },\n};\n\n\n<|start_filename|>components/twitter/actions/advanced-search/advanced-search.js<|end_filename|>\nconst twitter = require('../../twitter.app.js')\nconst moment = require('moment')\n \nmodule.exports = {\n key: \"twitter-advanced-search\",\n name: \"Advanced Search\",\n description: \"Return Tweets that matches your search criteria.\", \n version: \"0.0.2\",\n type: \"action\",\n props: {\n db: \"$.service.db\",\n twitter,\n q: { propDefinition: [twitter, \"q\"] },\n result_type: { propDefinition: [twitter, \"result_type\"] },\n includeRetweets: { propDefinition: [twitter, \"includeRetweets\"] },\n includeReplies: { propDefinition: [twitter, \"includeReplies\"] },\n lang: { propDefinition: [twitter, \"lang\"] },\n locale: { propDefinition: [twitter, \"locale\"] },\n geocode: { propDefinition: [twitter, \"geocode\"] },\n since_id: { propDefinition: [twitter, \"since_id\"] },\n enrichTweets: { propDefinition: [twitter, \"enrichTweets\"] },\n count: { propDefinition: [twitter, \"count\"] },\n maxRequests: { propDefinition: [twitter, \"maxRequests\"] },\n }, \n async run(event) {\n const { lang, locale, geocode, result_type, enrichTweets, includeReplies, includeRetweets, since_id, maxRequests, count } = this\n let q = this.q, max_id, limitFirstPage\n\n if (!since_id) {\n limitFirstPage = true\n } else {\n limitFirstPage = false\n }\n \n // run paginated search\n return await this.twitter.paginatedSearch({ \n q, \n since_id, \n lang, \n locale, \n geocode, \n result_type, \n enrichTweets, \n includeReplies, \n includeRetweets, \n maxRequests,\n count,\n limitFirstPage,\n })\n },\n}\n\n\n<|start_filename|>components/discord_webhook/actions/send-message/send-message.js<|end_filename|>\nconst discordWebhook = require(\"../../discord_webhook.app.js\");\n\nmodule.exports = {\n key: \"discord_webhook-send-message\",\n name: \"Send Message\",\n description: \"Send a simple message to a Discord channel\",\n version: \"0.1.2\",\n type: \"action\",\n props: {\n discordWebhook,\n message: {\n propDefinition: [\n discordWebhook,\n \"message\",\n ],\n },\n threadID: {\n propDefinition: [\n discordWebhook,\n \"threadID\",\n ],\n },\n username: {\n propDefinition: [\n discordWebhook,\n \"username\",\n ],\n },\n avatarURL: {\n propDefinition: [\n discordWebhook,\n \"avatarURL\",\n ],\n },\n },\n async run() {\n const {\n avatarURL,\n threadID,\n username,\n } = this;\n\n // No interesting data is returned from Discord\n await this.discordWebhook.sendMessage({\n avatarURL,\n content: this.message,\n threadID,\n username,\n });\n },\n};\n\n\n<|start_filename|>components/procore/sources/common.js<|end_filename|>\nconst procore = require(\"../procore.app.js\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n procore,\n db: \"$.service.db\",\n http: \"$.interface.http\",\n company: { propDefinition: [procore, \"company\"] },\n project: {\n propDefinition: [procore, \"project\", (c) => ({ company: c.company })],\n },\n },\n methods: {\n getComponentEventTypes() {\n return this.procore.getEventTypes();\n },\n getResourceName() {\n throw new Error(\"getResourceName is not implemented\");\n },\n },\n hooks: {\n async activate() {\n const hook = await this.procore.createHook(\n this.http.endpoint,\n this.company,\n this.project\n );\n this.db.set(\"hookId\", hook.id);\n // create hook triggers\n eventTypes = this.getComponentEventTypes();\n resourceName = this.getResourceName();\n const triggerIds = [];\n for (const eventType of eventTypes) {\n const trigger = await this.procore.createHookTrigger(\n hook.id,\n this.company,\n this.project,\n resourceName,\n eventType\n );\n triggerIds.push(trigger.id);\n }\n this.db.set(\"triggerIds\", triggerIds);\n },\n async deactivate() {\n const hookId = this.db.get(\"hookId\");\n const triggerIds = this.db.get(\"triggerIds\");\n // delete hook triggers\n for (const triggerId of triggerIds) {\n await this.procore.deleteHookTrigger(\n hookId,\n triggerId,\n this.company,\n this.project\n );\n }\n // delete hook\n await this.procore.deleteHook(hookId, this.company, this.project);\n },\n },\n async run(event) {\n const { body } = event;\n if (!body) {\n return;\n }\n\n const dataToEmit = await this.getDataToEmit(body);\n const meta = this.getMeta(dataToEmit);\n\n this.$emit(dataToEmit, meta);\n },\n};\n\n<|start_filename|>components/intercom/sources/conversation-closed/conversation-closed.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-conversation-closed\",\n name: \"New Closed Conversation\",\n description: \"Emits an event each time a conversation is closed.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const monthAgo = this.intercom.monthAgo();\n let lastConversationClosedAt =\n this.db.get(\"lastConversationClosedAt\") || Math.floor(monthAgo / 1000);\n const data = {\n query: {\n field: \"statistics.last_close_at\",\n operator: \">\",\n value: lastConversationClosedAt,\n },\n };\n\n const results = await this.intercom.searchConversations(data);\n for (const conversation of results) {\n if (conversation.created_at > lastConversationClosedAt)\n lastConversationClosedAt = conversation.statistics.last_close_at;\n this.$emit(conversation, {\n id: `${conversation.id}${conversation.last_close_at}`,\n summary: conversation.source.body,\n ts: conversation.last_close_at,\n });\n }\n\n this.db.set(\"lastConversationClosedAt\", lastConversationClosedAt);\n },\n};\n\n<|start_filename|>components/hubspot/sources/new-contact/new-contact.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-contact\",\n name: \"New Contacts\",\n description: \"Emits an event for each new contact added.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n generateMeta(contact) {\n const { id, properties, createdAt } = contact;\n const ts = Date.parse(createdAt);\n return {\n id,\n summary: `${properties.firstname} ${properties.lastname}`,\n ts,\n };\n },\n isRelevant(contact, createdAfter) {\n return Date.parse(contact.createdAt) > createdAfter;\n },\n },\n async run(event) {\n const createdAfter = this._getAfter();\n const data = {\n limit: 100,\n sorts: [\n {\n propertyName: \"createdate\",\n direction: \"DESCENDING\",\n },\n ],\n properties: this.db.get(\"properties\"),\n object: \"contacts\",\n };\n\n await this.paginate(\n data,\n this.hubspot.searchCRM.bind(this),\n \"results\",\n createdAfter\n );\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/webflow/sources/changed-collection-item/changed-collection-item.js<|end_filename|>\nconst common = require(\"../collection-common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-changed-collection-item\",\n name: \"Changed Collection Item (Instant)\",\n description: \"Emit an event when a collection item is changed\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"collection_item_changed\";\n },\n generateMeta(data) {\n const {\n _id: itemId,\n slug,\n \"updated-on\": updatedOn,\n } = data;\n const summary = `Collection item changed: ${slug}`;\n const ts = Date.parse(updatedOn);\n const id = `${itemId}-${ts}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/rss/actions/merge-rss-feeds/merge-rss-feeds.js<|end_filename|>\nconst Parser = require(\"rss-parser\");\n\nmodule.exports = {\n name: \"Merge RSS Feeds\",\n description: \"Retrieve multiple RSS feeds and return a merged array of items sorted by date.\",\n key: \"rss-merge-rss-feeds\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n feeds: {\n type: \"string[]\",\n label: \"Feeds\",\n description: \"The list of RSS feeds you want to parse.\",\n },\n merge: {\n type: \"boolean\",\n optional: true,\n default: true,\n description: \"If `true`, all items are returned in a date sorted array. If `false`, each feed is returned as one result in the array.\",\n },\n rss: {\n type: \"app\",\n app: \"rss\",\n },\n },\n async run() {\n\n /*\n\tIf merge is true, its an array of feed items where each item has a .feed\n\tproperty with info on the feed. A bit repetitve. It's sorted by date.\n\n\tIf merge is false, each array item is an object with:\n\n\t\t{\n\t\t\tfeed: info on feed\n\t\t\titems: items\n\t\t}\n\t*/\n let result = [];\n\n let parser = new Parser();\n const requests = this.feeds.map(feed => parser.parseURL(feed));\n\n const results = await Promise.all(requests);\n\n for (const feedResult of results) {\n const feed = {\n title: feedResult.title,\n description: feedResult.description,\n lastBuildDate: feedResult.lastBuildDate,\n link: feedResult.link,\n feedUrl: feedResult.feedUrl,\n };\n\n if (this.merge) {\n feedResult.items.forEach(f => {\n let newItem = f;\n newItem.feed = feed;\n result.push(newItem);\n });\n } else {\n result.push({\n feed,\n items: feedResult.items,\n });\n\n }\n\n }\n\n // now sort by pubDate, if merging of course\n if (this.merge) {\n result = result.sort((a, b) => {\n let aDate = new Date(a.isoDate);\n let bDate = new Date(b.isoDate);\n return bDate - aDate;\n });\n }\n\n return result;\n },\n};\n\n\n<|start_filename|>components/ringcentral/sources/new-event/new-event.js<|end_filename|>\nconst notificationTypes = require(\"../common/notification-types\");\nconst common = require(\"../common/http-based\");\n\nmodule.exports = {\n ...common,\n key: \"ringcentral-new-event\",\n name: \"New Event (Instant)\",\n description: \"Emits an event for each notification from RingCentral of a specified type\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n extensionId: {\n optional: true,\n propDefinition: [\n common.props.ringcentral,\n \"extensionId\",\n ],\n },\n deviceId: {\n optional: true,\n propDefinition: [\n common.props.ringcentral,\n \"deviceId\",\n c => ({ extensionId: c.extensionId }),\n ],\n },\n notificationTypes: {\n type: \"string[]\",\n label: \"Notification Types\",\n description: \"The types of notifications to emit events for\",\n options({ page = 0 }) {\n if (page !== 0) {\n return [];\n }\n\n return notificationTypes.map(({ label, key }) => ({\n label,\n value: key,\n }));\n },\n },\n },\n methods: {\n ...common.methods,\n _getEventTypeFromFilter(eventFilter) {\n return eventFilter\n .replace(/\\/restapi\\/v\\d+\\.\\d+\\//, \"\")\n .replace(/account\\/.*?\\//, \"\")\n .replace(/extension\\/.*?\\//, \"\");\n },\n getSupportedNotificationTypes() {\n return new Set(this.notificationTypes);\n },\n generateMeta(data) {\n const {\n uuid: id,\n timestamp,\n event: eventFilter,\n } = data;\n\n const eventType = this._getEventTypeFromFilter(eventFilter);\n const summary = `New event: ${eventType}`;\n const ts = Date.parse(timestamp);\n\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/bitbucket/sources/new-issue/new-issue.js<|end_filename|>\nconst common = require(\"../../common\");\nconst { bitbucket } = common.props;\n\nconst EVENT_SOURCE_NAME = \"New Issue (Instant)\";\n\nmodule.exports = {\n ...common,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-issue\",\n description: \"Emits an event when a new issue is created\",\n version: \"0.0.2\",\n props: {\n ...common.props,\n repositoryId: {\n propDefinition: [\n bitbucket,\n \"repositoryId\",\n c => ({ workspaceId: c.workspaceId }),\n ],\n },\n },\n methods: {\n ...common.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return [\n \"issue:created\",\n ];\n },\n getHookPathProps() {\n return {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n };\n },\n generateMeta(data) {\n const { headers, body } = data;\n const { id, title } = body.issue;\n const summary = `New Issue: #${id} ${title}`;\n const ts = +new Date(headers[\"x-event-time\"]);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/pagerduty/pagerduty.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"pagerduty\",\n propDefinitions: {\n escalationPolicies: {\n type: \"string[]\",\n label: \"Escalation Policies\",\n description:\n \"To filter your on-call rotations to specific escalation policies, select them here. **To listen for rotations across all escalation policies, leave this blank**.\",\n async options({ prevContext }) {\n const { offset } = prevContext;\n const escalationPolicies = await this.listEscalationPolicies(offset);\n const options = escalationPolicies.map((policy) => {\n return {\n label: policy.summary,\n value: policy.id,\n };\n });\n return {\n options,\n context: { offset },\n };\n },\n optional: true,\n },\n },\n methods: {\n async _makeRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers.authorization = `Bearer ${this.$auth.oauth_access_token}`;\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n opts.headers.accept = \"application/vnd.pagerduty+json;version=2\";\n const { path } = opts;\n delete opts.path;\n opts.url = `https://api.pagerduty.com${\n path[0] === \"/\" ? \"\" : \"/\"\n }${path}`;\n return await axios(opts);\n },\n async getEscalationPolicy(id) {\n return (\n await this._makeRequest({\n path: `/escalation_policies/${id}`,\n })\n ).data.escalation_policy;\n },\n async listEscalationPolicies(offset) {\n return (\n await this._makeRequest({\n path: \"/escalation_policies\",\n params: { offset },\n })\n ).data.escalation_policies;\n },\n async listOnCallUsers({ escalation_policy_ids }) {\n return (\n await this._makeRequest({\n path: \"/oncalls\",\n params: { escalation_policy_ids },\n })\n ).data.oncalls.map(({ user }) => user);\n },\n },\n};\n\n\n<|start_filename|>components/netlify/common.js<|end_filename|>\nconst netlify = require(\"./netlify.app\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n netlify,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n siteId: { propDefinition: [netlify, \"siteId\"] },\n },\n hooks: {\n async activate() {\n const event = this.getHookEvent();\n const opts = {\n event,\n url: this.http.endpoint,\n siteId: this.siteId,\n };\n const { hookId, token } = await this.netlify.createHook(opts);\n this.db.set(\"hookId\", hookId);\n this.db.set(\"token\", token);\n },\n async deactivate() {\n const hookId = this.db.get(\"hookId\");\n const opts = {\n hookId,\n siteId: this.siteId,\n };\n await this.netlify.deleteHook(opts);\n },\n },\n methods: {\n generateMeta(data) {\n const { id, created_at } = data;\n const ts = +new Date(created_at);\n const summary = this.getMetaSummary(data);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { headers, body, bodyRaw } = event;\n\n // Reject any calls not made by the proper Netlify webhook.\n if (!this.netlify.isValidSource(headers, bodyRaw, this.db)) {\n this.http.respond({\n status: 404,\n });\n return;\n }\n\n // Acknowledge the event back to Netlify.\n this.http.respond({\n status: 200,\n });\n\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n },\n};\n\n\n<|start_filename|>components/todoist/sources/common-project.js<|end_filename|>\nconst common = require(\"./common.js\");\n\nmodule.exports = {\n ...common,\n async run(event) {\n const syncResult = await this.todoist.syncProjects(this.db);\n Object.values(syncResult)\n .filter(Array.isArray)\n .flat()\n .forEach((element) => {\n element.summary = `Project: ${element.id}`;\n const meta = this.generateMeta(element);\n this.$emit(element, meta);\n });\n },\n};\n\n<|start_filename|>components/twitch/actions/get-clips/get-clips.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Clips\",\n key: \"twitch-get-clips\",\n description: \"Gets clip information by clip ID, user ID, or game ID\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n id: {\n type: \"string\",\n label: \"Clip ID\",\n description: `ID of the video being queried.\n For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`,\n optional: true,\n },\n broadcaster: {\n propDefinition: [\n common.props.twitch,\n \"broadcaster\",\n ],\n description: `ID of the broadcaster for whom clips are returned. Results are ordered by view count.\n For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`,\n optional: true,\n },\n gameId: {\n type: \"string\",\n label: \"Game ID\",\n description: `ID of the game the clip is of. \n For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`,\n optional: true,\n },\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of videos to return\",\n },\n },\n async run() {\n let params = {\n id: this.id,\n broadcaster_id: this.broadcaster,\n game_id: this.gameId,\n };\n // remove empty values from params\n Object.keys(params).forEach((k) => (params[k] == null || params[k] == \"\") && delete params[k]);\n const clips = await this.paginate(\n this.twitch.getClips.bind(this),\n params,\n this.max,\n );\n return await this.getPaginatedResults(clips);\n },\n};\n\n\n<|start_filename|>components/google_drive/constants.js<|end_filename|>\n/**\n * @typedef {string} UpdateType - a type of push notification as defined by\n * the [Google Drive API docs](https://bit.ly/3wcsY2X)\n */\n\n/**\n * A new channel was successfully created. You can expect to start receiving\n * notifications for it.\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_SYNC = \"sync\";\n\n/**\n * A new resource was created or shared\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_ADD = \"add\";\n\n/**\n * An existing resource was deleted or unshared\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_REMOVE = \"remove\";\n\n/**\n * One or more properties (metadata) of a resource have been updated\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_UPDATE = \"update\";\n\n/**\n * A resource has been moved to the trash\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_TRASH = \"trash\";\n\n/**\n * A resource has been removed from the trash\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_UNTRASH = \"untrash\";\n\n/**\n * One or more new changelog items have been added\n *\n * @type {UpdateType}\n */\nconst GOOGLE_DRIVE_NOTIFICATION_CHANGE = \"change\";\n\n/**\n * All the available Google Drive update types\n * @type {UpdateType[]}\n */\nconst GOOGLE_DRIVE_UPDATE_TYPES = [\n GOOGLE_DRIVE_NOTIFICATION_SYNC,\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_REMOVE,\n GOOGLE_DRIVE_NOTIFICATION_UPDATE,\n GOOGLE_DRIVE_NOTIFICATION_TRASH,\n GOOGLE_DRIVE_NOTIFICATION_UNTRASH,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n];\n\n/**\n * This is a custom string value to represent the 'My Drive' Google Drive, which\n * is represented as `null` by the Google Drive API. In order to simplify the\n * code by avoiding null values, we assign this special value to the 'My Drive'\n * drive.\n */\nconst MY_DRIVE_VALUE = \"myDrive\";\n\n/**\n * The maximum amount of time a subscription can be active without expiring is\n * 24 hours. In order to minimize subscription renewals (which involve the\n * execution of an event source) we set the expiration of subscriptions to its\n * maximum allowed value.\n *\n * More information can be found in the API docs:\n * https://developers.google.com/drive/api/v3/push#optional-properties\n */\nconst WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS = 24 * 60 * 60 * 1000;\n\n/**\n * The default time interval between webhook subscription renewals. Since\n * subscriptions expire after 24 hours at most, we set this time to 95% of this\n * time window by default to make sure the event sources don't miss any events\n * due to an expired subscription not being renewed on time.\n *\n * More information can be found in the API docs:\n * https://developers.google.com/drive/api/v3/push#optional-properties\n */\nconst WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS = (\n WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS * .95 / 1000\n);\n\nmodule.exports = {\n GOOGLE_DRIVE_NOTIFICATION_SYNC,\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_REMOVE,\n GOOGLE_DRIVE_NOTIFICATION_UPDATE,\n GOOGLE_DRIVE_NOTIFICATION_TRASH,\n GOOGLE_DRIVE_NOTIFICATION_UNTRASH,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n GOOGLE_DRIVE_UPDATE_TYPES,\n MY_DRIVE_VALUE,\n WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS,\n WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS,\n};\n\n\n<|start_filename|>components/firebase_admin_sdk/sources/new-doc-in-firestore-collection/new-doc-in-firestore-collection.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"firebase_admin_sdk-new-doc-in-firestore-collection\",\n name: \"New Document in Firestore Collection\",\n description: \"Emits an event when a structured query returns new documents\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n apiKey: {\n propDefinition: [\n common.props.firebase,\n \"apiKey\",\n ],\n },\n query: {\n propDefinition: [\n common.props.firebase,\n \"query\",\n ],\n },\n },\n methods: {\n ...common.methods,\n async processEvent() {\n const structuredQuery = JSON.parse(this.query);\n\n const queryResults = await this.firebase.runQuery(\n structuredQuery,\n this.apiKey,\n );\n\n for (const result of queryResults) {\n const meta = this.generateMeta(result);\n this.$emit(result, meta);\n }\n },\n generateMeta({ document }) {\n const {\n name,\n createTime,\n } = document;\n const id = name.substring(name.lastIndexOf(\"/\") + 1);\n return {\n id,\n summary: name,\n ts: Date.parse(createTime),\n };\n },\n },\n};\n\n\n<|start_filename|>components/slack/sources/new-message-in-channels/new-message-in-channels.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-new-message-in-channels\",\n name: \"New Message In Channels\",\n version: \"0.0.2\",\n description: \"Emit an event when a new message is posted to one or more channels\",\n dedupe: \"unique\",\n props: {\n slack,\n conversations: {\n type: \"string[]\",\n label: \"Channels\",\n description: \"Select one or more channels to monitor for new messages.\",\n optional: true,\n async options({ prevContext }) {\n let {\n types,\n cursor,\n userNames,\n } = prevContext;\n if (types == null) {\n const scopes = await this.slack.scopes();\n types = [\n \"public_channel\",\n ];\n if (scopes.includes(\"groups:read\")) {\n types.push(\"private_channel\");\n }\n if (scopes.includes(\"mpim:read\")) {\n types.push(\"mpim\");\n }\n if (scopes.includes(\"im:read\")) {\n types.push(\"im\");\n // TODO use paging\n userNames = {};\n for (const user of (await this.slack.users()).users) {\n userNames[user.id] = user.name;\n }\n }\n }\n const resp = await this.slack.availableConversations(types.join(), cursor);\n return {\n options: resp.conversations.map((c) => {\n if (c.is_im) {\n return {\n label: `Direct messaging with: @${userNames[c.user]}`,\n value: c.id,\n };\n } else if (c.is_mpim) {\n return {\n label: c.purpose.value,\n value: c.id,\n };\n } else {\n return {\n label: `${c.is_private ?\n \"Private\" :\n \"Public\"\n } channel: ${c.name}`,\n value: c.id,\n };\n }\n }),\n context: {\n types,\n cursor: resp.cursor,\n userNames\n },\n };\n },\n },\n slackApphook: {\n type: \"$.interface.apphook\",\n appProp: \"slack\",\n async eventNames() {\n return this.conversations || [];\n },\n },\n ignoreMyself: {\n type: \"boolean\",\n label: \"Ignore myself\",\n description: \"Ignore messages from me\",\n default: true,\n },\n resolveNames: {\n type: \"boolean\",\n label: \"Resolve names\",\n description: \"Resolve user and channel names (incurs extra API calls)\",\n default: false,\n },\n ignoreBot: {\n type: \"boolean\",\n label: \"Ignore bots\",\n description: \"Ignore messages from bots\",\n default: false,\n },\n nameCache: \"$.service.db\",\n },\n methods: {\n async maybeCached(key, refreshVal, timeoutMs = 3600000) {\n let record = this.nameCache.get(key);\n const time = Date.now();\n if (!record || time - record.ts > timeoutMs) {\n record = {\n ts: time,\n val: await refreshVal(),\n };\n this.nameCache.set(key, record);\n }\n return record.val;\n },\n async getBotName(id) {\n return this.maybeCached(`bots:${id}`, async () => {\n const info = await this.slack.sdk().bots.info({\n bot: id,\n });\n if (!info.ok) throw new Error(info.error);\n return info.bot.name;\n });\n },\n async getUserName(id) {\n return this.maybeCached(`users:${id}`, async () => {\n const info = await this.slack.sdk().users.info({\n user: id,\n });\n if (!info.ok) throw new Error(info.error);\n return info.user.name;\n });\n },\n async getConversationName(id) {\n return this.maybeCached(`conversations:${id}`, async () => {\n const info = await this.slack.sdk().conversations.info({\n channel: id,\n });\n if (!info.ok) throw new Error(info.error);\n if (info.channel.is_im) {\n return `DM with ${await this.getUserName(info.channel.user)}`;\n } else {\n return info.channel.name;\n }\n });\n },\n async getTeamName(id) {\n return this.maybeCached(`team:${id}`, async () => {\n try {\n const info = await this.slack.sdk().team.info({\n team: id,\n });\n return info.team.name;\n } catch (err) {\n console.log(\"Error getting team name, probably need to re-connect the account at pipedream.com/apps\", err);\n return id;\n }\n });\n },\n },\n async run(event) {\n if (event.subtype != null && event.subtype != \"bot_message\" && event.subtype != \"file_share\") {\n // This source is designed to just emit an event for each new message received.\n // Due to inconsistencies with the shape of message_changed and message_deleted\n // events, we are ignoring them for now. If you want to handle these types of\n // events, feel free to change this code!!\n console.log(\"Ignoring message with subtype.\");\n return;\n }\n if (this.ignoreMyself && event.user == this.slack.mySlackId()) {\n return;\n }\n if (this.ignoreBot && event.subtype == \"bot_message\") {\n return;\n }\n if (this.resolveNames) {\n if (event.user) {\n event.user_id = event.user;\n event.user = await this.getUserName(event.user);\n } else if (event.bot_id) {\n event.bot = await this.getBotName(event.bot_id);\n }\n event.channel_id = event.channel;\n event.channel = await this.getConversationName(event.channel);\n if (event.team) {\n event.team_id = event.team;\n event.team = await this.getTeamName(event.team);\n }\n }\n if (!event.client_msg_id) {\n event.pipedream_msg_id = `pd_${Date.now()}_${Math.random().toString(36)\n .substr(2, 10)}`;\n }\n\n this.$emit(event, {\n id: event.client_msg_id || event.pipedream_msg_id,\n });\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-engagement/new-engagement.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-engagement\",\n name: \"New Engagement\",\n description: \"Emits an event for each new engagement created.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(engagement) {\n const { id, type, createdAt } = engagement.engagement;\n const ts = Date.parse(createdAt);\n return {\n id,\n summary: type,\n ts,\n };\n },\n isRelevant(engagement, createdAfter) {\n return engagement.engagement.createdAt > createdAfter;\n },\n },\n async run(event) {\n const createdAfter = this._getAfter();\n const params = {\n limit: 250,\n };\n\n await this.paginateUsingHasMore(\n params,\n this.hubspot.getEngagements.bind(this),\n \"results\",\n createdAfter\n );\n },\n};\n\n<|start_filename|>components/activecampaign/sources/common-webhook.js<|end_filename|>\nconst activecampaign = require(\"../activecampaign.app.js\");\nconst common = require(\"./common.js\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n http: \"$.interface.http\",\n sources: { propDefinition: [activecampaign, \"sources\"] },\n },\n methods: {\n isRelevant(body) {\n return true;\n },\n },\n hooks: {\n async activate() {\n const sources =\n this.sources.length > 0\n ? this.sources\n : this.activecampaign.getAllSources();\n const hookData = await this.activecampaign.createHook(\n this.getEvents(),\n this.http.endpoint,\n sources\n );\n this.db.set(\"hookId\", hookData.webhook.id);\n },\n async deactivate() {\n await this.activecampaign.deleteHook(this.db.get(\"hookId\"));\n },\n },\n async run(event) {\n const { body } = event;\n if (!body) {\n return;\n }\n\n if (!this.isRelevant(body)) return;\n\n const meta = await this.getMeta(body);\n this.$emit(body, meta);\n },\n};\n\n<|start_filename|>components/sentry/sources/issue-event/issue-event.js<|end_filename|>\nconst sentry = require('../../sentry.app');\n\nconst EVENT_SOURCE_NAME = 'Issue Event (Instant)';\n\nmodule.exports = {\n key: 'sentry-issue-events',\n version: '0.0.1',\n name: EVENT_SOURCE_NAME,\n props: {\n db: '$.service.db',\n http: {\n type: '$.interface.http',\n customResponse: true,\n },\n sentry,\n organizationSlug: {propDefinition: [sentry, 'organizationSlug']},\n },\n hooks: {\n async activate() {\n const {slug: integrationSlug} = await this.sentry.createIntegration(\n this.getEventSourceName(),\n this.organizationSlug,\n this.http.endpoint,\n );\n this.db.set('integrationSlug', integrationSlug);\n\n const clientSecret = await this.sentry.getClientSecret(integrationSlug);\n this.db.set('clientSecret', clientSecret);\n },\n async deactivate() {\n const integrationSlug = this.db.get('integrationSlug');\n await this.sentry.disableIntegration(integrationSlug);\n },\n },\n methods: {\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n generateMeta(event) {\n const {body, headers} = event;\n const {\n 'request-id': id,\n 'sentry-hook-resource': resourceType,\n 'sentry-hook-timestamp': ts,\n } = headers;\n const {action, data} = body;\n const {[resourceType]: resource} = data;\n const summary = `${resourceType} #${resource.id} ${action}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const clientSecret = this.db.get('clientSecret');\n if (!this.sentry.isValidSource(event, clientSecret)) {\n this.http.respond({\n statusCode: 404,\n });\n return;\n }\n\n this.http.respond({\n statusCode: 200,\n });\n\n const {body} = event;\n const meta = this.generateMeta(event);\n this.$emit(body, meta);\n },\n};\n\n\n<|start_filename|>components/todoist/resource-types.js<|end_filename|>\nmodule.exports = [\n\t\"collaborators\",\n\t\"filters\",\n\t\"items\",\n\t\"labels\",\n\t\"live_notifications\",\n\t\"locations\",\n\t\"notes\",\n\t\"notification_settings\",\n\t\"projects\",\n\t\"reminders\",\n\t\"sections\",\n\t\"user\",\n\t\"user_settings\"\n]\n\n<|start_filename|>components/activecampaign/sources/common.js<|end_filename|>\nconst activecampaign = require(\"../activecampaign.app.js\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n activecampaign,\n db: \"$.service.db\",\n },\n};\n\n\n<|start_filename|>components/google_drive/actions/create-file/create-file.js<|end_filename|>\nconst googleDrive = require(\"../../google_drive.app\");\nconst fs = require(\"fs\");\nconst got = require(\"got\");\nconst isoLanguages = require(\"../language-codes.js\");\nconst googleMimeTypes = require(\"../google-mime-types.js\");\nconst mimeDb = require(\"mime-db\");\nconst mimeTypes = Object.keys(mimeDb);\n\nmodule.exports = {\n key: \"google_drive-create-file\",\n name: \"Create a New File\",\n description: \"Create a new file from a URL or /tmp/filepath.\",\n version: \"0.0.3\",\n type: \"action\",\n props: {\n googleDrive,\n drive: {\n propDefinition: [\n googleDrive,\n \"watchedDrive\",\n ],\n },\n parent: {\n type: \"string\",\n label: \"Parent Folder\",\n description:\n `The ID of the parent folder which contains the file. If not specified as part of a \n create request, the file will be placed directly in the user's My Drive folder.`,\n optional: true,\n async options({ prevContext }) {\n const { nextPageToken } = prevContext;\n let results;\n if (this.drive === \"myDrive\") {\n results = await this.googleDrive.listFolderOptions(nextPageToken);\n } else {\n results = await this.googleDrive.listFolderOptions(nextPageToken, {\n corpora: \"drive\",\n driveId: this.drive,\n includeItemsFromAllDrives: true,\n supportsAllDrives: true,\n });\n }\n return results;\n },\n },\n uploadType: {\n type: \"string\",\n label: \"Upload Type\",\n description: `The type of upload request to the /upload URI. If you are uploading data\n (using an /upload URI), this field is required. If you are creating a metadata-only file,\n this field is not required. \n media - Simple upload. Upload the media only, without any metadata.\n multipart - Multipart upload. Upload both the media and its metadata, in a single request.\n resumable - Resumable upload. Upload the file in a resumable fashion, using a series of \n at least two requests where the first request includes the metadata.`,\n options: [\n \"media\",\n \"multipart\",\n \"resumable\",\n ],\n },\n fileUrl: {\n type: \"string\",\n label: \"File URL\",\n description:\n `The URL of the file you want to upload to Google Drive. Must specify either File URL \n or File Path.`,\n optional: true,\n },\n filePath: {\n type: \"string\",\n label: \"File Path\",\n description:\n \"The path to the file, e.g. /tmp/myFile.csv . Must specify either File URL or File Path.\",\n optional: true,\n },\n ignoreDefaultVisibility: {\n type: \"boolean\",\n label: \"Ignore Default Visibility\",\n description: `Whether to ignore the domain's default visibility settings for the created \n file. Domain administrators can choose to make all uploaded files visible to the domain \n by default; this parameter bypasses that behavior for the request. Permissions are still \n inherited from parent folders.`,\n default: false,\n },\n includePermissionsForView: {\n type: \"string\",\n label: \"Include Permissions For View\",\n description:\n `Specifies which additional view's permissions to include in the response. Only \n 'published' is supported.`,\n optional: true,\n options: [\n \"published\",\n ],\n },\n keepRevisionForever: {\n type: \"boolean\",\n label: \"Keep Revision Forever\",\n description:\n `Whether to set the 'keepForever' field in the new head revision. This is only applicable\n to files with binary content in Google Drive. Only 200 revisions for the file can be kept \n forever. If the limit is reached, try deleting pinned revisions.`,\n default: false,\n },\n ocrLanguage: {\n type: \"string\",\n label: \"OCR Language\",\n description:\n \"A language hint for OCR processing during image import (ISO 639-1 code).\",\n optional: true,\n options: isoLanguages,\n },\n useContentAsIndexableText: {\n type: \"boolean\",\n label: \"Use Content As Indexable Text\",\n description:\n \"Whether to use the uploaded content as indexable text.\",\n default: false,\n },\n supportsAllDrives: {\n type: \"boolean\",\n label: \"Supports All Drives\",\n description:\n `Whether to include shared drives. Set to 'true' if saving to a shared drive.\n Defaults to 'false' if left blank.`,\n optional: true,\n },\n contentHintsIndexableText: {\n type: \"string\",\n label: \"Content Hints Indexable Text\",\n description:\n `Text to be indexed for the file to improve fullText queries. This is limited to 128KB in\n length and may contain HTML elements.`,\n optional: true,\n },\n contentRestrictionsReadOnly: {\n type: \"boolean\",\n label: \"Content Restrictions Read Only\",\n description:\n `Whether the content of the file is read-only. If a file is read-only, a new revision of \n the file may not be added, comments may not be added or modified, and the title of the file \n may not be modified.`,\n optional: true,\n },\n contentRestrictionsReason: {\n type: \"string\",\n label: \"Content Restrictions Reason\",\n description:\n `Reason for why the content of the file is restricted. This is only mutable on requests \n that also set readOnly=true.`,\n optional: true,\n },\n copyRequiresWriterPermission: {\n type: \"boolean\",\n label: \"Copy Requires Writer Permission\",\n description:\n `Whether the options to copy, print, or download this file, should be disabled for \n readers and commenters.`,\n optional: true,\n },\n description: {\n type: \"string\",\n label: \"Description\",\n description: \"A short description of the file.\",\n optional: true,\n },\n folderColorRgb: {\n type: \"string\",\n label: \"Folder Color RGB\",\n description:\n `The color for a folder as an RGB hex string. If an unsupported color is specified,\n the closest color in the palette will be used instead.`,\n optional: true,\n },\n mimeType: {\n type: \"string\",\n label: \"Mime Type\",\n description: `The MIME type of the file. Google Drive will attempt to automatically detect\n an appropriate value from uploaded content if no value is provided. The value cannot be \n changed unless a new revision is uploaded. If a file is created with a Google Doc MIME\n type, the uploaded content will be imported if possible. Google Workspace and Drive \n MIME Types: https://developers.google.com/drive/api/v3/mime-types`,\n optional: true,\n async options({ page = 0 }) {\n const allTypes = googleMimeTypes.concat(mimeTypes);\n const start = (page - 1) * 10;\n const end = start + 10;\n return allTypes.slice(start, end);\n },\n },\n name: {\n type: \"string\",\n label: \"Name\",\n description: \"Name of the file\",\n optional: true,\n },\n originalFilename: {\n type: \"string\",\n label: \"Original Filename\",\n description:\n \"The original filename of the uploaded content if available, or else the original value of the name field. This is only available for files with binary content in Google Drive.\",\n optional: true,\n },\n shortcutDetailsTargetId: {\n type: \"string\",\n label: \"Shortcut Details Target ID\",\n description: \"The ID of the file that this shortcut points to.\",\n optional: true,\n },\n starred: {\n type: \"boolean\",\n label: \"Starred\",\n description: \"Whether the user has starred the file.\",\n optional: true,\n },\n writersCanShare: {\n type: \"boolean\",\n label: \"Writers Can Share\",\n description:\n \"Whether users with only writer permission can modify the file's permissions. Not populated for items in shared drives.\",\n optional: true,\n },\n },\n async run() {\n const body = this.fileUrl\n ? await got.stream(this.fileUrl)\n : fs.createReadStream(this.filePath);\n return (\n await this.googleDrive.createFile({\n ignoreDefaultVisibility: this.ignoreDefaultVisibility,\n includePermissionsForView: this.includePermissionsForView,\n keepRevisionForever: this.keeprevisionForever,\n ocrLanguage: this.ocrLanguage,\n useContentAsIndexableText: this.useContentAsIndexableText,\n supportsAllDrives: this.supportsAllDrives,\n resource: {\n name: this.name,\n originalFilename: this.originalFilename,\n parents: [\n this.parent,\n ],\n mimeType: this.mimeType,\n description: this.description,\n folderColorRgb: this.folderColorRgb,\n shortcutDetails: {\n targetId: this.shortcutDetailsTargetId,\n },\n starred: this.starred,\n writersCanShare: this.writersCanShare,\n contentHints: {\n indexableText: this.contentHintsIndexableText,\n },\n contentRestrictions: {\n readOnly: this.contentRestrictionsReadOnly,\n reason: this.contentRestrictionsReason,\n },\n copyRequiresWriterPermission: this.copyRequiresWriterPermission,\n },\n media: {\n mimeType: this.mimeType,\n uploadType: this.uploadType,\n body,\n },\n fields: \"*\",\n })\n );\n },\n};\n\n\n<|start_filename|>components/docusign/docusign.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"docusign\",\n propDefinitions: {\n account: {\n type: \"string\",\n label: \"Account\",\n async options() {\n const { accounts } = await this.getUserInfo();\n return accounts.map((account) => {\n return {\n label: account.account_name,\n value: account.account_id,\n };\n });\n },\n },\n template: {\n type: \"string\",\n label: \"Template\",\n async options({ account }) {\n const baseUri = await this.getBaseUri(account);\n const { envelopeTemplates } = await this.listTemplates(baseUri);\n return envelopeTemplates.map((template) => {\n return {\n label: template.name,\n value: template.templateId,\n };\n });\n },\n },\n emailSubject: {\n type: \"string\",\n label: \"Email Subject\",\n description: \"Subject line of email\",\n },\n emailBlurb: {\n type: \"string\",\n label: \"Email Blurb\",\n description: \"Email message to recipient. Overrides template setting.\",\n optional: true,\n },\n recipientEmail: {\n type: \"string\",\n label: \"Recipient Email\",\n description: \"Email address of signature request recipient\",\n },\n recipientName: {\n type: \"string\",\n label: \"Recipient Name\",\n description: \"The full name of the recipient\",\n },\n role: {\n type: \"string\",\n label: \"Recipient Role\",\n description: \"Choose role as defined on template or use a custom value\",\n async options({\n account, template,\n }) {\n const baseUri = await this.getBaseUri(account);\n const { signers } = await this.listTemplateRecipients(\n baseUri,\n template,\n );\n return signers.map((signer) => {\n return signer.roleName;\n });\n },\n },\n },\n methods: {\n _getHeaders() {\n return {\n \"Authorization\": `Bearer ${this.$auth.oauth_access_token}`,\n \"Content-Type\": \"application/json\",\n };\n },\n async _makeRequest(method, url, data = null, params = null) {\n const config = {\n method,\n url,\n headers: this._getHeaders(),\n data,\n params,\n };\n return (await axios(config)).data;\n },\n async getUserInfo() {\n return await this._makeRequest(\n \"GET\",\n \"https://account-d.docusign.com/oauth/userinfo\",\n );\n },\n async getBaseUri(accountId) {\n const { accounts } = await this.getUserInfo();\n const account = accounts.find((a) => a.account_id === accountId);\n const { base_uri: baseUri } = account;\n return `${baseUri}/restapi/v2.1/accounts/${accountId}/`;\n },\n async listTemplates(baseUri) {\n return await this._makeRequest(\"GET\", `${baseUri}templates`);\n },\n async listTemplateRecipients(baseUri, templateId) {\n return await this._makeRequest(\n \"GET\",\n `${baseUri}templates/${templateId}/recipients`,\n );\n },\n async createEnvelope(baseUri, data) {\n return await this._makeRequest(\"POST\", `${baseUri}envelopes`, data);\n },\n async listFolders(baseUri, params) {\n return await this._makeRequest(\"GET\", `${baseUri}folders`, null, params);\n },\n async listFolderItems(baseUri, params, folderId) {\n return await this._makeRequest(\"GET\", `${baseUri}folders/${folderId}`, null, params);\n },\n async listEnvelopes(baseUri, params) {\n return await this._makeRequest(\n \"GET\",\n `${baseUri}envelopes`,\n null,\n params,\n );\n },\n },\n};\n\n\n<|start_filename|>components/slack/actions/update-message/update-message.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-update-message\",\n name: \"Update Message\",\n description: \"Update a message\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n timestamp: {\n propDefinition: [\n slack,\n \"timestamp\",\n ],\n },\n text: {\n propDefinition: [\n slack,\n \"text\",\n ],\n },\n as_user: {\n propDefinition: [\n slack,\n \"as_user\",\n ],\n description: \"Pass true to update the message as the authed user. Bot users in this context are considered authed users.\",\n },\n attachments: {\n propDefinition: [\n slack,\n \"attachments\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().chat.update({\n ts: this.timestamp,\n text: this.text,\n channel: this.conversation,\n as_user: this.as_user,\n attachments: this.attachments,\n });\n },\n};\n\n\n<|start_filename|>components/dev_to/dev_to.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"dev_to\",\n}\n\n<|start_filename|>components/intercom/intercom.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"intercom\",\n methods: {\n _getBaseURL() {\n return \"https://api.intercom.io\";\n },\n _getHeader() {\n return {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n Accept: \"application/json\",\n };\n },\n monthAgo() {\n const now = new Date();\n const monthAgo = new Date(now.getTime());\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return monthAgo;\n },\n async getCompanies(lastCompanyCreatedAt) {\n let results = null;\n let starting_after = null;\n let done = false;\n const companies = [];\n while ((!results || results.data.pages.next) && !done) {\n if (results) starting_after = results.data.pages.next.starting_after;\n const config = {\n method: \"GET\",\n url: `${this._getBaseURL()}/companies${starting_after ? \"?starting_after=\" + starting_after : \"\"}`,\n headers: this._getHeader(),\n };\n results = await axios(config);\n for (const company of results.data.data) {\n if (company.created_at > lastCompanyCreatedAt)\n companies.push(company);\n else\n done = true;\n }\n }\n return companies;\n },\n async getConversation(id) {\n const config = {\n method: \"GET\",\n url: `${this._getBaseURL()}/conversations/${id}`,\n headers: this._getHeader(),\n };\n return await axios(config);\n },\n async getEvents(user_id, nextURL = null) {\n let results = null;\n let since = null;\n const events = [];\n while (!results || results.data.pages.next) {\n if (results) nextURL = results.data.pages.next;\n const url = nextURL || `${this._getBaseURL()}/events?type=user&intercom_user_id=${user_id}`;\n const config = {\n method: \"GET\",\n url,\n headers: this._getHeader(),\n };\n results = await axios(config);\n for (const result of results.data.events) {\n events.push(result);\n }\n if (results.data.pages.since)\n since = results.data.pages.since;\n }\n return { events, since };\n }, \n async searchContacts(data, starting_after = null) {\n const config = {\n method: \"POST\",\n url: `${this._getBaseURL()}/contacts/search${\n starting_after ? \"?starting_after=\" + starting_after : \"\"\n }`,\n headers: this._getHeader(),\n data,\n };\n return await axios(config);\n },\n async searchContacts(data) {\n let results = null;\n let starting_after = null;\n let config = null;\n const contacts = [];\n while (!results || results.data.pages.next) {\n if (results) starting_after = results.data.pages.next.starting_after;\n config = {\n method: \"POST\",\n url: `${this._getBaseURL()}/contacts/search${starting_after ? \"?starting_after=\" + starting_after : \"\"}`,\n headers: this._getHeader(),\n data,\n };\n results = await axios(config);\n for (const contact of results.data.data) {\n contacts.push(contact);\n }\n }\n return contacts;\n },\n async searchConversations(data) {\n let results = null;\n let starting_after = null;\n let config = null;\n const conversations = [];\n while (!results || results.data.pages.next) {\n if (results) starting_after = results.data.pages.next.starting_after;\n config = {\n method: \"POST\",\n url: `${this._getBaseURL()}/conversations/search${starting_after ? \"?starting_after=\" + starting_after : \"\"}`,\n headers: this._getHeader(),\n data,\n };\n results = await axios(config);\n for (const result of results.data.conversations) {\n conversations.push(result);\n }\n }\n return conversations;\n }, \n },\n};\n\n<|start_filename|>components/github/sources/new-watcher/new-watcher.js<|end_filename|>\nconst github = require(\"../../github.app.js\");\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n key: \"github-new-watcher\",\n name: \"New Watcher\",\n description: \"Emit new events when new watchers are added to a repository\",\n version: \"0.0.3\",\n type: \"source\",\n dedupe: \"last\",\n props: {\n ...common.props,\n repoFullName: {\n propDefinition: [\n github,\n \"repoFullName\",\n ],\n },\n },\n methods: {\n generateMeta(data) {\n const ts = Date.now();\n return {\n id: data.id,\n summary: data.login,\n ts,\n };\n },\n },\n async run() {\n const watchers = await this.github.getWatchers({\n repoFullName: this.repoFullName,\n });\n\n watchers.forEach((watcher) => {\n const meta = this.generateMeta(watcher);\n this.$emit(watcher, meta);\n });\n },\n};\n\n\n<|start_filename|>components/intercom/sources/tag-added-to-lead/tag-added-to-lead.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-tag-added-to-lead\",\n name: \"Tag Added To Lead\",\n description: \"Emits an event each time a new tag is added to a lead.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const data = {\n query: {\n field: \"role\",\n operator: \"=\",\n value: \"lead\",\n },\n };\n\n const results = await this.intercom.searchContacts(data);\n for (const lead of results) {\n if (lead.tags.data.length > 0) {\n for (const tag of lead.tags.data) {\n this.$emit(tag, {\n id: `${lead.id}${tag.id}`,\n summary: `Tag added to ${lead.name ? lead.name : lead.id}`,\n ts: Date.now(),\n });\n }\n }\n }\n },\n};\n\n<|start_filename|>components/google_drive/sources/common-webhook.js<|end_filename|>\nconst includes = require(\"lodash/includes\");\nconst { v4: uuid } = require(\"uuid\");\n\nconst googleDrive = require(\"../google_drive.app.js\");\nconst { WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS } = require(\"../constants.js\");\n\nmodule.exports = {\n props: {\n googleDrive,\n db: \"$.service.db\",\n http: \"$.interface.http\",\n drive: {\n propDefinition: [\n googleDrive,\n \"watchedDrive\",\n ],\n },\n watchForPropertiesChanges: {\n propDefinition: [\n googleDrive,\n \"watchForPropertiesChanges\",\n ],\n },\n timer: {\n label: \"Push notification renewal schedule\",\n description:\n \"The Google Drive API requires occasional renewal of push notification subscriptions. **This runs in the background, so you should not need to modify this schedule**.\",\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS,\n },\n },\n },\n hooks: {\n async activate() {\n // Called when a component is created or updated. Handles all the logic\n // for starting and stopping watch notifications tied to the desired\n // files.\n const channelID = uuid();\n const {\n startPageToken,\n expiration,\n resourceId,\n } = await this.googleDrive.activateHook(\n channelID,\n this.http.endpoint,\n this.getDriveId(),\n );\n\n // We use and increment the pageToken as new changes arrive, in run()\n this._setPageToken(startPageToken);\n\n // Save metadata on the subscription so we can stop / renew later\n // Subscriptions are tied to Google's resourceID, \"an opaque value that\n // identifies the watched resource\". This value is included in request headers\n this._setSubscription({\n resourceId,\n expiration,\n });\n this._setChannelID(channelID);\n },\n async deactivate() {\n const channelID = this._getChannelID();\n const { resourceId } = this._getSubscription();\n await this.googleDrive.deactivateHook(channelID, resourceId);\n\n this._setSubscription(null);\n this._setChannelID(null);\n this._setPageToken(null);\n },\n },\n methods: {\n _getSubscription() {\n return this.db.get(\"subscription\");\n },\n _setSubscription(subscription) {\n this.db.set(\"subscription\", subscription);\n },\n _getChannelID() {\n return this.db.get(\"channelID\");\n },\n _setChannelID(channelID) {\n this.db.set(\"channelID\", channelID);\n },\n _getPageToken() {\n return this.db.get(\"pageToken\");\n },\n _setPageToken(pageToken) {\n this.db.set(\"pageToken\", pageToken);\n },\n isMyDrive(drive = this.drive) {\n return googleDrive.methods.isMyDrive(drive);\n },\n getDriveId(drive = this.drive) {\n return googleDrive.methods.getDriveId(drive);\n },\n /**\n * This method returns the types of updates/events from Google Drive that\n * the event source should listen to. This base implementation returns an\n * empty list, which means that any event source that extends this module\n * and that does not refine this implementation will essentially ignore\n * every incoming event from Google Drive.\n *\n * @returns\n * @type {UpdateType[]}\n */\n getUpdateTypes() {\n return [];\n },\n /**\n * This method is responsible for processing a list of changed files\n * according to the event source's purpose. As an abstract method, it must\n * be implemented by every event source that extends this module.\n *\n * @param {object[]} [changedFiles] - the list of file changes, as [defined\n * by the API](https://bit.ly/3h7WeUa)\n * @param {object} [headers] - an object containing the request headers of\n * the webhook call made by Google Drive\n */\n processChanges() {\n throw new Error(\"processChanges is not implemented\");\n },\n },\n async run(event) {\n // This function is polymorphic: it can be triggered as a cron job, to make\n // sure we renew watch requests for specific files, or via HTTP request (the\n // change payloads from Google)\n const subscription = this._getSubscription();\n const channelID = this._getChannelID();\n const pageToken = this._getPageToken();\n\n // Component was invoked by timer\n if (event.timestamp) {\n const {\n newChannelID,\n newPageToken,\n expiration,\n resourceId,\n } = await this.googleDrive.invokedByTimer(\n this.drive,\n subscription,\n this.http.endpoint,\n channelID,\n pageToken,\n );\n\n this._setSubscription({\n expiration,\n resourceId,\n });\n this._setChannelID(newChannelID);\n this._setPageToken(newPageToken);\n return;\n }\n\n const { headers } = event;\n if (!this.googleDrive.checkHeaders(headers, subscription, channelID)) {\n return;\n }\n\n if (!includes(this.getUpdateTypes(), headers[\"x-goog-resource-state\"])) {\n console.log(\n `Update type ${headers[\"x-goog-resource-state\"]} not in list of updates to watch: `,\n this.getUpdateTypes(),\n );\n return;\n }\n\n // We observed false positives where a single change to a document would trigger two changes:\n // one to \"properties\" and another to \"content,properties\". But changes to properties\n // alone are legitimate, most users just won't want this source to emit in those cases.\n // If x-goog-changed is _only_ set to \"properties\", only move on if the user set the prop\n if (\n !this.watchForPropertiesChanges &&\n headers[\"x-goog-changed\"] === \"properties\"\n ) {\n console.log(\n \"Change to properties only, which this component is set to ignore. Exiting\",\n );\n return;\n }\n\n const driveId = this.getDriveId();\n const changedFilesStream = this.googleDrive.listChanges(pageToken, driveId);\n for await (const changedFilesPage of changedFilesStream) {\n const {\n changedFiles,\n nextPageToken,\n } = changedFilesPage;\n\n // Process all the changed files retrieved from the current page\n await this.processChanges(changedFiles, headers);\n\n // After successfully processing the changed files, we store the page\n // token of the next page\n this._setPageToken(nextPageToken);\n }\n },\n};\n\n\n<|start_filename|>components/ringcentral/sources/common/http-based.js<|end_filename|>\nconst template = require(\"lodash/template\");\nconst { v4: uuid } = require(\"uuid\");\n\nconst base = require(\"./base\");\nconst notificationTypes = require(\"./notification-types\");\n\nmodule.exports = {\n ...base,\n dedupe: \"unique\",\n props: {\n ...base.props,\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n hooks: {\n ...base.hooks,\n async activate() {\n const verificationToken = this._getVerificationToken();\n this.db.set(\"verificationToken\", verificationToken);\n\n const opts = {\n address: this.http.endpoint,\n eventFilters: this._getEventFilters(),\n verificationToken,\n };\n const {\n id: webhookId,\n } = await this.ringcentral.createHook(opts);\n this.db.set(\"webhookId\", webhookId);\n },\n async deactivate() {\n const webhookId = this.db.get(\"webhookId\");\n await this.ringcentral.deleteHook(webhookId);\n\n this.db.set(\"verificationToken\", null);\n },\n },\n methods: {\n ...base.methods,\n _getPropValues() {\n return Object.entries(this)\n .filter(([_, value]) => value != null)\n .reduce((accum, [prop, value]) => ({\n ...accum,\n [prop]: value,\n }), {});\n },\n _getEventFilters() {\n const eventKeys = this.getSupportedNotificationTypes();\n const propValues = this._getPropValues();\n return notificationTypes\n .filter(({ key }) => eventKeys.has(key))\n .map(({ filter }) => template(filter))\n .map((templateFn) => templateFn(propValues));\n },\n _getVerificationToken() {\n return uuid().replace(/-/g, \"\");\n },\n /**\n * Provides the set of notification types to which an HTTP-based event\n * source subscribes. This should be a subset of the `key` properties\n * available in the `notification-types` module.\n *\n * @return {Set} The set of supported notification type keys\n */\n getSupportedNotificationTypes() {\n throw new Error(\"getSupportedNotificationTypes is not implemented\");\n },\n /**\n * Validate that the incoming HTTP event comes from the expected source, and\n * reply with a `200` status code and the proper validation token header, as\n * described here:\n * https://community.ringcentral.com/questions/1306/validation-token-is-not-returned-when-creating-a-s.html\n *\n * In case the event comes from an unrecognized source, reply with a `404`\n * status code.\n *\n * The result of this method indicates whether the incoming event was valid\n * or not.\n *\n * @param {object} event The HTTP event that triggers this event source\n * @return {boolean} The outcome of the validation check (`true` for valid\n * events, `false` otherwise)\n */\n validateEvent(event) {\n const {\n \"validation-token\": validationToken,\n \"verification-token\": verificationToken,\n } = event.headers;\n\n const expectedVerificationToken = this.db.get(\"verificationToken\") || verificationToken;\n if (verificationToken !== expectedVerificationToken) {\n this.http.respond({ status: 404 });\n return false;\n }\n\n this.http.respond({\n status: 200,\n headers: {\n \"validation-token\": validationToken,\n },\n });\n return true;\n },\n /**\n * Determines if the incoming event is relevant to this particular event\n * source, so that it's either processed or skipped in case it's relevant or\n * not, respectively.\n *\n * @param {object} event The HTTP event that triggers this event source\n * @return {boolean} Whether the incoming event is relevant to this event\n * source or not\n */\n isEventRelevant(event) {\n return true;\n },\n processEvent(event) {\n const { body } = event;\n if (!body) {\n console.log(\"Empty event payload. Skipping...\");\n return;\n }\n\n if (!this.isEventRelevant(event)) {\n console.log(\"Event is irrelevant. Skipping...\")\n return;\n }\n\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n },\n },\n async run(event) {\n const isValidEvent = this.validateEvent(event);\n if (!isValidEvent) {\n console.log(\"Invalid event. Skipping...\");\n return;\n }\n\n return this.processEvent(event);\n },\n};\n\n\n<|start_filename|>components/webflow/webflow.app.js<|end_filename|>\nconst Webflow = require(\"webflow-api\");\n\nmodule.exports = {\n type: \"app\",\n app: \"webflow\",\n methods: {\n _apiVersion() {\n return \"1.0.0\";\n },\n _authToken() {\n return this.$auth.oauth_access_token;\n },\n _createApiClient() {\n const token = this._authToken();\n const version = this._apiVersion();\n const clientOpts = {\n token,\n version,\n };\n return new Webflow(clientOpts);\n },\n async listSites() {\n const apiClient = this._createApiClient();\n return apiClient.sites();\n },\n async createWebhook(siteId, url, triggerType, filter = {}) {\n const apiClient = this._createApiClient();\n const params = {\n siteId,\n triggerType,\n url,\n filter,\n };\n return apiClient.createWebhook(params);\n },\n async removeWebhook(siteId, webhookId) {\n const apiClient = this._createApiClient();\n const params = {\n siteId,\n webhookId,\n };\n return apiClient.removeWebhook(params);\n },\n async listCollections(siteId) {\n const apiClient = this._createApiClient();\n const params = {\n siteId,\n };\n return apiClient.collections(params);\n },\n },\n};\n\n\n<|start_filename|>components/twitter/sources/new-tweet-in-list/new-tweet-in-list.js<|end_filename|>\nconst base = require(\"../common/tweets\");\n\nmodule.exports = {\n ...base,\n key: \"twitter-new-tweet-in-list\",\n name: \"New Tweet in List\",\n description: \"Emit new Tweets posted by members of a list\",\n version: \"0.0.1\",\n props: {\n ...base.props,\n includeRetweets: {\n propDefinition: [\n base.props.twitter,\n \"includeRetweets\",\n ],\n },\n list: {\n type: \"string\",\n description: \"The Twitter list to watch for new Tweets\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return [];\n }\n\n const lists = await this.twitter.getLists();\n return lists.map(({\n name,\n id_str,\n }) => ({\n label: name,\n value: id_str,\n }));\n },\n },\n includeEntities: {\n type: \"boolean\",\n label: \"Entities\",\n description: `\n Include the 'entities' node, which offers a variety of metadata about the\n tweet in a discreet structure, including: user_mentions, urls, and hashtags\n `,\n default: false,\n },\n },\n methods: {\n ...base.methods,\n shouldIncludeRetweets() {\n return this.includeRetweets !== \"exclude\";\n },\n retrieveTweets() {\n return this.twitter.getListTweets({\n list_id: this.list,\n count: this.count,\n since_id: this.getSinceId(),\n includeEntities: this.includeEntities,\n includeRetweets: this.shouldIncludeRetweets(),\n });\n },\n },\n};\n\n\n<|start_filename|>components/twitter_developer_app/sources/new-tweet-metrics/new-tweet-metrics.js<|end_filename|>\nconst isEqual = require(\"lodash/isEqual\");\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"twitter_developer_app-new-tweet-metrics\",\n name: \"New Tweet Metrics\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n tweetIds: {\n type: \"string[]\",\n label: \"Tweet IDs\",\n description: \"The IDs of the Tweets for which to retrieve metrics\",\n },\n onlyChangedMetrics: {\n type: \"boolean\",\n label: \"Only Changed Metrics?\",\n description: `\n When enabled, this event source will only emit events if the values of the\n retrieved metrics changed\n `,\n default: false,\n },\n excludePublic: {\n type: \"boolean\",\n label: \"Exclude Public Metrics\",\n description: \"Exclude public metrics from the emitted events\",\n default: false,\n },\n excludeNonPublic: {\n type: \"boolean\",\n label: \"Exclude Non-Public Metrics\",\n description: \"Exclude non-public metrics from the emitted events\",\n default: false,\n },\n excludeOrganic: {\n type: \"boolean\",\n label: \"Exclude Organic Metrics\",\n description: \"Exclude organic metrics from the emitted events\",\n default: false,\n },\n },\n hooks: {\n deactivate() {\n this._setLastMetrics(null);\n },\n },\n methods: {\n ...common.methods,\n _getLastMetrics() {\n return this.db.get(\"lastmetrics\");\n },\n _setLastMetrics(metrics) {\n this.db.set(\"lastmetrics\", metrics);\n },\n _shouldSkipExecution(metrics) {\n return (\n this.onlyChangedMetrics &&\n isEqual(this._getLastMetrics(), metrics)\n );\n },\n generateMeta({\n event,\n metrics,\n }) {\n const { id: tweetId } = metrics;\n const { timestamp: ts } = event;\n const id = `${tweetId}-${ts}`;\n const summary = \"New metrics\";\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const metrics = await this.twitter_developer_app.getMetricsForIds({\n tweetIds: this.tweetIds,\n excludePublic: this.excludePublic,\n excludeNonPublic: this.excludeNonPublic,\n excludeOrganic: this.excludeOrganic,\n });\n\n if (this._shouldSkipExecution(metrics)) {\n console.log(\"No new metrics found. Skipping...\");\n return;\n }\n\n const meta = this.generateMeta({\n event,\n metrics,\n });\n this.$emit(metrics, meta);\n\n this._setLastMetrics(metrics);\n },\n};\n\n\n<|start_filename|>components/twitch/actions/unblock-user/unblock-user.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Unblock User\",\n key: \"twitch-unblock-user\",\n description: \"Unblocks a user; that is, deletes a specified target user to your blocks list\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n user: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"User ID of the user to be unblocked\",\n },\n },\n async run() {\n const params = {\n target_user_id: this.user,\n };\n const {\n status,\n statusText,\n } = await this.twitch.unblockUser(params);\n return status == 204\n ? \"User Successfully Unblocked\"\n : `${status} ${statusText}`;\n },\n};\n\n\n<|start_filename|>components/microsoft_onedrive/microsoft_onedrive.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst get = require(\"lodash/get\");\nconst querystring = require(\"querystring\");\nconst retry = require(\"async-retry\");\n\nmodule.exports = {\n type: \"app\",\n app: \"microsoft_onedrive\",\n methods: {\n _apiUrl() {\n return \"https://graph.microsoft.com/v1.0\";\n },\n _authToken() {\n return this.$auth.oauth_access_token;\n },\n /**\n * This is a utility method that returns the path to the authenticated\n * user's OneDrive drive\n *\n * @returns the path to the user's drive\n */\n _getMainDrivePath() {\n return \"/me/drive\";\n },\n /**\n * This is a utility method that returns the path to a OneDrive drive based\n * on its identifier, or the authenticated user's drive if an identifier is\n * not specified.\n *\n * @param {string} [driveId] the OneDrive drive identifier. When not\n * provided, the method returns the path of the authenticated user's drive.\n * @returns the path to the specified drive\n */\n _getDrivePath(driveId) {\n return driveId\n ? `/drives/${driveId}`\n : this._getMainDrivePath();\n },\n /**\n * This is a utility method that returns the path to a OneDrive item based\n * on its identifier, or the root if an identifier is not specified.\n *\n * @param {string} [itemId] the OneDrive item identifier. When not\n * provided, the method returns the path of the root item.\n * @returns the path to the specified drive\n */\n _getDriveItemPath(itemId) {\n return itemId\n ? `/items/${itemId}`\n : \"/root\";\n },\n /**\n * This is a utility method that returns the API URL that references a\n * OneDrive drive\n *\n * @param {string} [driveId] the OneDrive drive identifier. When not\n * provided, the method returns the URL of the authenticated user's drive.\n * @returns the API URL referrencing a OneDrive drive\n */\n _driveEndpoint(driveId) {\n const baseUrl = this._apiUrl();\n const drivePath = this._getDrivePath(driveId);\n return `${baseUrl}${drivePath}`;\n },\n /**\n * This is a utility method that returns the API URL of the [OneDrive Delta\n * Link](https://bit.ly/3fNawcs) endpoint. Depending on the input arguments\n * provided by the caller, the endpoint will refer to the Delta endpoint of\n * a particular drive and/or folder.\n *\n * @example\n * // returns `${baseUrl}/me/drive/root/delta`\n * this._deltaEndpoint();\n *\n * @example\n * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/root/delta`\n * this._deltaEndpoint({ driveId: \"bf3ec8cc5e81199f\" });\n *\n * @example\n * // returns `${baseUrl}/me/drive/items/BF3EC8CC5E81199F!104/delta`\n * this._deltaEndpoint({ folderId: \"BF3EC8CC5E81199F!104\" });\n *\n * @example\n * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/items/BF3EC8CC5E81199F!104/delta`\n * this._deltaEndpoint({\n * driveId: \"bf3ec8cc5e81199f\",\n * folderId: \"BF3EC8CC5E81199F!104\",\n * });\n *\n * @param {object} [opts] an object containing the different options\n * referring to the target of the Delta Link endpoint\n * @param {string} [opts.driveId] the OneDrive drive identifier. When not\n * provided, the method uses the ID of the authenticated user's drive.\n * @param {string} [opts.folderId] when provided, the returned URL will\n * point to the Delta Link endpoint of the specified folder. Otherwise, it\n * will point to the root of the drive.\n * @returns a [OneDrive Delta Link](https://bit.ly/3fNawcs) endpoint URL\n */\n _deltaEndpoint({\n driveId,\n folderId,\n } = {}) {\n const baseUrl = this._apiUrl();\n const drivePath = this._getDrivePath(driveId);\n const itemPath = this._getDriveItemPath(folderId);\n return `${baseUrl}${drivePath}${itemPath}/delta`;\n },\n /**\n * This is a utility method that returns the API URL of the endpoint\n * referencing to a drive folder's [children](https://bit.ly/3sC6V3F). The\n * specific drive and item are customizable.\n *\n * @example\n * // returns `${baseUrl}/me/drive/root/children`\n * this._deltaEndpoint();\n *\n * @example\n * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/root/children`\n * this._deltaEndpoint({ driveId: \"bf3ec8cc5e81199f\" });\n *\n * @example\n * // returns `${baseUrl}/me/drive/items/BF3EC8CC5E81199F!104/children`\n * this._deltaEndpoint({ folderId: \"BF3EC8CC5E81199F!104\" });\n *\n * @example\n * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/items/BF3EC8CC5E81199F!104/children`\n * this._deltaEndpoint({\n * driveId: \"bf3ec8cc5e81199f\",\n * folderId: \"BF3EC8CC5E81199F!104\",\n * });\n *\n * @param {object} [opts] an object containing the different options\n * referring to the target of the Delta Link endpoint\n * @param {string} [opts.driveId] the OneDrive drive identifier. When not\n * provided, the method uses the ID of the authenticated user's drive.\n * @param {string} [opts.folderId] when provided, the returned URL will\n * point to the children endpoint of the specified folder. Otherwise, it\n * will point to the root of the drive.\n * @returns an endpoint URL referencing the drive folder's children\n */\n _driveChildrenEndpoint({\n driveId,\n folderId,\n } = {}) {\n const baseUrl = this._apiUrl();\n const drivePath = this._getDrivePath(driveId);\n const itemPath = this._getDriveItemPath(folderId);\n return `${baseUrl}${drivePath}${itemPath}/children`;\n },\n _subscriptionsEndpoint(id) {\n const baseUrl = this._apiUrl();\n const url = `${baseUrl}/subscriptions`;\n return id\n ? `${url}/${id}`\n : url;\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n /**\n * This method is intended to be used as a decorator around external API\n * calls. It provides exponential backoff retries for the calls made to a\n * specified function, and aborts with an exception if the call fails with a\n * non-retriable error or if the maximum retry count is reached.\n *\n * @param {function} apiCall is a function that encapsulates an API call.\n * The function will be called without any additional parameters, so this\n * argument should already define the closure needed to operate.\n * @param {function} [isRequestRetriable] is a function that determines\n * whether a failed request should be retried or not based on the exception\n * thrown by a call to the `apiCall` argument. When it's not provided, the\n * behaviour defaults to retrying the call based on the value of\n * `exception.response.status` (see the `_isStatusCodeRetriable` method).\n * @returns a promise containing the result of the call to `apiCall`, or an\n * exception containing the details about the last error\n */\n _withRetries(\n apiCall,\n isRequestRetriable = this._isStatusCodeRetriable.bind(this),\n ) {\n const retryOpts = {\n retries: 5,\n factor: 2,\n minTimeout: 2000, // In milliseconds\n };\n return retry(async (bail, retryCount) => {\n try {\n return await apiCall();\n } catch (err) {\n if (!isRequestRetriable(err)) {\n const statusCode = get(err, [\n \"response\",\n \"status\",\n ]);\n const errData = get(err, [\n \"response\",\n \"data\",\n ], {});\n return bail(new Error(`\n Unexpected error (status code: ${statusCode}):\n ${JSON.stringify(errData, null, 2)}\n `));\n }\n\n console.log(`\n [Attempt #${retryCount}] Temporary error: ${err.message}\n `);\n throw err;\n }\n }, retryOpts);\n },\n _isStatusCodeRetriable(responseErr) {\n const statusCode = get(responseErr, [\n \"response\",\n \"status\",\n ]);\n return [\n 429,\n 500,\n 503,\n 509,\n ].includes(statusCode);\n },\n _isHookRequestRetriable(responseErr) {\n // Sometimes an API call to create a webhook/subscription fails because\n // our component was unable to quickly validate the subscription. In those\n // cases, we want to retry the request since at this point the webhook is\n // not created but the request itself is well formed.\n //\n // See the docs for more information on how webhooks are validated upon\n // creation: https://bit.ly/3fzc3Tr\n const errPattern = /endpoint must respond .*? to validation request/i;\n const errMsg = get(responseErr, [\n \"response\",\n \"data\",\n \"error\",\n \"message\",\n ], \"\");\n return (\n errPattern.test(errMsg) ||\n this._isStatusCodeRetriable(responseErr)\n );\n },\n _getDefaultHookExpirationDateTime() {\n // 30 days from now\n const futureTimestamp = Date.now() + 43200 * 60 * 1000;\n return new Date(futureTimestamp).toISOString();\n },\n /**\n * This method creates a [OneDrive webhook](https://bit.ly/2PxfQ9j) to\n * monitor a specific resource, defaulted to the authenticated user's drive.\n *\n * @param {string} notificationUrl the target URL of the webhook\n * @param {object} [opts] an object containing the different options for\n * the hook creation\n * @param {string} [opts.driveId] the resource to which the webhook will\n * subscribe for events\n * @param {string} [opts.expirationDateTime] the timestamp of the hook\n * subscription expiration, in ISO-8601 format. Defaults to 30 days after\n * the time this method is called.\n * @returns the ID of the created webhook\n */\n async createHook(notificationUrl, {\n driveId,\n expirationDateTime = this._getDefaultHookExpirationDateTime(),\n } = {}) {\n const url = this._subscriptionsEndpoint();\n const drivePath = this._getDrivePath(driveId);\n const resource = `${drivePath}/root`;\n const requestData = {\n notificationUrl,\n resource,\n expirationDateTime,\n changeType: \"updated\",\n };\n const requestConfig = this._makeRequestConfig();\n const { data: { id: hookId } = {} } = await this._withRetries(\n () => axios.post(url, requestData, requestConfig),\n this._isHookRequestRetriable.bind(this),\n );\n return hookId;\n },\n /**\n * This method performs an update to a [OneDrive\n * webhook](https://bit.ly/2PxfQ9j). An example of such operation is to\n * extend the expiration time of a webhook subscription.\n *\n * @param {string} id the ID of the webhook to update\n * @param {object} [opts] the fields to update in the webhook\n * @param {string} [opts.expirationDateTime] the new expiration date of the\n * webhook subscription\n */\n async updateHook(id, { expirationDateTime } = {}) {\n const url = this._subscriptionsEndpoint(id);\n const requestData = {\n expirationDateTime,\n };\n const requestConfig = this._makeRequestConfig();\n await this._withRetries(\n () => axios.patch(url, requestData, requestConfig),\n this._isHookRequestRetriable.bind(this),\n );\n },\n /**\n * This method deletes an existing [OneDrive\n * webhook](https://bit.ly/2PxfQ9j)\n *\n * @param {string} id the ID of the webhook to delete\n */\n async deleteHook(id) {\n const url = this._subscriptionsEndpoint(id);\n const requestConfig = this._makeRequestConfig();\n await this._withRetries(\n () => axios.delete(url, requestConfig),\n );\n },\n /**\n * This method returns a parameterized [OneDrive Delta\n * Link](https://bit.ly/3fNawcs) for a particular drive and/or item\n * (defaulting to the root of the authenticated user's drive). The link will\n * also include additional query parameters, depending on the options\n * provded by the caller.\n *\n * @param {object} [opts] an object containing the different options to\n * customize the Delta Link\n * @param {string} [opts.driveId] the OneDrive drive identifier. When not\n * provided, the method uses the ID of the authenticated user's drive.\n * @param {string} [opts.folderId] the top-level folder that the returned\n * Delta Link will track. When left unset, the link will refer to the entire\n * drive.\n * @param {number} [opts.pageSize] the size of the page that a call to the\n * returned Delta Link will retrieve (see the `$top` parameter in the [Delta\n * Link docs](https://bit.ly/3sRzRpn))\n * @param {string} [opts.token] a [Delta Link\n * token](https://bit.ly/3ncApEf), which will be directly added to the\n * returned link. Especially useful when retrieving the _latest_ Delta Link.\n * @returns a [OneDrive Delta Link](https://bit.ly/3fNawcs)\n */\n getDeltaLink({\n driveId,\n folderId,\n pageSize,\n token,\n } = {}) {\n const url = this._deltaEndpoint({\n driveId,\n folderId,\n });\n\n const params = {};\n if (pageSize) {\n params.$top = Math.max(pageSize, 1);\n }\n if (token) {\n params.token = token;\n }\n const paramsString = querystring.stringify(params);\n\n return `${url}?${paramsString}`;\n },\n /**\n * This method retrieves the [latest OneDrive Delta\n * Link](https://bit.ly/3wB5d5O) for the authenticated user's drive\n *\n * @param {object} [opts] an object containing the different options to\n * customize the retrieved Delta Link\n * @param {string} [opts.folderId] the top-level folder to track with the\n * Delta Link. When left unset, the link will refer to the entire drive.\n * @returns the [latest OneDrive Delta Link](https://bit.ly/3wB5d5O)\n */\n async getLatestDeltaLink({ folderId } = {}) {\n const params = {\n token: \"\",\n folderId,\n };\n const url = this.getDeltaLink(params);\n const requestConfig = this._makeRequestConfig();\n const { data } = await this._withRetries(\n () => axios.get(url, requestConfig),\n );\n return data[\"@odata.deltaLink\"];\n },\n /**\n * This generator method scans the latest updated items in a OneDrive drive\n * based on the provided Delta Link. It yields drive items until the updated\n * items collection is exhausted, after which it finally returns the Delta\n * Link to use in future scans.\n *\n * @param {string} deltaLink the [OneDrive Delta\n * Link](https://bit.ly/3fNawcs) from where to start scanning the drive's\n * items\n * @yields the next updated item in the drive\n * @returns the Delta Link to use in the next drive scan\n */\n async *scanDeltaItems(deltaLink) {\n const requestConfig = this._makeRequestConfig();\n let url = deltaLink;\n while (url) {\n // See the docs for more information on the format of the delta API\n // response: https://bit.ly/31I0wZP\n const { data } = await this._withRetries(\n () => axios.get(url, requestConfig),\n );\n const {\n \"@odata.nextLink\": nextLink,\n \"@odata.deltaLink\": nextDeltaLink,\n \"value\": items,\n } = data;\n for (const item of items) {\n yield item;\n }\n\n if (items.length === 0 || nextDeltaLink) {\n return nextDeltaLink;\n }\n\n url = nextLink;\n }\n },\n /**\n * This generator method scans the folders under the specified OneDrive\n * drive and/or folder. The scan is limited to the root of the specified\n * drive and/or folder (i.e. it does **not** perform a recursive scan).\n *\n * @param {object} [opts] an object containing the different options\n * referring to the target of the Delta Link endpoint\n * @param {string} [opts.driveId] the OneDrive drive identifier. When not\n * provided, the method uses the ID of the authenticated user's drive.\n * @param {string} [opts.folderId] when provided, the method will return\n * the child folders under this one. Otherwise, it will stick to the root of\n * the drive.\n * @yields the next child folder\n */\n async *listFolders({\n driveId,\n folderId,\n } = {}) {\n const fieldsToRetrieve = [\n \"folder\",\n \"id\",\n \"name\",\n ];\n const params = {\n $orderby: \"name\",\n $select: fieldsToRetrieve.join(\",\"),\n };\n const baseRequestConfig = this._makeRequestConfig();\n const requestConfig = {\n ...baseRequestConfig,\n params,\n };\n\n let url = this._driveChildrenEndpoint({\n driveId,\n folderId,\n });\n while (url) {\n const { data } = await this._withRetries(\n () => axios.get(url, requestConfig),\n );\n const {\n \"@odata.nextLink\": nextLink,\n \"value\": children,\n } = data;\n for (const child of children) {\n if (!child.folder) {\n // We skip non-folder children\n continue;\n }\n\n yield child;\n }\n\n url = nextLink;\n }\n },\n },\n};\n\n\n<|start_filename|>components/twitter_developer_app/actions/send-dm/send-dm.js<|end_filename|>\nconst twitter = require('../../twitter_developer_app.app.js')\nconst Twit = require('twit')\n \nmodule.exports = {\n key: \"twitter_developer_app-send-dm\",\n name: \"Send Direct Message (DM)\",\n description: \"Send a DM to a user.\", \n version: \"0.0.2\",\n type: \"action\",\n props: {\n twitter,\n recipient_id: { \n type: \"string\",\n label: \"Recipient ID\",\n description: \"The ID of the user who should receive the direct message. You must pass the string value of the numeric id (i.e, the value for the `id_str` field in Twitter's `user` object). For example, the correct ID to send a DM to `@pipedream` is `1067926271856766976`. If you only have the user's screen name, lookup the user first and pass the `id_str` to this field.\"\n },\n message: { \n type: \"string\",\n description: \"The text of your direct message. Max length of 10,000 characters. Max length of 9,990 characters if used as a [Welcome Message](https://developer.twitter.com/en/docs/direct-messages/welcome-messages/api-reference/new-welcome-message).\"\n },\n }, \n async run(event) {\n const { api_key, api_secret_key, access_token, access_token_secret } = this.twitter.$auth\n\n const T = new Twit({\n consumer_key: api_key,\n consumer_secret: api_secret_key,\n access_token,\n access_token_secret,\n timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.\n strictSSL: true, // optional - requires SSL certificates to be valid.\n })\n \n const response = await T.post(\"direct_messages/events/new\", {\n \"event\": {\n \"type\": \"message_create\",\n \"message_create\": {\n \"target\": {\n \"recipient_id\": this.recipient_id\n },\n \"message_data\": {\n \"text\": this.message\n }\n }\n }\n });\n \n return response.data.event\n },\n}\n\n\n<|start_filename|>components/sentry/sentry.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst { createHmac } = require(\"crypto\");\nconst parseLinkHeader = require(\"parse-link-header\");\nconst slugify = require(\"slugify\");\n\nmodule.exports = {\n type: \"app\",\n app: \"sentry\",\n propDefinitions: {\n organizationSlug: {\n type: \"string\",\n label: \"Organization\",\n description: \"The organization for which to consider issues events\",\n async options(context) {\n const url = this._organizationsEndpoint();\n const params = {}; // We don't need to provide query parameters at the moment.\n const { data, next } = await this._propDefinitionsOptions(url, params, context);\n const options = data.map(this._organizationObjectToOption);\n return {\n options,\n context: {\n nextPage: next,\n },\n };\n },\n },\n },\n methods: {\n _apiUrl() {\n return \"https://sentry.io/api/0\";\n },\n _organizationsEndpoint() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/organizations/`;\n },\n _integrationsEndpoint(integrationSlug) {\n const baseUrl = this._apiUrl();\n const url = `${baseUrl}/sentry-apps`;\n return integrationSlug ? `${url}/${integrationSlug}/` : `${url}/`;\n },\n _authToken() {\n return this.$auth.auth_token;\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `Bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n _organizationObjectToOption(organization) {\n const { name, slug } = organization;\n const label = `${name} (${slug})`;\n return {\n label,\n value: slug,\n };\n },\n async _propDefinitionsOptions(url, params, { page, prevContext }) {\n let requestConfig = this._makeRequestConfig(); // Basic axios request config\n if (page === 0) {\n // First time the options are being retrieved.\n // Include the parameters provided, which will be persisted\n // across the different pages.\n requestConfig = {\n ...requestConfig,\n params,\n };\n } else if (prevContext.nextPage) {\n // Retrieve next page of options.\n url = prevContext.nextPage.url;\n } else {\n // No more options available.\n return { data: [] };\n }\n\n const {\n data,\n headers: { link },\n } = await axios.get(url, requestConfig);\n // https://docs.sentry.io/api/pagination/\n const { next } = parseLinkHeader(link);\n\n return {\n data,\n next,\n };\n },\n _baseIntegrationParams() {\n return {\n scopes: [\n \"event:read\",\n ],\n events: [\n \"issue\",\n ],\n isAlertable: true,\n isInternal: true,\n verifyInstall: false,\n };\n },\n _formatIntegrationName(rawName) {\n const options = {\n remove: /[()]/g,\n lower: true,\n };\n const enrichedRawName = `pd-${rawName}`;\n return slugify(enrichedRawName, options).substring(0, 57);\n },\n async createIntegration(eventSourceName, organization, webhookUrl) {\n const url = this._integrationsEndpoint();\n const name = this._formatIntegrationName(eventSourceName);\n const requestData = {\n ...this._baseIntegrationParams(),\n name,\n organization,\n webhookUrl,\n };\n const requestConfig = this._makeRequestConfig();\n const { data } = await axios.post(url, requestData, requestConfig);\n return data;\n },\n async deleteIntegration(integrationSlug) {\n const url = this._integrationsEndpoint(integrationSlug);\n const requestConfig = this._makeRequestConfig();\n await axios.delete(url, requestConfig);\n },\n async disableIntegration(integrationSlug) {\n const url = this._integrationsEndpoint(integrationSlug);\n const requestConfig = this._makeRequestConfig();\n const requestData = {\n events: null,\n isAlertable: false,\n name: \"pipedream (disabled)\",\n webhookUrl: null,\n };\n await axios.put(url, requestData, requestConfig);\n },\n async getClientSecret(integrationSlug) {\n const url = this._integrationsEndpoint(integrationSlug);\n const requestConfig = this._makeRequestConfig();\n const { data } = await axios.get(url, requestConfig);\n return data.clientSecret;\n },\n isValidSource(event, clientSecret) {\n const {\n headers: {\n \"sentry-hook-signature\": signature,\n },\n bodyRaw,\n } = event;\n const hmac = createHmac(\"sha256\", clientSecret);\n hmac.update(bodyRaw, \"utf8\");\n const digest = hmac.digest(\"hex\");\n return digest === signature;\n },\n },\n};\n\n\n<|start_filename|>components/textlocal/sources/common/timer-based.js<|end_filename|>\nconst base = require(\"./base\");\n\nmodule.exports = {\n ...base,\n props: {\n ...base.props,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15, // 15 minutes\n },\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/eventbrite.app.js<|end_filename|>\nconst axios = require(\"axios\");\n/* timezone-list: https://www.npmjs.com/package/timezones-list */\nconst timezones = require(\"timezones-list\");\n\nmodule.exports = {\n type: \"app\",\n app: \"eventbrite\",\n propDefinitions: {\n organization: {\n type: \"string\",\n label: \"Organization\",\n async options({ prevContext }) {\n const {\n prevHasMore: hasMore = false,\n prevContinuation: continuation,\n } = prevContext;\n const params = hasMore\n ? {\n continuation,\n }\n : null;\n const {\n organizations,\n pagination,\n } = await this.listMyOrganizations(\n params,\n );\n const options = organizations.map((org) => {\n const {\n name,\n id,\n } = org;\n return {\n label: name,\n value: id,\n };\n });\n const {\n has_more_items: prevHasMore,\n continuation: prevContinuation,\n } = pagination;\n return {\n options,\n context: {\n prevHasMore,\n prevContinuation,\n },\n };\n },\n },\n eventId: {\n type: \"integer\",\n label: \"Event ID\",\n description: \"Enter the ID of an event\",\n },\n timezone: {\n type: \"string\",\n label: \"Timezone\",\n description: \"The timezone\",\n default: \"UTC\",\n async options() {\n timezones.unshift({\n label: \"UTC (GMT+00:00)\",\n tzCode: \"UTC\",\n });\n return timezones.map(({\n label, tzCode,\n }) => ({\n label,\n value: tzCode,\n }));\n },\n },\n },\n methods: {\n _getBaseUrl() {\n return \"https://www.eventbriteapi.com/v3/\";\n },\n _getHeaders() {\n return {\n \"Authorization\": `Bearer ${this.$auth.oauth_access_token}`,\n \"Content-Type\": \"application/json\",\n };\n },\n async _makeRequest(\n method,\n endpoint,\n params = null,\n data = null,\n url = `${this._getBaseUrl()}${endpoint}`,\n ) {\n const config = {\n method,\n url,\n headers: this._getHeaders(),\n params,\n data,\n };\n return (await axios(config)).data;\n },\n async createHook(orgId, data) {\n return await this._makeRequest(\n \"POST\",\n `organizations/${orgId}/webhooks/`,\n null,\n data,\n );\n },\n async deleteHook(hookId) {\n return await this._makeRequest(\"DELETE\", `webhooks/${hookId}/`);\n },\n async listMyOrganizations(params) {\n return await this._makeRequest(\"GET\", \"users/me/organizations\", params);\n },\n async listEvents(\n {\n orgId,\n params,\n },\n ) {\n return await this._makeRequest(\n \"GET\",\n `organizations/${orgId}/events/`,\n params,\n );\n },\n async getResource(url) {\n return await this._makeRequest(\"GET\", null, null, null, url);\n },\n async getEvent(eventId, params = null) {\n return await this._makeRequest(\"GET\", `events/${eventId}/`, params);\n },\n async getOrderAttendees(orderId) {\n return await this._makeRequest(\"GET\", `orders/${orderId}/attendees/`);\n },\n async getEventAttendees(eventId, params = null) {\n return await this._makeRequest(\n \"GET\",\n `events/${eventId}/attendees/`,\n params,\n );\n },\n async createEvent(orgId, data) {\n return await this._makeRequest(\n \"POST\",\n `organizations/${orgId}/events/`,\n null,\n data,\n );\n },\n },\n};\n\n\n<|start_filename|>components/clickup/package-lock.json<|end_filename|>\n{\n \"name\": \"@pipedream/clickup\",\n \"version\": \"0.0.1\",\n \"lockfileVersion\": 1,\n \"requires\": true,\n \"dependencies\": {\n \"axios\": {\n \"version\": \"0.21.1\",\n \"resolved\": \"https://registry.npmjs.org/axios/-/axios-0.21.1.tgz\",\n \"integrity\": \"\n \"requires\": {\n \"follow-redirects\": \"^1.10.0\"\n }\n },\n \"axios-retry\": {\n \"version\": \"3.1.9\",\n \"resolved\": \"https://registry.npmjs.org/axios-retry/-/axios-retry-3.1.9.tgz\",\n \"integrity\": \"sha512-NFCoNIHq8lYkJa6ku4m+V1837TP6lCa7n79Iuf8/AqATAHYB0ISaAS1eyIenDOfHOLtym34W65Sjke2xjg2fsA==\",\n \"requires\": {\n \"is-retry-allowed\": \"^1.1.0\"\n }\n },\n \"follow-redirects\": {\n \"version\": \"1.14.2\",\n \"resolved\": \"https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.2.tgz\",\n \"integrity\": \"\n },\n \"is-retry-allowed\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz\",\n \"integrity\": \"\n }\n }\n}\n\n\n<|start_filename|>components/mailgun/actions/send-email/send-email.js<|end_filename|>\nconst mailgun = require(\"../../mailgun.app.js\");\n\nmodule.exports = {\n key: \"mailgun-send-email\",\n name: \"Mailgun Send Email\",\n description: \"Send email with Mailgun.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n mailgun,\n domain: {\n propDefinition: [\n mailgun,\n \"domain\",\n ],\n },\n fromName: {\n type: \"string\",\n label: \"From Name\",\n description: \"Sender name\",\n },\n from: {\n type: \"string\",\n label: \"From Email\",\n description: \"Sender email address\",\n },\n replyTo: {\n type: \"string\",\n label: \"Reply-To\",\n description: \"Sender reply email address\",\n optional: true,\n },\n to: {\n type: \"string[]\",\n label: \"To\",\n description: \"Recipient email address(es)\",\n },\n cc: {\n type: \"string[]\",\n label: \"CC\",\n description: \"Copy email address(es)\",\n optional: true,\n },\n bcc: {\n type: \"string[]\",\n label: \"BCC\",\n description: \"Blind copy email address(es)\",\n optional: true,\n },\n subject: {\n type: \"string\",\n label: \"Subject\",\n description: \"Message subject\",\n },\n text: {\n type: \"string\",\n label: \"Message Body (text)\",\n },\n html: {\n type: \"string\",\n label: \"Message Body (HTML)\",\n optional: true,\n },\n testMode: {\n type: \"boolean\",\n label: \"Send in test mode?\",\n default: true,\n description: \"Enables sending in test mode. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)\",\n },\n dkim: {\n type: \"boolean\",\n label: \"Use DKIM?\",\n default: true,\n description: \"Enables or disables DKIM signatures. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)\",\n optional: true,\n },\n tracking: {\n type: \"boolean\",\n label: \"Use Tracking?\",\n default: true,\n description: \"Enables or disables tracking. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)\",\n optional: true,\n },\n haltOnError: {\n propDefinition: [\n mailgun,\n \"haltOnError\",\n ],\n },\n },\n async run () {\n try {\n const msg = {\n \"from\": `${this.fromName} <${this.from}>`,\n \"to\": this.to,\n \"cc\": this.cc,\n \"bcc\": this.bcc,\n \"subject\": this.subject,\n \"text\": this.text,\n \"html\": this.html,\n \"o:testmode\": this.testMode,\n };\n if (this.replyTo) {\n msg[\"h:Reply-To\"] = this.replyTo;\n }\n if (this.dkim !== null) {\n msg[\"o:dkim\"] = this.dkim\n ? \"yes\"\n : \"no\";\n }\n if (this.tracking) {\n msg[\"o:tracking\"] = \"yes\";\n }\n return await this.mailgun.api(\"messages\").create(this.domain, msg);\n } catch (err) {\n if (this.haltOnError) {\n throw err;\n }\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/zoom/package.json<|end_filename|>\n{\n \"name\": \"@pipedream/zoom\",\n \"version\": \"0.3.3\",\n \"description\": \"Pipedream Zoom Components\",\n \"main\": \"zoom.app.js\",\n \"keywords\": [\n \"pipedream\",\n \"zoom\"\n ],\n \"homepage\": \"https://pipedream.com/apps/zoom\",\n \"author\": \"Pipedream <> (https://pipedream.com/)\",\n \"license\": \"MIT\",\n \"gitHead\": \"e12480b94cc03bed4808ebc6b13e7fdb3a1ba535\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n\n\n<|start_filename|>components/microsoft_onedrive/sources/common/constants.js<|end_filename|>\nmodule.exports = {\n\n // Defaulting to 15 days. The maximum allowed expiration time is 30 days,\n // according to their API response message: \"Subscription expiration can only\n // be 43200 minutes in the future\".\n //\n // More information can be found in the official API docs:\n // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/using-webhooks?view=odsp-graph-online#expiration\n WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS: 43200 * 60 / 2,\n\n // The maximum amount of events sent during the initialization of the event\n // source. The number of emitted events might be lower than this, depending on\n // whether there's enough data to emit them or not.\n MAX_INITIAL_EVENT_COUNT: 10,\n\n};\n\n\n<|start_filename|>components/twitch/actions/update-channel/update-channel.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Update Channel\",\n key: \"twitch-update-channel\",\n description: `Update information for the channel owned by the authenticated user.\n At least one parameter must be provided.`,\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n title: {\n type: \"string\",\n label: \"Title\",\n description: \"The title of the stream. Value must not be an empty string\",\n optional: true,\n },\n game: {\n type: \"string\",\n label: \"Game ID\",\n description: `The current game ID being played on the channel. Use “0” or “” (an empty string)\n to unset the game`,\n optional: true,\n },\n language: {\n type: \"string\",\n label: \"Stream Language\",\n description:\n `A language value must be either the ISO 639-1 two-letter code for a supported stream\n language or \"other\".`,\n optional: true,\n },\n delay: {\n type: \"string\",\n label: \"Delay\",\n description: `Stream delay in seconds. Stream delay is a Twitch Partner feature trying to\n set this value for other account types will return a 400 error.`,\n optional: true,\n },\n },\n async run() {\n // get the userID of the authenticated user\n const userId = await this.getUserId();\n let params = {\n broadcaster_id: userId,\n game_id: this.game,\n broadcaster_language: this.language,\n title: this.title,\n delay: this.delay,\n };\n // remove empty values from params\n Object.keys(params).forEach((k) => (params[k] == null || params[k] == \"\") && delete params[k]);\n const result = (await this.twitch.updateChannel(params));\n\n // Response code of 204 indicates Channel/Stream updated successfully\n if (result.status !== 204)\n return result.data;\n\n // return updated channel information\n params = {\n broadcaster_id: userId,\n };\n return (await this.twitch.getChannelInformation(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/supersaas/envConf.js<|end_filename|>\nexports.urlPrefix = 'https://supersaas.com';\n\n\n<|start_filename|>components/netlify/sources/new-deploy-failure/new-deploy-failure.js<|end_filename|>\nconst common = require(\"../../common\");\n\nmodule.exports = {\n ...common,\n key: \"netlify-new-deploy-failure\",\n name: \"New Deploy Failure (Instant)\",\n description: \"Emits an event when a new deployment fails\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getHookEvent() {\n return \"deploy_failed\";\n },\n getMetaSummary(data) {\n const { commit_ref } = data;\n return `Deploy failed for commit ${commit_ref}`;\n },\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/new-automation-webhook/new-automation-webhook.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Automation Webhook\",\n key: \"activecampaign-new-automation-webhook\",\n description: \"Emits an event each time an automation sends out webhook data.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n automations: { propDefinition: [activecampaign, \"automations\"] },\n },\n methods: {\n isWatchedAutomation(automation) {\n return (\n this.automations.length === 0 ||\n this.automations.includes(automation.id)\n );\n },\n isAutomationRelevant(automation) {\n if (!this.isWatchedAutomation(automation)) return false;\n const entered = this.db.get(automation.id) || 0; // number of times automation has run\n if (parseInt(automation.entered) <= entered) return false;\n this.db.set(automation.id, parseInt(automation.entered));\n return true;\n },\n getMeta(automation) {\n return {\n id: `${automation.id}${automation.entered}`,\n summary: automation.name,\n ts: Date.now(),\n };\n },\n },\n async run() {\n let prevContext = { offset: 0 };\n let total = 1;\n let count = 0;\n while (count < total) {\n const { results, context } = await this.activecampaign._getNextOptions(\n this.activecampaign.listAutomations.bind(this),\n prevContext\n );\n prevContext = context;\n total = results.meta.total;\n\n if (total == 0) continue;\n\n for (const automation of results.automations) {\n count++;\n if (!this.isAutomationRelevant(automation)) continue;\n const { id, summary, ts } = this.getMeta(automation);\n this.$emit(automation, {\n id,\n summary,\n ts,\n });\n }\n }\n },\n};\n\n<|start_filename|>components/twitch/actions/check-channel-subscription/check-channel-subscription.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Check Channel Subscription\",\n key: \"twitch-check-channel-subscription\",\n description: \"Checks if you are subscribed to the specified user's channel\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n user: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"User ID of the channel to check for a subscription to\",\n },\n },\n async run() {\n // get the userID of the authenticated user\n const userId = await this.getUserId();\n const params = {\n broadcaster_id: this.user,\n user_id: userId,\n };\n try {\n return (await this.twitch.checkUserSubscription(params)).data.data;\n } catch (err) {\n // if no subscription is found, a 404 error is returned\n if (err.message.includes(\"404\"))\n return `${userId} has no subscription to ${this.user}`;\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/slack/actions/find-user-by-email/find-user-by-email.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-find-user-by-email\",\n name: \"Find User by Email\",\n description: \"Find a user by matching against their email\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n email: {\n propDefinition: [\n slack,\n \"email\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().users.lookupByEmail({\n email: this.email,\n });\n },\n};\n\n\n<|start_filename|>components/pipefy/sources/common.js<|end_filename|>\nconst pipefy = require(\"../pipefy.app.js\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n pipefy,\n db: \"$.service.db\",\n pipeId: {\n type: \"integer\",\n label: \"Pipe ID\",\n description: \"ID of the Pipe, found in the URL when viewing the Pipe.\",\n },\n },\n};\n\n<|start_filename|>components/aws/.upm/store.json<|end_filename|>\n{\"version\":2,\"languages\":{\"nodejs-npm\":{\"guessedImports\":[\"aws-sdk\",\"axios\",\"shortid\"],\"guessedImportsHash\":\"08190b61ee0169fd35ea81dce6f4754d\"}}}\n\n\n<|start_filename|>components/datadog/datadog.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst { v4: uuid } = require(\"uuid\");\n\nmodule.exports = {\n type: \"app\",\n app: \"datadog\",\n methods: {\n _apiKey() {\n return this.$auth.api_key;\n },\n _applicationKey() {\n return this.$auth.application_key;\n },\n _baseUrl() {\n return (\n this.$auth.base_url ||\n \"https://api.datadoghq.com/api/v1\"\n );\n },\n _webhooksUrl(name) {\n const baseUrl = this._baseUrl();\n const basePath = \"/integration/webhooks/configuration/webhooks\";\n const path = name ? `${basePath}/${name}` : basePath;\n return `${baseUrl}${path}`;\n },\n _monitorsUrl(id) {\n const baseUrl = this._baseUrl();\n const basePath = \"/monitor\";\n const path = id ? `${basePath}/${id}` : basePath;\n return `${baseUrl}${path}`;\n },\n _monitorsSearchUrl() {\n const baseUrl = this._baseUrl();\n return `${baseUrl}/monitor/search`;\n },\n _makeRequestConfig() {\n const apiKey = this._apiKey();\n const applicationKey = this._applicationKey();\n const headers = {\n \"DD-API-KEY\": apiKey,\n \"DD-APPLICATION-KEY\": applicationKey,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n _webhookSecretKeyHeader() {\n return \"x-webhook-secretkey\";\n },\n _webhookTagPattern(webhookName) {\n return `@webhook-${webhookName}`;\n },\n isValidSource(event, secretKey) {\n const { headers } = event;\n return headers[this._webhookSecretKeyHeader()] === secretKey;\n },\n async _getMonitor(monitorId) {\n const apiUrl = this._monitorsUrl(monitorId);\n const requestConfig = this._makeRequestConfig();\n const { data } = await axios.get(apiUrl, requestConfig);\n return data;\n },\n async _editMonitor(monitorId, monitorChanges) {\n const apiUrl = this._monitorsUrl(monitorId);\n const requestConfig = this._makeRequestConfig();\n await axios.put(apiUrl, monitorChanges, requestConfig);\n },\n async *_searchMonitors(query) {\n const apiUrl = this._monitorsSearchUrl();\n const baseRequestConfig = this._makeRequestConfig();\n let page = 0;\n let pageCount;\n let perPage;\n do {\n const params = {\n page,\n query,\n };\n const requestConfig = {\n ...baseRequestConfig,\n params,\n };\n const {\n data: {\n monitors,\n metadata,\n },\n } = await axios.get(apiUrl, requestConfig);\n for (const monitor of monitors) {\n yield monitor;\n }\n\n ++page;\n pageCount = metadata.page_count;\n perPage = metadata.per_page;\n } while (pageCount === perPage);\n },\n async listMonitors(page, pageSize) {\n const apiUrl = this._monitorsUrl();\n const baseRequestConfig = this._makeRequestConfig();\n const params = {\n page,\n page_size: pageSize,\n };\n const requestConfig = {\n ...baseRequestConfig,\n params,\n };\n const { data } = await axios.get(apiUrl, requestConfig);\n return data;\n },\n async createWebhook(\n url,\n payloadFormat = null,\n secretKey = uuid(),\n ) {\n const apiUrl = this._webhooksUrl();\n const requestConfig = this._makeRequestConfig();\n\n const name = `pd-${uuid()}`;\n const customHeaders = {\n [this._webhookSecretKeyHeader()]: secretKey,\n };\n const requestData = {\n custom_headers: JSON.stringify(customHeaders),\n payload: JSON.stringify(payloadFormat),\n name,\n url,\n };\n\n await axios.post(apiUrl, requestData, requestConfig);\n return {\n name,\n secretKey,\n };\n },\n async deleteWebhook(webhookName) {\n const apiUrl = this._webhooksUrl(webhookName);\n const requestConfig = this._makeRequestConfig();\n await axios.delete(apiUrl, requestConfig);\n },\n async addWebhookNotification(webhookName, monitorId) {\n const { message } = await this._getMonitor(monitorId);\n const webhookTagPattern = this._webhookTagPattern(webhookName);\n if (new RegExp(webhookTagPattern).test(message)) {\n // Monitor is already notifying this webhook\n return;\n }\n\n const newMessage = `${message}\\n${webhookTagPattern}`;\n const monitorChanges = {\n message: newMessage,\n };\n await this._editMonitor(monitorId, monitorChanges);\n },\n async removeWebhookNotifications(webhookName) {\n // Users could have manually added this webhook in other monitors, or\n // removed the webhook from the monitors specified as user props. Hence,\n // we need to search through all the monitors that notify this webhook and\n // remove the notification.\n const webhookTagPattern = new RegExp(\n `\\n?${this._webhookTagPattern(webhookName)}`\n );\n const monitorSearchResults = this._searchMonitors(webhookName);\n for await (const monitorInfo of monitorSearchResults) {\n const { id: monitorId } = monitorInfo;\n const { message } = await this._getMonitor(monitorId);\n\n if (!new RegExp(webhookTagPattern).test(message)) {\n // Monitor is not notifying this webhook, skip it...\n return;\n }\n\n\n const newMessage = message.replace(webhookTagPattern, \"\");\n const monitorChanges = {\n message: newMessage,\n };\n await this._editMonitor(monitorId, monitorChanges);\n }\n },\n },\n};\n\n\n<|start_filename|>components/mailgun/actions/verify-email/verify-email.js<|end_filename|>\nconst mailgun = require(\"../../mailgun.app.js\");\n\nmodule.exports = {\n key: \"mailgun-verify-email\",\n name: \"Mailgun Verify Email\",\n description: \"Verify email address deliverability with Mailgun.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n mailgun,\n email: {\n propDefinition: [\n mailgun,\n \"email\",\n ],\n },\n haltOnError: {\n propDefinition: [\n mailgun,\n \"haltOnError\",\n ],\n },\n },\n async run () {\n try {\n return await this.mailgun.api(\"validate\").get(this.email);\n } catch (err) {\n if (this.haltOnError) {\n throw err;\n }\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/twilio/twilio.app.js<|end_filename|>\nconst twilioClient = require(\"twilio\");\n\nmodule.exports = {\n type: \"app\",\n app: \"twilio\",\n propDefinitions: {\n authToken: {\n type: \"string\",\n secret: true,\n label: \"Twilio Auth Token\",\n description:\n \"Your Twilio auth token, found [in your Twilio console](https://www.twilio.com/console). Required for validating Twilio events.\",\n },\n body: {\n type: 'string',\n label: 'Message Body',\n description: 'The text of the message you want to send, limited to 1600 characters.'\n },\n from: {\n type: \"string\",\n label: \"From\",\n async options() {\n const client = this.getClient();\n const numbers = await client.incomingPhoneNumbers.list();\n return numbers.map((number) => {\n return number.friendlyName\n });\n },\n },\n incomingPhoneNumber: {\n type: \"string\",\n label: \"Incoming Phone Number\",\n description:\n \"The Twilio phone number where you'll receive messages. This source creates a webhook tied to this incoming phone number, **overwriting any existing webhook URL**.\",\n async options() {\n const numbers = await this.listIncomingPhoneNumbers();\n return numbers.map((number) => {\n return { label: number.friendlyName, value: number.sid };\n });\n },\n },\n mediaUrl: {\n type: 'string[]',\n label: 'Media URL',\n description: 'The URL of the media you wish to send out with the message. The media size limit is `5MB`. You may provide up to 10 media URLs per message.',\n optional: true\n },\n responseMessage: {\n type: \"string\",\n optional: true,\n label: \"Response Message\",\n description:\n \"The message you want to send in response to incoming messages. Leave this blank if you don't need to issue a response.\",\n },\n to: {\n type: 'string',\n label: 'To',\n description: 'The destination phone number in E.164 format. Format with a `+` and country code (e.g., `+16175551212`).'\n },\n },\n methods: {\n getClient() {\n return twilioClient(this.$auth.Sid, this.$auth.Secret, {\n accountSid: this.$auth.AccountSid,\n });\n },\n async setWebhookURL(phoneNumberSid, params) {\n const client = this.getClient();\n return await client.incomingPhoneNumbers(phoneNumberSid).update(params);\n },\n async setIncomingSMSWebhookURL(phoneNumberSid, url) {\n const params = {\n smsMethod: \"POST\",\n smsUrl: url,\n };\n return await this.setWebhookURL(phoneNumberSid, params);\n },\n async setIncomingCallWebhookURL(phoneNumberSid, url) {\n const params = {\n statusCallbackMethod: \"POST\",\n statusCallback: url,\n };\n return await this.setWebhookURL(phoneNumberSid, params);\n },\n async listIncomingPhoneNumbers(params) {\n const client = this.getClient();\n return await client.incomingPhoneNumbers.list(params);\n },\n async listRecordings(params) {\n const client = this.getClient();\n return await client.recordings.list(params);\n },\n async listTranscriptions(params) {\n const client = this.getClient();\n return await client.transcriptions.list(params);\n },\n },\n};\n\n<|start_filename|>components/strava/strava.app.js<|end_filename|>\n// Strava API app file\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"strava\",\n methods: {\n async _makeAPIRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers[\"Authorization\"] = `Bearer ${this.$auth.oauth_access_token}`;\n opts.headers[\"Content-Type\"] = \"application/json\";\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n const { path } = opts;\n delete opts.path;\n opts.url = `https://www.strava.com/api/v3${\n path[0] === \"/\" ? \"\" : \"/\"\n }${path}`;\n return await axios(opts);\n },\n async getActivity(id) {\n return (\n await this._makeAPIRequest({\n path: `/activities/${id}`,\n })\n ).data;\n },\n async getAuthenticatedAthlete() {\n return (\n await this._makeAPIRequest({\n path: \"/athlete\",\n })\n ).data;\n },\n },\n};\n\n\n<|start_filename|>components/slack/actions/delete_file/delete_file.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-delete-file\",\n name: \"Delete File\",\n description: \"Delete a file\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n file: {\n propDefinition: [\n slack,\n \"file\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().files.delete({\n file: this.file,\n });\n },\n};\n\n\n<|start_filename|>components/twitch/sources/followed-streams/followed-streams.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n name: \"Followed Streams\",\n key: \"twitch-followed-streams\",\n description: \"Emits an event when a followed stream is live.\",\n version: \"0.0.3\",\n methods: {\n ...common.methods,\n getMeta(item) {\n const { id, started_at: startedAt, title: summary } = item;\n const ts = new Date(startedAt).getTime();\n return {\n id,\n summary,\n ts,\n };\n },\n },\n hooks: {\n async deploy() {\n // get the authenticated user\n const { data: authenticatedUserData } = await this.twitch.getUsers();\n this.db.set(\"authenticatedUserId\", authenticatedUserData[0].id);\n },\n },\n async run() {\n const params = {\n from_id: this.db.get(\"authenticatedUserId\"),\n };\n // get the user_ids of the streamers followed by the authenticated user\n const follows = await this.paginate(\n this.twitch.getUserFollows.bind(this),\n params\n );\n const followedIds = [];\n for await (const follow of follows) {\n followedIds.push(follow.to_id);\n }\n // get and emit streams for the followed streamers\n const streams = await this.paginate(this.twitch.getStreams.bind(this), {\n user_id: followedIds,\n });\n for await (const stream of streams) {\n this.$emit(stream, this.getMeta(stream));\n }\n },\n};\n\n<|start_filename|>components/calendly/sources/common-webhook.js<|end_filename|>\nconst calendly = require(\"../calendly.app.js\");\nconst get = require(\"lodash/get\");\n\nmodule.exports = {\n props: {\n calendly,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n hooks: {\n async activate() {\n const events = this.getEvents();\n const body = {\n url: this.http.endpoint,\n events,\n };\n const resp = await this.calendly.createHook(body);\n this.db.set(\"hookId\", resp.data.id);\n },\n async deactivate() {\n await this.calendly.deleteHook(this.db.get(\"hookId\"));\n },\n },\n methods: {\n generateMeta() {\n throw new Error(\"generateMeta is not implemented\");\n },\n generateInviteeMeta(body) {\n const eventId = get(body, \"payload.event.uuid\");\n const inviteeId = get(body, \"payload.invitee.uuid\");\n const summary = get(body, \"payload.event_type.name\");\n const ts = Date.parse(get(body, \"time\"));\n return {\n id: `${eventId}${inviteeId}`,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { body, headers } = event;\n\n if (headers[\"x-calendly-hook-id\"] != this.db.get(\"hookId\")) {\n return this.http.respond({ status: 404 });\n }\n\n this.http.respond({ status: 200 });\n\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n },\n};\n\n<|start_filename|>components/hubspot/sources/common.js<|end_filename|>\nconst hubspot = require(\"../hubspot.app.js\");\n\nmodule.exports = {\n props: {\n hubspot,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n hooks: {\n async deploy() {\n // By default, only a limited set of properties are returned from the API.\n // Get all possible contact properties to request for each contact.\n const properties = await this.hubspot.createPropertiesArray();\n this.db.set(\"properties\", properties);\n },\n },\n methods: {\n _getAfter() {\n return this.db.get(\"after\") || Date.parse(this.hubspot.monthAgo());\n },\n _setAfter(after) {\n this.db.set(\"after\", after);\n },\n async paginate(params, resourceFn, resultType = null, after = null) {\n let results = null;\n let done = false;\n while ((!results || params.after) && !done) {\n results = await resourceFn(params);\n if (results.paging) params.after = results.paging.next.after;\n else delete params.after;\n if (resultType) results = results[resultType];\n for (const result of results) {\n if (this.isRelevant(result, after)) {\n this.emitEvent(result);\n } else {\n done = true;\n }\n }\n }\n },\n // pagination for endpoints that return hasMore property of true/false\n async paginateUsingHasMore(\n params,\n resourceFn,\n resultType = null,\n after = null\n ) {\n let hasMore = true;\n let results, items;\n while (hasMore) {\n results = await resourceFn(params);\n hasMore = results.hasMore;\n if (hasMore) params.offset = results.offset;\n if (resultType) items = results[resultType];\n else items = results;\n for (const item of items) {\n if (this.isRelevant(item, after)) this.emitEvent(item);\n }\n }\n },\n emitEvent(result) {\n const meta = this.generateMeta(result);\n this.$emit(result, meta);\n },\n isRelevant(result, after) {\n return true;\n },\n },\n};\n\n<|start_filename|>components/twitter/sources/new-unfollower-of-user/new-unfollower-of-user.js<|end_filename|>\nconst base = require(\"../new-unfollower-of-me/new-unfollower-of-me\");\n\nmodule.exports = {\n ...base,\n key: \"twitter-new-unfollower-of-user\",\n name: \"New Unfollower of User\",\n description: \"Emit an event when a specific user loses a follower on Twitter\",\n version: \"0.0.5\",\n props: {\n ...base.props,\n screen_name: {\n propDefinition: [\n base.props.twitter,\n \"screen_name\",\n ],\n },\n },\n methods: {\n ...base.methods,\n getScreenName() {\n return this.screen_name;\n },\n },\n};\n\n\n<|start_filename|>components/twitch/sources/new-videos/new-videos.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\nconst twitch = require(\"../../twitch.app.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Videos\",\n key: \"twitch-new-videos\",\n description:\n \"Emits an event when there is a new video from channels you follow.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n max: { propDefinition: [twitch, \"max\"] },\n },\n methods: {\n ...common.methods,\n getMeta({ id, title: summary, created_at: createdAt }) {\n const ts = new Date(createdAt).getTime();\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n // get the authenticated user\n const { data: authenticatedUserData } = await this.twitch.getUsers();\n const params = {\n from_id: authenticatedUserData[0].id,\n };\n // get the channels followed by the authenticated user\n const followedUsers = await this.paginate(\n this.twitch.getUserFollows.bind(this),\n params\n );\n\n // get and emit new videos from each followed user\n let count = 0;\n for await (const followed of followedUsers) {\n const videos = await this.paginate(\n this.twitch.getVideos.bind(this),\n {\n user_id: followed.to_id,\n period: \"day\", // Period during which the video was created. Valid values: \"all\", \"day\", \"week\", \"month\".\n },\n this.max\n );\n for await (const video of videos) {\n this.$emit(video, this.getMeta(video));\n count++;\n if (count >= this.max) return;\n }\n }\n },\n};\n\n<|start_filename|>components/twitch/actions/get-my-followers/get-my-followers.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get My Followers\",\n key: \"twitch-get-my-followers\",\n description: \"Retrieves a list of users who follow the authenticated user\",\n version: \"0.0.1\",\n type: \"action\",\n async run() {\n // get the userID of the authenticated user\n const userId = await this.getUserId();\n const params = {\n to_id: userId,\n };\n // get the users who follow the authenticated user\n const follows = await this.paginate(\n this.twitch.getUserFollows.bind(this),\n params,\n );\n return await this.getPaginatedResults(follows);\n },\n};\n\n\n<|start_filename|>components/netlify/sources/new-deploy-success/new-deploy-success.js<|end_filename|>\nconst common = require(\"../../common\");\n\nmodule.exports = {\n ...common,\n key: \"netlify-new-deploy-success\",\n name: \"New Deploy Success (Instant)\",\n description: \"Emits an event when a new deployment is completed\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getHookEvent() {\n return \"deploy_created\";\n },\n getMetaSummary(data) {\n const { commit_ref } = data;\n return `Deploy succeeded for commit ${commit_ref}`;\n },\n },\n};\n\n\n<|start_filename|>components/uservoice/sources/new-nps-ratings/new-nps-ratings.js<|end_filename|>\nconst uservoice = require(\"../../uservoice.app.js\");\nconst NUM_SAMPLE_RESULTS = 10;\n\nmodule.exports = {\n name: \"New NPS Ratings\",\n version: \"0.0.2\",\n key: \"uservoice-new-nps-ratings\",\n description: `Emits new NPS ratings submitted through the UserVoice NPS widget. On first run, emits up to ${NUM_SAMPLE_RESULTS} sample NPS ratings users have previously submitted.`,\n dedupe: \"unique\",\n props: {\n uservoice,\n timer: {\n label: \"Polling schedule\",\n description:\n \"Pipedream will poll the UserVoice API for new NPS ratings on this schedule\",\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15, // by default, run every 15 minutes\n },\n },\n db: \"$.service.db\",\n },\n hooks: {\n async deploy() {\n // Emit sample records on the first run\n const { npsRatings } = await this.uservoice.listNPSRatings({\n numSampleResults: NUM_SAMPLE_RESULTS,\n });\n this.emitWithMetadata(npsRatings);\n },\n },\n methods: {\n emitWithMetadata(ratings) {\n for (const rating of ratings) {\n const { id, rating: score, body, created_at } = rating;\n const summary = body && body.length ? `${score} - ${body}` : `${score}`;\n this.$emit(rating, {\n summary,\n id,\n ts: +new Date(created_at),\n });\n }\n },\n },\n async run() {\n let updated_after =\n this.db.get(\"updated_after\") || new Date().toISOString();\n const { npsRatings, maxUpdatedAt } = await this.uservoice.listNPSRatings({\n updated_after,\n });\n this.emitWithMetadata(npsRatings);\n\n if (maxUpdatedAt) {\n updated_after = maxUpdatedAt;\n }\n this.db.set(\"updated_after\", updated_after);\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/campaign-bounce/campaign-bounce.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-campaign.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Campaign Bounce (Instant)\",\n key: \"activecampaign-campaign-bounce\",\n description:\n \"Emits an event when a contact email address bounces from a sent campaign.\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"bounce\"];\n },\n },\n};\n\n<|start_filename|>components/github/actions/search-issues-and-pull-requests/search-issues-and-pull-requests.js<|end_filename|>\nconst github = require('../../github.app.js')\nconst { Octokit } = require('@octokit/rest')\n\nmodule.exports = {\n key: \"github-search-issues-and-pull-requests\",\n name: \"Search Issues and Pull Requests\",\n description: \"Find issues by state and keyword.\",\n version: \"0.0.15\",\n type: \"action\",\n props: {\n github,\n q: { propDefinition: [github, \"q_issues_and_pull_requests\"] },\n sort: { propDefinition: [github, \"sortIssues\"] },\n order: { propDefinition: [github, \"order\"] },\n paginate: { propDefinition: [github, \"paginate\"] },\n },\n async run() {\n const octokit = new Octokit({\n auth: this.github.$auth.oauth_access_token\n })\n \n if(this.paginate) {\n return await octokit.paginate(octokit.search.issuesAndPullRequests, { \n q: this.q,\n sort: this.sort,\n order: this.order,\n per_page: 100,\n })\n } else {\n return (await octokit.search.issuesAndPullRequests({\n q: this.q,\n sort: this.sort,\n order: this.order,\n per_page: 100,\n })).data.items\n }\n },\n}\n\n<|start_filename|>components/intercom/sources/lead-added-email/lead-added-email.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-lead-added-email\",\n name: \"Lead Added Email\",\n description: \"Emits an event each time a lead adds their email address.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const monthAgo = this.intercom.monthAgo();\n let lastLeadUpdatedAt =\n this.db.get(\"lastLeadUpdatedAt\") || Math.floor(monthAgo / 1000);\n const data = {\n query: {\n operator: \"AND\",\n value: [\n {\n field: \"updated_at\",\n operator: \">\",\n value: lastLeadUpdatedAt,\n },\n {\n field: \"role\",\n operator: \"=\",\n value: \"lead\",\n },\n {\n field: \"email\",\n operator: \"!=\",\n value: null,\n },\n ],\n },\n };\n\n const results = await this.intercom.searchContacts(data);\n for (const lead of results) {\n if (lead.updated_at > lastLeadUpdatedAt)\n lastLeadUpdatedAt = lead.updated_at;\n this.$emit(lead, {\n id: lead.id,\n summary: lead.email,\n ts: lead.updated_at,\n });\n }\n\n this.db.set(\"lastLeadUpdatedAt\", lastLeadUpdatedAt);\n },\n};\n\n<|start_filename|>components/google_docs/google_docs.app.js<|end_filename|>\nconst { google } = require(\"googleapis\");\nconst googleDrive = require(\"../google_drive/google_drive.app\");\n\nmodule.exports = {\n type: \"app\",\n app: \"google_docs\",\n propDefinitions: {\n ...googleDrive.propDefinitions,\n docId: {\n type: \"string\",\n label: \"Document\",\n description: \"Select a document or disable structured mode to pass a value exported from a previous step (e.g., `{{steps.foo.$return_value.documentId}}`) or to manually enter a static ID (e.g., `1KuEN7k8jVP3Qi0_svM5OO8oEuiLkq0csihobF67eat8`).\",\n async options({\n prevContext, driveId,\n }) {\n const { nextPageToken } = prevContext;\n return this.listDocsOptions(driveId, nextPageToken);\n },\n },\n },\n methods: {\n ...googleDrive.methods,\n docs() {\n const auth = new google.auth.OAuth2();\n auth.setCredentials({\n access_token: this.$auth.oauth_access_token,\n });\n return google.docs({\n version: \"v1\",\n auth,\n });\n },\n async listDocsOptions(driveId, pageToken = null) {\n const q = \"mimeType='application/vnd.google-apps.document'\";\n let request = {\n q,\n };\n if (driveId) {\n request = {\n ...request,\n corpora: \"drive\",\n driveId,\n pageToken,\n includeItemsFromAllDrives: true,\n supportsAllDrives: true,\n };\n }\n return this.listFilesOptions(pageToken, request);\n },\n },\n};\n\n\n<|start_filename|>components/bandwidth/bandwidth.app.js<|end_filename|>\nconst bandwidthMessaging = require(\"@bandwidth/messaging\");\n\nmodule.exports = {\n type: \"app\",\n app: \"bandwidth\",\n propDefinitions: {\n messageTo: {\n type: \"string\",\n label: \"To\",\n description: \"The number the message will be sent to, in E164 format ex `+19195551234`\",\n },\n from: {\n type: \"string\",\n label: \"From\",\n description: \"The number the call or message event will come from, in E164 format ex `+19195551234`\",\n },\n message: {\n type: \"string\",\n label: \"Message\",\n description: \"The text message content\",\n },\n messagingApplicationId: {\n type: \"string\",\n label: \"Messaging Application ID\",\n description: \"The ID from the messaging application created in the [Bandwidth Dashboard](https://dashboard.bandwidth.com).\\n\\nThe application must be associated with the location that the `from` number lives on.\",\n },\n mediaUrl: {\n type: \"string[]\",\n label: \"Media URL\",\n description: \"Publicly addressible URL of the media you would like to send with the SMS\",\n },\n },\n methods: {\n getMessagingClient() {\n return new bandwidthMessaging.Client({\n basicAuthUserName: this.$auth.username,\n basicAuthPassword: this.$auth.password,\n });\n },\n async sendSms(to, from, message, messagingApplicationId) {\n const controller = new bandwidthMessaging.ApiController(this.getMessagingClient());\n const data = {\n applicationId: messagingApplicationId,\n to: [\n to,\n ],\n from: from,\n text: message,\n };\n return await controller.createMessage(this.$auth.accountId, data);\n },\n },\n};\n\n\n<|start_filename|>components/webflow/sources/common.js<|end_filename|>\nconst { v4: uuidv4 } = require(\"uuid\");\nconst webflow = require(\"../webflow.app\");\n\nmodule.exports = {\n props: {\n db: \"$.service.db\",\n http: \"$.interface.http\",\n webflow,\n siteId: {\n type: \"string\",\n label: \"Site\",\n description: \"The site from which to listen events\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return {\n options: []\n };\n }\n\n const sites = await this.webflow.listSites();\n const options = sites.map(site => ({\n label: site.name,\n value: site._id,\n }));\n return {\n options,\n };\n },\n },\n },\n methods: {\n getWebhookTriggerType() {\n throw new Error('getWebhookTriggerType is not implemented');\n },\n getWebhookFilter() {\n return {};\n },\n isEventRelevant(event) {\n return true;\n },\n generateMeta(data) {\n return {\n id: uuidv4(),\n summary: \"New event\",\n ts: Date.now(),\n };\n },\n processEvent(event) {\n if (!this.isEventRelevant(event)) {\n return;\n }\n\n const { body } = event;\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n },\n },\n hooks: {\n async activate() {\n const { endpoint } = this.http;\n const triggerType = this.getWebhookTriggerType();\n const filter = this.getWebhookFilter();\n const webhook = await this.webflow.createWebhook(\n this.siteId, endpoint, triggerType, filter);\n const { _id: webhookId } = webhook;\n this.db.set(\"webhookId\", webhookId);\n },\n async deactivate() {\n const webhookId = this.db.get(\"webhookId\");\n await this.webflow.removeWebhook(this.siteId, webhookId);\n },\n },\n async run(event) {\n await this.processEvent(event);\n },\n};\n\n\n<|start_filename|>components/twitter_developer_app/twitter_developer_app.app.js<|end_filename|>\nconst TwitterV1 = require(\"twit\");\nconst TwitterV2 = require(\"twitter-v2\");\n\nmodule.exports = {\n type: \"app\",\n app: \"twitter_developer_app\",\n methods: {\n _newClientV1() {\n return new TwitterV1({\n consumer_key: this.$auth.api_key,\n consumer_secret: this.$auth.api_secret_key,\n access_token: this.$auth.access_token,\n access_token_secret: this.$auth.access_token_secret,\n });\n },\n _newClientV2() {\n return new TwitterV2({\n consumer_key: this.$auth.api_key,\n consumer_secret: this.$auth.api_secret_key,\n access_token_key: this.$auth.access_token,\n access_token_secret: this.$auth.access_token_secret,\n });\n },\n async getAccountId() {\n const client = this._newClientV1();\n const path = \"account/verify_credentials\";\n const params = {\n skip_status: true,\n };\n const { data } = await client.get(path, params);\n return data.id_str;\n },\n /**\n * This function retrieves the list of Twitter Direct Messages sent to the\n * authenticated account. The function will perform an exhaustive retrieval\n * of all the available messages unless a `lastMessageId` argument is\n * provided, in which case the function will retrieve messages up until the\n * specified ID (exclusive).\n *\n * The function calls this API internally:\n * https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/sending-and-receiving/api-reference/list-events\n *\n * @param {object} opts parameters for the retrieval of new direct messages\n * @param {string} [opts.lastMessageId] the ID of the direct message to use\n * as a lower bound for the retrieval\n * @returns a list of direct message objects\n */\n async getNewDirectMessages({ lastMessageId }) {\n const client = this._newClientV1();\n const path = \"direct_messages/events/list\";\n const result = [];\n\n let cursor;\n do {\n const params = {\n cursor,\n };\n const { data } = await client.get(path, params);\n\n const {\n events: messages = [],\n next_cursor: nextCursor,\n } = data;\n for (const message of messages) {\n if (message.id == lastMessageId) return result;\n result.push(message);\n }\n\n cursor = nextCursor;\n } while (cursor);\n\n return result;\n },\n /**\n * This function retrieves the metrics for a list of Tweet ID's. By default,\n * it retrieves the public, non-public and organic metrics, but these can be\n * excluded by providing different values for the flag arguments.\n *\n * For more information about the specific metrics, see the API docs:\n * https://developer.twitter.com/en/docs/twitter-api/metrics\n *\n * @param {object} opts parameters for the retrieval of Tweets metrics\n * @param {string[]} opts.tweetIds the list of Tweet ID's for which to\n * retrieve the metrics\n * @param {boolean} [opts.excludePublic=false] if set, the public metrics\n * will not be retrieved\n * @param {boolean} [opts.excludeNonPublic=false] if set, the non-public\n * metrics will not be retrieved\n * @param {boolean} [opts.excludeOrganic=false] if set, the organic\n * metrics will not be retrieved\n * @returns a metrics object containing the metrics for the specified Tweet\n * ID's\n */\n async getMetricsForIds({\n tweetIds,\n excludePublic = false,\n excludeNonPublic = false,\n excludeOrganic = false,\n }) {\n if (!tweetIds) {\n throw new Error(\"The 'tweetIds' argument is mandatory\");\n }\n\n const client = this._newClientV2();\n const path = \"tweets\";\n const metrics = [\n excludePublic\n ? undefined\n : \"public_metrics\",\n excludeNonPublic\n ? undefined\n : \"non_public_metrics\",\n excludeOrganic\n ? undefined\n : \"organic_metrics\",\n ].filter(i => i);\n const params = {\n \"ids\": tweetIds,\n \"expansions\": [\n \"attachments.media_keys\",\n ],\n \"media.fields\": metrics,\n \"tweet.fields\": metrics,\n };\n return client.get(path, params);\n },\n },\n};\n\n\n<|start_filename|>components/twist/sources/common.js<|end_filename|>\nconst twist = require(\"../twist.app.js\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n twist,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n workspace: {\n propDefinition: [twist, \"workspace\"],\n },\n },\n hooks: {\n async activate() {\n const data = this.getHookActivationData();\n await this.twist.createHook(data);\n },\n async deactivate() {\n await this.twist.deleteHook(this.http.endpoint);\n },\n },\n async run(event) {\n const { body } = event;\n if (!body) return;\n\n this.http.respond({\n status: 200,\n });\n\n const meta = this.getMeta(body);\n\n this.$emit(body, meta);\n },\n};\n\n<|start_filename|>components/pagerduty/package.json<|end_filename|>\n{\n \"name\": \"@pipedream/pagerduty\",\n \"version\": \"0.3.3\",\n \"description\": \"Pipedream Pagerduty Components\",\n \"main\": \"pagerduty.app.js\",\n \"keywords\": [\n \"pipedream\",\n \"pagerduty\"\n ],\n \"homepage\": \"https://pipedream.com/apps/pagerduty\",\n \"author\": \"Pipedream <> (https://pipedream.com/)\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"axios\": \"^0.21.1\"\n },\n \"gitHead\": \"e12480b94cc03bed4808ebc6b13e7fdb3a1ba535\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n\n\n<|start_filename|>components/shopify/sources/new-order/new-order.js<|end_filename|>\nconst shopify = require(\"../../shopify.app.js\");\n\nmodule.exports = {\n key: \"shopify-new-order\",\n name: \"New Order\",\n description: \"Emits an event for each new order submitted to a store.\",\n version: \"0.0.4\",\n dedupe: \"unique\",\n props: {\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n shopify,\n },\n async run() {\n const sinceId = this.db.get(\"since_id\") || null;\n let results = await this.shopify.getOrders(\"any\", true, sinceId);\n\n for (const order of results) {\n this.$emit(order, {\n id: order.id,\n summary: `Order ${order.name}`,\n ts: Date.now(),\n });\n }\n\n if (results[results.length - 1])\n this.db.set(\"since_id\", results[results.length - 1].id);\n },\n};\n\n<|start_filename|>components/activecampaign/sources/contact-added-to-list/contact-added-to-list.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Contact Added to List\",\n key: \"activecampaign-contact-added-to-list\",\n description: \"Emits an event each time a new contact is added to a list.\",\n version: \"0.0.2\",\n props: {\n ...common.props,\n lists: { propDefinition: [activecampaign, \"lists\"] },\n },\n hooks: {\n async activate() {\n const sources =\n this.sources.length > 0\n ? this.sources\n : this.activecampaign.getAllSources();\n const hookIds = [];\n const events = this.getEvents();\n if (this.lists.length > 0) {\n try {\n for (const list of this.lists) {\n const { webhook } = await this.activecampaign.createHook(\n events,\n this.http.endpoint,\n sources,\n list\n );\n hookIds.push(webhook.id);\n }\n } catch (err) {\n // if webhook creation fails, delete all hooks created so far\n for (const id of hookIds) {\n await this.activecampaign.deleteHook(id);\n }\n this.db.set(\"hookIds\", []);\n throw new Error(err);\n }\n } \n // if no lists specified, create a webhook to watch all lists\n else {\n const { webhook } = await this.activecampaign.createHook(\n events,\n this.http.endpoint,\n sources\n );\n hookIds.push(webhook.id);\n }\n this.db.set(\"hookIds\", hookIds);\n },\n async deactivate() {\n const hookIds = this.db.get(\"hookIds\");\n for (const id of hookIds) {\n await this.activecampaign.deleteHook(id);\n }\n },\n },\n methods: {\n ...common.methods,\n getEvents() {\n return [\"subscribe\"];\n },\n async getMeta(body) {\n const { list } = await this.activecampaign.getList(body.list);\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: `${body[\"contact[id]\"]}${list.id}${ts}`,\n summary: `${body[\"contact[email]\"]} added to ${list.name}`,\n ts,\n };\n },\n },\n};\n\n<|start_filename|>components/eventbrite/sources/new-event-ended/new-event-ended.js<|end_filename|>\nconst common = require(\"../common/event.js\");\n\nmodule.exports = {\n ...common,\n key: \"eventbrite-new-event-ended\",\n name: \"New Event Ended\",\n description: \"Emits an event when an event has ended\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n hooks: {\n ...common.hooks,\n async deploy() {\n const params = {\n orgId: this.organization,\n params: {\n status: \"ended,completed\",\n },\n };\n const eventStream = await this.resourceStream(\n this.eventbrite.listEvents.bind(this),\n \"events\",\n params\n );\n for await (const event of eventStream) {\n this.emitEvent(event);\n }\n },\n activate() {},\n deactivate() {},\n },\n async run(event) {\n const params = {\n orgId: this.organization,\n params: {\n status: \"ended,completed\",\n },\n };\n const eventStream = await this.resourceStream(\n this.eventbrite.listEvents.bind(this),\n \"events\",\n params\n );\n for await (const newEvent of eventStream) {\n this.emitEvent(newEvent);\n }\n },\n};\n\n<|start_filename|>components/todoist/sources/new-or-modified-task/new-or-modified-task.js<|end_filename|>\nconst common = require(\"../common-task.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-new-or-modified-task\",\n name: \"New or Modified Task\",\n description: \"Emit an event for each new or modified task\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n isElementRelevant(element) {\n return true;\n },\n },\n};\n\n\n<|start_filename|>components/twitch/sources/common-webhook.js<|end_filename|>\nconst common = require(\"./common.js\");\nconst { v4: uuidv4 } = require(\"uuid\");\nconst subscriptionExpiration = 864000; // seconds until webhook subscription expires, maximum 10 days (864000 seconds)\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n timer: {\n type: \"$.interface.timer\",\n default: {\n // set timer to refresh subscription halfway until the expiration\n intervalSeconds: subscriptionExpiration / 2,\n },\n },\n },\n hooks: {\n async activate() {\n const topics = await this.getTopics();\n this.db.set(\"topics\", topics);\n await this.manageHookForTopics(\"subscribe\", topics);\n },\n async deactivate() {\n const topics = this.db.get(\"topics\");\n await this.manageHookForTopics(\"unsubscribe\", topics);\n },\n },\n methods: {\n ...common.methods,\n async manageHookForTopics(mode, topics) {\n const secretToken = uuidv4();\n this.db.set(\"secretToken\", secretToken);\n for (const topic of topics)\n try {\n await this.twitch.manageHook(\n mode,\n this.http.endpoint,\n topic,\n subscriptionExpiration,\n secretToken\n );\n } catch (err) {\n console.log(err);\n }\n },\n },\n async run(event) {\n const {\n query,\n body,\n bodyRaw,\n headers,\n interval_seconds: intervalSeconds,\n } = event;\n\n // if event was invoked by timer, renew the subscription\n if (intervalSeconds) {\n await this.manageHookForTopics(\"subscribe\", this.db.get(\"topics\"));\n return;\n }\n\n // Respond with success response\n const response = {\n status: 200,\n };\n // Twitch will send a request immediately after creating the hook. We must respond back\n // with the hub.challenge provided in the headers.\n if (query[\"hub.challenge\"]) response.body = query[\"hub.challenge\"];\n this.http.respond(response);\n\n if (!body) return;\n\n // verify that the incoming webhook request is valid\n const secretToken = this.db.get(\"secretToken\");\n if (!this.twitch.verifyWebhookRequest(headers, bodyRaw, secretToken))\n return;\n\n const { data } = body;\n if (data.length === 0) return;\n\n for (const item of data) {\n const meta = this.getMeta(item, headers);\n this.$emit(item, meta);\n }\n },\n};\n\n\n<|start_filename|>components/ringcentral/ringcentral.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"ringcentral\",\n propDefinitions: {\n extensionId: {\n type: \"string\",\n label: \"Extension\",\n description: \"The extension (or user) that will trigger the event source\",\n async options(context) {\n const { page } = context;\n\n const { records: extensions } = await this._getExtensionList({\n // Pages in the RingCentral API are 1-indexed\n page: page + 1,\n perPage: 10,\n status: \"Enabled\",\n });\n const options = extensions.map((extension) => {\n const {\n id: value,\n extensionNumber,\n contact: {\n firstName,\n lastName,\n },\n } = extension;\n const label = `${firstName} ${lastName} (ext: ${extensionNumber})`;\n return {\n label,\n value,\n };\n });\n\n return {\n options,\n context: {\n nextPage: page + 1,\n },\n };\n },\n },\n deviceId: {\n type: \"string\",\n label: \"Device\",\n description: \"The extension's device that will trigger the event source\",\n default: \"\",\n async options(context) {\n const {\n page,\n extensionId,\n } = context;\n\n const { records: devices } = await this._getDeviceList(extensionId, {\n // Pages in the RingCentral API are 1-indexed\n page: page + 1,\n perPage: 10,\n });\n const options = devices.map((extension) => {\n const {\n id: value,\n type,\n name,\n } = extension;\n const label = `${name} (type: ${type})`;\n return {\n label,\n value,\n };\n });\n\n return {\n options,\n context: {\n nextPage: page + 1,\n extensionId,\n },\n };\n },\n },\n },\n methods: {\n _authToken() {\n return this.$auth.oauth_access_token;\n },\n _apiUrl() {\n const {\n base_url: baseUrl = \"https://platform.ringcentral.com/restapi/v1.0\",\n } = this.$auth;\n return baseUrl;\n },\n _accountUrl() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/account/~`;\n },\n _extensionUrl() {\n const baseUrl = this._accountUrl();\n return `${baseUrl}/extension`;\n },\n _deviceUrl(extensionId = \"~\") {\n const baseUrl = this._extensionUrl();\n return `${baseUrl}/${extensionId}/device`;\n },\n _callLogUrl(extensionId = \"~\") {\n const baseUrl = this._extensionUrl();\n return `${baseUrl}/${extensionId}/call-log`;\n },\n _subscriptionUrl(id) {\n const baseUrl = this._apiUrl();\n const basePath = \"/subscription\";\n const path = id ? `${basePath}/${id}` : basePath;\n return `${baseUrl}${path}`;\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `Bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n async _getExtensionList(params) {\n // `params` refers to the query params listed in the API docs:\n // https://developers.ringcentral.com/api-reference/Extensions/listExtensions\n const url = this._extensionUrl();\n const requestConfig = {\n ...this._makeRequestConfig(),\n params,\n };\n const { data } = await axios.get(url, requestConfig);\n return data;\n },\n async _getDeviceList(extensionId, params) {\n // `params` refers to the query params listed in the API docs:\n // https://developers.ringcentral.com/api-reference/Devices/listExtensionDevices\n const url = this._deviceUrl(extensionId);\n const requestConfig = {\n ...this._makeRequestConfig(),\n params,\n };\n const { data } = await axios.get(url, requestConfig);\n return data;\n },\n async _getExtensionCallLog(extensionId, params, nextPage = {}) {\n // `params` refers to the query params listed in the API docs:\n // https://developers.ringcentral.com/api-reference/Call-Log/readUserCallLog\n const {\n uri: url = this._callLogUrl(extensionId),\n } = nextPage;\n const requestConfig = {\n ...this._makeRequestConfig(),\n params,\n };\n const { data } = await axios.get(url, requestConfig);\n return data;\n },\n async *getCallRecordings(extensionId, dateFrom, dateTo) {\n const params = {\n dateFrom,\n dateTo,\n withRecording: true,\n };\n\n let nextPage = {};\n do {\n const {\n records,\n navigation,\n } = await this._getExtensionCallLog(extensionId, params, nextPage);\n\n for (const record of records) {\n yield record;\n }\n\n nextPage = navigation.nextPage;\n } while (nextPage);\n },\n async createHook({\n address,\n eventFilters,\n verificationToken,\n }) {\n const url = this._subscriptionUrl();\n const requestConfig = this._makeRequestConfig();\n\n // Details about the different webhook parameters can be found in the\n // RingCentral API docs:\n // https://developers.ringcentral.com/api-reference/Subscriptions/createSubscription\n const requestData = {\n eventFilters,\n deliveryMode: {\n transportType: \"WebHook\",\n address,\n verificationToken,\n expiresIn: 630720000, // 20 years (max. allowed by the API)\n },\n };\n\n const { data } = await axios.post(url, requestData, requestConfig);\n return {\n ...data,\n verificationToken,\n };\n },\n deleteHook(hookId) {\n const url = this._subscriptionUrl(hookId);\n const requestConfig = this._makeRequestConfig();\n return axios.delete(url, requestConfig);\n },\n },\n};\n\n\n<|start_filename|>components/todoist/sources/new-project/new-project.js<|end_filename|>\nconst common = require(\"../common-project.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-new-project\",\n name: \"New Project\",\n description: \"Emit an event for each new project\",\n version: \"0.0.1\",\n dedupe: \"greatest\",\n};\n\n\n<|start_filename|>components/twist/sources/new-comment/new-comment.js<|end_filename|>\nconst twist = require(\"../../twist.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Comment (Instant)\",\n version: \"0.0.1\",\n key: \"twist-new-comment\",\n description: \"Emits an event for any new comment in a workspace\",\n props: {\n ...common.props,\n channel: {\n propDefinition: [twist, \"channel\", (c) => ({ workspace: c.workspace })],\n },\n thread: {\n propDefinition: [twist, \"thread\", (c) => ({ channel: c.channel })],\n },\n },\n methods: {\n getHookActivationData() {\n return {\n target_url: this.http.endpoint,\n event: \"comment_added\",\n workspace_id: this.workspace,\n channel_id: this.channel,\n thread_id: this.thread,\n };\n },\n getMeta(body) {\n const { id, content, posted } = body;\n return {\n id,\n summary: content,\n ts: Date.parse(posted),\n };\n },\n },\n};\n\n<|start_filename|>components/bitbucket/bitbucket.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"bitbucket\",\n propDefinitions: {\n workspaceId: {\n type: \"string\",\n label: \"Workspace\",\n description: \"The workspace that contains the repositories to work with\",\n async options(context) {\n const url = this._userWorkspacesEndpoint();\n const params = {\n sort: \"name\",\n fields: [\n \"next\",\n \"values.name\",\n \"values.slug\",\n ],\n };\n\n const data = await this._propDefinitionsOptions(url, params, context);\n const options = data.values.map(workspace => ({\n label: workspace.name,\n value: workspace.slug,\n }));\n return {\n options,\n context: {\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination\n nextPageUrl: data.next,\n },\n };\n },\n },\n repositoryId: {\n type: \"string\",\n label: \"Repository\",\n description: \"The repository for which the events will be processed\",\n async options(context) {\n const { workspaceId } = context;\n const url = this._workspaceRepositoriesEndpoint(workspaceId);\n const params = {\n sort: \"slug\",\n fields: [\n \"next\",\n \"values.slug\",\n ],\n };\n\n const data = await this._propDefinitionsOptions(url, params, context);\n const options = data.values.map(repository => ({\n label: repository.slug,\n value: repository.slug,\n }));\n return {\n options,\n context: {\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination\n nextPageUrl: data.next,\n },\n };\n },\n },\n branchName: {\n type: \"string\",\n label: \"Branch Name\",\n description: \"The name of the branch\",\n async options(context) {\n const { workspaceId, repositoryId } = context;\n const url = this._repositoryBranchesEndpoint(workspaceId, repositoryId);\n const params = {\n sort: \"name\",\n fields: [\n \"next\",\n \"values.name\",\n ],\n };\n\n const data = await this._propDefinitionsOptions(url, params, context);\n const options = data.values.map(branch => ({\n label: branch.name,\n value: branch.name,\n }));\n return {\n options,\n context: {\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination\n nextPageUrl: data.next,\n },\n };\n },\n },\n eventTypes: {\n type: \"string[]\",\n label: \"Event Types\",\n description: \"The type of events to watch\",\n async options(context) {\n const { subjectType } = context;\n const url = this._eventTypesEndpoint(subjectType);\n const params = {\n fields: [\n \"next\",\n \"values.category\",\n \"values.event\",\n \"values.label\",\n ],\n };\n\n const data = await this._propDefinitionsOptions(url, params, context);\n const options = data.values.map(this._formatEventTypeOption);\n return {\n options,\n context: {\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination\n nextPageUrl: data.next,\n },\n };\n },\n },\n },\n methods: {\n _apiUrl() {\n return \"https://api.bitbucket.org/2.0\";\n },\n _userWorkspacesEndpoint() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/workspaces`;\n },\n _workspaceRepositoriesEndpoint(workspaceId) {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/repositories/${workspaceId}`;\n },\n _eventTypesEndpoint(subjectType) {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/hook_events/${subjectType}`;\n },\n _repositoryBranchesEndpoint(workspaceId, repositoryId) {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/repositories/${workspaceId}/${repositoryId}/refs`;\n },\n _branchCommitsEndpoint(workspaceId, repositoryId, branchName) {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/repositories/${workspaceId}/${repositoryId}/commits/${branchName}`;\n },\n _hooksEndpointUrl(hookPathProps) {\n const { workspaceId, repositoryId } = hookPathProps;\n return repositoryId ?\n this._repositoryHooksEndpointUrl(workspaceId, repositoryId) :\n this._workspaceHooksEndpointUrl(workspaceId);\n },\n _hookEndpointUrl(hookPathProps, hookId) {\n const { workspaceId, repositoryId } = hookPathProps;\n return repositoryId ?\n this._repositoryHookEndpointUrl(workspaceId, repositoryId, hookId) :\n this._workspaceHookEndpointUrl(workspaceId, hookId);\n },\n _workspaceHooksEndpointUrl(workspaceId) {\n const baseUrl = this._userWorkspacesEndpoint();\n return `${baseUrl}/${workspaceId}/hooks`;\n },\n _workspaceHookEndpointUrl(workspaceId, hookId) {\n const baseUrl = this._workspaceHooksEndpointUrl(workspaceId);\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/uri-uuid#uuid\n return `${baseUrl}/{${hookId}}`;\n },\n _repositoryHooksEndpointUrl(workspaceId, repositoryId) {\n const baseUrl = this._workspaceRepositoriesEndpoint(workspaceId);\n return `${baseUrl}/${repositoryId}/hooks`;\n },\n _repositoryHookEndpointUrl(workspaceId, repositoryId, hookId) {\n const baseUrl = this._repositoryHooksEndpointUrl(workspaceId, repositoryId);\n // https://developer.atlassian.com/bitbucket/api/2/reference/meta/uri-uuid#uuid\n return `${baseUrl}/{${hookId}}`;\n },\n _formatEventTypeOption(eventType) {\n const { category, label, event } = eventType;\n const optionLabel = `${category} ${label}`;\n return {\n label: optionLabel,\n value: event,\n };\n },\n async _propDefinitionsOptions(url, params, { page, prevContext }) {\n let requestConfig = this._makeRequestConfig(); // Basic axios request config\n if (page === 0) {\n // First time the options are being retrieved.\n //\n // In such case, we include the query parameters provided\n // as arguments to this function.\n //\n // For subsequent pages, the \"next page\" URL's (provided by\n // the BitBucket API) will already include these parameters,\n // so we don't need to explicitly provide them again.\n requestConfig = {\n ...requestConfig,\n params,\n };\n } else if (prevContext.nextPageUrl) {\n // Retrieve next page of options.\n url = prevContext.nextPageUrl;\n } else {\n // No more options available.\n return { values: [] };\n }\n\n const { data } = await axios.get(url, requestConfig);\n return data;\n },\n async *getCommits(opts) {\n const {\n workspaceId,\n repositoryId,\n branchName,\n lastProcessedCommitHash,\n } = opts;\n const requestConfig = this._makeRequestConfig();\n\n let url = this._branchCommitsEndpoint(workspaceId, repositoryId, branchName);\n do {\n const { data } = await axios.get(url, requestConfig);\n const { values, next } = data;\n\n // Yield the retrieved commits in a serial manner, until\n // we exhaust the response from the BitBucket API, or we reach\n // the last processed commit, whichever comes first.\n for (const commit of values) {\n if (commit.hash === lastProcessedCommitHash) return;\n yield commit;\n }\n\n url = next;\n } while (url);\n },\n _authToken() {\n return this.$auth.oauth_access_token;\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `Bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n async createHook(opts) {\n const {\n hookParams,\n hookPathProps\n } = opts;\n const url = this._hooksEndpointUrl(hookPathProps);\n const requestConfig = this._makeRequestConfig();\n const response = await axios.post(url, hookParams, requestConfig);\n const hookId = response.data.uuid.match(/^{(.*)}$/)[1];\n return {\n hookId,\n };\n },\n async deleteHook(opts) {\n const { hookId, hookPathProps } = opts;\n const url = this._hookEndpointUrl(hookPathProps, hookId);\n const requestConfig = this._makeRequestConfig();\n return axios.delete(url, requestConfig);\n },\n },\n};\n\n\n<|start_filename|>components/yahoo_fantasy_sports/sources/new-football-league-transactions/new-football-league-transactions.js<|end_filename|>\nconst yfs = require('../../yahoo_fantasy_sports.app.js')\n\nfunction displayPlayer(p) {\n return `${p.name.full}, ${p.editorial_team_abbr} - ${p.display_position}`\n}\n\nmodule.exports = {\n key: \"yahoo_fantasy_sports-new-football-league-transactions\",\n name: \"New Football League Transactions\",\n version: \"0.0.1\",\n props: {\n yfs,\n league: {\n type: \"string\",\n async options() {\n return await this.yfs.getLeagueOptions()\n },\n },\n eventTypes: {\n type: \"string[]\",\n options: [\"*\", \"add\", \"drop\", \"commish\", \"trade\"], // not type with team_key\n optional: true,\n default: [\"*\"],\n },\n timer: \"$.interface.timer\",\n },\n dedupe: \"unique\",\n async run() {\n let eventTypes = []\n if (this.eventTypes.includes(\"*\")) {\n eventTypes.push(\"add\", \"drop\", \"commish\", \"trade\")\n } else {\n eventTypes = this.eventTypes\n }\n const transactions = await this.yfs.getLeagueTransactions(this.league, eventTypes)\n // XXX figure out count... field any integer greater than 0 but nothing about default limit or pagination?\n for (const txn of transactions) {\n txn._summary = this.yfs.transactionSummary(txn)\n this.$emit(txn, {\n id: txn.transaction_key,\n ts: (+txn.timestamp)*1000,\n summary: txn._summary,\n })\n }\n },\n}\n\n\n<|start_filename|>components/gitlab/sources/new-branch/new-branch.js<|end_filename|>\nconst gitlab = require(\"../../gitlab.app.js\");\n\nmodule.exports = {\n key: \"gitlab-new-branch\",\n name: \"New Branch (Instant)\",\n description: \"Emits an event when a new branch is created\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n gitlab,\n projectId: { propDefinition: [gitlab, \"projectId\"] },\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n db: \"$.service.db\",\n },\n hooks: {\n async activate() {\n const hookParams = {\n push_events: true,\n url: this.http.endpoint,\n };\n const opts = {\n hookParams,\n projectId: this.projectId,\n };\n const { hookId, token } = await this.gitlab.createHook(opts);\n console.log(\n `Created \"push events\" webhook for project ID ${this.projectId}.\n (Hook ID: ${hookId}, endpoint: ${hookParams.url})`\n );\n this.db.set(\"hookId\", hookId);\n this.db.set(\"token\", token);\n },\n async deactivate() {\n const hookId = this.db.get(\"hookId\");\n const opts = {\n hookId,\n projectId: this.projectId,\n };\n await this.gitlab.deleteHook(opts);\n console.log(\n `Deleted webhook for project ID ${this.projectId}.\n (Hook ID: ${hookId})`\n );\n },\n },\n methods: {\n isNewBranch(body) {\n // Logic based on https://gitlab.com/gitlab-org/gitlab-foss/-/issues/31723.\n const { before } = body;\n const expectedBeforeValue = \"0000000000000000000000000000000000000000\";\n return before === expectedBeforeValue;\n },\n generateMeta(data) {\n const newBranchName = data.ref;\n const summary = `New Branch: ${newBranchName}`;\n const ts = +new Date();\n return {\n id: newBranchName,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { headers, body } = event;\n\n // Reject any calls not made by the proper Gitlab webhook.\n if (!this.gitlab.isValidSource(headers, this.db)) {\n this.http.respond({\n status: 404,\n });\n return;\n }\n\n // Acknowledge the event back to Gitlab.\n this.http.respond({\n status: 200,\n });\n\n // Gitlab doesn't offer a specific hook for \"new branch\" events,\n // but such event can be deduced from the payload of \"push\" events.\n if (this.isNewBranch(body)) {\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n }\n },\n};\n\n\n<|start_filename|>components/pipefy/sources/card-created/card-created.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"Card Created (Instant)\",\n key: \"pipefy-card-created\",\n description: \"Emits an event for each new card created in a Pipe.\",\n version: \"0.0.2\",\n methods: {\n ...common.methods,\n getActions() {\n return [\"card.create\"];\n },\n getMeta(card, cardData) {\n return {\n body: { card, cardData },\n id: card.id,\n summary: card.title,\n };\n },\n },\n};\n\n<|start_filename|>components/formstack/formstack.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"formstack\",\n propDefinitions: {\n formId: {\n type: \"string\",\n label: \"Forms\",\n optional: true,\n async options({ page, prevContext }) {\n const options = [];\n const per_page = 100;\n let results = [];\n page = prevContext.page || 1;\n let total = prevContext.total >= 0 ? prevContext.total : per_page;\n if (total === per_page) {\n results = await this.getForms(page, per_page);\n for (const form of results) {\n options.push({ label: form.name, value: form.id });\n }\n }\n total = results.length;\n page++;\n return {\n options,\n context: { page, total },\n };\n },\n },\n },\n methods: {\n monthAgo() {\n const monthAgo = new Date();\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return monthAgo;\n },\n _getBaseURL() {\n return \"https://www.formstack.com/api/v2\";\n },\n _getAuthHeaders() {\n return {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n \"Content-Type\": \"application/json\",\n };\n },\n async createHook({ id, url }) {\n const config = {\n method: \"POST\",\n url: `${this._getBaseURL()}/form/${id}/webhook.json`,\n headers: this._getAuthHeaders(),\n params: {\n url,\n content_type: \"json\",\n handshake_key: this.$auth.oauth_refresh_token,\n },\n };\n return (await axios(config)).data;\n },\n async deleteHook({ hookId }) {\n const config = {\n method: \"DELETE\",\n url: `${this._getBaseURL()}/webhook/${hookId}.json`,\n headers: this._getAuthHeaders(),\n };\n return await axios(config);\n },\n async getForms(page, per_page) {\n const config = {\n method: \"GET\",\n url: `${this._getBaseURL()}/form.json`,\n headers: this._getAuthHeaders(),\n params: {\n page,\n per_page,\n folders: false,\n },\n };\n return (await axios(config)).data.forms;\n },\n },\n};\n\n<|start_filename|>components/slack/actions/send-custom-message/send-custom-message.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-send-custom-message\",\n name: \"Send a Custom Message\",\n description: \"Customize advanced setttings and send a message to a channel, group or user\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n text: {\n propDefinition: [\n slack,\n \"text\",\n ],\n },\n attachments: {\n propDefinition: [\n slack,\n \"attachments\",\n ],\n },\n unfurl_links: {\n propDefinition: [\n slack,\n \"unfurl_links\",\n ],\n },\n unfurl_media: {\n propDefinition: [\n slack,\n \"unfurl_media\",\n ],\n },\n parse: {\n propDefinition: [\n slack,\n \"parse\",\n ],\n },\n as_user: {\n propDefinition: [\n slack,\n \"as_user\",\n ],\n },\n username: {\n propDefinition: [\n slack,\n \"username\",\n ],\n },\n icon_emoji: {\n propDefinition: [\n slack,\n \"icon_emoji\",\n ],\n },\n icon_url: {\n propDefinition: [\n slack,\n \"icon_url\",\n ],\n },\n mrkdwn: {\n propDefinition: [\n slack,\n \"mrkdwn\",\n ],\n },\n blocks: {\n propDefinition: [\n slack,\n \"blocks\",\n ],\n },\n link_names: {\n propDefinition: [\n slack,\n \"link_names\",\n ],\n },\n reply_broadcast: {\n propDefinition: [\n slack,\n \"reply_broadcast\",\n ],\n },\n thread_ts: {\n propDefinition: [\n slack,\n \"thread_ts\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().chat.postMessage({\n text: this.text,\n channel: this.conversation,\n attachments: this.attachments,\n unfurl_links: this.unfurl_links,\n unfurl_media: this.unfurl_media,\n parse: this.parse,\n as_user: this.as_user,\n username: this.username,\n icon_emoji: this.icon_emoji,\n icon_url: this.icon_url,\n mrkdwn: this.mrkdwn,\n blocks: this.blocks,\n link_names: this.link_names,\n reply_broadcast: this.reply_broadcast,\n thread_ts: this.thread_ts,\n });\n },\n};\n\n\n<|start_filename|>components/twitter/sources/my-tweets/my-tweets.js<|end_filename|>\nconst base = require(\"../common/tweets\");\n\nmodule.exports = {\n ...base,\n key: \"twitter-my-tweets\",\n name: \"My Tweets\",\n description: \"Emit new Tweets you post to Twitter\",\n version: \"0.0.5\",\n props: {\n ...base.props,\n q: {\n propDefinition: [\n base.props.twitter,\n \"keyword_filter\",\n ],\n },\n result_type: {\n propDefinition: [\n base.props.twitter,\n \"result_type\",\n ],\n },\n includeRetweets: {\n propDefinition: [\n base.props.twitter,\n \"includeRetweets\",\n ],\n },\n includeReplies: {\n propDefinition: [\n base.props.twitter,\n \"includeReplies\",\n ],\n },\n lang: {\n propDefinition: [\n base.props.twitter,\n \"lang\",\n ],\n },\n locale: {\n propDefinition: [\n base.props.twitter,\n \"locale\",\n ],\n },\n geocode: {\n propDefinition: [\n base.props.twitter,\n \"geocode\",\n ],\n },\n enrichTweets: {\n propDefinition: [\n base.props.twitter,\n \"enrichTweets\",\n ],\n },\n },\n methods: {\n ...base.methods,\n async getSearchQuery() {\n const account = await this.twitter.verifyCredentials();\n const from = `from:${account.screen_name}`;\n return this.q\n ? `${from} ${this.q}`\n : from;\n },\n async retrieveTweets() {\n const {\n lang,\n locale,\n geocode,\n result_type,\n enrichTweets,\n includeReplies,\n includeRetweets,\n maxRequests,\n count,\n } = this;\n const since_id = this.getSinceId();\n const limitFirstPage = !since_id;\n const q = await this.getSearchQuery();\n\n // run paginated search\n return this.twitter.paginatedSearch({\n q,\n since_id,\n lang,\n locale,\n geocode,\n result_type,\n enrichTweets,\n includeReplies,\n includeRetweets,\n maxRequests,\n count,\n limitFirstPage,\n });\n },\n },\n};\n\n\n<|start_filename|>components/gitlab/sources/new-review-request/new-review-request.js<|end_filename|>\nconst gitlab = require(\"../../gitlab.app.js\");\n\nmodule.exports = {\n key: \"gitlab-new-review-request\",\n name: \"New Review Request (Instant)\",\n description: \"Emits an event when a reviewer is added to a merge request\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n gitlab,\n projectId: { propDefinition: [gitlab, \"projectId\"] },\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n db: \"$.service.db\",\n },\n hooks: {\n async activate() {\n const hookParams = {\n merge_requests_events: true,\n push_events: false,\n url: this.http.endpoint,\n };\n const opts = {\n hookParams,\n projectId: this.projectId,\n };\n const { hookId, token } = await this.gitlab.createHook(opts);\n console.log(\n `Created \"merge request events\" webhook for project ID ${this.projectId}.\n (Hook ID: ${hookId}, endpoint: ${hookParams.url})`\n );\n this.db.set(\"hookId\", hookId);\n this.db.set(\"token\", token);\n },\n async deactivate() {\n const hookId = this.db.get(\"hookId\");\n const opts = {\n hookId,\n projectId: this.projectId,\n };\n await this.gitlab.deleteHook(opts);\n console.log(\n `Deleted webhook for project ID ${this.projectId}.\n (Hook ID: ${hookId})`\n );\n },\n },\n methods: {\n getNewReviewers(body) {\n const { action, title } = body.object_attributes;\n\n // When a merge request is first created, any assignees\n // in it are interpreted as new review requests.\n if (action === \"open\" || action === \"reopen\") {\n const { assignees = [] } = body;\n return assignees;\n }\n\n // Gitlab API provides any merge request update diff\n // as part of their response. We can check the presence of\n // the `assignees` attribute within those changes to verify\n // if there are new review requests.\n const { assignees } = body.changes;\n if (!assignees) {\n console.log(`No new assignees in merge request \"${title}\"`);\n return [];\n }\n\n // If the assignees of the merge request changed, we need to compute\n // the difference in order to extract the new reviewers.\n const previousAssigneesUsernames = new Set(assignees.previous.map(a => a.username));\n const newAssignees = assignees.current.filter(a => !previousAssigneesUsernames.has(a.username));\n if (newAssignees.length > 0) {\n console.log(\n `Assignees added to merge request \"${title}\": ${newAssignees.map(a => a.username).join(', ')}`\n );\n }\n return newAssignees;\n },\n generateMeta(data, reviewer) {\n const {\n id,\n title,\n updated_at\n } = data.object_attributes;\n const summary = `New reviewer for \"${title}\": ${reviewer.username}`;\n const ts = +new Date(updated_at);\n const compositeId = `${id}-${ts}-${reviewer.username}`;\n return {\n id: compositeId,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { headers, body } = event;\n\n // Reject any calls not made by the proper Gitlab webhook.\n if (!this.gitlab.isValidSource(headers, this.db)) {\n this.http.respond({\n status: 404,\n });\n return;\n }\n\n // Acknowledge the event back to Gitlab.\n this.http.respond({\n status: 200,\n });\n\n // Gitlab doesn't offer a specific hook for \"new merge request reviewers\" events,\n // but such event can be deduced from the payload of \"merge request\" events.\n this.getNewReviewers(body).forEach(reviewer => {\n const meta = this.generateMeta(body, reviewer);\n const event = {\n ...body,\n reviewer,\n };\n this.$emit(event, meta);\n });\n },\n};\n\n\n<|start_filename|>components/clickup/actions/create-subtask/create-subtask.js<|end_filename|>\nconst clickup = require(\"../../clickup.app.js\");\nconst {\n props,\n run,\n} = require(\"../create-task/create-task.js\");\n\nmodule.exports = {\n key: \"clickup-create-subtask\",\n name: \"Create Subtask\",\n description: \"Creates a new subtask\",\n version: \"0.0.2\",\n type: \"action\",\n props: {\n ...props,\n parent: {\n propDefinition: [\n clickup,\n \"parent\",\n (c) => ({\n list: c.list,\n }),\n ],\n },\n },\n run,\n};\n\n\n<|start_filename|>components/hubspot/sources/new-blog-article/new-blog-article.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-blog-article\",\n name: \"New Blog Posts\",\n description: \"Emits an event for each new blog post.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(blogpost) {\n const { id, name: summary, created } = blogpost;\n const ts = Date.parse(blogpost.created);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const createdAfter = this._getAfter();\n const params = {\n limit: 100,\n createdAfter, // return entries created since event last ran\n };\n\n await this.paginate(\n params,\n this.hubspot.getBlogPosts.bind(this),\n \"results\"\n );\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/microsoft_onedrive/sources/new-file-in-folder/new-file-in-folder.js<|end_filename|>\nconst base = require(\"../new-file/new-file\");\n\nmodule.exports = {\n ...base,\n key: \"microsoft_onedrive-new-file-in-folder\",\n name: \"New File in Folder (Instant)\",\n description: \"Emit an event when a new file is added to a specific folder in a OneDrive drive\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...base.props,\n folder: {\n type: \"string\",\n label: \"Folder\",\n description: \"The OneDrive folder to watch for new files\",\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return [];\n }\n\n const foldersStream = this.microsoft_onedrive.listFolders();\n const result = [];\n for await (const folder of foldersStream) {\n const {\n name: label,\n id: value,\n } = folder;\n result.push({\n label,\n value,\n });\n }\n return result;\n },\n },\n },\n methods: {\n ...base.methods,\n getDeltaLinkParams() {\n return {\n folderId: this.folder,\n };\n },\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/new-contact-task/new-contact-task.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Contact Task\",\n key: \"activecampaign-new-contact-task\",\n description: \"Emits an event each time a new contact task is created.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n contacts: { propDefinition: [activecampaign, \"contacts\"] },\n },\n methods: {\n getEvents() {\n return [\"contact_task_add\"];\n },\n isRelevant(body) {\n return (\n this.contacts.length === 0 ||\n this.contacts.includes(body[\"contact[id]\"])\n );\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: body[\"task[id]\"],\n summary: `${body[\"task[title]\"]}`,\n ts\n };\n },\n },\n};\n\n<|start_filename|>components/webflow/sources/new-collection-item/new-collection-item.js<|end_filename|>\nconst common = require(\"../collection-common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-new-collection-item\",\n name: \"New Collection Item (Instant)\",\n description: \"Emit an event when a collection item is created\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"collection_item_created\";\n },\n generateMeta(data) {\n const {\n _id: id,\n \"created-on\": createdOn,\n slug,\n } = data;\n const summary = `Collection item created: ${slug}`;\n const ts = Date.parse(createdOn);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/firebase_admin_sdk/firebase_admin_sdk.app.js<|end_filename|>\nconst admin = require(\"firebase-admin\");\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"firebase_admin_sdk\",\n propDefinitions: {\n path: {\n type: \"string\",\n label: \"Path\",\n description: \"A [relative path](https://firebase.google.com/docs/reference/rules/rules.Path) to the location of child data\",\n },\n query: {\n type: \"string\",\n label: \"Structured Query\",\n description:\n \"Enter a [structured query](https://cloud.google.com/firestore/docs/reference/rest/v1beta1/StructuredQuery) that returns new records from your target collection. Example: `{ \\\"select\\\": { \\\"fields\\\": [] }, \\\"from\\\": [ { \\\"collectionId\\\": \\\"\\\", \\\"allDescendants\\\": \\\"true\\\" } ] }`\",\n },\n apiKey: {\n type: \"string\",\n label: \"Web API Key\",\n description:\n \"You can find the Web API key in the **Project Settings** of your Firebase admin console\",\n secret: true,\n },\n },\n methods: {\n /**\n * Creates and initializes a Firebase app instance.\n */\n async initializeApp() {\n const {\n projectId,\n clientEmail,\n privateKey,\n } = this.$auth;\n const formattedPrivateKey = privateKey.replace(/\\\\n/g, \"\\n\");\n return await admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: formattedPrivateKey,\n }),\n databaseURL: `https://${projectId}-default-rtdb.firebaseio.com/`,\n });\n },\n /**\n * Renders this app instance unusable and frees the resources of all associated services.\n */\n async deleteApp() {\n return await this.getApp().delete();\n },\n /**\n * Retrieves the default Firebase app instance.\n */\n getApp() {\n return admin.app();\n },\n _getHeaders(token) {\n const defaultHeader = {\n \"Content-Type\": \"applicaton/json\",\n };\n const headers = token\n ? {\n ...defaultHeader,\n Authorization: `Bearer ${token}`,\n }\n : defaultHeader;\n return headers;\n },\n async _makeRequest(method, url, data, params = {}, token = null) {\n const config = {\n method,\n url,\n headers: this._getHeaders(token),\n data,\n params,\n };\n return (await axios(config)).data;\n },\n /**\n * Retrieves a Bearer token for use with the Firebase REST API.\n * @param {string} apiKey - the Web API Key, which is obtained from the project\n * settings page in the admin console\n * @returns {object} returns an object containing a new token and refresh token\n */\n async _getToken(apiKey) {\n const { clientEmail } = this.$auth;\n const newCustomToken = await admin\n .auth()\n .createCustomToken(clientEmail)\n .catch((error) => {\n console.log(\"Error creating custom token:\", error);\n });\n const data = {\n token: newCustomToken,\n returnSecureToken: true,\n };\n const params = {\n key: apiKey,\n };\n return await this._makeRequest(\n \"POST\",\n \"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken\",\n data,\n params,\n );\n },\n /**\n * @param {string} structuredQuery - A structured query in the format specified in\n * this documentation:\n * https://cloud.google.com/firestore/docs/reference/rest/v1/StructuredQuery\n * @param {string} apiKey - the Web API Key, which is obtained from the project settings\n * page in the admin console\n * @returns {array} an array of the documents returned from the structured query\n */\n async runQuery(structuredQuery, apiKey) {\n const { idToken } = await this._getToken(apiKey);\n const { projectId } = this.$auth;\n const parent = `projects/${projectId}/databases/(default)/documents`;\n const data = {\n structuredQuery,\n };\n return await this._makeRequest(\n \"POST\",\n `https://firestore.googleapis.com/v1/${parent}:runQuery`,\n data,\n null,\n idToken,\n );\n },\n },\n};\n\n\n<|start_filename|>components/netlify/sources/new-form-submission/new-form-submission.js<|end_filename|>\nconst common = require(\"../../common\");\n\nmodule.exports = {\n ...common,\n key: \"netlify-new-form-submission\",\n name: \"New Form Submission (Instant)\",\n description: \"Emits an event when a user submits a form\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getHookEvent() {\n return \"submission_created\";\n },\n getMetaSummary(data) {\n const { form_name } = data;\n return `New form submission for ${form_name}`;\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/actions/locales.js<|end_filename|>\nmodule.exports = [\n {\n label: \"German (Austria)\",\n value: \"de_AT\",\n },\n {\n label: \"German (Switzerland)\",\n value: \"de_CH\",\n },\n {\n label: \"German (Germany)\",\n value: \"de_DE\",\n },\n {\n label: \"English (Australia)\",\n value: \"en_AU\",\n },\n {\n label: \"English (Canada)\",\n value: \"en_CA\",\n },\n {\n label: \"English (Denmark)\",\n value: \"en_DK\",\n },\n {\n label: \"English (Finland)\",\n value: \"en_FI\",\n },\n {\n label: \"English (United Kingdom)\",\n value: \"en_GB\",\n },\n {\n label: \"English (Hong Kong)\",\n value: \"en_KH\",\n },\n {\n label: \"English (Ireland)\",\n value: \"en_IE\",\n },\n {\n label: \"English (India)\",\n value: \"en_IN\",\n },\n {\n label: \"English (New Zealand)\",\n value: \"en_NZ\",\n },\n {\n label: \"English (Sweden)\",\n value: \"en_SE\",\n },\n {\n label: \"English (U.S.A.)\",\n value: \"en_US\",\n },\n {\n label: \"Spanish (Argentina)\",\n value: \"es_AR\",\n },\n {\n label: \"Spanish (Chile)\",\n value: \"es_CL\",\n },\n {\n label: \"Spanish (Colombia)\",\n value: \"es_CO\",\n },\n {\n label: \"Spanish (Spain)\",\n value: \"es_ES\",\n },\n {\n label: \"French (Belgium)\",\n value: \"fr_BE\",\n },\n {\n label: \"French (Canada)\",\n value: \"fr_CA\",\n },\n {\n label: \"German (Switzerland)\",\n value: \"fr_CH\",\n },\n {\n label: \"French (France)\",\n value: \"fr_FR\",\n },\n {\n label: \"Hindi (India)\",\n value: \"hi_IN\",\n },\n {\n label: \"Italian (Italy)\",\n value: \"it_IT\",\n },\n {\n label: \"Dutch (Belgium)\",\n value: \"nl_BE\",\n },\n {\n label: \"Dutch (Netherlands)\",\n value: \"nl_NL\",\n },\n {\n label: \"Portuguese (Brazil)\",\n value: \"pt_BR\",\n },\n {\n label: \"Portuguese (Portugal)\",\n value: \"pt_PT\",\n },\n];\n\n\n<|start_filename|>components/netlify/sources/new-deploy-start/new-deploy-start.js<|end_filename|>\nconst common = require(\"../../common\");\n\nmodule.exports = {\n ...common,\n key: \"netlify-new-deploy-start\",\n name: \"New Deploy Start (Instant)\",\n description: \"Emits an event when a new deployment is started\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getHookEvent() {\n return \"deploy_building\";\n },\n getMetaSummary(data) {\n const { commit_ref } = data;\n return `Deploy started for commit ${commit_ref}`;\n },\n },\n};\n\n\n<|start_filename|>components/todoist/sources/new-or-modified-project/new-or-modified-project.js<|end_filename|>\nconst common = require(\"../common-project.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-new-or-modified-project\",\n name: \"New or Modified Project\",\n description: \"Emit an event for each new or modified project\",\n version: \"0.0.1\",\n};\n\n\n<|start_filename|>components/twitch/sources/common.js<|end_filename|>\nconst twitch = require(\"../twitch.app.js\");\nconst { promisify } = require(\"util\");\nconst pause = promisify((delay, fn) => setTimeout(fn, delay));\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n twitch,\n db: \"$.service.db\",\n },\n methods: {\n async *paginate(resourceFn, params, max = null) {\n const items = [];\n let done = false;\n let count = 0;\n do {\n const { data, pagination } = await this.retryFn(resourceFn, params);\n for (const item of data) {\n yield item;\n count++;\n if (max && count >= max) {\n return;\n }\n }\n // pass cursor to get next page of results; if no cursor, no more pages\n const { cursor } = pagination;\n params.after = cursor;\n done = !cursor;\n } while (!done);\n },\n async retryFn(resourceFn, params, retries = 3) {\n let response;\n try {\n response = await resourceFn(params);\n return response.data;\n } catch (err) {\n if (retries <= 1) {\n throw new Error(err);\n }\n delay = response ? response.headers[\"ratelimit-limit\"] : 500;\n await pause(delay);\n return await this.retryFn(resourceFn, params, retries - 1);\n }\n },\n },\n};\n\n<|start_filename|>components/clickup/actions/create-list/create-list.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"clickup-create-list\",\n name: \"Create List\",\n description: \"Creates a new list\",\n version: \"0.0.4\",\n type: \"action\",\n props: {\n ...common.props,\n name: {\n propDefinition: [\n common.props.clickup,\n \"name\",\n ],\n description: \"New list name\",\n },\n content: {\n type: \"string\",\n label: \"Content\",\n description: \"New list content\",\n optional: true,\n },\n dueDate: {\n propDefinition: [\n common.props.clickup,\n \"dueDate\",\n ],\n description:\n `The date by which you must complete the tasks in this list. Use [UTC time](https://www.epochconverter.com/) in \n milliseconds (e.g. \\`1508369194377\\`)`,\n },\n dueDateTime: {\n propDefinition: [\n common.props.clickup,\n \"dueDateTime\",\n ],\n description:\n \"Set to `true` if you want to enable the due date time for the tasks in this list\",\n },\n assignee: {\n propDefinition: [\n common.props.clickup,\n \"assignees\",\n (c) => ({\n workspace: c.workspace,\n }),\n ],\n type: \"string\",\n label: \"Assignee\",\n description: \"Assignee to be added to this list\",\n optional: true,\n },\n status: {\n type: \"string\",\n label: \"Status\",\n description:\n \"The status refers to the List color rather than the task Statuses available in the List\",\n optional: true,\n },\n },\n async run() {\n const data = {\n name: this.name,\n content: this.content,\n due_date: this.dueDate,\n due_date_time: this.dueDateTime,\n priority: this.priority,\n assignee: this.assignee,\n status: this.status,\n };\n return this.folder\n ? await this.clickup.createList(this.folder, data)\n : await this.clickup.createFolderlessList(this.space, data);\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/updated-contact/updated-contact.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"Updated Contact (Instant)\",\n key: \"activecampaign-updated-contact\",\n description: \"Emits an event each time a contact is updated.\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"update\"];\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: `${body[\"contact[id]\"]}${new Date(body.date_time).getTime()}`,\n summary: body[\"contact[email]\"],\n ts\n };\n },\n },\n};\n\n<|start_filename|>components/intercom/sources/new-admin-reply/new-admin-reply.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\nconst get = require(\"lodash.get\");\n\nmodule.exports = {\n key: \"intercom-new-admin-reply\",\n name: \"New Reply From Admin\",\n description: \"Emits an event each time an admin replies to a conversation.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const monthAgo = this.intercom.monthAgo();\n let lastAdminReplyAt =\n this.db.get(\"lastAdminReplyAt\") || Math.floor(monthAgo / 1000);\n lastAdminReplyAt = Math.floor(monthAgo / 1000);\n const data = {\n query: {\n field: \"statistics.last_admin_reply_at\",\n operator: \">\",\n value: lastAdminReplyAt,\n },\n };\n\n const results = await this.intercom.searchConversations(data);\n for (const conversation of results) {\n if (conversation.statistics.last_admin_reply_at > lastAdminReplyAt)\n lastAdminReplyAt = conversation.statistics.last_admin_reply_at;\n const conversationData = (\n await this.intercom.getConversation(conversation.id)\n ).data;\n const total_count = conversationData.conversation_parts.total_count;\n const conversationBody = get(\n conversationData,\n `conversation_parts.conversation_parts[${total_count - 1}].body`\n );\n if (total_count > 0 && conversationBody) {\n // emit id & summary from last part/reply added\n this.$emit(conversationData, {\n id:\n conversationData.conversation_parts.conversation_parts[\n total_count - 1\n ].id,\n summary: conversationBody,\n ts: conversation.statistics.last_admin_reply_at,\n });\n }\n }\n\n this.db.set(\"lastAdminReplyAt\", lastAdminReplyAt);\n },\n};\n\n<|start_filename|>components/twitter/sources/watch-retweets-of-my-tweet/watch-retweets-of-my-tweet.js<|end_filename|>\nconst base = require(\"../common/tweets\");\n\nmodule.exports = {\n ...base,\n key: \"twitter-watch-retweets-of-my-tweet\",\n name: \"Watch Retweets of My Tweet\",\n description: \"Emit an event when a specific Tweet from the authenticated user is retweeted\",\n version: \"0.0.1\",\n props: {\n ...base.props,\n tweetId: {\n type: \"string\",\n label: \"Tweet\",\n description: \"The Tweet to watch for retweets\",\n options(context) {\n return this.tweetIdOptions(context);\n },\n },\n },\n methods: {\n ...base.methods,\n async getScreenName() {\n const { screen_name: screenName } = await this.twitter.verifyCredentials();\n return screenName;\n },\n generateMeta(tweet) {\n const baseMeta = base.methods.generateMeta.bind(this)(tweet);\n const { screen_name: screenName = \"N/A\" } = tweet.user;\n const summary = `Retweet by @${screenName}`;\n return {\n ...baseMeta,\n summary,\n };\n },\n retrieveTweets() {\n return this.twitter.getRetweets({\n id: this.tweetId,\n count: this.count,\n since_id: this.getSinceId(),\n });\n },\n },\n};\n\n\n<|start_filename|>components/intercom/sources/new-company/new-company.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-new-company\",\n name: \"New Companies\",\n description: \"Emits an event each time a new company is added.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const monthAgo = this.intercom.monthAgo();\n let lastCompanyCreatedAt =\n this.db.get(\"lastCompanyCreatedAt\") || Math.floor(monthAgo / 1000);\n\n const companies = await this.intercom.getCompanies(lastCompanyCreatedAt);\n for (const company of companies) {\n if (company.created_at > lastCompanyCreatedAt)\n lastCompanyCreatedAt = company.created_at;\n this.$emit(company, {\n id: company.id,\n summary: company.name,\n ts: company.created_at,\n });\n }\n\n this.db.set(\"lastCompanyCreatedAt\", lastCompanyCreatedAt);\n },\n};\n\n<|start_filename|>components/todoist/sources/sync-resources/sync-resources.js<|end_filename|>\nconst todoist = require(\"../../todoist.app.js\");\nconst common = require(\"../common-project.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-sync-resources\",\n name: \"Sync Resources\",\n description: \"Emit updates for your selected resources\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n includeResourceTypes: { propDefinition: [todoist, \"includeResourceTypes\"] },\n },\n async run(event) {\n let emitCount = 0;\n\n const syncResult = await this.todoist.syncResources(\n this.db,\n this.includeResourceTypes\n );\n\n for (const property in syncResult) {\n if (Array.isArray(syncResult[property])) {\n syncResult[property].forEach((element) => {\n let data = {};\n data.resource = property;\n data.data = element;\n this.$emit(data, {\n summary: property,\n });\n emitCount++;\n });\n }\n }\n\n console.log(`Emitted ${emitCount} events.`);\n },\n};\n\n<|start_filename|>components/slack/actions/add_star/add_star.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-add-star\",\n name: \"Add Star\",\n description: \"Add a star to an item on behalf of the authenticated user\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n optional: true,\n description: \"Channel to add star to, or channel where the message to add star to was posted (used with timestamp).\",\n },\n timestamp: {\n propDefinition: [\n slack,\n \"timestamp\",\n ],\n optional: true,\n description: \"Timestamp of the message to add star to.\",\n },\n file: {\n propDefinition: [\n slack,\n \"file\",\n ],\n optional: true,\n description: \"File to add star to.\",\n },\n },\n async run() {\n return await this.slack.sdk().stars.add({\n conversation: this.conversation,\n timestamp: this.timestamp,\n file: this.file,\n });\n },\n};\n\n\n<|start_filename|>components/slack/actions/delete-message/delete-message.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-delete-message\",\n name: \"Delete Message\",\n description: \"Delete a message\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n timestamp: {\n propDefinition: [\n slack,\n \"timestamp\",\n ],\n },\n as_user: {\n propDefinition: [\n slack,\n \"as_user\",\n ],\n description: \"Pass true to update the message as the authed user. Bot users in this context are considered authed users.\",\n },\n },\n async run() {\n return await this.slack.sdk().chat.delete({\n channel: this.conversation,\n ts: this.timestamp,\n as_user: this.as_user,\n });\n },\n};\n\n\n<|start_filename|>components/gorgias/sources/new-events/new-events.js<|end_filename|>\nconst gorgias = require('../../gorgias.app.js')\nconst moment = require('moment')\n\nconst axios = require('axios')\nmodule.exports = {\n key: \"gorgias-new-events\",\n name: \"New Events\",\n description: \"Emit when there is a new event\",\n version: \"0.0.1\",\n props: {\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60,\n },\n },\n gorgias,\n },\n dedupe: \"greatest\",\n async run(event) {\n const url = `https://${this.gorgias.$auth.domain}.gorgias.com/api/events/?per_page=100`\n const data = (await axios({\n method: \"get\",\n url,\n auth: {\n username: `${this.gorgias.$auth.email}`,\n password: }`,\n },\n })).data\n data.data.forEach(gorgias_event=>{\n this.$emit(gorgias_event,{\n id: gorgias_event.id,\n ts: moment(gorgias_event.created_datetime).valueOf(), \n summary: gorgias_event.type,\n })\n }) \n },\n}\n\n\n<|start_filename|>components/pagerduty/sources/new-oncall-rotation/new-oncall-rotation.js<|end_filename|>\nconst differenceBy = require(\"lodash.differenceby\");\nconst pagerduty = require(\"../../pagerduty.app.js\");\n\nmodule.exports = {\n key: \"pagerduty-new-on-call-rotation\",\n name: \"New On-Call Rotation\",\n version: \"0.0.1\",\n description:\n \"Emits an event each time a new user rotates onto an on-call rotation\",\n props: {\n pagerduty,\n db: \"$.service.db\",\n escalationPolicies: { propDefinition: [pagerduty, \"escalationPolicies\"] },\n timer: {\n type: \"$.interface.timer\",\n label: \"Interval to poll for new rotations\",\n description:\n \"The PagerDuty API doesn't support webhook notifications for on-call rotations, so we must poll the API to check for these changes. Change this interval according to your needs.\",\n default: {\n intervalSeconds: 60 * 10,\n },\n },\n },\n async run(event) {\n // If the user didn't watch specific escalation policies,\n // iterate through all of the policies on the account\n const escalationPolicies =\n this.escalationPolicies && this.escalationPolicies.length\n ? this.escalationPolicies\n : (await this.pagerduty.listEscalationPolicies()).map(({ id }) => id);\n\n // Since we can watch multiple escalation policies for rotations, we must\n // keep track of the last users who were on-call for a given policy.\n const onCallUsersByEscalationPolicy =\n this.db.get(\"onCallUsersByEscalationPolicy\") || {};\n\n for (const policy of escalationPolicies) {\n // Multiple users can technically be on-call at the same time if the account\n // has multiple schedules attached to an escalation policy, so we must watch\n // for any new users in the list of on-call users who were not in the list of\n // users previously on-call. See\n // https://community.pagerduty.com/forum/t/how-do-i-add-more-than-one-person-on-call-for-a-schedule/751\n const onCallUsers = await this.pagerduty.listOnCallUsers({\n escalation_policy_ids: [policy],\n });\n const usersPreviouslyOnCall = onCallUsersByEscalationPolicy[policy] || [];\n\n // Retrieve the list of users who were previously not on-call,\n // but now entered the rotation\n const newOnCallUsers = differenceBy(\n onCallUsers,\n usersPreviouslyOnCall,\n \"id\"\n );\n\n onCallUsersByEscalationPolicy[policy] = onCallUsers;\n\n if (!newOnCallUsers.length) {\n console.log(\n `No change to on-call users for escalation policy ${policy}`\n );\n continue;\n }\n\n // Include escalation policy metadata in emit\n const escalationPolicy = await this.pagerduty.getEscalationPolicy(policy);\n\n for (const user of newOnCallUsers) {\n this.$emit(\n { user, escalationPolicy },\n {\n summary: `${user.summary} is now on-call for escalation policy ${escalationPolicy.name}`,\n }\n );\n }\n }\n // Persist the new set of on-call users for the next run\n this.db.set(\"onCallUsersByEscalationPolicy\", onCallUsersByEscalationPolicy);\n },\n};\n\n\n<|start_filename|>components/zoom_admin/zoom_admin.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst sortBy = require(\"lodash/sortBy\");\n\nmodule.exports = {\n type: \"app\",\n app: \"zoom_admin\",\n propDefinitions: {\n webinars: {\n type: \"string[]\",\n label: \"Webinars\",\n optional: true,\n description:\n \"Webinars you want to watch for new events. **Leave blank to watch all webinars**.\",\n async options({ nextPageToken }) {\n const { webinars, next_page_token } = await this.listWebinars({\n nextPageToken,\n });\n if (!webinars.length) {\n return [];\n }\n const rawOptions = webinars.map((w) => ({\n label: w.topic,\n value: w.id,\n }));\n const options = sortBy(rawOptions, [\"label\"]);\n\n return {\n options,\n context: {\n nextPageToken: next_page_token,\n },\n };\n },\n },\n },\n methods: {\n _apiUrl() {\n return `https://api.zoom.us/v2`;\n },\n _accessToken() {\n return this.$auth.oauth_access_token;\n },\n async _makeRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers[\"Accept\"] = \"application/json\";\n opts.headers[\"Content-Type\"] = \"application/json\";\n opts.headers[\"Authorization\"] = `Bearer ${this._accessToken()}`;\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n const { path } = opts;\n delete opts.path;\n opts.url = `${this._apiUrl()}${path[0] === \"/\" ? \"\" : \"/\"}${path}`;\n return await axios(opts);\n },\n async listWebinars({ pageSize, nextPageToken }) {\n const { data } = await this._makeRequest({\n path: `/users/me/webinars`,\n params: {\n page_size: pageSize || 300,\n next_page_token: nextPageToken,\n },\n });\n return data;\n },\n async listWebinarPanelists(webinarID) {\n const { data } = await this._makeRequest({\n path: `/webinars/${webinarID}/panelists`,\n });\n return data;\n },\n },\n};\n\n\n<|start_filename|>components/snowflake/snowflake.app.js<|end_filename|>\nconst { promisify } = require(\"util\");\nconst snowflake = require(\"snowflake-sdk\");\n\nmodule.exports = {\n app: \"snowflake\",\n type: \"app\",\n methods: {\n async _getConnection() {\n if (this.connection) {\n return this.connection;\n }\n\n this.connection = snowflake.createConnection(this.$auth);\n await promisify(this.connection.connect).bind(this.connection)();\n return this.connection;\n },\n async getRows(statement) {\n const connection = await this._getConnection();\n const executedStatement = connection.execute(statement);\n return executedStatement.streamRows();\n },\n async collectRows(statement) {\n const rowStream = await this.getRows(statement);\n const rows = [];\n for await (const row of rowStream) {\n rows.push(row);\n }\n return rows;\n },\n async *collectRowsPaginated(statement, pageSize = 1) {\n const rowStream = await this.getRows(statement);\n let rows = [];\n for await (const row of rowStream) {\n rows.push(row);\n if (rows.length === pageSize) {\n yield rows;\n rows = [];\n }\n }\n yield rows;\n },\n async listTables() {\n const sqlText = \"SHOW TABLES\";\n return this.collectRows({ sqlText });\n },\n async listFieldsForTable(tableName) {\n const sqlText = \"DESCRIBE TABLE IDENTIFIER(:1)\";\n const binds = [\n tableName,\n ];\n const statement = {\n sqlText,\n binds,\n };\n return this.collectRows(statement);\n },\n },\n};\n\n\n<|start_filename|>components/bitbucket/sources/new-pipeline-event/new-pipeline-event.js<|end_filename|>\nconst isEmpty = require(\"lodash/isEmpty\");\nconst common = require(\"../../common\");\nconst { bitbucket } = common.props;\n\nconst EVENT_SOURCE_NAME = \"New Pipeline Event (Instant)\";\n\nmodule.exports = {\n ...common,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-pipeline-event\",\n description: \"Emits an event when a pipeline event occurs.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n repositoryId: {\n optional: true,\n propDefinition: [\n bitbucket,\n \"repositoryId\",\n c => ({ workspaceId: c.workspaceId }),\n ],\n },\n eventTypes: {\n type: \"string[]\",\n label: \"Pipeline Event Types\",\n description: \"The type of pipeline events that will trigger this event source\",\n optional: true,\n options: [\n // See https://support.atlassian.com/bitbucket-cloud/docs/event-payloads/\n { label: 'Build started', value: 'INPROGRESS' },\n { label: 'Build succeeded', value: 'SUCCESSFUL' },\n { label: 'Build failed', value: 'FAILED' },\n ],\n },\n },\n methods: {\n ...common.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return [\n 'repo:commit_status_created',\n 'repo:commit_status_updated',\n ];\n },\n getHookPathProps() {\n return {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n };\n },\n isEventRelevant(event) {\n const { state: eventType } = event.body.commit_status;\n return (\n isEmpty(this.eventTypes) ||\n this.eventTypes.some(i => i === eventType)\n );\n },\n generateMeta(data) {\n const {\n \"x-request-uuid\": id,\n \"x-event-time\": eventDate,\n } = data.headers;\n const {\n repository,\n state: eventType,\n } = data.body.commit_status;\n const summary = `New pipeline event in ${repository.name}: ${eventType}`;\n const ts = +new Date(eventDate);\n return {\n id,\n summary,\n ts,\n };\n },\n processEvent(event) {\n if (this.isEventRelevant(event)) {\n const parent = common.methods.processEvent.bind(this);\n return parent(event);\n }\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/actions/get-event-attendees/get-event-attendees.js<|end_filename|>\nconst eventbrite = require(\"../../eventbrite.app\");\n\nmodule.exports = {\n key: \"eventbrite-get-event-attendees\",\n name: \"Get Event Attendees\",\n description: \"Get event attendees for a specified event.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n eventbrite,\n eventId: {\n propDefinition: [\n eventbrite,\n \"eventId\",\n ],\n },\n },\n methods: {\n async *attendeeStream(params = {}) {\n let hasMoreItems;\n do {\n const {\n attendees,\n pagination = {},\n } = await this.eventbrite.getEventAttendees(this.eventId, params);\n for (const attendee of attendees) {\n yield attendee;\n }\n\n hasMoreItems = !!pagination.has_more_items;\n params.continuation = pagination.continuation;\n } while (hasMoreItems);\n },\n },\n async run() {\n const attendeeStream = await this.attendeeStream();\n const attendees = [];\n for await (const attendee of attendeeStream) {\n attendees.push(attendee);\n }\n return attendees;\n },\n};\n\n\n<|start_filename|>components/slack/actions/send-message-public-channel/send-message-public-channel.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-send-message-public-channel\",\n name: \"Send Message to a Public Channel\",\n description: \"Send a message to a public channel and customize the name and avatar of the bot that posts the message\",\n version: \"0.1.0\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"publicChannel\",\n ],\n },\n text: {\n propDefinition: [\n slack,\n \"text\",\n ],\n },\n as_user: {\n propDefinition: [\n slack,\n \"as_user\",\n ],\n },\n username: {\n propDefinition: [\n slack,\n \"username\",\n ],\n description: \"Optionally customize your bot's username (default is `Pipedream`).\",\n },\n icon_emoji: {\n propDefinition: [\n slack,\n \"icon_emoji\",\n ],\n description: \"Optionally use an emoji as the bot icon for this message (e.g., `:fire:`). This value overrides `icon_url` if both are provided.\",\n },\n icon_url: {\n propDefinition: [\n slack,\n \"icon_url\",\n ],\n description: \"Optionally provide an image URL to use as the bot icon for this message.\",\n },\n },\n async run() {\n return await this.slack.sdk().chat.postMessage({\n channel: this.conversation,\n text: this.text,\n as_user: this.as_user,\n username: this.username,\n icon_emoji: this.icon_emoji,\n icon_url: this.icon_url,\n });\n },\n};\n\n\n<|start_filename|>components/eventbrite/sources/new-event/new-event.js<|end_filename|>\nconst common = require(\"../common/event.js\");\n\nmodule.exports = {\n ...common,\n key: \"eventbrite-new-event\",\n name: \"New Event (Instant)\",\n description: \"Emits an event when an event has been created\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getActions() {\n return \"event.created\";\n },\n async getData(event) {\n return event;\n },\n },\n};\n\n<|start_filename|>components/npm/sources/download-counts/download-counts.js<|end_filename|>\nconst npm = require('../../npm.app.js')\n\nconst axios = require('axios')\nmodule.exports = {\n key: \"npm-download-counts\",\n name: \"npm Download Counts\",\n description: \"Emit an event with the latest count of downloads for an npm package\",\n version: \"0.0.1\",\n props: {\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 60 * 24,\n },\n },\n period: {\n type: \"string\", \n label: \"Period\",\n description: \"Select last-day, last-week or last-month.\",\n optional: false,\n default: \"last-day\", \n options: [\"last-day\", \"last-week\", \"last-month\"],\n },\n package: {\n type: \"string\", \n label: \"Package\",\n description: \"Enter an npm package name. Leave blank for all\",\n optional: true,\n default: '@pipedreamhq/platform',\n },\n npm,\n },\n async run(event) {\n const npm_event = (await axios({\n method: \"get\",\n url: `https://api.npmjs.org/downloads/point/${encodeURIComponent(this.period)}/${encodeURIComponent(this.package)}`,\n })).data\n this.$emit(npm_event, {\n summary: \"\"+npm_event.downloads,\n }) \n },\n}\n\n\n<|start_filename|>interfaces/timer/examples/create-component/api-payload.json<|end_filename|>\n{\n \"component_code\": \"module.exports = { name: 'cronjob', version: '0.0.1', props: { timer: { type: '$.interface.timer', default: { intervalSeconds: 60, } }, }, run() { console.log('Run any Node.js code here'); }, };\",\n \"name\": \"cronjob-api-test\"\n}\n\n\n<|start_filename|>components/clickup/clickup.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst axiosRetry = require(\"axios-retry\");\n\nmodule.exports = {\n type: \"app\",\n app: \"clickup\",\n propDefinitions: {\n workspace: {\n type: \"string\",\n label: \"Workspace\",\n description: \"Workspace\",\n async options() {\n const workspaces = (await this.getWorkspaces()).teams;\n return workspaces.map((workspace) => ({\n label: workspace.name,\n value: workspace.id,\n }));\n },\n },\n space: {\n type: \"string\",\n label: \"Space\",\n description: \"Space\",\n async options({ workspace }) {\n const spaces = (await this.getSpaces(workspace)).spaces;\n return spaces.map((space) => ({\n label: space.name,\n value: space.id,\n }));\n },\n },\n folder: {\n type: \"string\",\n label: \"Folder\",\n description: \"Folder\",\n async options({ space }) {\n const folders = (await this.getFolders(space)).folders;\n return folders.map((folder) => ({\n label: folder.name,\n value: folder.id,\n }));\n },\n optional: true,\n },\n list: {\n type: \"string\",\n label: \"List\",\n description: \"List\",\n async options({\n folder, space,\n }) {\n const lists = folder\n ? (await this.getLists(folder)).lists\n : (await this.getFolderlessLists(space)).lists;\n return lists.map((list) => ({\n label: list.name,\n value: list.id,\n }));\n },\n },\n assignees: {\n type: \"string[]\",\n label: \"Assignees\",\n description: \"Select the assignees for the task\",\n async options({ workspace }) {\n const members = await this.getWorkspaceMembers(workspace);\n return members.map((member) => ({\n label: member.user.username,\n value: member.user.id,\n }));\n },\n optional: true,\n },\n tags: {\n type: \"string[]\",\n label: \"Tags\",\n description:\n \"Select the tags for the task to filter when searching for the tasks\",\n async options({ space }) {\n const tags = (await this.getTags(space)).tags;\n return tags.map((tag) => tag.name);\n },\n optional: true,\n },\n status: {\n type: \"string\",\n label: \"Status\",\n description: \"Select the status of the task\",\n async options({ list }) {\n const statuses = (await this.getList(list)).statuses;\n return statuses.map((status) => status.status);\n },\n optional: true,\n },\n task: {\n type: \"string\",\n label: \"Task\",\n description: \"Task\",\n async options({\n list, page,\n }) {\n const tasks = (await this.getTasks(list, page)).tasks;\n return tasks.map((task) => ({\n label: task.name,\n value: task.id,\n }));\n },\n },\n priority: {\n type: \"integer\",\n label: \"Priority\",\n description: `1 is Urgent\n 2 is High\n 3 is Normal\n 4 is Low`,\n optional: true,\n },\n name: {\n type: \"string\",\n label: \"Name\",\n description: \"Name\",\n },\n dueDate: {\n type: \"integer\",\n label: \"Due Date\",\n description: \"Due Date\",\n optional: true,\n },\n dueDateTime: {\n type: \"boolean\",\n label: \"Due Date Time\",\n description: \"Due Date Time\",\n optional: true,\n },\n parent: {\n type: \"string\",\n label: \"Parent\",\n description:\n `Pass an existing task ID in the parent property to make the new task a subtask of that parent. \n The parent you pass must not be a subtask itself, and must be part of the specified list.`,\n async options({\n list, page,\n }) {\n const tasks = (await this.getTasks(list, page)).tasks;\n return tasks.map((task) => ({\n label: task.name,\n value: task.id,\n }));\n },\n },\n },\n methods: {\n async _makeRequest(method, endpoint, data = null, params = null) {\n axiosRetry(axios, {\n retries: 3,\n });\n const config = {\n headers: {\n \"content-type\": \"application/json\",\n \"Authorization\": this.$auth.oauth_access_token,\n },\n method,\n url: `https://api.clickup.com/api/v2/${endpoint}`,\n params,\n };\n if (data) config.data = data;\n const response = await axios(config).catch((err) => {\n if (err.response.status !== 200) {\n throw new Error(`API call failed with status code: ${err.response.status} after 3 retry attempts`);\n }\n });\n return response.data;\n },\n async getWorkspaces() {\n return await this._makeRequest(\"GET\", \"team\");\n },\n async getSpaces(workspaceId) {\n return await this._makeRequest(\n \"GET\",\n `team/${workspaceId}/space?archived=false`,\n );\n },\n async getFolders(spaceId) {\n return await this._makeRequest(\n \"GET\",\n `space/${spaceId}/folder?archived=false`,\n );\n },\n async getList(listId) {\n return await this._makeRequest(\"GET\", `list/${listId}`);\n },\n async getLists(folderId) {\n return await this._makeRequest(\n \"GET\",\n `folder/${folderId}/list?archived=false`,\n );\n },\n async getFolderlessLists(spaceId) {\n return await this._makeRequest(\n \"GET\",\n `space/${spaceId}/list?archived=false`,\n );\n },\n async getWorkspaceMembers(workspaceId) {\n const { teams } = (await this.getWorkspaces());\n const workspace = teams.filter(\n (workspace) => workspace.id == workspaceId,\n );\n return workspace\n ? workspace[0].members\n : [];\n },\n async getTags(spaceId) {\n return await this._makeRequest(\"GET\", `space/${spaceId}/tag`);\n },\n async getTasks(listId, page = 0) {\n return await this._makeRequest(\n \"GET\",\n `list/${listId}/task?archived=false&page=${page}`,\n );\n },\n async createTask(listId, data) {\n return await this._makeRequest(\"POST\", `list/${listId}/task`, data);\n },\n async createList(folderId, data) {\n return await this._makeRequest(\"POST\", `folder/${folderId}/list`, data);\n },\n async createFolderlessList(spaceId, data) {\n return await this._makeRequest(\"POST\", `space/${spaceId}/list`, data);\n },\n },\n};\n\n\n<|start_filename|>components/hubspot/hubspot.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"hubspot\",\n propDefinitions: {\n lists: {\n type: \"string[]\",\n label: \"Lists\",\n description: \"Select the lists to watch for new contacts.\",\n async options(prevContext) {\n const { offset = 0 } = prevContext;\n const params = {\n count: 250,\n offset,\n };\n const results = await this.getLists(params);\n const options = results.map((result) => {\n const { name: label, listId } = result;\n return {\n label,\n value: JSON.stringify({ label, value: listId }),\n };\n });\n return {\n options,\n context: {\n offset: params.offset + params.count,\n },\n };\n },\n },\n stages: {\n type: \"string[]\",\n label: \"Stages\",\n description: \"Select the stages to watch for new deals in.\",\n async options() {\n const results = await this.getDealStages();\n const options = results.results[0].stages.map((result) => {\n const { label, stageId } = result;\n return {\n label,\n value: JSON.stringify({ label, value: stageId }),\n };\n });\n return options;\n },\n },\n objectType: {\n type: \"string\",\n label: \"Object Type\",\n description: \"Watch for new events concerning the object type specified.\",\n async options(opts) {\n return [\n {\n label: \"Companies\",\n value: \"company\",\n },\n {\n label: \"Contacts\",\n value: \"contact\",\n },\n {\n label: \"Deals\",\n value: \"deal\",\n },\n {\n label: \"Tickets\",\n value: \"ticket\",\n },\n ];\n },\n },\n objectIds: {\n type: \"string[]\",\n label: \"Object\",\n description: \"Watch for new events concerning the objects selected.\",\n async options(opts) {\n let objectType = null;\n if (opts.objectType == \"company\") objectType = \"companies\";\n else objectType = `${opts.objectType}s`;\n const results = await this.getObjects(objectType);\n const options = results.map((result) => {\n const { id, properties } = result;\n switch (objectType) {\n case \"companies\":\n label = properties.name;\n break;\n case \"contacts\":\n label = `${properties.firstname} ${properties.lastname}`;\n break;\n case \"deals\":\n label = properties.dealname;\n break;\n case \"tickets\":\n label = properties.subject;\n break;\n }\n return { label, value: id };\n });\n return options;\n },\n },\n forms: {\n type: \"string[]\",\n label: \"Form\",\n description: \"Watch for new submissions of the specified forms.\",\n async options(prevContext) {\n const { offset } = prevContext;\n const params = {\n count: 50,\n offset: offset || 0,\n };\n const results = await this.getForms();\n const options = results.map((result) => {\n const { name: label, guid } = result;\n return {\n label,\n value: JSON.stringify({ label, value: guid }),\n };\n });\n return {\n options,\n context: {\n offset: params.offset + params.count,\n },\n };\n },\n },\n },\n methods: {\n _getBaseURL() {\n return \"https://api.hubapi.com\";\n },\n _getHeaders() {\n return {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n \"Content-Type\": \"application/json\",\n };\n },\n monthAgo() {\n const monthAgo = new Date();\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return monthAgo;\n },\n async makeGetRequest(endpoint, params = null) {\n const config = {\n method: \"GET\",\n url: `${this._getBaseURL()}${endpoint}`,\n headers: this._getHeaders(),\n params,\n };\n return (await axios(config)).data;\n },\n async searchCRM({ object, ...data }) {\n const config = {\n method: \"POST\",\n url: `${this._getBaseURL()}/crm/v3/objects/${object}/search`,\n headers: this._getHeaders(),\n data,\n };\n return (await axios(config)).data;\n },\n async getBlogPosts(params) {\n return await this.makeGetRequest(\"/cms/v3/blogs/posts\", params);\n },\n async getCalendarTasks(endDate) {\n params = {\n startDate: Date.now(),\n endDate,\n };\n return await this.makeGetRequest(\"/calendar/v1/events/task\", params);\n },\n async getContactProperties() {\n return await this.makeGetRequest(\"/properties/v1/contacts/properties\");\n },\n async createPropertiesArray() {\n const allProperties = await this.getContactProperties();\n return allProperties.map((property) => property.name);\n },\n async getDealProperties() {\n return await this.makeGetRequest(\"/properties/v1/deals/properties\");\n },\n async getDealStages() {\n return await this.makeGetRequest(\"/crm-pipelines/v1/pipelines/deal\");\n },\n async getEmailEvents(params) {\n return await this.makeGetRequest(\"/email/public/v1/events\", params);\n },\n async getEngagements(params) {\n return await this.makeGetRequest(\n \"/engagements/v1/engagements/paged\",\n params\n );\n },\n async getEvents(params) {\n return await this.makeGetRequest(\"/events/v3/events\", params);\n },\n async getForms(params) {\n return await this.makeGetRequest(\"/forms/v2/forms\", params);\n },\n async getFormSubmissions(params) {\n const { formId } = params;\n delete params.formId;\n return await this.makeGetRequest(\n `/form-integrations/v1/submissions/forms/${formId}`,\n params\n );\n },\n async getLists(params) {\n const { lists } = await this.makeGetRequest(\"/contacts/v1/lists\", params);\n return lists;\n },\n async getListContacts(params, listId) {\n return await this.makeGetRequest(\n `/contacts/v1/lists/${listId}/contacts/all`,\n params\n );\n },\n async getObjects(objectType) {\n const params = {\n limit: 100,\n };\n let results = null;\n const objects = [];\n while (!results || params.next) {\n results = await this.makeGetRequest(\n `/crm/v3/objects/${objectType}`,\n params\n );\n if (results.paging) params.next = results.paging.next.after;\n else delete params.next;\n for (const result of results.results) {\n objects.push(result);\n }\n }\n return objects;\n },\n async getContact(contactId, properties) {\n const params = {\n properties,\n };\n return await this.makeGetRequest(\n `/crm/v3/objects/contacts/${contactId}`,\n params\n );\n },\n },\n};\n\n<|start_filename|>components/twist/sources/new-thread/new-thread.js<|end_filename|>\nconst twist = require(\"../../twist.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Thread (Instant)\",\n version: \"0.0.1\",\n key: \"twist-new-thread\",\n description: \"Emits an event for any new thread in a workspace\",\n props: {\n ...common.props,\n channel: {\n propDefinition: [twist, \"channel\", (c) => ({ workspace: c.workspace })],\n },\n },\n methods: {\n getHookActivationData() {\n return {\n target_url: this.http.endpoint,\n event: \"thread_added\",\n workspace_id: this.workspace,\n channel_id: this.channel,\n };\n },\n getMeta(body) {\n const { id, title, posted } = body;\n return {\n id,\n summary: title,\n ts: Date.parse(posted),\n };\n },\n },\n};\n\n<|start_filename|>components/supersaas/sources/changed-appointments.js<|end_filename|>\nconst dayjs = require('dayjs');\nconst makeEventSummary = require('../utils/makeEventSummary.js');\nconst supersaas = require('../supersaas.app.js');\n\nmodule.exports = {\n key: 'supersaas-changed-appointments',\n name: 'New or changed appointments',\n description: `Emits an event for every changed appointments from the selected schedules.`,\n version: '0.0.1',\n props: {\n supersaas,\n schedules: { propDefinition: [supersaas, 'schedules'] },\n db: \"$.service.db\",\n http: '$.interface.http',\n },\n hooks: {\n async activate() {\n const { http, schedules } = this;\n\n this.db.set('activeHooks', await this.supersaas.createHooks(schedules.map(x => ({\n event: 'C', // change_appointment\n parent_id: Number(x),\n target_url: http.endpoint,\n }))));\n },\n async deactivate() {\n await this.supersaas.destroyHooks(this.db.get('activeHooks') || []);\n this.db.set('activeHooks', []);\n },\n },\n async run(ev) {\n const outEv = {\n meta: {\n summary: makeEventSummary(ev),\n ts: dayjs(ev.body.created_on).valueOf(),\n },\n body: ev.body,\n };\n\n console.log('Emitting:', outEv);\n this.$emit(outEv, outEv.meta);\n },\n};\n\n\n<|start_filename|>components/yotpo/sources/new-reviews/new-reviews.js<|end_filename|>\nconst _get = require(\"lodash.get\")\nconst _truncate = require(\"lodash.truncate\")\nconst he = require(\"he\")\nconst moment = require('moment')\nconst yotpo = require('../../yotpo.app.js')\nmodule.exports = {\n name: \"New Reviews\",\n description: \"Emits a new event any time a Yotpo review is created or updated\",\n key: \"yotpo-new-reviews\",\n version: '0.0.1',\n dedupe: \"unique\",\n props: {\n http: {\n type: \"$.interface.http\",\n },\n yotpo,\n },\n hooks: {\n async activate() {\n await this.yotpo.createWebhook(\"review_create\", this.http.endpoint)\n await this.yotpo.createWebhook(\"review_updated\", this.http.endpoint)\n },\n async deactivate() {\n await this.yotpo.deleteWebhook(\"review_create\", this.http.endpoint)\n await this.yotpo.deleteWebhook(\"review_updated\", this.http.endpoint)\n },\n },\n async run(event) {\n const id = _get(event, \"body.data.id\")\n const updatedAt = _get(event, \"body.data.updated_at\")\n if (id && updatedAt) {\n const dedupeId = `${id}-${updatedAt}`\n const flag = _get(event, \"body.data.new\") ? \"\" : \" [UPDATED]\"\n const score = _get(event, \"body.data.score\", \"?\")\n const text = _truncate(he.decode(_get(event, \"body.data.title\", _get(event, \"body.data.content\", \"- no content -\"))))\n const summary = `${score} stars:${flag} ${text}`\n const ts = moment(updatedAt).valueOf()\n this.$emit(event.body, { id: dedupeId, summary, ts })\n }\n },\n}\n\n\n<|start_filename|>components/hubspot/sources/new-form-submission/new-form-submission.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-form-submission\",\n name: \"New Form Submission\",\n description: \"Emits an event for each new submission of a form.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n forms: { propDefinition: [common.props.hubspot, \"forms\"] },\n },\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(result) {\n const { pageUrl, submittedAt: ts } = result;\n const submitted = new Date(ts);\n return {\n id: `${pageUrl}${ts}`,\n summary: `Form submitted at ${submitted.toLocaleDateString()} ${submitted.toLocaleTimeString()}`,\n ts,\n };\n },\n isRelevant(result, submittedAfter) {\n return result.submittedAt > submittedAfter;\n },\n },\n async run(event) {\n const submittedAfter = this._getAfter();\n const baseParams = {\n limit: 50,\n };\n\n await Promise.all(\n this.forms\n .map(JSON.parse)\n .map(({ value }) => ({\n ...baseParams,\n formId: value,\n }))\n .map((params) =>\n this.paginate(\n params,\n this.hubspot.getFormSubmissions.bind(this),\n \"results\",\n submittedAfter\n )\n )\n );\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/twilio/sources/new-phone-number/new-phone-number.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n key: \"twilio-new-phone-number\",\n name: \"New Phone Number\",\n description: \"Emits an event when you add a new phone number to your account\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n async listResults(...args) {\n return await this.twilio.listIncomingPhoneNumbers(...args);\n },\n generateMeta(number) {\n const { sid: id, friendlyName: summary, dateCreated } = number;\n return {\n id,\n summary,\n ts: Date.parse(dateCreated),\n };\n },\n },\n};\n\n<|start_filename|>components/ringcentral/sources/new-voicemail-message/new-voicemail-message.js<|end_filename|>\nconst common = require(\"../common/http-based\");\n\nmodule.exports = {\n ...common,\n key: \"ringcentral-new-voicemail-message\",\n name: \"New Voicemail Message (Instant)\",\n description: \"Emits an event when a new voicemail message is received\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n extensionId: { propDefinition: [common.props.ringcentral, \"extensionId\"] },\n },\n methods: {\n ...common.methods,\n getSupportedNotificationTypes() {\n return new Set([\n \"voicemail-message-event\",\n ]);\n },\n generateMeta(data) {\n const {\n uuid: id,\n timestamp,\n body: eventDetails,\n } = data;\n const {\n from: {\n phoneNumber: callerPhoneNumber,\n },\n } = eventDetails;\n\n const maskedCallerNumber = this.getMaskedNumber(callerPhoneNumber);\n const summary = `New voicemail from ${maskedCallerNumber}`;\n const ts = Date.parse(timestamp);\n\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/calendly/sources/invitee-created/invitee-created.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n key: \"calendly-invitee-created\",\n name: \"Invitee Created (Instant)\",\n description: \"Emits an event when an invitee schedules an event\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"invitee.created\"];\n },\n generateMeta(body) {\n return this.generateInviteeMeta(body);\n },\n },\n};\n\n<|start_filename|>components/ahrefs/actions/get-backlinks/get-backlinks.js<|end_filename|>\nconst ahrefs = require('../../ahrefs.app.js')\nconst axios = require('axios')\n\nmodule.exports = {\n name: 'Get Backlinks',\n key: \"ahrefs-get-backlinks\",\n description: \"Get the backlinks for a domain or URL with details for the referring pages (e.g., anchor and page title).\",\n version: '0.0.8',\n type: \"action\",\n props: {\n ahrefs,\n target: { propDefinition: [ahrefs, \"target\"] },\n mode: { propDefinition: [ahrefs, \"mode\"] },\n limit: { propDefinition: [ahrefs, \"limit\"] },\n },\n async run() {\n return (await axios({\n url: `https://apiv2.ahrefs.com`,\n params: {\n token: this.ahrefs.$auth.oauth_access_token,\n from: \"backlinks\",\n target: this.target,\n mode: this.mode,\n limit: this.limit,\n order_by: \"ahrefs_rank:desc\",\n output: \"json\"\n },\n })).data\n },\n}\n\n<|start_filename|>components/hacker_news/hacker_news.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"hacker_news\",\n}\n\n<|start_filename|>components/calendly/sources/common-polling.js<|end_filename|>\nconst calendly = require(\"../calendly.app.js\");\n\nmodule.exports = {\n props: {\n calendly,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n _getLastEvent() {\n const lastEvent = this.db.get(\"lastEvent\") || this.calendly.monthAgo();\n return lastEvent;\n },\n _setLastEvent(lastEvent) {\n this.db.set(\"lastEvent\", lastEvent);\n },\n },\n async run(event) {\n const lastEvent = this._getLastEvent();\n\n const results = await this.getResults();\n for (const result of results) {\n if (this.isRelevant(result, lastEvent)) {\n const meta = this.generateMeta(result);\n this.$emit(result, meta);\n }\n }\n\n this._setLastEvent(Date.now());\n },\n};\n\n<|start_filename|>components/webflow/sources/collection-common.js<|end_filename|>\nconst common = require(\"./common\");\n\nmodule.exports = {\n ...common,\n dedupe: \"unique\",\n props: {\n ...common.props,\n collectionIds: {\n type: \"string[]\",\n label: \"Collections\",\n description: \"The collections to monitor for item changes\",\n optional: true,\n async options(context) {\n const { page } = context;\n if (page !== 0) {\n return {\n options: [],\n };\n }\n\n const collections = await this.webflow.listCollections(this.siteId);\n const options = collections.map(collection => ({\n label: collection.name,\n value: collection._id,\n }));\n return {\n options,\n };\n },\n },\n },\n methods: {\n ...common.methods,\n isEventRelevant(event) {\n const { body: { _cid: collectionId } } = event;\n return this.collectionIds.includes(collectionId);\n },\n },\n};\n\n\n<|start_filename|>components/todoist/sources/completed-task/completed-task.js<|end_filename|>\nconst common = require(\"../common-task.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-completed-task\",\n name: \"Completed Task\",\n description: \"Emit an event for each completed task\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n isElementRelevant(element) {\n return element.checked === 1;\n },\n },\n};\n\n\n<|start_filename|>components/google_drive/sources/new-or-modified-files/new-or-modified-files.js<|end_filename|>\n// This source processes changes to any files in a user's Google Drive,\n// implementing strategy enumerated in the Push Notifications API docs:\n// https://developers.google.com/drive/api/v3/push and here:\n// https://developers.google.com/drive/api/v3/manage-changes\n//\n// This source has two interfaces:\n//\n// 1) The HTTP requests tied to changes in the user's Google Drive\n// 2) A timer that runs on regular intervals, renewing the notification channel as needed\n\nconst common = require(\"../common-webhook.js\");\nconst {\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n GOOGLE_DRIVE_NOTIFICATION_UPDATE,\n} = require(\"../../constants\");\n\nmodule.exports = {\n ...common,\n key: \"google_drive-new-or-modified-files\",\n name: \"New or Modified Files\",\n description:\n \"Emits a new event any time any file in your linked Google Drive is added, modified, or deleted\",\n version: \"0.0.14\",\n type: \"source\",\n // Dedupe events based on the \"x-goog-message-number\" header for the target channel:\n // https://developers.google.com/drive/api/v3/push#making-watch-requests\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getUpdateTypes() {\n return [\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n GOOGLE_DRIVE_NOTIFICATION_UPDATE,\n ];\n },\n generateMeta(data, headers) {\n const {\n id: fileId,\n name: summary,\n modifiedTime: tsString,\n } = data;\n const { \"x-goog-message-number\": eventId } = headers;\n return {\n id: `${fileId}-${eventId}`,\n summary,\n ts: Date.parse(tsString),\n };\n },\n async processChanges(changedFiles, headers) {\n for (const file of changedFiles) {\n const eventToEmit = {\n file,\n change: {\n state: headers[\"x-goog-resource-state\"],\n resourceURI: headers[\"x-goog-resource-uri\"],\n changed: headers[\"x-goog-changed\"], // \"Additional details about the changes. Possible values: content, parents, children, permissions\"\n },\n };\n const meta = this.generateMeta(file, headers);\n this.$emit(eventToEmit, meta);\n }\n },\n },\n};\n\n\n<|start_filename|>components/mysql/mysql.app.js<|end_filename|>\nconst mysqlClient = require(\"mysql2/promise\");\n\nmodule.exports = {\n type: \"app\",\n app: \"mysql\",\n propDefinitions: {\n table: {\n type: \"string\",\n label: \"Table\",\n description: \"The database table to watch for changes\",\n async options() {\n const { database } = this.$auth;\n const connection = await this.getConnection();\n const tables = await this.listTables(connection);\n await this.closeConnection(connection);\n return tables.map((table) => {\n return table[`Tables_in_${database}`];\n });\n },\n },\n column: {\n type: \"string\",\n label: \"Column\",\n description:\n \"The name of a column in the table to use for deduplication. Defaults to the table's primary key\",\n async options(opts) {\n return this.listColumnNames(opts.table);\n },\n },\n query: {\n type: \"string\",\n label: \"SQL Query\",\n description: \"Your custom SQL query\",\n },\n },\n methods: {\n async getConnection() {\n const { host, port, username, password, database } = this.$auth;\n return await mysqlClient.createConnection({\n host,\n port,\n user: username,\n password,\n database,\n });\n },\n async closeConnection(connection) {\n const connectionClosed = new Promise((resolve) => {\n connection.connection.stream.on(\"close\", resolve);\n });\n await connection.end();\n await connectionClosed;\n },\n async executeQuery(connection, query) {\n const results = await connection.execute(query);\n return results[0];\n },\n async listTables(connection) {\n const options = {\n sql: \"SHOW FULL TABLES\",\n };\n return await this.executeQuery(connection, options);\n },\n async listBaseTables(connection, lastResult) {\n const options = {\n sql: `\n SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE = 'BASE TABLE'\n AND CREATE_TIME > ?\n ORDER BY CREATE_TIME DESC\n `,\n values: [lastResult],\n };\n return await this.executeQuery(connection, options);\n },\n async listTopTables(connection, maxCount = 10) {\n const options = {\n sql: `\n SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE = 'BASE TABLE'\n ORDER BY CREATE_TIME DESC\n LIMIT ?\n `,\n values: [maxCount],\n };\n return await this.executeQuery(connection, options);\n },\n async listColumns(connection, table) {\n const options = {\n sql: `SHOW COLUMNS FROM \\`${table}\\``,\n };\n return await this.executeQuery(connection, options);\n },\n async listNewColumns(connection, table, previousColumns) {\n const options = {\n sql: `\n SHOW COLUMNS FROM \\`${table}\\`\n WHERE Field NOT IN (?)\n `,\n values: [previousColumns.join()],\n };\n return await this.executeQuery(connection, options);\n },\n /**\n * Returns rows from a specified table.\n * @param {object} connection - The database connection.\n * @param {string} table - Name of the table to search.\n * @param {string} column - Name of the table column to order by\n * @param {string} lastResult - Maximum result in the specified table column that has been previously returned.\n */\n async listRows(connection, table, column, lastResult) {\n const options = {\n sql: `\n SELECT * FROM \\`${table}\\`\n WHERE \\`${column}\\` > ? \n ORDER BY \\`${column}\\` DESC\n `,\n values: [lastResult],\n };\n return await this.executeQuery(connection, options);\n },\n /**\n * Returns rows from a specified table. Used when lastResult has not yet been set. Returns a maximum of 10 results\n * ordered by the specified column.\n * @param {object} connection - The database connection.\n * @param {string} table - Name of the table to search.\n * @param {string} column - Name of the table column to order by\n */\n async listMaxRows(connection, table, column, maxCount = 10) {\n const options = {\n sql: `\n SELECT * FROM \\`${table}\\`\n ORDER BY \\`${column}\\` DESC\n LIMIT ?\n `,\n values: [maxCount],\n };\n return await this.executeQuery(connection, options);\n },\n async getPrimaryKey(connection, table) {\n const options = {\n sql: `SHOW KEYS FROM ? WHERE Key_name = 'PRIMARY'`,\n values: [table],\n };\n return await this.executeQuery(connection, options);\n },\n async listColumnNames(table) {\n const connection = await this.getConnection();\n const columns = await this.listColumns(connection, table);\n await this.closeConnection(connection);\n return columns.map((column) => column.Field);\n },\n },\n};\n\n<|start_filename|>components/ringcentral/sources/common/message-types.js<|end_filename|>\nmodule.exports = [\n \"Fax\",\n \"Pager\",\n \"SMS\",\n \"Voicemail\",\n];\n\n\n<|start_filename|>components/swapi/actions/get-film/get-film.js<|end_filename|>\nconst swapi = require('../../swapi.app.js')\nconst axios = require('axios')\n\nmodule.exports = {\n key: \"swapi-get-film\",\n name: \"Get Film\",\n version: \"0.0.12\",\n type: \"action\",\n props: {\n swapi,\n film: { propDefinition: [swapi, \"film\"] },\n },\n async run() {\n return (await axios({\n url: `https://swapi.dev/api/films/${this.film}`\n })).data\n },\n}\n\n<|start_filename|>components/activecampaign/sources/new-or-updated-deal/new-or-updated-deal.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Deal Added or Updated (Instant)\",\n key: \"activecampaign-new-or-updated-deal\",\n description: \"Emits an event each time a deal is added or updated.\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"deal_add\", \"deal_update\"];\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: `${body[\"deal[id]\"]}${new Date(body.date_time).getTime()}`,\n summary: body[\"deal[title]\"],\n ts\n };\n },\n },\n};\n\n<|start_filename|>components/twilio/actions/send-mms/send-mms.js<|end_filename|>\n// Read the Twilio docs at https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource\nconst twilio = require(\"../../twilio.app.js\");\nconst { phone } = require(\"phone\");\n\nmodule.exports = {\n key: \"twilio-send-mms\",\n name: \"Send MMS\",\n description: \"Send an SMS with text and media files.\",\n type: \"action\",\n version: \"0.0.4\",\n props: {\n twilio,\n from: {\n propDefinition: [\n twilio,\n \"from\",\n ],\n },\n to: {\n propDefinition: [\n twilio,\n \"to\",\n ],\n },\n body: {\n propDefinition: [\n twilio,\n \"body\",\n ],\n },\n mediaUrl: {\n propDefinition: [\n twilio,\n \"mediaUrl\",\n ],\n },\n },\n async run() {\n // Parse the given number into its E.164 equivalent\n // The E.164 phone number will be included in the first element\n // of the array, but the array will be empty if parsing fails.\n // See https://www.npmjs.com/package/phone\n const toParsed = phone(this.to);\n if (!toParsed || !toParsed.phoneNumber) {\n throw new Error(`Phone number ${this.to} couldn't be parsed as a valid number.`);\n }\n\n const data = {\n to: toParsed.phoneNumber,\n from: this.from,\n body: this.body,\n mediaUrl: this.mediaUrl,\n };\n\n return await this.twilio.getClient().messages.create(data);\n },\n};\n\n\n<|start_filename|>components/twilio/sources/new-call/new-call.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n key: \"twilio-new-call\",\n name: \"New Call (Instant)\",\n description:\n \"Configures a webhook in Twilio, tied to a phone number, and emits an event each time a call to that number is completed\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n async setWebhook(...args) {\n return await this.twilio.setIncomingCallWebhookURL(...args);\n },\n generateMeta(body, headers) {\n return {\n /** if Twilio retries a message, but we've already emitted, dedupe */\n id: headers[\"i-twilio-idempotency-token\"],\n summary: `New call from ${this.getMaskedNumber(body.From)}`,\n ts: Date.now(),\n };\n },\n isRelevant(body) {\n return body.CallStatus == \"completed\";\n },\n getMaskedNumber(number) {\n const { length: numberLength } = number;\n return number.slice(numberLength - 4).padStart(numberLength, \"#\");\n },\n },\n};\n\n<|start_filename|>components/supersaas/supersaas.app.js<|end_filename|>\nconst envConf = require('./envConf.js');\n\nmodule.exports = {\n type: 'app',\n app: 'supersaas',\n propDefinitions: {\n schedules: {\n type: 'string[]',\n label: 'Schedules',\n description: `The schedules you'd like to watch for changes`,\n async options() {\n return await this.getSchedules();\n },\n },\n },\n methods: {\n async axios(path, opts = {}) {\n const { axios } = await require('@pipedreamhq/platform');\n\n return await axios(this, {\n url: `${envConf.urlPrefix}${path}`,\n ...opts,\n params: {\n account: this.$auth.account,\n api_key: this.$auth.api_key,\n ...opts.params || {},\n },\n });\n },\n async getSchedules() {\n const xs = await this.axios('/api/schedules.json');\n return xs.map(x => ({ value: x.id, label: x.name }));\n },\n async createHooks(hookParams) {\n const { axios } = this;\n\n console.log('Creating hooks:', hookParams);\n\n return await Promise.all(hookParams.map(\n x => axios('/api/hooks', { method: 'POST', params: x }),\n ));\n },\n // TODO: Better error handling. Dylan suggested retries with a backoff\n // algorithm, but that sounds a little overkill to me; but I guess we\n // could at least remember failed hook destructions and retry on every\n // activate/deactivate cycle?\n async destroyHooks(activeHooks) {\n const { axios } = this;\n\n console.log('Destroying hooks:', activeHooks || []);\n\n if (!activeHooks || !activeHooks.length) {\n return;\n }\n\n return await Promise.all(activeHooks.map(x => axios('/api/hooks', {\n method: 'DELETE',\n params: { id: x.id, parent_id: x.parent_id },\n })));\n },\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/deal-updated/deal-updated.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-deal-updated\",\n name: \"Deal Updated\",\n description: \"Emits an event each time a deal is updated.\",\n version: \"0.0.2\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(deal) {\n const { id, properties, updatedAt } = deal;\n const ts = Date.parse(updatedAt);\n return {\n id: `${id}${ts}`,\n summary: properties.dealname,\n ts,\n };\n },\n isRelevant(deal, updatedAfter) {\n return Date.parse(deal.updatedAt) > updatedAfter;\n },\n },\n async run(event) {\n const updatedAfter = this._getAfter();\n const data = {\n limit: 100,\n sorts: [\n {\n propertyName: \"hs_lastmodifieddate\",\n direction: \"DESCENDING\",\n },\n ],\n object: \"deals\",\n };\n await this.paginate(\n data,\n this.hubspot.searchCRM.bind(this),\n \"results\",\n updatedAfter\n );\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/twitch/actions/get-channel-editors/get-channel-editors.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Channel Editors\",\n key: \"twitch-get-channel-editors\",\n description: \"Gets a list of users who are editors for your channel\",\n version: \"0.0.1\",\n type: \"action\",\n async run() {\n // get the userID of the authenticated user\n const userId = await this.getUserId();\n const params = {\n broadcaster_id: userId,\n };\n return (await this.twitch.getChannelEditors(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/eventbrite/sources/common/base.js<|end_filename|>\nconst eventbrite = require(\"../../eventbrite.app.js\");\n\nmodule.exports = {\n props: {\n eventbrite,\n db: \"$.service.db\",\n organization: { propDefinition: [eventbrite, \"organization\"] },\n },\n methods: {\n generateMeta() {\n throw new Error(\"generateMeta is not implemented\");\n },\n emitEvent(data) {\n const meta = this.generateMeta(data);\n this.$emit(data, meta);\n },\n async *resourceStream(resourceFn, resource, params = null) {\n let hasMoreItems;\n do {\n const { [resource]: items, pagination = {} } = await resourceFn(params);\n for (const item of items) {\n yield item;\n }\n\n hasMoreItems = !!pagination.has_more_items;\n params.continuation = pagination.continuation;\n } while (hasMoreItems);\n },\n },\n};\n\n<|start_filename|>components/mailgun/actions/suppress-email/suppress-email.js<|end_filename|>\nconst mailgun = require(\"../../mailgun.app.js\");\n\nmodule.exports = {\n key: \"mailgun-suppress-email\",\n name: \"Mailgun Suppress Email\",\n description: \"Add email to the Mailgun suppression list.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n mailgun,\n domain: {\n propDefinition: [\n mailgun,\n \"domain\",\n ],\n },\n email: {\n propDefinition: [\n mailgun,\n \"email\",\n ],\n },\n category: {\n type: \"string\",\n options: [\n \"bounces\",\n \"unsubscribes\",\n \"complaints\",\n ],\n },\n bounceErrorCode: {\n type: \"string\",\n label: \"Bounce Error Code\",\n default: \"550\",\n optional: true,\n },\n bounceErrorMessage: {\n type: \"string\",\n label: \"Bounce Error Message\",\n optional: true,\n },\n unsubscribeFrom: {\n type: \"string\",\n label: \"Tag to unsubscribe from\",\n description: \"Use * to unsubscribe an address from all domain’s correspondence\",\n default: \"*\",\n optional: true,\n },\n haltOnError: {\n propDefinition: [\n mailgun,\n \"haltOnError\",\n ],\n },\n },\n async run () {\n try {\n const suppression = {\n address: this.email,\n };\n\n switch (this.category) {\n case \"bounces\":\n suppression.code = this.bounceErrorCode;\n suppression.error = this.bounceErrorMessage;\n break;\n\n case \"unsubscribes\":\n suppression.tag = this.unsubscribeFrom;\n break;\n }\n\n return await this.mailgun.suppress(this.domain, this.category, suppression);\n } catch (err) {\n if (this.haltOnError) {\n throw err;\n }\n if (err.response) {\n return err.response.data;\n }\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/google_drive/actions/google-mime-types.js<|end_filename|>\nmodule.exports = [\n \"application/vnd.google-apps.audio\",\n \"application/vnd.google-apps.document\",\n \"application/vnd.google-apps.drive-sdk\",\n \"application/vnd.google-apps.drawing\",\n \"application/vnd.google-apps.file\",\n \"application/vnd.google-apps.folder\",\n \"application/vnd.google-apps.form\",\n \"application/vnd.google-apps.fusiontable\",\n \"application/vnd.google-apps.map\",\n \"application/vnd.google-apps.photo\",\n \"application/vnd.google-apps.presentation\",\n \"application/vnd.google-apps.script\",\n \"application/vnd.google-apps.shortcut\",\n \"application/vnd.google-apps.site\",\n \"application/vnd.google-apps.spreadsheet\",\n \"application/vnd.google-apps.unknown\",\n \"application/vnd.google-apps.video\",\n];\n\n\n<|start_filename|>components/twitch/actions/get-channel-teams/get-channel-teams.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Channel Teams\",\n key: \"twitch-get-channel-teams\",\n description: \"Gets a list of teams to which a specified channel belongs\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n broadcaster: {\n propDefinition: [\n common.props.twitch,\n \"broadcaster\",\n ],\n description: \"The broadcaster ID of the channel to get teams for\",\n },\n },\n async run() {\n const params = {\n broadcaster_id: this.broadcaster,\n };\n return (await this.twitch.getChannelTeams(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/dropbox/sources/new-folder/new-folder.js<|end_filename|>\nconst dropbox = require(\"../../dropbox.app.js\");\n\nmodule.exports = {\n key: \"dropbox-new-folder\",\n name: \"New Folder\",\n version: \"0.0.4\",\n description:\n \"Emits an event when a new folder is created. Make sure the number of files/folders in the watched folder does not exceed 4000.\",\n props: {\n dropbox,\n path: { propDefinition: [dropbox, \"path\"] },\n recursive: { propDefinition: [dropbox, \"recursive\"] },\n dropboxApphook: {\n type: \"$.interface.apphook\",\n appProp: \"dropbox\",\n static: [],\n },\n db: \"$.service.db\",\n },\n hooks: {\n async activate() {\n await this.dropbox.initState(this);\n },\n },\n async run(event) {\n const updates = await this.dropbox.getUpdates(this);\n for (update of updates) {\n if (update[\".tag\"] == \"folder\") {\n this.$emit(update);\n }\n }\n },\n};\n\n\n<|start_filename|>components/twitter/sources/user-tweets/user-tweets.js<|end_filename|>\nconst base = require(\"../common/tweets\");\n\nmodule.exports = {\n ...base,\n key: \"twitter-user-tweets\",\n name: \"User Tweets\",\n description: \"Emit new Tweets posted by a user\",\n version: \"0.0.5\",\n props: {\n ...base.props,\n screen_name: {\n propDefinition: [\n base.props.twitter,\n \"screen_name\",\n ],\n },\n includeRetweets: {\n propDefinition: [\n base.props.twitter,\n \"includeRetweets\",\n ],\n },\n includeReplies: {\n propDefinition: [\n base.props.twitter,\n \"includeReplies\",\n ],\n },\n },\n methods: {\n ...base.methods,\n shouldExcludeReplies() {\n return this.includeReplies === \"exclude\";\n },\n shouldIncludeRetweets() {\n return this.includeRetweets !== \"exclude\";\n },\n retrieveTweets() {\n return this.twitter.getUserTimeline({\n screen_name: this.screen_name,\n count: this.count,\n since_id: this.getSinceId(),\n exclude_replies: this.shouldExcludeReplies(),\n include_rts: this.shouldIncludeRetweets(),\n });\n },\n },\n};\n\n\n<|start_filename|>components/intercom/sources/new-event/new-event.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-new-event\",\n name: \"New Event\",\n description: \"Emits an event for each new Intercom event for a user.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n userIds: {\n type: \"string[]\",\n label: \"Users\",\n async options(opts) {\n const data = {\n query: {\n field: \"role\",\n operator: \"=\",\n value: \"user\",\n },\n };\n const results = await this.intercom.searchContacts(data);\n return results.map((user) => {\n return { label: user.name || user.id, value: user.id };\n });\n },\n },\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n for (const userId of this.userIds) {\n let since = this.db.get(userId) || null;\n const results = await this.intercom.getEvents(userId, since);\n for (const result of results.events) {\n this.$emit(result, {\n id: result.id,\n summary: result.event_name,\n ts: result.created_at,\n });\n }\n // store the latest 'since' url by the userId\n if (results.since) this.db.set(userId, results.since);\n }\n },\n};\n\n<|start_filename|>components/ongage/actions/find-subscriber/find-subscriber.js<|end_filename|>\nconst ongage = require(\"../../ongage.app.js\");\n\nmodule.exports = {\n key: \"ongage-find-subscriber\",\n name: \"Ongage Find Subscriber\",\n description: \"Find a list subscriber in Ongage.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ongage,\n email: {\n propDefinition: [\n ongage,\n \"email\",\n ],\n },\n haltOnError: {\n propDefinition: [\n ongage,\n \"haltOnError\",\n ],\n },\n },\n async run () {\n try {\n return await this.ongage.findSubscriber(\n this.email,\n );\n } catch (err) {\n if (this.haltOnError) {\n throw err;\n }\n if (err.response) {\n return err.response.data;\n }\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/docusign/sources/new-folder/new-folder.js<|end_filename|>\nconst docusign = require(\"../../docusign.app.js\");\n\nmodule.exports = {\n key: \"docusign-new-folder\",\n name: \"New Folder\",\n description: \"Emits an event when a new folder is created\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n docusign,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n account: {\n propDefinition: [\n docusign,\n \"account\",\n ],\n },\n include: {\n type: \"string[]\",\n label: \"Folder types\",\n description: \"Folder types to include in the response\",\n options: [\n \"envelope_folders\",\n \"template_folders\",\n \"shared_template_folders\",\n ],\n default: [\n \"envelope_folders\",\n \"template_folders\",\n \"shared_template_folders\",\n ],\n },\n },\n methods: {\n async processFolders(baseUri, params, folders, ts) {\n for (const folder of folders) {\n if (folder.hasSubFolders == \"true\") {\n for (const subfolder of folder.folders) {\n let done = false;\n do {\n const {\n folders: subfolders,\n nextUri,\n resultSetSize,\n } = await this.docusign.listFolderItems(baseUri, params, subfolder.folderId);\n await this.processFolders(baseUri, params, subfolders, ts);\n if (nextUri) params.start_postion += resultSetSize + 1;\n else done = true;\n } while (!done);\n }\n }\n const meta = this.generateMeta(folder, ts);\n this.$emit(folder, meta);\n }\n },\n generateMeta({\n folderId: id, name: summary,\n }, ts) {\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { timestamp: ts } = event;\n const baseUri = await this.docusign.getBaseUri(this.account);\n let done = false;\n const params = {\n start_position: 0,\n include: (this.include).join(),\n include_items: true,\n };\n do {\n const {\n folders = [],\n nextUri,\n resultSetSize,\n } = await this.docusign.listFolders(baseUri, params);\n if (nextUri) params.start_position += resultSetSize + 1;\n else done = true;\n\n await this.processFolders(baseUri, params, folders, ts);\n\n } while (!done);\n },\n};\n\n\n<|start_filename|>components/google_drive/sources/new-files-instant/new-files-instant.js<|end_filename|>\nconst common = require(\"../common-webhook.js\");\nconst {\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n} = require(\"../../constants\");\n\nmodule.exports = {\n ...common,\n key: \"google_drive-new-files-instant\",\n name: \"New Files (Instant)\",\n description:\n \"Emits a new event any time a new file is added in your linked Google Drive\",\n version: \"0.0.8\",\n type: \"source\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n folders: {\n type: \"string[]\",\n label: \"Folders\",\n description:\n \"(Optional) The folders you want to watch for changes. Leave blank to watch for any new file in the Drive.\",\n optional: true,\n default: [],\n options({ prevContext }) {\n const { nextPageToken } = prevContext;\n const baseOpts = {\n q: \"mimeType = 'application/vnd.google-apps.folder'\",\n };\n const opts = this.isMyDrive()\n ? baseOpts\n : {\n ...baseOpts,\n corpora: \"drive\",\n driveId: this.getDriveId(),\n includeItemsFromAllDrives: true,\n supportsAllDrives: true,\n };\n return this.googleDrive.listFilesOptions(nextPageToken, opts);\n },\n },\n },\n hooks: {\n ...common.hooks,\n async activate() {\n await common.hooks.activate.bind(this)();\n this._setLastFileCreatedTime(Date.now());\n },\n },\n methods: {\n ...common.methods,\n _getLastFileCreatedTime() {\n return this.db.get(\"lastFileCreatedTime\");\n },\n _setLastFileCreatedTime(lastFileCreatedTime) {\n this.db.set(\"lastFileCreatedTime\", lastFileCreatedTime);\n },\n shouldProcess(file) {\n const watchedFolders = new Set(this.folders);\n return (\n watchedFolders.size == 0 ||\n (file.parents && file.parents.some((p) => watchedFolders.has(p)))\n );\n },\n getUpdateTypes() {\n return [\n GOOGLE_DRIVE_NOTIFICATION_ADD,\n GOOGLE_DRIVE_NOTIFICATION_CHANGE,\n ];\n },\n async processChanges(changedFiles) {\n const lastFileCreatedTime = this._getLastFileCreatedTime();\n let maxCreatedTime = lastFileCreatedTime;\n\n for (const file of changedFiles) {\n const fileInfo = await this.googleDrive.getFile(file.id);\n const createdTime = Date.parse(fileInfo.createdTime);\n if (\n !this.shouldProcess(fileInfo) ||\n createdTime < lastFileCreatedTime\n ) {\n continue;\n }\n\n this.$emit(fileInfo, {\n summary: `New File ID: ${file.id}`,\n id: file.id,\n ts: createdTime,\n });\n\n maxCreatedTime = Math.max(createdTime, maxCreatedTime);\n this._setLastFileCreatedTime(maxCreatedTime);\n }\n },\n },\n};\n\n\n<|start_filename|>components/slack/actions/delete_reminder/delete-reminder.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-delete-reminder\",\n name: \"Delete Reminder\",\n description: \"Delete a reminder\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n reminder: {\n propDefinition: [\n slack,\n \"reminder\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().reminders.delete({\n reminder: this.reminder,\n });\n },\n};\n\n\n<|start_filename|>components/pipefy/sources/common-polling.js<|end_filename|>\nconst common = require(\"./common.js\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const cards = await this.pipefy.listCards(this.pipeId);\n for (const edge of cards.edges) {\n const { node } = edge;\n if (!this.isCardRelevant({ node, event })) continue;\n const meta = this.getMeta({ node, event });\n this.$emit(node, meta);\n }\n },\n};\n\n<|start_filename|>components/twitch/actions/block-user/block-user.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Block User\",\n key: \"twitch-block-user\",\n description: \"Blocks a user; that is, adds a specified target user to your blocks list\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n user: {\n propDefinition: [\n common.props.twitch,\n \"user\",\n ],\n description: \"User ID of the user to be blocked\",\n },\n sourceContext: {\n type: \"string\",\n label: \"Source Context\",\n description: \"Source context for blocking the user. Valid values: \\\"chat\\\", \\\"whisper\\\".\",\n optional: true,\n options: [\n \"chat\",\n \"whisper\",\n ],\n },\n reason: {\n type: \"string\",\n label: \"Reason\",\n description: \"Reason for blocking the user. Valid values: \\\"spam\\\", \\\"harassment\\\", or \\\"other\\\".\",\n optional: true,\n options: [\n \"spam\",\n \"harassment\",\n \"other\",\n ],\n },\n },\n async run() {\n const params = {\n target_user_id: this.user,\n source_context: this.sourceContext,\n reason: this.reason,\n };\n const {\n status,\n statusText,\n } = await this.twitch.blockUser(params);\n return status == 204\n ? \"User Blocked Successfully\"\n : `${status} ${statusText}`;\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-email-event/new-email-event.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-email-event\",\n name: \"New Email Event\",\n description: \"Emits an event for each new Hubspot email event.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(emailEvent) {\n const { id, recipient, type, created } = emailEvent;\n const ts = Date.parse(created);\n return {\n id,\n summary: `${recipient} - ${type}`,\n ts,\n };\n },\n },\n async run(event) {\n const startTimestamp = this._getAfter();\n const params = {\n limit: 100,\n startTimestamp,\n };\n\n await this.paginateUsingHasMore(\n params,\n this.hubspot.getEmailEvents.bind(this),\n \"events\"\n );\n },\n};\n\n<|start_filename|>components/mailgun/mailgun.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst formData = require(\"form-data\");\nconst Mailgun = require(\"mailgun.js\");\n\nmodule.exports = {\n type: \"app\",\n app: \"mailgun\",\n methods: {\n api (api) {\n const mailgun = new Mailgun(formData);\n const mg = mailgun.client({\n username: \"api\",\n key: this.$auth.api_key,\n public_key: this.$auth.api_key,\n });\n return mg[api];\n },\n async suppress (domain, type, suppression) {\n const res = await axios({\n url: `https://api.mailgun.net/v3/${encodeURIComponent(domain)}/${encodeURIComponent(type)}`,\n method: \"POST\",\n auth: {\n username: \"api\",\n password: ,\n },\n headers: {\n \"content-type\": \"application/json\",\n },\n // eslint-disable-next-line multiline-ternary, array-bracket-newline\n data: JSON.stringify(Array.isArray(suppression) ? suppression : [suppression]),\n });\n return res.data;\n },\n },\n propDefinitions: {\n domain: {\n type: \"string\",\n label: \"Domain Name\",\n async options ({ page }) {\n const query = {\n limit: 50,\n skip: 50 * page,\n };\n const domains = await this.api(\"domains\").list(query);\n return domains.map(domain => domain.name);\n },\n },\n email: {\n type: \"string\",\n label: \"Email Address\",\n },\n haltOnError: {\n type: \"boolean\",\n label: \"Halt on error?\",\n default: true,\n },\n },\n};\n\n\n<|start_filename|>components/pipefy/sources/card-late/card-late.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n name: \"Card Late\",\n key: \"pipefy-card-late\",\n description: \"Emits an event each time a card becomes late in a Pipe.\",\n version: \"0.0.1\",\n methods: {\n isCardRelevant({ node }) {\n return (\n node.late && \n !node.done\n );\n },\n getMeta({ node, event }) {\n const {\n id: nodeId,\n title: summary,\n current_phase: { id: currentPhaseId },\n } = node;\n const id = `${nodeId}${currentPhaseId}`;\n const { timestamp: ts } = event;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n<|start_filename|>components/twist/twist.app.js<|end_filename|>\nconst events = require(\"./event-types.js\");\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"twist\",\n propDefinitions: {\n workspace: {\n type: \"string\",\n label: \"Workspace\",\n description: \"The workspace to watch for new events.\",\n optional: true,\n async options() {\n const workspaces = await this.getWorkspaces();\n return workspaces.map((workspace) => {\n return {\n label: workspace.name,\n value: workspace.id,\n };\n });\n },\n },\n channel: {\n type: \"string\",\n label: \"Channel\",\n description: \"The channel to watch for new events.\",\n optional: true,\n async options(opts) {\n if (!opts.workspace)\n return [{ label: \"No Channels Found\", value: \"none\" }];\n const channels = await this.getChannels(opts.workspace);\n return channels.map((channel) => {\n return {\n label: channel.name,\n value: channel.id,\n };\n });\n },\n },\n thread: {\n type: \"string\",\n label: \"Thread\",\n description: \"The thread to watch for new events.\",\n optional: true,\n async options(opts) {\n if (!opts.channel)\n return [{ label: \"No Threads Found\", value: \"none\" }];\n const threads = await this.getThreads(opts.channel);\n return threads.map((thread) => {\n return {\n label: thread.title,\n value: thread.id,\n };\n });\n },\n },\n conversation: {\n type: \"string\",\n label: \"Conversation\",\n description: \"The conversation to watch for new messages.\",\n optional: true,\n async options(opts) {\n if (!opts.workspace)\n return [{ label: \"No Conversations Found\", value: \"none\" }];\n const conversations = await this.getConversations(opts.workspace);\n return conversations.map((conversation) => {\n return {\n label: conversation.title || `Conversation ID ${conversation.id}`,\n value: conversation.id,\n };\n });\n },\n },\n eventType: {\n type: \"string\",\n label: \"Event Type\",\n description: \"Watch for the selected event type.\",\n options: events,\n },\n },\n methods: {\n async _getBaseUrl() {\n return \"https://api.twist.com/api/v3\";\n },\n async _getHeaders() {\n return {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n };\n },\n async _makePostRequest(endpoint, data = null) {\n config = {\n method: \"POST\",\n url: `${await this._getBaseUrl()}/${endpoint}`,\n headers: await this._getHeaders(),\n data,\n };\n return (await axios(config)).data;\n },\n async _makeGetRequest(endpoint, params = null) {\n config = {\n method: \"GET\",\n url: `${await this._getBaseUrl()}/${endpoint}`,\n headers: await this._getHeaders(),\n params,\n };\n return (await axios(config)).data;\n },\n async createHook(data) {\n return await this._makePostRequest(\"hooks/subscribe\", data);\n },\n async deleteHook(target_url) {\n return await this._makePostRequest(\"hooks/unsubscribe\", { target_url });\n },\n async getWorkspaces() {\n return await this._makeGetRequest(\"workspaces/get\");\n },\n async getChannels(workspace_id) {\n return await this._makeGetRequest(\"channels/get\", { workspace_id });\n },\n async getThreads(channel_id) {\n return await this._makeGetRequest(\"threads/get\", { channel_id });\n },\n async getConversations(workspace_id) {\n return await this._makeGetRequest(\"conversations/get\", { workspace_id });\n },\n },\n};\n\n<|start_filename|>components/ongage/actions/update-subscriber/update-subscriber.js<|end_filename|>\nconst ongage = require(\"../../ongage.app.js\");\n\nmodule.exports = {\n key: \"ongage-update-subscriber\",\n name: \"Ongage Update Subscriber\",\n description: \"Update a list subscriber in Ongage.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ongage,\n listId: {\n propDefinition: [\n ongage,\n \"listId\",\n ],\n optional: true,\n },\n email: {\n propDefinition: [\n ongage,\n \"email\",\n ],\n },\n fields: {\n propDefinition: [\n ongage,\n \"fields\",\n ],\n optional: true,\n },\n haltOnError: {\n propDefinition: [\n ongage,\n \"haltOnError\",\n ],\n },\n },\n async run () {\n try {\n return await this.ongage.updateSubscriber(\n this.listId,\n this.email,\n this.fields,\n );\n } catch (err) {\n if (this.haltOnError) {\n throw err;\n }\n if (err.response) {\n return err.response.data;\n }\n return err;\n }\n },\n};\n\n\n<|start_filename|>components/slack/actions/set-channel-topic/set-channel-topic.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-set-channel-topic\",\n name: \"Set Channel Topic\",\n description: \"Set the topic on a selected channel\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n topic: {\n propDefinition: [\n slack,\n \"topic\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().conversations.setTopic({\n channel: this.conversation,\n topic: this.topic,\n });\n },\n};\n\n\n<|start_filename|>components/slack/actions/create-reminder/create-reminder.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-create-reminder\",\n name: \"Create Reminder\",\n description: \"Create a reminder\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n text: {\n propDefinition: [\n slack,\n \"text\",\n ],\n },\n timestamp: {\n propDefinition: [\n slack,\n \"timestamp\",\n ],\n description: \"When this reminder should happen: the Unix timestamp (up to five years from now), the number of seconds until the reminder (if within 24 hours), or a natural language description (Ex. in 15 minutes, or every Thursday)\",\n },\n team_id: {\n propDefinition: [\n slack,\n \"team_id\",\n ],\n optional: true,\n },\n user: {\n propDefinition: [\n slack,\n \"user\",\n ],\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().reminders.add({\n text: this.text,\n team_id: this.team_id,\n time: this.timestamp,\n user: this.user,\n });\n },\n};\n\n\n<|start_filename|>components/twilio/sources/new-transcription/new-transcription.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n key: \"twilio-new-transcription\",\n name: \"New Transcription\",\n description: \"Emits an event when a new call transcription is created\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n async listResults(...args) {\n return await this.twilio.listTranscriptions(...args);\n },\n generateMeta(transcription) {\n const { sid: id, dateCreated } = transcription;\n return {\n id,\n summary: `New transcription ${id}`,\n ts: Date.parse(dateCreated),\n };\n },\n },\n};\n\n<|start_filename|>components/slack/actions/get-file/get-file.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-get-file\",\n name: \"Get File\",\n description: \"Return information about a file\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n file: {\n propDefinition: [\n slack,\n \"file\",\n ],\n },\n count: {\n propDefinition: [\n slack,\n \"count\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().files.info({\n file: this.file,\n count: this.count,\n });\n },\n};\n\n\n<|start_filename|>components/airtable/actions/create-multiple-records/create-multiple-records.js<|end_filename|>\nconst chunk = require(\"lodash.chunk\");\nconst airtable = require(\"../../airtable.app.js\");\nconst common = require(\"../common.js\");\n\nconst BATCH_SIZE = 10; // The Airtable API allows us to update up to 10 rows per request.\n\nmodule.exports = {\n key: \"airtable-create-multiple-records\",\n name: \"Create Multiple Records\",\n description: \"Create one or more records in a table by passing an array of objects containing field names and values as key/value pairs.\",\n version: \"0.1.1\",\n type: \"action\",\n props: {\n ...common.props,\n records: {\n propDefinition: [\n airtable,\n \"records\",\n ],\n },\n typecast: {\n propDefinition: [\n airtable,\n \"typecast\",\n ],\n },\n },\n async run() {\n const table = this.airtable.base(this.baseId)(this.tableId);\n\n let data = this.records;\n if (!Array.isArray(data)) {\n data = JSON.parse(data);\n }\n data = data.map((fields) => ({\n fields,\n }));\n if (!data.length) {\n throw new Error(\"No Airtable record data passed to step. Please pass at least one record\");\n }\n\n const params = {\n typecast: this.typecast,\n };\n\n const responses = [];\n for (const c of chunk(data, BATCH_SIZE)) {\n try {\n responses.push(...(await table.create(c, params)));\n } catch (err) {\n this.airtable.throwFormattedError(err);\n }\n }\n\n return responses;\n },\n};\n\n\n<|start_filename|>components/cliniko/actions/get-patient/get-patient.js<|end_filename|>\nconst cliniko = require(\"../../cliniko.app.js\");\n\nmodule.exports = {\n name: \"Get Patient\",\n key: \"cliniko-get-patient\",\n description: \"Get the details of a patient by patient ID.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n cliniko,\n patientId: {\n propDefinition: [\n cliniko,\n \"patientId\",\n ],\n },\n },\n async run() {\n return await this.cliniko.getPatient(this.patientId);\n },\n};\n\n\n<|start_filename|>components/slack/actions/list-files/list-files.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-list-files\",\n name: \"List Files\",\n description: \"Return a list of files within a team\",\n version: \"0.0.29\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n count: {\n propDefinition: [\n slack,\n \"count\",\n ],\n optional: true,\n },\n team_id: {\n propDefinition: [\n slack,\n \"team_id\",\n ],\n optional: true,\n },\n user: {\n propDefinition: [\n slack,\n \"user\",\n ],\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().files.list({\n channel: this.conversation,\n count: this.count,\n user: this.user,\n team_id: this.team_id,\n });\n },\n};\n\n\n<|start_filename|>components/procore/procore.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst eventTypes = [\n { label: \"Create\", value: \"create\" },\n { label: \"Update\", value: \"update\" },\n { label: \"Delete\", value: \"delete\" },\n];\nconst resourceNames = [\n \"Budget View Snapshots\",\n \"Change Events\",\n \"Change Order Packages\",\n \"Projects\",\n \"Prime Contracts\",\n \"Purchase Order Contracts\",\n \"RFIs\",\n \"Submittals\",\n];\n\nmodule.exports = {\n type: \"app\",\n app: \"procore\",\n propDefinitions: {\n company: {\n type: \"integer\",\n label: \"Company\",\n description: \"Select the company to watch for changes in.\",\n async options({ page, prevContext }) {\n const limit = 100;\n const { offset = 0 } = prevContext;\n const results = await this.listCompanies(limit, offset);\n const options = results.map((c) => ({\n label: c.name,\n value: c.id,\n }));\n return {\n options,\n context: { limit, offset: offset + limit },\n };\n },\n },\n project: {\n type: \"integer\",\n label: \"Project\",\n description:\n \"Select the project to watch for changes in. Leave blank for company-level resources (eg. Projects).\",\n optional: true,\n async options({ page, prevContext, company }) {\n const limit = 100;\n const { offset = 0 } = prevContext;\n const results = await this.listProjects(company, limit, offset);\n const options = results.map((p) => ({\n label: p.name,\n value: p.id,\n }));\n return {\n options,\n context: { limit, offset: offset + limit, company },\n };\n },\n },\n resourceName: {\n type: \"string\",\n label: \"Resource\",\n description: \"The type of resource on which to trigger events.\",\n options: resourceNames,\n },\n eventTypes: {\n type: \"string[]\",\n label: \"Event Type\",\n description: \"Only events of the selected event type will be emitted.\",\n options: eventTypes,\n },\n },\n methods: {\n getEventTypes() {\n return eventTypes.map(({ value }) => value);\n },\n _getBaseUrl() {\n return \"https://api.procore.com/rest/v1.0\";\n },\n _getHeaders(companyId = null) {\n let headers = {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n };\n if (companyId) headers[\"Procore-Company-Id\"] = companyId;\n return headers;\n },\n async _makeRequest(\n method,\n endpoint,\n companyId = null,\n params = null,\n data = null\n ) {\n const config = {\n method,\n url: `${this._getBaseUrl()}/${endpoint}`,\n headers: this._getHeaders(companyId),\n };\n if (params) config.params = params;\n else if (data) config.data = data;\n return (await axios(config)).data;\n },\n async createHook(destinationUrl, companyId, projectId) {\n const data = {\n hook: {\n api_version: \"v1.0\",\n destination_url: destinationUrl,\n },\n };\n if (projectId) data.project_id = projectId;\n else if (companyId) data.company_id = companyId;\n return await this._makeRequest(\n \"POST\",\n \"webhooks/hooks\",\n companyId,\n null,\n data\n );\n },\n async createHookTrigger(\n hookId,\n companyId,\n projectId,\n resourceName,\n eventType\n ) {\n const data = {\n api_version: \"v1.0\",\n trigger: {\n resource_name: resourceName,\n event_type: eventType,\n },\n };\n if (projectId) data.project_id = projectId;\n else if (companyId) data.company_id = companyId;\n return await this._makeRequest(\n \"POST\",\n `webhooks/hooks/${hookId}/triggers`,\n companyId,\n null,\n data\n );\n },\n async deleteHook(id, companyId, projectId) {\n const params = projectId\n ? { project_id: projectId }\n : { company_id: companyId };\n return await this._makeRequest(\n \"DELETE\",\n `webhooks/hooks/${id}`,\n companyId,\n params\n );\n },\n async deleteHookTrigger(hookId, triggerId, companyId, projectId) {\n const params = projectId\n ? { project_id: projectId }\n : { company_id: companyId };\n return await this._makeRequest(\n \"DELETE\",\n `webhooks/hooks/${hookId}/triggers/${triggerId}`,\n companyId,\n params\n );\n },\n async listCompanies(perPage, page) {\n return await this._makeRequest(\"GET\", \"companies\", null, {\n per_page: perPage,\n page,\n });\n },\n async listProjects(companyId, perPage, page) {\n return await this._makeRequest(\"GET\", \"projects\", companyId, {\n company_id: companyId,\n per_page: perPage,\n page,\n });\n },\n async getBudgetViewSnapshot(\n companyId,\n projectId,\n budgetViewSnapshotId,\n perPage,\n page\n ) {\n return await this._makeRequest(\n \"GET\",\n `budget_view_snapshots/${budgetViewSnapshotId}/detail_rows`,\n companyId,\n { project_id: projectId, per_page: perPage, page }\n );\n },\n async getChangeEvent(companyId, projectId, changeEventId) {\n return await this._makeRequest(\n \"GET\",\n `change_events/${changeEventId}`,\n companyId,\n { project_id: projectId }\n );\n },\n async getChangeOrderPackage(companyId, projectId, changeOrderPackageId) {\n return await this._makeRequest(\n \"GET\",\n `change_order_packages/${changeOrderPackageId}`,\n companyId,\n { project_id: projectId }\n );\n },\n async getPrimeContract(companyId, projectId, primeContractId) {\n return await this._makeRequest(\n \"GET\",\n `prime_contract/${primeContractId}`,\n companyId,\n { project_id: projectId }\n );\n },\n async getPurchaseOrder(companyId, projectId, poId) {\n return await this._makeRequest(\n \"GET\",\n `purchase_order_contracts/${poId}`,\n companyId,\n { project_id: projectId }\n );\n },\n async getRFI(companyId, projectId, rfiId) {\n return await this._makeRequest(\n \"GET\",\n `projects/${projectId}/rfis/${rfiId}`,\n companyId\n );\n },\n async getSubmittal(companyId, projectId, submittalId) {\n return await this._makeRequest(\n \"GET\",\n `projects/${projectId}/submittals/${submittalId}`,\n companyId\n );\n },\n },\n};\n\n<|start_filename|>components/threads/threads.app.js<|end_filename|>\n// See API docs here:\n// https://gist.github.com/gauravmk/c9263120b9309c24d6f14df6668e5326\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"threads\",\n propDefinitions: {\n forumID: {\n type: \"integer\",\n label: \"Forum ID\",\n description:\n \"The ID of the forum you want to post to. Navigate to your forum on the Threads website. The URL will be threads.com/${forum_id}\",\n },\n title: {\n type: \"string\",\n label: \"Thread Title\",\n description:\n \"The title of your thread (max 60 characters)\",\n },\n body: {\n type: \"string\",\n label: \"Thread Body\",\n description:\n \"The body of your thread. Supports Markdown\",\n },\n threadID: {\n type: \"string\",\n label: \"Thread ID\",\n description:\n \"Navigate to your thread on the Threads website. The URL will be threads.com/${thread_id}\",\n },\n },\n methods: {\n _apiUrl() {\n return \"https://threads.com/api/public\";\n },\n _apiKey() {\n return this.$auth.api_key;\n },\n async _makeRequest(opts) {\n if (!opts.headers) opts.headers = {};\n opts.headers[\"Content-Type\"] = \"application/json\";\n opts.headers[\"Authorization\"] = `Bearer ${this._apiKey()}`;\n opts.headers[\"user-agent\"] = \"@PipedreamHQ/pipedream v0.1\";\n const { path } = opts;\n delete opts.path;\n opts.url = `${this._apiUrl()}${path[0] === \"/\"\n ? \"\"\n : \"/\"}${path}`;\n const {\n status,\n data,\n } = await axios({\n ...opts,\n validateStatus: () => true,\n });\n if (status >= 400) {\n throw new Error(JSON.stringify(data, null, 2));\n }\n return data;\n },\n async postThread({\n forumID, title, body,\n }) {\n return await this._makeRequest({\n path: \"/postThread\",\n method: \"POST\",\n data: {\n forumID,\n title,\n body,\n },\n });\n },\n async deleteThread({ threadID }) {\n return await this._makeRequest({\n path: \"/deleteThread\",\n method: \"POST\",\n data: {\n threadID,\n },\n });\n },\n },\n};\n\n\n<|start_filename|>components/twitter/sources/common/followers.js<|end_filename|>\nconst twitter = require(\"../../twitter.app\");\n\nmodule.exports = {\n props: {\n db: \"$.service.db\",\n twitter,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n hooks: {\n async activate() {\n await this._provisionFollowersCache();\n },\n },\n deactivate() {\n this._clearFollowersCache();\n },\n methods: {\n /**\n * This method returns the size of the internal cache used by the event\n * source to keep track of the latest Twitter followers of the corresponding\n * account.\n *\n * The size represents the maximum amount of entries/ID's that will be\n * cached at any given time (or 0 for unlimited). Keep in mind that the\n * Pipedream platform itself imposes size limits as well in terms of DB\n * usage.\n *\n * @returns The maximum amount of Twitter followers entries to be cached at\n * any given moment (or 0 for unlimited).\n */\n getFollowersCacheSize() {\n return 0;\n },\n getScreenName() {\n // When screen name is not explicitly provided, the Twitter API defaults\n // it to the user making the API request\n return undefined;\n },\n /**\n * This function provides the list of relevant, follower-related, user ID's\n * that are used by the event source to emit events. How each event source\n * that implements it depends on the purpose of the event source itself. For\n * example, an event source that emits an event for every new follower will\n * implement this function in such a way that its result is a list of user\n * ID's for each new follower detected.\n *\n * @returns the list of relevant user ID's for this event source to process\n */\n getRelevantIds() {\n return [];\n },\n generateMeta(data) {\n const {\n timestamp,\n user,\n } = data;\n const {\n id_str: id,\n screen_name: summary,\n } = user;\n // Event timestamp is expressed in seconds, whereas Javascript timestamps\n // are expressed in milliseconds\n const ts = timestamp * 1000;\n return {\n id,\n summary,\n ts,\n };\n },\n _clearFollowersCache() {\n this.setFollowersCache([]);\n },\n async _provisionFollowersCache() {\n const screenName = this.getScreenName();\n const followerIdsGen = this.twitter.scanFollowerIds(screenName);\n const maxFollowerListSize = Math.max(this.getFollowersCacheSize(), 0);\n const result = [];\n for await (const id of followerIdsGen) {\n if (maxFollowerListSize !== 0 && maxFollowerListSize === result.length) {\n break;\n }\n\n result.push(id);\n }\n\n this.setFollowersCache(result);\n return result;\n },\n getFollowersCache() {\n return this.db.get(\"followers\");\n },\n setFollowersCache(followers) {\n const followersCacheSize = Math.max(this.getFollowersCacheSize(), 0);\n const trimmedFollowers = followersCacheSize !== 0\n ? followers.slice(0, followersCacheSize)\n : followers;\n this.db.set(\"followers\", trimmedFollowers);\n console.log(`\n Updated followers cache: ${trimmedFollowers.length} records\n `);\n },\n /**\n * This generator method scans the list of Twitter followers until it finds\n * the ID of a follower that was already processed.\n *\n * @param {string[]} processedFollowerIds a list of the ID's of the most\n * recent Twitter followers processed by the event source\n * @yields the ID of a new Twitter follower\n */\n async *scanNewFollowers(processedFollowerIds = []) {\n const processeedFollowerIdsSet = new Set(processedFollowerIds);\n const screenName = this.getScreenName();\n const followerIdsGen = this.twitter.scanFollowerIds(screenName);\n for await (const id of followerIdsGen) {\n if (processeedFollowerIdsSet.has(id)) {\n break;\n }\n yield id;\n }\n },\n async getUnfollowers() {\n const prevFollowers = this.getFollowersCache();\n const currFollowers = await this._provisionFollowersCache();\n const currFollowersSet = new Set(currFollowers);\n return prevFollowers.filter(pf => !currFollowersSet.has(pf));\n },\n },\n async run(event) {\n const { timestamp } = event;\n const relevantIds = await this.getRelevantIds();\n if (relevantIds.length <= 0) {\n console.log(`\n No changes in followers data for this event source to emit a new event\n `);\n return;\n }\n\n const users = await this.twitter.lookupUsers(relevantIds);\n users.forEach(user => {\n const data = {\n timestamp,\n user,\n };\n user.profile_url = `https://twitter.com/${user.screen_name}/`\n const meta = this.generateMeta(data);\n this.$emit(user, meta);\n });\n },\n};\n\n\n<|start_filename|>components/twitch/actions/delete-video/delete-video.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Delete Video\",\n key: \"twitch-delete-video\",\n description: \"Deletes a specified video\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n id: {\n type: \"string\",\n label: \"Video ID\",\n description: \"ID of the video to be deleted\",\n optional: true,\n },\n },\n async run() {\n const params = {\n id: this.id,\n };\n return (await this.twitch.deleteVideo(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/slack/actions/update-profile/update-profile.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-update-profile\",\n name: \"Update Profile\",\n description: \"Update basic profile field such as name or title\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n name: {\n propDefinition: [\n slack,\n \"name\",\n ],\n },\n value: {\n propDefinition: [\n slack,\n \"value\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().users.profile.set({\n name: this.name,\n value: this.value,\n });\n },\n};\n\n\n<|start_filename|>components/calendly/sources/new-event/new-event.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\nconst get = require(\"lodash/get\");\n\nmodule.exports = {\n ...common,\n key: \"calendly-new-event\",\n name: \"New Event\",\n description: \"Emits an event for each new event created\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n async getResults() {\n return await this.calendly.getEvents();\n },\n isRelevant(event, lastEvent) {\n const createdAt = this.getCreatedAt(event);\n return createdAt > lastEvent;\n },\n generateMeta(event) {\n const { id } = event;\n const createdAt = this.getCreatedAt(event);\n const startTime = new Date(get(event, \"attributes.start_time\"));\n return {\n id,\n summary: `New Event at ${startTime.toLocaleString()}`,\n ts: Date.parse(createdAt),\n };\n },\n getCreatedAt(event) {\n return Date.parse(get(event, \"attributes.created_at\"));\n },\n },\n};\n\n<|start_filename|>components/activecampaign/sources/campaign-opened/campaign-opened.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-campaign.js\");\n\nmodule.exports = {\n ...common,\n name: \"Campaign Opened (Instant)\",\n key: \"activecampaign-campaign-opened\",\n description:\n \"Emits an event when a contact opens a campaign (will trigger once per contact per campaign).\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"open\"];\n },\n },\n};\n\n<|start_filename|>components/activecampaign/activecampaign.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst { humanize } = require(\"inflection\");\n\nmodule.exports = {\n type: \"app\",\n app: \"activecampaign\",\n propDefinitions: {\n eventType: {\n type: \"string\",\n label: \"Event Type\",\n description:\n \"Emit events for the selected event type. See the official docs for more information on event types. https://developers.activecampaign.com/page/webhooks\",\n async options({ page }) {\n if (page !== 0) {\n return [];\n }\n const results = await this.listWebhookEvents();\n return results.webhookEvents.map((e) => ({\n label: humanize(e),\n value: e,\n }));\n },\n },\n sources: {\n type: \"string[]\",\n label: \"Sources\",\n description:\n \"The sources causing an event to occur. Leave blank to include all sources.\",\n optional: true,\n default: [],\n options() {\n return this.getAllSources();\n },\n },\n automations: {\n type: \"string[]\",\n label: \"Automations\",\n description:\n \"Emit events for the selected webhooks only. Leave blank to watch all available webhooks.\",\n optional: true,\n default: [],\n async options({ prevContext }) {\n const { results, context } = await this._getNextOptions(\n this.listAutomations.bind(this),\n prevContext\n );\n const options = results.automations.map((a) => ({\n label: a.name,\n value: a.id,\n }));\n return {\n options,\n context,\n };\n },\n },\n campaigns: {\n type: \"string[]\",\n label: \"Campaigns\",\n description:\n \"Watch the selected campaigns for updates. Leave blank to watch all available campaigns.\",\n optional: true,\n default: [],\n async options({ prevContext }) {\n const { results, context } = await this._getNextOptions(\n this.listCampaigns.bind(this),\n prevContext\n );\n const options = results.campaigns.map((c) => ({\n label: c.name,\n value: c.id,\n }));\n return {\n options,\n context,\n };\n },\n },\n contacts: {\n type: \"string[]\",\n label: \"Contacts\",\n description:\n \"Watch the selected contacts for updates. Leave blank to watch all available contacts.\",\n optional: true,\n default: [],\n async options({ prevContext }) {\n const { results, context } = await this._getNextOptions(\n this.listContacts.bind(this),\n prevContext\n );\n const options = results.contacts.map((c) => ({\n label: c.email,\n value: c.id,\n }));\n return {\n options,\n context,\n };\n },\n },\n deals: {\n type: \"string[]\",\n label: \"Deals\",\n description:\n \"Watch the selected deals for updates. Leave blank to watch all available deals.\",\n optional: true,\n default: [],\n async options({ prevContext }) {\n const { results, context } = await this._getNextOptions(\n this.listDeals.bind(this),\n prevContext\n );\n const options = results.deals.map((d) => ({\n label: d.title,\n value: d.id,\n }));\n return {\n options,\n context,\n };\n },\n },\n lists: {\n type: \"string[]\",\n label: \"Lists\",\n description:\n \"Watch the selected lists for updates. Leave blank to watch all available lists.\",\n optional: true,\n default: [],\n async options({ prevContext }) {\n const { results, context } = await this._getNextOptions(\n this.listLists.bind(this),\n prevContext\n );\n const options = results.lists.map((d) => ({\n label: d.name,\n value: d.id,\n }));\n return {\n options,\n context,\n };\n },\n },\n },\n methods: {\n _getHeaders() {\n return { \"Api-Token\": this.$auth.api_key };\n },\n async createHook(events, url, sources, listid = null) {\n const componentId = process.env.PD_COMPONENT;\n const webhookName = `Pipedream Hook (${componentId})`;\n const config = {\n method: \"POST\",\n url: `${this.$auth.base_url}/api/3/webhooks`,\n headers: this._getHeaders(),\n data: {\n webhook: {\n name: webhookName,\n url,\n events,\n sources,\n listid,\n },\n },\n };\n return (await axios(config)).data;\n },\n async deleteHook(hookId) {\n const config = {\n method: \"DELETE\",\n url: `${this.$auth.base_url}/api/3/webhooks/${hookId}`,\n headers: this._getHeaders(),\n };\n await axios(config);\n },\n async _makeGetRequest(\n endpoint,\n limit = null,\n offset = null,\n params = {},\n url = null\n ) {\n const config = {\n method: \"GET\",\n url: url || `${this.$auth.base_url}/api/3/${endpoint}`,\n headers: this._getHeaders(),\n params,\n };\n if (limit) config.params.limit = limit;\n if (offset) config.params.offset = offset;\n return await axios(config);\n },\n async _getNextOptions(optionsFn, prevContext) {\n const limit = 100;\n const { offset = 0 } = prevContext;\n const results = await optionsFn(limit, offset);\n const context = {\n offset: offset + limit,\n };\n return {\n results,\n context,\n };\n },\n getAllSources() {\n return [\"public\", \"admin\", \"api\", \"system\"];\n },\n async getList(id) {\n return (await this._makeGetRequest(`lists/${id}`)).data;\n },\n async listAutomations(limit, offset) {\n return (await this._makeGetRequest(\"automations\", limit, offset)).data;\n },\n async listCampaigns(limit, offset) {\n return (await this._makeGetRequest(\"campaigns\", limit, offset)).data;\n },\n async listContacts(limit, offset) {\n return (await this._makeGetRequest(\"contacts\", limit, offset)).data;\n },\n async listDeals(limit, offset) {\n return (await this._makeGetRequest(\"deals\", limit, offset)).data;\n },\n async listLists(limit, offset) {\n return (await this._makeGetRequest(\"lists\", limit, offset)).data;\n },\n async listWebhookEvents() {\n return (await this._makeGetRequest(\"webhook/events\")).data;\n },\n },\n};\n\n<|start_filename|>components/ringcentral/sources/new-inbound-message/new-inbound-message.js<|end_filename|>\nconst common = require(\"../common/http-based\");\nconst messageTypes = require(\"../common/message-types\");\n\nmodule.exports = {\n ...common,\n key: \"ringcentral-new-inbound-message-event\",\n name: \"New Inbound Message Event (Instant)\",\n description: \"Emits an event for each status change of inbound messages of a specific type\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n extensionId: { propDefinition: [common.props.ringcentral, \"extensionId\"] },\n messageType: {\n type: \"string\",\n label: \"Message Type\",\n description: \"The type of message to monitor for status changes\",\n options({ page = 0}) {\n return page === 0 ? messageTypes : [];\n },\n },\n },\n methods: {\n ...common.methods,\n getSupportedNotificationTypes() {\n return new Set([\n \"message-event-inbound\",\n ]);\n },\n generateMeta(data) {\n const {\n timestamp,\n uuid: id,\n } = data;\n const summary = \"New inbound message event\";\n const ts = Date.parse(timestamp);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/todoist/sources/common.js<|end_filename|>\nconst todoist = require(\"../todoist.app.js\");\n\nmodule.exports = {\n props: {\n todoist,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 5,\n },\n },\n db: \"$.service.db\",\n },\n methods: {\n generateMeta(element) {\n const {\n id: elementId,\n summary,\n date_completed: dateCompleted,\n } = element;\n const ts = new Date(dateCompleted).getTime();\n const id = `${elementId}-${ts}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n<|start_filename|>components/yotpo/yotpo.app.js<|end_filename|>\nconst axios = require(\"axios\")\nconst _get = require(\"lodash.get\")\n\nmodule.exports = {\n type: \"app\",\n app: \"yotpo\",\n methods: {\n api() {\n return {\n core: axios.create({\n baseURL: `https://api.yotpo.com`,\n headers: {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n Accept: \"application/json\",\n },\n }),\n dev: axios.create({\n baseURL: `https://developers.yotpo.com/v2/${this.$auth.app_key}`,\n params: {\n access_token: this.$auth.oauth_access_token,\n },\n }),\n }\n },\n async createWebhook(event_name = \"review_create\", url) {\n const api = this.api().dev\n const webhook = _get(await api.get(\"/webhooks\"), \"data.webhooks.webhooks\", []).find(w => w.webhook_event_name == event_name)\n if(webhook) {\n if (webhook.url != url) {\n console.error(\"Cannot setup Yotpo webhook. An existing webhook of this type already exists\", webhook)\n } else {\n console.log(\"Existing webhook found:\", webhook)\n } \n } else {\n const response = await api.post(\"/webhooks\", { event_name, url })\n console.log(\"Webhook created:\", { event_name, url }, _get(response, \"data\", \"No response when creating webhook\"))\n }\n },\n async deleteWebhook(event_name = \"review_create\", url) {\n const api = this.api().dev\n const webhook = _get(await api.get(\"/webhooks\"), \"data.webhooks.webhooks\", []).find(w => w.webhook_event_name == event_name)\n if (webhook && webhook.id) {\n if (webhook.url == url) {\n const response = await api.delete(`/webhooks/${webhook.id}`)\n console.log(\"Webhook deleted\", webhook, _get(response, \"data\", \"No response when deleting webhook\"))\n } else {\n console.error(\"Cannot delete webhook - existing webhook does not match this endpoint:\", {event_name, url}, webhook)\n }\n } else {\n console.error(\"Cannot delete webhook - not found:\", {event_name, url})\n }\n },\n },\n}\n\n\n<|start_filename|>components/intercom/sources/new-unsubscription/new-unsubscription.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-new-unsubscription\",\n name: \"New Unsubscriptions\",\n description:\n \"Emits an event each time a user unsubscribes from receiving emails.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const data = {\n query: {\n operator: \"AND\",\n value: [\n {\n field: \"unsubscribed_from_emails\",\n operator: \"=\",\n value: true,\n },\n {\n field: \"role\",\n operator: \"=\",\n value: \"user\",\n },\n ],\n },\n };\n\n const results = await this.intercom.searchContacts(data);\n for (const user of results) {\n this.$emit(user, {\n id: user.id,\n summary: user.name,\n ts: Date.now(),\n });\n }\n },\n};\n\n<|start_filename|>components/bandwidth/package.json<|end_filename|>\n{\n \"name\": \"@pipedream/bandwidth\",\n \"version\": \"1.0.0\",\n \"description\": \"Pipedream Bandwidth Components\",\n \"main\": \"index.js\",\n \"keywords\": [\n \"pipedream\",\n \"bandwidth\"\n ],\n \"author\": \"Bandwidth\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@bandwidth/messaging\": \"^4.0.0\"\n }\n}\n\n\n<|start_filename|>components/microsoft_onedrive/sources/common/base.js<|end_filename|>\nconst microsoft_onedrive = require(\"../../microsoft_onedrive.app\");\nconst {\n MAX_INITIAL_EVENT_COUNT,\n WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS,\n} = require(\"./constants\");\n\nfunction toSingleLineString(multiLineString) {\n return multiLineString\n .trim()\n .replace(/\\n/g, \" \")\n .replace(/\\s{2,}/g, \"\");\n}\n\nmodule.exports = {\n props: {\n microsoft_onedrive,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n timer: {\n label: \"Webhook subscription renewal schedule\",\n description: toSingleLineString(`\n The OneDrive API requires occasional renewal of webhook notification subscriptions.\n **This runs in the background, so you should not need to modify this schedule**.\n `),\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS,\n },\n },\n },\n hooks: {\n async deploy() {\n const params = this.getDeltaLinkParams();\n const deltaLink = this.microsoft_onedrive.getDeltaLink(params);\n const itemsStream = this.microsoft_onedrive.scanDeltaItems(deltaLink);\n\n // We skip the first drive item, since it represents the root directory\n await itemsStream.next();\n\n let eventsToProcess = Math.max(MAX_INITIAL_EVENT_COUNT, 1);\n for await (const driveItem of itemsStream) {\n if (driveItem.deleted) {\n // We don't want to process items that were deleted from the drive\n // since they no longer exist\n continue;\n }\n\n await this.processEvent(driveItem);\n if (--eventsToProcess <= 0) {\n break;\n }\n }\n },\n async activate() {\n await this._createNewSubscription();\n const deltaLinkParams = this.getDeltaLinkParams();\n const deltaLink = await this.microsoft_onedrive.getLatestDeltaLink(deltaLinkParams);\n this._setDeltaLink(deltaLink);\n },\n async deactivate() {\n await this._deactivateSubscription();\n },\n },\n methods: {\n _getNextExpirationDateTime() {\n const nowTimestamp = Date.now();\n const expirationTimestampDelta = 2 * WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS * 1000;\n return new Date(nowTimestamp + expirationTimestampDelta);\n },\n async _createNewSubscription() {\n const hookOpts = {\n expirationDateTime: this._getNextExpirationDateTime(),\n };\n const hookId = await this.microsoft_onedrive.createHook(this.http.endpoint, hookOpts);\n this._setHookId(hookId);\n },\n _renewSubscription() {\n const hookOpts = {\n expirationDateTime: this._getNextExpirationDateTime(),\n };\n const hookId = this._getHookId();\n return this.microsoft_onedrive.updateHook(hookId, hookOpts);\n },\n async _deactivateSubscription() {\n const hookId = this._getHookId();\n await this.microsoft_onedrive.deleteHook(hookId);\n this._setHookId(null);\n },\n _getHookId() {\n return this.db.get(\"hookId\");\n },\n _setHookId(hookId) {\n this.db.set(\"hookId\", hookId);\n },\n _getDeltaLink() {\n return this.db.get(\"deltaLink\");\n },\n _setDeltaLink(deltaLink) {\n this.db.set(\"deltaLink\", deltaLink);\n },\n _validateSubscription(validationToken) {\n // See the docs for more information on how webhooks are validated upon\n // creation: https://bit.ly/3fzc3Tr\n const headers = {\n \"Content-Type\": \"text/plain\",\n };\n this.http.respond({\n // OK\n status: 200,\n headers,\n body: validationToken,\n });\n },\n async _processEventsFromDeltaLink(deltaLink) {\n const itemsStream = this.microsoft_onedrive.scanDeltaItems(deltaLink);\n\n while (true) {\n // We iterate through the `itemsStream` generator using explicit calls to\n // `next()` since the last/returned value is also useful because it\n // contains the latest Delta Link (using a `for...of` loop will discard\n // such value).\n const {\n done,\n value,\n } = await itemsStream.next();\n\n if (done) {\n // No more items to retrieve from OneDrive. We update the cached Delta\n // Link and move on.\n this._setDeltaLink(value);\n break;\n }\n\n if (!this.isItemRelevant(value)) {\n // If the retrieved item is not relevant to the event source, we skip it\n continue;\n }\n\n await this.processEvent(value);\n }\n\n await this.postProcessEvent();\n },\n /**\n * The purpose of this method is for the different OneDrive event sources to\n * parameterize the OneDrive Delta Link to use. These parameters will be\n * forwarded to the `microsoft_onedrive.getLatestDeltaLink` method.\n *\n * @returns an object containing options/parameters to use when querying the\n * OneDrive API for a Delta Link\n */\n getDeltaLinkParams() {\n return {};\n },\n /**\n * This method determines whether an item that's about to be processed is\n * relevant to the event source or not. This is helpful when the event\n * source has to go through a collection of items, some of which should be\n * skipped/ignored.\n *\n * @param {Object} item the item under evaluation\n * @returns a boolean value that indicates whether the item should be\n * processed or not\n */\n isItemRelevant() {\n throw new Error(\"isItemRelevant is not implemented\");\n },\n /**\n * This method generates the metadata that accompanies an event being\n * emitted by the event source, as outlined [in the\n * docs](https://github.com/PipedreamHQ/pipedream/blob/master/COMPONENT-API.md#emit)\n *\n * @param {Object} data the event data to consider in order to build the\n * metadata object\n * @returns an event metadata object containing, as described in the docs\n */\n generateMeta() {\n throw new Error(\"generateMeta is not implemented\");\n },\n /**\n * This method emits an event which payload is set to the provided [OneDrive\n * item](https://bit.ly/39T7mQz). The functionality provided by this method\n * is very basic and complex event sources probably need to override it.\n *\n * @param {Object} driveItem a OneDrive item object\n */\n processEvent(driveItem) {\n const meta = this.generateMeta(driveItem);\n this.$emit(driveItem, meta);\n },\n /**\n * This method is executed after processing all the items/events in a\n * particular execution. A normal use case for it is to store/cache some\n * final value that should be picked up by the next execution (e.g. an event\n * timestamp, the ID of the last processed item, etc.).\n */\n postProcessEvent() {},\n },\n async run(event) {\n // The very first HTTP call that the event source receives is from the\n // OneDrive API to verify the webhook subscription. The response for such\n // call should be as fast as possible in order for the subscription to be\n // confirmed and activated.\n const { query: { validationToken } = {} } = event;\n if (validationToken) {\n this._validateSubscription(validationToken);\n console.log(`\n Received an HTTP call containing 'validationToken'.\n Validating webhook subscription and exiting...\n `);\n return;\n }\n\n if (event.interval_seconds || event.cron) {\n // Component was invoked by timer. When that happens, it means that it's\n // time to renew the webhook subscription, not that there are changes in\n // OneDrive to process.\n return this._renewSubscription();\n }\n\n // Every HTTP call made by a OneDrive webhook expects a '202 Accepted`\n // response, and it should be done as soon as possible.\n this.http.respond({\n status: 202,\n });\n\n // Using the last known Delta Link, we retrieve and process the items that\n // changed after such Delta Link was obtained\n const deltaLink = this._getDeltaLink();\n await this._processEventsFromDeltaLink(deltaLink);\n },\n};\n\n\n<|start_filename|>components/twilio/sources/common-webhook.js<|end_filename|>\nconst twilio = require(\"../twilio.app.js\");\nconst twilioClient = require(\"twilio\");\n\nmodule.exports = {\n props: {\n twilio,\n incomingPhoneNumber: { propDefinition: [twilio, \"incomingPhoneNumber\"] },\n authToken: { propDefinition: [twilio, \"authToken\"] },\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n hooks: {\n async activate() {\n const createWebhookResp = await this.setWebhook(\n this.incomingPhoneNumber,\n this.http.endpoint\n );\n console.log(createWebhookResp);\n },\n async deactivate() {\n const deleteWebhookResp = await this.setWebhook(\n this.incomingPhoneNumber,\n \"\" // remove the webhook URL\n );\n console.log(deleteWebhookResp);\n },\n },\n methods: {\n getResponseBody() {\n return null;\n },\n isRelevant(body) {\n return true;\n },\n validateRequest(body, headers) {\n const twilioSignature = headers[\"x-twilio-signature\"];\n if (!twilioSignature) {\n console.log(\"No x-twilio-signature header in request. Exiting.\");\n return false;\n }\n\n /** See https://www.twilio.com/docs/usage/webhooks/webhooks-security */\n return twilioClient.validateRequest(\n this.authToken,\n twilioSignature,\n /** This must match the incoming URL exactly, which contains a / */\n `${this.http.endpoint}/`,\n body\n );\n },\n emitEvent(body, headers) {\n const meta = this.generateMeta(body, headers);\n this.$emit(body, meta);\n },\n },\n async run(event) {\n let { body, headers } = event;\n\n const responseBody = this.getResponseBody();\n if (responseBody) {\n this.http.respond({\n status: 200,\n headers: { \"Content-Type\": \"text/xml\" },\n body: responseBody,\n });\n }\n\n if (typeof body !== \"object\")\n body = Object.fromEntries(new URLSearchParams(body));\n\n if (!this.isRelevant(body)) {\n console.log(\"Event not relevant. Skipping...\");\n return;\n }\n\n if (!this.validateRequest(body, headers)) {\n console.log(\"Event could not be validated. Skipping...\");\n return;\n }\n\n this.emitEvent(body, headers);\n },\n};\n\n<|start_filename|>components/google_docs/actions/append-text/append-text.js<|end_filename|>\nconst googleDocs = require(\"../../google_docs.app\");\n\nmodule.exports = {\n key: \"google_docs-append-text\",\n name: \"Append Text\",\n description: \"Append text to an existing document\",\n version: \"0.0.12\",\n type: \"action\",\n props: {\n googleDocs,\n docId: {\n propDefinition: [\n googleDocs,\n \"docId\",\n ],\n },\n text: {\n type: \"string\",\n description: \"Enter static text (e.g., `hello world`) or a reference to a string exported by a previous step (e.g., `{{steps.foo.$return_value}}`).\",\n\n },\n },\n async run() {\n const docs = this.googleDocs.docs();\n return (await docs.documents.batchUpdate({\n documentId: this.docId,\n requestBody: {\n requests: [\n {\n insertText: {\n location: {\n index: 1,\n },\n text: this.text,\n },\n },\n ],\n },\n })).data;\n },\n};\n\n\n<|start_filename|>components/webflow/sources/changed-ecomm-order/changed-ecomm-order.js<|end_filename|>\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-changed-ecomm-order\",\n name: \"Changed E-commerce Order (Instant)\",\n description: \"Emit an event when an e-commerce order is changed\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"ecomm_order_changed\";\n },\n generateMeta(data) {\n const { orderId } = data;\n const summary = `E-comm order changed: ${orderId}`;\n const ts = Date.now();\n const id = `${orderId}-${ts}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/reddit/sources/new-hot-posts-on-a-subreddit/region-data.js<|end_filename|>\nmodule.exports = [\n \"GLOBAL\",\n \"US\",\n \"AR\",\n \"AU\",\n \"BG\",\n \"CA\",\n \"CL\",\n \"CO\",\n \"HR\",\n \"CZ\",\n \"FI\",\n \"FR\",\n \"DE\",\n \"GR\",\n \"HU\",\n \"IS\",\n \"IN\",\n \"IE\",\n \"IT\",\n \"JP\",\n \"MY\",\n \"MX\",\n \"NZ\",\n \"PH\",\n \"PL\",\n \"PT\",\n \"PR\",\n \"RO\",\n \"RS\",\n \"SG\",\n \"ES\",\n \"SE\",\n \"TW\",\n \"TH\",\n \"TR\",\n \"GB\",\n \"US_WA\",\n \"US_DE\",\n \"US_DC\",\n \"US_WI\",\n \"US_WV\",\n \"US_HI\",\n \"US_FL\",\n \"US_WY\",\n \"US_NH\",\n \"US_NJ\",\n \"US_NM\",\n \"US_TX\",\n \"US_LA\",\n \"US_NC\",\n \"US_ND\",\n \"US_NE\",\n \"US_TN\",\n \"US_NY\",\n \"US_PA\",\n \"US_CA\",\n \"US_NV\",\n \"US_VA\",\n \"US_CO\",\n \"US_AK\",\n \"US_AL\",\n \"US_AR\",\n \"US_VT\",\n \"US_IL\",\n \"US_GA\",\n \"US_IN\",\n \"US_IA\",\n \"US_OK\",\n \"US_AZ\",\n \"US_ID\",\n \"US_CT\",\n \"US_ME\",\n \"US_MD\",\n \"US_MA\",\n \"US_OH\",\n \"US_UT\",\n \"US_MO\",\n \"US_MN\",\n \"US_MI\",\n \"US_RI\",\n \"US_KS\",\n \"US_MT\",\n \"US_MS\",\n \"US_SC\",\n \"US_KY\",\n \"US_OR\",\n \"US_SD\",\n];\n\n\n<|start_filename|>components/airtable/actions/common-list.js<|end_filename|>\n// Shared code for list-* actions\nconst airtable = require(\"../airtable.app.js\");\n\nmodule.exports = {\n props: {\n sortFieldId: {\n propDefinition: [\n airtable,\n \"sortFieldId\",\n ],\n },\n sortDirection: {\n propDefinition: [\n airtable,\n \"sortDirection\",\n ],\n },\n maxRecords: {\n propDefinition: [\n airtable,\n \"maxRecords\",\n ],\n },\n filterByFormula: {\n propDefinition: [\n airtable,\n \"filterByFormula\",\n ],\n },\n },\n async run() {\n const base = this.airtable.base(this.baseId);\n const data = [];\n const config = {};\n\n if (this.viewId) { config.view = this.viewId; }\n if (this.filterByFormula) { config.filterByFormula = this.filterByFormula; }\n if (this.maxRecords) { config.maxRecords = this.maxRecords; }\n if (this.sortFieldId && this.sortDirection) {\n config.sort = [\n {\n field: this.sortFieldId,\n direction: this.sortDirection,\n },\n ];\n }\n\n await base(this.tableId).select({\n ...config,\n })\n .eachPage(function page(records, fetchNextPage) {\n // This function (`page`) will get called for each page of records.\n records.forEach(function(record) {\n data.push(record._rawJson);\n });\n\n // To fetch the next page of records, call `fetchNextPage`.\n // If there are more records, `page` will get called again.\n // If there are no more records, `done` will get called.\n fetchNextPage();\n });\n\n return data;\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/common-campaign.js<|end_filename|>\nconst activecampaign = require(\"../activecampaign.app.js\");\nconst common = require(\"./common-webhook.js\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n campaigns: { propDefinition: [activecampaign, \"campaigns\"] },\n },\n methods: {\n isRelevant(body) {\n return (\n this.campaigns.length === 0 ||\n this.campaigns.includes(body[\"campaign[id]\"])\n );\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: `${body[\"campaign[id]\"]}${body[\"contact[id]\"]}`,\n summary: `${body[\"contact[email]\"]}, Campaign: ${body[\"campaign[name]\"]}`,\n ts\n };\n },\n },\n};\n\n\n<|start_filename|>components/jotform/jotform.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst querystring = require(\"querystring\");\n\nfunction ensureTrailingSlash(str) {\n if (str.endsWith(\"/\")) return str;\n return `${str}/`;\n}\n\nmodule.exports = {\n type: \"app\",\n app: \"jotform\",\n propDefinitions: {\n formId: {\n type: \"string\",\n label: \"Form\",\n description: \"The form to watch for new submissions\",\n async options() {\n const forms = await this.getForms(this.$auth.api_key);\n return forms.content.map((form) => {\n return {\n label: form.title,\n value: form.id,\n };\n });\n },\n },\n },\n methods: {\n _getBaseUrl() {\n return `https://${this.$auth.region}.jotform.com/`;\n },\n async _makeRequest(config) {\n config.headers = {\n \"APIKEY\": this.$auth.api_key,\n };\n if (config.params) {\n const query = querystring.stringify(config.params);\n delete config.params;\n const sep = config.url.indexOf(\"?\") === -1\n ? \"?\"\n : \"&\";\n config.url += `${sep}${query}`;\n config.url = config.url.replace(\"?&\", \"?\");\n }\n return await axios(config);\n },\n async getForms() {\n return (await this._makeRequest({\n url: `${this._getBaseUrl()}user/forms`,\n method: \"GET\",\n })).data;\n },\n async getWebhooks(opts = {}) {\n const { formId } = opts;\n return (await this._makeRequest({\n url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks`,\n method: \"GET\",\n })).data;\n },\n async createHook(opts = {}) {\n const {\n formId,\n endpoint,\n } = opts;\n return (await this._makeRequest({\n url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks`,\n method: \"POST\",\n params: {\n webhookURL: ensureTrailingSlash(endpoint),\n },\n }));\n },\n async deleteHook(opts = {}) {\n const {\n formId,\n endpoint,\n } = opts;\n const result = await this.getWebhooks({\n formId,\n });\n let webhooks = Object.values(result && result.content || {});\n let webhookIdx = -1;\n for (let idx in webhooks) {\n if (webhooks[idx] === ensureTrailingSlash(endpoint)) {\n webhookIdx = idx;\n }\n }\n if (webhookIdx === -1) {\n console.log(`Did not detect ${endpoint} as a webhook registered for form ID ${formId}.`);\n return;\n }\n console.log(`Deleting webhook at index ${webhookIdx}...`);\n return (await this._makeRequest({\n url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks/${encodeURIComponent(webhookIdx)}`,\n method: \"DELETE\",\n }));\n },\n },\n};\n\n\n<|start_filename|>components/todoist/todoist.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst querystring = require(\"querystring\");\nconst resourceTypes = require(\"./resource-types.js\")\n\nmodule.exports = {\n type: \"app\",\n app: \"todoist\",\n propDefinitions: {\n includeResourceTypes: {\n type: \"string[]\",\n label: \"Resource Types\",\n description: \"Select one or more resources to include\",\n async options() {\n resourceTypes.unshift(\"all\");\n return resourceTypes;\n },\n },\n selectProjects: {\n type: \"integer[]\",\n label: \"Select Projects\",\n description:\n \"Filter for events that match one or more projects. Leave this blank to emit results for any project.\",\n optional: true,\n async options() {\n return (await this.getProjects()).map((project) => {\n return { label: project.name, value: project.id };\n });\n },\n },\n },\n methods: {\n /**\n * Make a request to Todoist's sync API.\n * @params {Object} opts - An object representing the configuration options for this method\n * @params {String} opts.path [opts.path=/sync/v8/sync] - The path for the sync request\n * @params {String} opts.payload - The data to send in the API request at the POST body. This data will converted to `application/x-www-form-urlencoded`\n * @returns {Object} When the request succeeds, an HTTP 200 response will be returned with a JSON object containing the requested resources and also a new `sync_token`.\n */\n async _makeSyncRequest(opts) {\n const { path = `/sync/v8/sync` } = opts;\n delete opts.path;\n opts.url = `https://api.todoist.com${path[0] === \"/\" ? \"\" : \"/\"}${path}`;\n opts.payload.token = this.$auth.oauth_access_token;\n opts.data = querystring.stringify(opts.payload);\n delete opts.payload;\n return await axios(opts);\n },\n /**\n * Make a request to Todoist's REST API.\n * @params {Object} opts - An object representing the Axios configuration options for this method\n * @params {String} opts.path - The path for the REST API request\n * @returns {*} The response may vary depending the specific API request.\n */\n async _makeRestRequest(opts) {\n const { path } = opts;\n delete opts.path;\n opts.url = `https://api.todoist.com${path[0] === \"/\" ? \"\" : \"/\"}${path}`;\n opts.headers = {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n };\n return await axios(opts);\n },\n /**\n * Check whether an array of project IDs contains the given proejct ID. This method is used in multiple sources to validate if an event matches the selection in the project filter.\n * @params {Integer} project_id - The ID for a Todoist project\n * @params {Array} selectedProjectIds - An array of Todoist project IDs\n * @returns {Boolean} Returns `true` if the `project_id` matches a value in the arrar or if the array is empty. Otherwise returns `false`.\n */\n isProjectInList(projectId, selectedProjectIds) {\n return (\n selectedProjectIds.length === 0 ||\n selectedProjectIds.includes(projectId)\n );\n },\n /**\n * Public method to make a sync request.\n * @params {Object} opts - The configuration for an axios request with a `path` key.\n * @returns {Object} When the request succeeds, an HTTP 200 response will be returned with a JSON object containing the requested resources and also a new `sync_token`.\n */\n async sync(opts) {\n return (\n await this._makeSyncRequest({\n path: `/sync/v8/sync`,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n payload: opts,\n })\n ).data;\n },\n /**\n * Get the list of project for the authenticated user\n * @returns {Array} Returns a JSON-encoded array containing all user projects\n */\n async getProjects() {\n return (\n await this._makeRestRequest({\n path: `/rest/v1/projects`,\n method: \"GET\",\n })\n ).data;\n },\n async syncItems(db) {\n return await this.syncResources(db, [\"items\"]);\n },\n async syncProjects(db) {\n return await this.syncResources(db, [\"projects\"]);\n },\n async syncResources(db, resourceTypes) {\n const syncToken = db.get(\"syncToken\") || \"*\";\n const result = await this.sync({\n resource_types: JSON.stringify(resourceTypes),\n sync_token: syncToken,\n });\n db.set(\"syncToken\", result.sync_token);\n return result;\n },\n },\n};\n\n<|start_filename|>components/twitch/sources/streams-by-streamer/streams-by-streamer.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n name: \"Streams By Streamer\",\n key: \"twitch-streams-by-streamer\",\n description:\n \"Emits an event when a live stream starts from the streamers you specify.\",\n version: \"0.0.3\",\n props: {\n ...common.props,\n streamerLoginNames: {\n propDefinition: [common.props.twitch, \"streamerLoginNames\"],\n },\n },\n methods: {\n ...common.methods,\n getMeta(item) {\n const { id, started_at: startedAt, title: summary } = item;\n const ts = Date.parse(startedAt);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n // get and emit streams for the specified streamers\n const streams = await this.paginate(this.twitch.getStreams.bind(this), {\n user_login: this.streamerLoginNames,\n });\n for await (const stream of streams) {\n this.$emit(stream, this.getMeta(stream));\n }\n },\n};\n\n<|start_filename|>components/microsoft_onedrive/sources/new-file/new-file.js<|end_filename|>\nconst common = require(\"../common/base\");\n\nmodule.exports = {\n ...common,\n key: \"microsoft_onedrive-new-file\",\n name: \"New File (Instant)\",\n description: \"Emit an event when a new file is added to a specific drive in OneDrive\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n hooks: {\n ...common.hooks,\n async activate() {\n await common.hooks.activate.bind(this)();\n this._setLastCreatedTimestamp();\n },\n },\n methods: {\n ...common.methods,\n _getLastCreatedTimestamp() {\n return this.db.get(\"lastCreatedTimestamp\") || 0;\n },\n _setLastCreatedTimestamp(lastCreatedTimestamp = Date.now()) {\n this.db.set(\"lastCreatedTimestamp\", lastCreatedTimestamp);\n },\n _getMaxCreatedTimestamp() {\n return this.db.get(\"maxCreatedTimestamp\") || 0;\n },\n _setMaxCreatedTimestamp(maxCreatedTimestamp = Date.now()) {\n this.db.set(\"maxCreatedTimestamp\", maxCreatedTimestamp);\n },\n isItemRelevant(driveItem) {\n // Drive items that were created prior to the latest cached creation time\n // are not relevant to this event source\n const { createdDateTime } = driveItem;\n const createdTimestamp = Date.parse(createdDateTime);\n return createdTimestamp > this._getLastCreatedTimestamp();\n },\n generateMeta(driveItem) {\n const {\n id,\n createdDateTime,\n name,\n } = driveItem;\n const summary = `New file: ${name}`;\n const ts = Date.parse(createdDateTime);\n return {\n id,\n summary,\n ts,\n };\n },\n processEvent(driveItem) {\n const meta = this.generateMeta(driveItem);\n this.$emit(driveItem, meta);\n\n const { createdDateTime } = driveItem;\n const createdTimestamp = Date.parse(createdDateTime);\n if (createdTimestamp > this._getMaxCreatedTimestamp()) {\n this._setMaxCreatedTimestamp(createdTimestamp);\n }\n },\n postProcessEvent() {\n const maxCreatedTimestamp = this._getMaxCreatedTimestamp();\n this._setLastCreatedTimestamp(maxCreatedTimestamp);\n },\n },\n};\n\n\n<|start_filename|>components/github/actions/create-issue/create-issue.js<|end_filename|>\nconst github = require('../../github.app.js')\nconst { Octokit } = require('@octokit/rest')\n\nmodule.exports = {\n key: \"github-create-issue\",\n name: \"Create Issue\",\n description: \"Create a new issue in a Gihub repo.\",\n version: \"0.0.13\",\n type: \"action\",\n props: {\n github,\n repoFullName: { propDefinition: [github, \"repoFullName\"] },\n title: { propDefinition: [github, \"issueTitle\"] },\n body: { propDefinition: [github, \"issueBody\"] },\n labels: { \n propDefinition: [github, \"labelNames\", c => ({ repoFullName: c.repoFullName })],\n optional: true,\n },\n milestone: { \n propDefinition: [github, \"milestone\", c => ({ repoFullName: c.repoFullName })],\n optional: true \n },\n assignees: { propDefinition: [github, \"issueAssignees\"] },\n },\n async run() {\n const octokit = new Octokit({\n auth: this.github.$auth.oauth_access_token\n })\n \n return (await octokit.issues.create({\n owner: this.repoFullName.split(\"/\")[0],\n repo: this.repoFullName.split(\"/\")[1],\n title: this.title,\n body: this.body,\n labels: this.labels,\n assignees: this.assignees,\n milestone: this.milestone,\n })).data\n },\n}\n\n<|start_filename|>interfaces/http/examples/http-db-example.js<|end_filename|>\n// Example of how to use $.service.db methods\n// Each time this component receives an HTTP request,\n// it increments the requestCount key and emits it\nmodule.exports = {\n name: \"http-db\",\n version: \"0.0.2\",\n props: {\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n db: \"$.service.db\",\n },\n async run(event) {\n this.http.respond({\n status: 200,\n body: event,\n });\n let requestCount = this.db.get(\"requestCount\") || 0;\n requestCount += 1;\n this.$emit({\n requestCount,\n });\n this.db.set(\"requestCount\", requestCount);\n },\n};\n\n\n<|start_filename|>components/airtable/actions/create-single-record/create-single-record.js<|end_filename|>\nconst airtable = require(\"../../airtable.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n key: \"airtable-create-single-record\",\n name: \"Create single record\",\n description: \"Adds a record to a table.\",\n version: \"0.1.1\",\n type: \"action\",\n props: {\n ...common.props,\n record: {\n propDefinition: [\n airtable,\n \"record\",\n ],\n },\n typecast: {\n propDefinition: [\n airtable,\n \"typecast\",\n ],\n },\n },\n async run() {\n const table = this.airtable.base(this.baseId)(this.tableId);\n\n this.airtable.validateRecord(this.record);\n\n const data = [\n {\n fields: this.record,\n },\n ];\n\n const params = {\n typecast: this.typecast,\n };\n\n try {\n const [\n response,\n ] = await table.create(data, params);\n return response;\n } catch (err) {\n this.airtable.throwFormattedError(err);\n }\n },\n};\n\n\n<|start_filename|>components/mysql/sources/new-column/new-column.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"\",\n name: \"New Column\",\n description: \"Emits an event when you add a new column to a table\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n db: \"$.service.db\",\n table: { propDefinition: [common.props.mysql, \"table\"] },\n },\n methods: {\n ...common.methods,\n _getPreviousColumns() {\n return this.db.get(\"previousColumns\");\n },\n _setPreviousColumns(previousColumns) {\n this.db.set(\"previousColumns\", previousColumns);\n },\n async listResults(connection) {\n let previousColumns = this._getPreviousColumns() || [];\n const columns = await this.mysql.listNewColumns(\n connection,\n this.table,\n previousColumns\n );\n this.iterateAndEmitEvents(columns);\n\n const columnNames = columns.map((column) => column.Field);\n const newColumnNames = columnNames.filter(\n (c) => !previousColumns.includes(c)\n );\n previousColumns = previousColumns.concat(newColumnNames);\n this._setPreviousColumns(previousColumns);\n },\n generateMeta(column) {\n const columnName = column.Field;\n return {\n id: `${columnName}${this.table}`,\n summary: columnName,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/ringcentral/sources/new-call-recording/new-call-recording.js<|end_filename|>\nconst common = require(\"../common/timer-based\");\n\nmodule.exports = {\n ...common,\n key: \"ringcentral-new-call-recording\",\n name: \"New Call Recording\",\n description: \"Emits an event when a call recording is created\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n extensionId: { propDefinition: [common.props.ringcentral, \"extensionId\"] },\n },\n methods: {\n ...common.methods,\n generateMeta(data) {\n const {\n id,\n startTime: timestamp,\n direction,\n } = data;\n const ts = Date.parse(timestamp);\n\n const { phoneNumber } = direction === \"Outbound\" ? data.to : data.from;\n const maskedPhoneNumber = this.getMaskedNumber(phoneNumber);\n const summary = `New call recording (${maskedPhoneNumber})`;\n\n return {\n id,\n summary,\n ts,\n };\n },\n async processEvent(opts) {\n const {\n dateFrom,\n dateTo,\n } = opts;\n\n const callRecordingsScan = this.ringcentral.getCallRecordings(\n this.extensionId,\n dateFrom,\n dateTo,\n );\n for await (const record of callRecordingsScan) {\n const meta = this.generateMeta(record);\n this.$emit(record, meta);\n }\n }\n },\n};\n\n\n<|start_filename|>components/mysql/sources/new-row-custom-query/new-row-custom-query.js<|end_filename|>\nconst common = require(\"../common.js\");\nconst { v4: uuidv4 } = require(\"uuid\");\n\nmodule.exports = {\n ...common,\n key: \"mysql-new-row-custom-query\",\n name: \"New Row (Custom Query)\",\n description: \"Emits an event when new rows are returned from a custom query\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n table: { propDefinition: [common.props.mysql, \"table\"] },\n column: {\n propDefinition: [\n common.props.mysql,\n \"column\",\n (c) => ({ table: c.table }),\n ],\n label: \"De-duplication Key\",\n description:\n \"The name of a column in the table to use for de-duplication\",\n optional: true,\n },\n query: { propDefinition: [common.props.mysql, \"query\"] },\n },\n methods: {\n ...common.methods,\n async listResults(connection) {\n const rows = await this.mysql.executeQuery(connection, this.query);\n this.iterateAndEmitEvents(rows);\n },\n generateMeta(row) {\n const id = this.column ? row[this.column] : uuidv4();\n return {\n id,\n summary: `New Row ${id}`,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/cliniko/cliniko.app.js<|end_filename|>\nconst { axios } = require(\"@pipedreamhq/platform\");\n\nmodule.exports = {\n type: \"app\",\n app: \"cliniko\",\n propDefinitions: {\n patientId: {\n type: \"integer\",\n label: \"Patient ID\",\n description: \"Enter a unique patient ID.\",\n },\n },\n methods: {\n /**\n * Get the Cliniko API key for the authenticated user.\n * @returns {String} The Cliniko API key.\n */\n _apiKey() {\n return this.$auth.api_key;\n },\n _shard() {\n return this.$auth.shard;\n },\n _baseApiUrl() {\n return `https://api.${this._shard()}.cliniko.com/v1`;\n },\n _makeRequestConfig(url) {\n const auth = {\n username: this._apiKey(),\n password: \"\", // No password needed.\n };\n // Cliniko requires contact email address in User-Agent header.\n // See https://github.com/redguava/cliniko-api#identifying-your-application.\n const headers = {\n \"Accept\": \"application/json\",\n \"User-Agent\": \"Pipedream ()\",\n };\n return {\n url,\n headers,\n auth,\n };\n },\n _patientsApiUrl(id = undefined) {\n const baseUrl = this._baseApiUrl();\n const basePath = \"/patients\";\n const path = id\n ? `${basePath}/${id}`\n : basePath;\n return `${baseUrl}${path}`;\n },\n /**\n * Get the details of a specified patient.\n * @params {Integer} patientId - The unique identifier of the patient\n * @returns {Object} The details of the specified patient.\n */\n async getPatient(patientId) {\n const apiUrl = this._patientsApiUrl(patientId);\n const requestConfig = this._makeRequestConfig(apiUrl);\n return await axios(this, requestConfig);\n },\n },\n};\n\n\n<|start_filename|>components/twitch/actions/get-top-games/get-top-games.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Top Games\",\n key: \"twitch-get-top-games\",\n description: \"Gets games sorted by number of current viewers on Twitch, most popular first\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of games to return\",\n },\n },\n async run() {\n const topGames = await this.paginate(\n this.twitch.getTopGames.bind(this),\n {},\n this.max,\n );\n return await this.getPaginatedResults(topGames);\n },\n};\n\n\n<|start_filename|>components/mysql/sources/new-row/new-row.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"mysql-new-row\",\n name: \"New Row\",\n description: \"Emits an event when you add a new row to a table\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n db: \"$.service.db\",\n table: { propDefinition: [common.props.mysql, \"table\"] },\n column: {\n propDefinition: [\n common.props.mysql,\n \"column\",\n (c) => ({ table: c.table }),\n ],\n optional: true,\n },\n },\n hooks: {\n /** If column prop is left blank, get the table's primary key to use for ordering and deduping. */\n async deploy() {\n const connection = await this.mysql.getConnection();\n let column = this.column;\n if (!column) {\n const keyData = await this.mysql.getPrimaryKey(connection, this.table);\n column = keyData[0].Column_name;\n }\n this._setColumn(column);\n\n await this.listTopRows(connection, column);\n await this.mysql.closeConnection(connection);\n },\n },\n methods: {\n ...common.methods,\n _getColumn() {\n return this.db.get(\"column\");\n },\n _setColumn(column) {\n this.db.set(\"column\", column);\n },\n async listResults(connection) {\n const column = this._getColumn();\n await this.listRowResults(connection, column);\n },\n iterateAndEmitEvents(rows) {\n const column = this._getColumn();\n for (const row of rows) {\n const meta = this.generateMeta(row, column);\n this.$emit(row, meta);\n }\n },\n generateMeta(row, column) {\n return {\n id: row[column],\n summary: `New Row Added ${column}: ${row[column]}`,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/swapi/swapi.app.js<|end_filename|>\nconst axios = require('axios')\n\nmodule.exports = {\n type: 'app',\n app: 'swapi',\n propDefinitions: {\n film: {\n type: \"string\",\n async options() {\n return (await axios({ url: 'https://swapi.dev/api/films' })).data.results.map(function(film, index) {\n return {\n label: film.title,\n value: index + 1\n }\n })\n }\n }\n }\n}\n\n<|start_filename|>examples/async-options.js<|end_filename|>\nmodule.exports = {\n name: \"Async Options Example\",\n version: \"0.1\",\n props: {\n msg: {\n type: \"string\",\n label: \"Message\",\n description: \"Select a message to `console.log()`\",\n async options() {\n return [\n \"This is option 1\",\n \"This is option 2\",\n ];\n },\n },\n },\n async run() {\n this.$emit(this.msg);\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/contact-updated/contact-updated.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-contact-updated\",\n name: \"\",\n description: \"Emits an event each time a contact is updated.\",\n version: \"0.0.2\",\n methods: {\n ...common.methods,\n generateMeta(contact) {\n const { id, properties, updatedAt } = contact;\n const ts = Date.parse(updatedAt);\n return {\n id: `${id}${ts}`,\n summary: `${properties.firstname} ${properties.lastname}`,\n ts,\n };\n },\n isRelevant(contact, updatedAfter) {\n return Date.parse(contact.updatedAt) > updatedAfter;\n },\n },\n async run(event) {\n const updatedAfter = this._getAfter();\n const data = {\n limit: 100,\n sorts: [\n {\n propertyName: \"lastmodifieddate\",\n direction: \"DESCENDING\",\n },\n ],\n properties: this.db.get(\"properties\"),\n object: \"contacts\",\n };\n await this.paginate(\n data,\n this.hubspot.searchCRM.bind(this),\n \"results\",\n updatedAfter\n );\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/dropbox/dropbox.app.js<|end_filename|>\nconst Dropbox = require(\"dropbox\").Dropbox;\nconst fetch = require(\"isomorphic-fetch\");\n\nmodule.exports = {\n type: \"app\",\n app: \"dropbox\",\n propDefinitions: {\n path: {\n type: \"string\",\n label: \"Path\",\n description: \"Path to the folder you want to watch for changes.\",\n optional: false,\n useQuery: true,\n async options({ query }) {\n return await this.pathOptions(query);\n },\n },\n recursive: {\n type: \"boolean\",\n label: \"Recursive\",\n description: \"Also watch sub-directories and their contents.\",\n optional: false,\n default: false,\n },\n },\n methods: {\n async sdk() {\n const baseClientOpts = {\n accessToken: this.$auth.oauth_access_token,\n fetch,\n };\n\n // In order to properly set the [root\n // path](https://www.dropbox.com/developers/reference/path-root-header-modes)\n // to use in every API request we first need to extract some information\n // from the authenticated user's account, for which we need to create a\n // client and issue an API request.\n const dpx = new Dropbox(baseClientOpts);\n const { result } = await dpx.usersGetCurrentAccount();\n\n const pathRoot = JSON.stringify({\n \".tag\": \"root\",\n \"root\": result.root_info.root_namespace_id,\n });\n return new Dropbox({\n ...baseClientOpts,\n pathRoot,\n });\n },\n async pathOptions(path) {\n const limit = 50;\n let options = [];\n let entries, has_more, cursor;\n path = path === \"/\" || path === null ? \"\" : path;\n try {\n const dpx = await this.sdk();\n let files = await dpx.filesListFolder({ path, limit });\n if (files.result) {\n files = files.result;\n }\n do {\n ({ entries, has_more, cursor } = files);\n for (entry of entries) {\n if (entry[\".tag\"] == \"folder\") {\n options.push(entry.path_display);\n }\n }\n // TODO break after a certain number of folders has been found??\n if (has_more) {\n files = await dpx.filesListFolderContinue({ cursor });\n if (files.result) {\n files = files.result;\n }\n }\n } while (has_more);\n options = options.sort((a, b) => {\n return a.toLowerCase().localeCompare(b.toLowerCase());\n });\n if (path) {\n options.unshift(require(\"path\").dirname(path));\n }\n options.unshift(path);\n } catch (err) {\n console.log(err);\n throw `Error connecting to Dropbox API to get directory listing for path: ${path}`;\n }\n const labeledOptions = options.map((opt) => {\n if (opt === \"\") {\n return { label: \"/\", value: \"\" };\n }\n return { label: opt, value: opt };\n });\n return { options: labeledOptions };\n },\n async initState(context) {\n const { path, recursive, db } = context;\n try {\n const fixedPath = path == \"/\" ? \"\" : path;\n const dpx = await this.sdk();\n let response = await dpx.filesListFolderGetLatestCursor({\n path: fixedPath,\n recursive,\n });\n if (response.result) {\n response = response.result;\n }\n const { cursor } = response;\n const state = { path, recursive, cursor };\n db.set(\"dropbox_state\", state);\n return state;\n } catch (err) {\n console.log(err);\n throw `Error connecting to Dropbox API to get latest cursor for folder: ${path}${\n recursive ? \" (recursive)\" : \"\"\n }`;\n }\n },\n async getState(context) {\n const { path, recursive, db } = context;\n let state = db.get(\"dropbox_state\");\n if (state == null || state.path != path || state.recursive != recursive) {\n state = await this.initState(context);\n }\n return state;\n },\n async getUpdates(context) {\n let ret = [];\n const state = await this.getState(context);\n if (state) {\n try {\n const { db } = context;\n let [cursor, has_more, entries] = [state.cursor, true, null];\n while (has_more) {\n const dpx = await this.sdk();\n let response = await dpx.filesListFolderContinue({ cursor });\n if (response.result) {\n response = response.result;\n }\n ({ entries, cursor, has_more } = response);\n ret = ret.concat(entries);\n }\n state.cursor = cursor;\n db.set(\"dropbox_state\", state);\n } catch (err) {\n console.log(err);\n throw `Error connecting to Dropbox API to get list of updated files/folders for cursor: ${state.cursor}`;\n }\n }\n return ret;\n },\n },\n};\n\n\n<|start_filename|>components/twitter/sources/common/tweets.js<|end_filename|>\nconst twitter = require(\"../../twitter.app\");\n\nmodule.exports = {\n props: {\n db: \"$.service.db\",\n twitter,\n count: {\n propDefinition: [\n twitter,\n \"count\",\n ],\n },\n maxRequests: {\n propDefinition: [\n twitter,\n \"maxRequests\",\n ],\n },\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n _addParsedId(tweet) {\n // This is needed since the numeric value of a Tweet's ID can exceed the\n // maximum supported value of `number`\n const parsedId = BigInt(tweet.id_str);\n return {\n ...tweet,\n parsedId,\n };\n },\n _compareByIdAsc({ parsedId: a }, { parsedId: b }) {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n },\n sortTweets(tweets) {\n return tweets\n .map(this._addParsedId)\n .sort(this._compareByIdAsc);\n },\n /**\n * This function returns the Twitter screen name of the subject account\n *\n * @returns a string containing the relevant Twitter screen name\n */\n getScreenName() {\n throw new Error(\"getScreenName is not implemented\");\n },\n /**\n * This function provides the list of options for the `tweetId` user prop.\n * It is meant to be called by Pipedream during the setup of the user prop\n * and not during normal operations of the event source.\n *\n * @param {object} context the context object for the pagination of the\n * prop options\n * @param {object} context.prevContext the context object of a previous\n * call to this method\n * @returns an object containing the list of Tweet ID options for the\n * `tweetId` user prop and the context for pagination\n */\n async tweetIdOptions(context) {\n const { prevContext = {} } = context;\n const {\n screenName = await this.getScreenName(),\n sinceId = \"1\",\n } = prevContext;\n\n const userTimelineOpts = {\n screen_name: screenName,\n since_id: sinceId,\n count: 10,\n trim_user: true,\n exclude_replies: false,\n include_rts: false,\n };\n const tweets = await this.twitter.getUserTimeline(userTimelineOpts);\n if (tweets.length === 0) {\n // There are no more tweets to go through\n return {\n options: null,\n context: prevContext,\n };\n }\n\n const sortedTweets = this.sortTweets(tweets);\n const { id_str: lastId } = sortedTweets[sortedTweets.length-1];\n const options = sortedTweets.map(({\n full_text,\n id_str,\n }) => ({\n label: full_text,\n value: id_str,\n }));\n\n return {\n options,\n context: {\n screenName,\n sinceId: lastId,\n },\n };\n },\n getSinceId() {\n return this.db.get(\"since_id\") || \"1\";\n },\n setSinceId(sinceId = \"1\") {\n this.db.set(\"since_id\", sinceId);\n },\n generateMeta(tweet) {\n const {\n created_at: createdAt,\n full_text: fullText,\n id_str: id,\n text,\n } = tweet;\n const summary = fullText || text;\n const ts = this.twitter.parseDate(createdAt);\n return {\n id,\n summary,\n ts,\n };\n },\n /**\n * The purpose of this function is to retrieve the relevant Tweets for the\n * event source that implements it. For example, if the event source emits\n * an event for each new Tweet of a specific user, the implementation of\n * this function will perform the retrieval of such Tweets and return it as\n * a list of [Tweet\n * objects](https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/tweet)\n *\n * @returns a list of Tweet objects for which to emit new events\n */\n retrieveTweets() {\n throw new Error(\"retrieveTweets is not implemented\");\n },\n },\n async run() {\n const tweets = await this.retrieveTweets();\n if (tweets.length === 0) {\n console.log(\"No new tweets available. Skipping...\");\n return;\n }\n\n const sortedTweets = this.sortTweets(tweets);\n const { id_str: lastId } = sortedTweets[sortedTweets.length-1];\n this.setSinceId(lastId);\n\n // Emit array of tweet objects\n sortedTweets.forEach(tweet => {\n const meta = this.generateMeta(tweet);\n this.$emit(tweet, meta);\n });\n },\n};\n\n\n<|start_filename|>components/npm/npm.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"npm\",\n}\n\n<|start_filename|>components/twitch/sources/new-clips/new-clips.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\nconst twitch = require(\"../../twitch.app.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Clips\",\n key: \"twitch-new-clips\",\n description:\n \"Emits an event when there is a new clip for the specified game.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n game: { propDefinition: [twitch, \"game\"] },\n max: { propDefinition: [twitch, \"max\"] },\n },\n methods: {\n ...common.methods,\n getMeta({ id, title: summary, created_at: createdAt }) {\n const ts = new Date(createdAt).getTime();\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n const { data: gameData } = await this.twitch.getGames([this.game]);\n if (gameData.length == 0) {\n console.log(`No game found with the name ${this.game}`);\n return;\n }\n\n // get and emit new clips of the specified game\n const params = {\n game_id: gameData[0].id,\n started_at: this.getLastEvent(this.db.get(\"lastEvent\")),\n };\n const clips = await this.paginate(\n this.twitch.getClips.bind(this),\n params,\n this.max\n );\n for await (const clip of clips) {\n this.$emit(clip, this.getMeta(clip));\n }\n\n this.db.set(\"lastEvent\", Date.now());\n },\n};\n\n<|start_filename|>components/clickup/actions/create-task/create-task.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"clickup-create-task\",\n name: \"\",\n description: \"Creates a new task\",\n version: \"0.0.2\",\n type: \"action\",\n props: {\n ...common.props,\n list: {\n propDefinition: [\n common.props.clickup,\n \"list\",\n (c) => ({\n folder: c.folder,\n space: c.space,\n }),\n ],\n },\n name: {\n propDefinition: [\n common.props.clickup,\n \"name\",\n ],\n description: \"New task name\",\n },\n description: {\n type: \"string\",\n label: \"Description\",\n description: \"New task description\",\n optional: true,\n },\n assignees: {\n propDefinition: [\n common.props.clickup,\n \"assignees\",\n (c) => ({\n workspace: c.workspace,\n }),\n ],\n },\n tags: {\n propDefinition: [\n common.props.clickup,\n \"tags\",\n (c) => ({\n space: c.space,\n }),\n ],\n },\n status: {\n propDefinition: [\n common.props.clickup,\n \"status\",\n (c) => ({\n list: c.list,\n }),\n ],\n },\n dueDate: {\n propDefinition: [\n common.props.clickup,\n \"dueDate\",\n ],\n description:\n `The date by which you must complete the task. Use UTC time in \n milliseconds (ex. 1508369194377)`,\n },\n dueDateTime: {\n propDefinition: [\n common.props.clickup,\n \"dueDateTime\",\n ],\n description:\n \"Set to true if you want to enable the due date time for the task\",\n },\n timeEstimate: {\n type: \"integer\",\n label: \"Time Estimate\",\n description: \"Use milliseconds\",\n optional: true,\n },\n startDate: {\n type: \"integer\",\n label: \"Start Date\",\n description:\n \"The start date of the task. Use UTC time in milliseconds (ex. 1567780450202)\",\n optional: true,\n },\n startDateTime: {\n type: \"boolean\",\n label: \"Start Date Time\",\n description: \"Select true if you want to enable the start date time\",\n optional: true,\n },\n notifyAll: {\n type: \"boolean\",\n label: \"Notify All\",\n description:\n `If Notify All is true, creation notifications will be sent to everyone including the \n creator of the task.`,\n optional: true,\n },\n parent: {\n propDefinition: [\n common.props.clickup,\n \"parent\",\n (c) => ({\n list: c.list,\n }),\n ],\n optional: true,\n },\n linksTo: {\n propDefinition: [\n common.props.clickup,\n \"task\",\n (c) => ({\n list: c.list,\n }),\n ],\n label: \"Links To\",\n description:\n \"Accepts a task ID to create a linked dependency on the new task\",\n optional: true,\n },\n checkRequiredCustomFields: {\n type: \"boolean\",\n label: \"Check Required Custom Fields\",\n description:\n `Indicates whether or not your new task will include data for required \n Custom Fields (true) or not (false). The default is false. If you set this option to true, \n and do not include information for required Custom Fields, then you will receive an error \n that 'One or more required fields is missing'.`,\n optional: true,\n },\n customFields: {\n type: \"string[]\",\n label: \"Custom Fields\",\n description: `An array of objects containing 'id' and 'value' keys.\n Example:\n {\n \"id\": \"0a52c486-5f05-403b-b4fd-c512ff05131c\",\n \"value\": 23\n },\n `,\n optional: true,\n },\n },\n async run() {\n const data = {\n name: this.name,\n description: this.description,\n assignees: this.assignees,\n tags: this.tags,\n status: this.status,\n priority: this.priority,\n due_date: this.dueDate,\n due_date_time: this.dueDateTime,\n time_estimate: this.timeEstimate,\n start_date: this.startDate,\n start_date_time: this.startDateTime,\n notify_all: this.notifyAll,\n parent: this.parent,\n links_to: this.linksTo,\n check_required_custom_fields: this.checkRequiredCustomFields,\n custom_fields: this.customFields,\n };\n return await this.clickup.createTask(this.list, data);\n },\n};\n\n\n<|start_filename|>components/stack_exchange/sources/new-answers-from-users/new-answers-from-users.js<|end_filename|>\nconst stack_exchange = require('../../stack_exchange.app');\n\nmodule.exports = {\n key: \"stack_exchange-new-answers-from-users\",\n name: \"New Answers from Specific Users\",\n description: \"Emits an event when a new answer is posted by one of the specified users\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n stack_exchange,\n db: \"$.service.db\",\n siteId: { propDefinition: [stack_exchange, \"siteId\"] },\n userIds: {\n propDefinition: [\n stack_exchange,\n \"userIds\",\n c => ({ siteId: c.siteId }),\n ],\n },\n timer: {\n type: '$.interface.timer',\n default: {\n intervalSeconds: 60 * 15, // 15 minutes\n },\n },\n },\n hooks: {\n async activate() {\n const fromDate = this._getCurrentEpoch();\n this.db.set(\"fromDate\", fromDate);\n },\n },\n methods: {\n _getCurrentEpoch() {\n // The StackExchange API works with Unix epochs in seconds.\n return Math.floor(Date.now() / 1000);\n },\n generateMeta(data) {\n const {\n answer_id: id,\n owner: owner,\n creation_date: ts,\n } = data;\n const { display_name: username } = owner;\n const summary = `New answer from ${username}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n const fromDate = this.db.get(\"fromDate\");\n const toDate = this._getCurrentEpoch();\n const filter = '!SWKA(ozr4ec2cHE9JK'; // See https://api.stackexchange.com/docs/filters\n const searchParams = {\n fromDate,\n toDate,\n filter,\n sort: 'creation',\n order: 'asc',\n site: this.siteId,\n }\n\n const items = this.stack_exchange.answersFromUsers(this.userIds, searchParams);\n for await (const item of items) {\n const meta = this.generateMeta(item);\n this.$emit(item, meta);\n }\n\n this.db.set(\"fromDate\", toDate);\n },\n};\n\n\n<|start_filename|>components/airtable/actions/list-records-in-view/list-records-in-view.js<|end_filename|>\nconst common = require(\"../common.js\");\nconst commonList = require(\"../common-list.js\");\n\nmodule.exports = {\n key: \"airtable-list-records-in-view\",\n name: \"List Records in View\",\n description: \"Retrieve records in a view with automatic pagination. Optionally sort and filter results.\",\n type: \"action\",\n version: \"0.1.0\",\n ...commonList,\n props: {\n ...common.props,\n viewId: {\n type: \"$.airtable.viewId\",\n tableIdProp: \"tableId\",\n },\n ...commonList.props,\n },\n};\n\n\n<|start_filename|>components/textlocal/sources/common/base.js<|end_filename|>\nconst { v4: uuidv4 } = require(\"uuid\");\n\nconst textlocal = require(\"../../textlocal.app\");\n\nmodule.exports = {\n props: {\n db: \"$.service.db\",\n textlocal,\n },\n methods: {\n generateMeta() {\n throw new Error('generateMeta is not implemented')\n },\n /**\n * Given a person's name, return a masked version of it. The purpose of a\n * masked name is to hide personal information so that it is not exposed to\n * an unintended audience.\n *\n * Examples:\n *\n * - Input: (first name \"John\", last name \"Doe\")\n * - Output: .\n *\n * - Input: Jane (first name \"Jane\", last name not provided)\n * - Output: Jane #.\n *\n * @param {object} nameProps Object containing the name to be masked\n * @param {string} nameProps.firstName The first name\n * @param {string} nameProps.lastName The last name\n * @return {string} The masked full name\n */\n getMaskedName({\n firstName = \"\",\n lastName = \"\",\n }) {\n const lastNameInitial = lastName.slice(0, 1).toUpperCase() || \"#\";\n return `${firstName} ${lastNameInitial}.`;\n },\n /**\n * Given a phone number, return a masked version of it. The purpose of a\n * masked number is to avoid exposing it to an unintended audience.\n *\n * Example:\n *\n * - Input: 6505551234\n * - Output: ######1234\n *\n * @param {number} number The phone number to mask\n * @return {string} The masked phone number\n */\n getMaskedNumber(number) {\n const numberAsString = Number(number).toString();\n const { length: numberLength } = numberAsString;\n return numberAsString\n .slice(numberLength - 4)\n .padStart(numberLength, \"#\");\n },\n processEvent(event) {\n const meta = this.generateMeta(event);\n this.$emit(event, meta);\n },\n },\n async run(event) {\n await this.processEvent(event);\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-event/new-event.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-event\",\n name: \"New Events\",\n description: \"Emits an event for each new Hubspot event.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n ...common.props,\n objectType: { propDefinition: [common.props.hubspot, \"objectType\"] },\n objectIds: {\n propDefinition: [\n common.props.hubspot,\n \"objectIds\",\n (c) => ({ objectType: c.objectType }),\n ],\n },\n },\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(result) {\n const { id, eventType } = result;\n return {\n id,\n summary: eventType,\n ts: Date.now(),\n };\n },\n },\n async run(event) {\n const occurredAfter = this._getAfter();\n\n for (const objectId of this.objectIds) {\n const params = {\n limit: 100,\n objectType: this.objectType,\n objectId,\n occurredAfter,\n };\n\n await this.paginate(\n params,\n this.hubspot.getEvents.bind(this),\n \"results\",\n occurredAfter\n );\n }\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/intercom/sources/tag-added-to-conversation/tag-added-to-conversation.js<|end_filename|>\nconst intercom = require(\"../../intercom.app.js\");\n\nmodule.exports = {\n key: \"intercom-tag-added-to-conversation\",\n name: \"Tag Added To Conversation\",\n description: \"Emits an event each time a new tag is added to a conversation.\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n props: {\n intercom,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n async run(event) {\n const data = {\n query: {\n field: \"tag_ids\",\n operator: \"!=\",\n value: null,\n },\n };\n\n results = await this.intercom.searchConversations(data);\n for (const conversation of results) {\n for (const tag of conversation.tags.tags) {\n this.$emit(tag, {\n id: `${conversation.id}${tag.id}`,\n summary: tag.name,\n ts: tag.applied_at,\n });\n }\n }\n },\n};\n\n<|start_filename|>components/twitch/actions/get-users/get-users.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Get Users\",\n key: \"twitch-get-users\",\n description: \"Gets the user objects for the specified Twitch login names\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n login: {\n type: \"string[]\",\n label: \"Login names\",\n description: \"User login name. Multiple login names can be specified. Limit: 100.\",\n },\n },\n async run() {\n const params = {\n login: this.login,\n };\n return (await this.twitch.getMultipleUsers(params)).data.data;\n },\n};\n\n\n<|start_filename|>components/twitch/actions/search-games/search-games.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"Search Games\",\n key: \"twitch-search-games\",\n description: `Searches for games based on a specified query parameter. A game is\n returned if the query parameter is matched entirely or partially in the channel\n description or game name`,\n version: \"0.0.1\",\n type: \"action\",\n props: {\n ...common.props,\n max: {\n propDefinition: [\n common.props.twitch,\n \"max\",\n ],\n description: \"Maximum number of games to return\",\n },\n query: {\n type: \"string\",\n label: \"Query\",\n description: \"The search query\",\n },\n },\n async run() {\n const params = {\n query: this.query,\n };\n const searchResults = await this.paginate(\n this.twitch.searchGames.bind(this),\n params,\n this.max,\n );\n return await this.getPaginatedResults(searchResults);\n },\n};\n\n\n<|start_filename|>components/todoist/sources/incomplete-task/incomplete-task.js<|end_filename|>\nconst common = require(\"../common-task.js\");\n\nmodule.exports = {\n ...common,\n key: \"todoist-incomplete-task\",\n name: \"Incomplete Task\",\n description: \"Emit an event for each new incomplete task\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n isElementRelevant(element) {\n return element.checked === 0;\n },\n },\n};\n\n\n<|start_filename|>components/snowflake/sources/common.js<|end_filename|>\nconst snowflake = require(\"../snowflake.app\");\n\nmodule.exports = {\n dedupe: \"unique\",\n props: {\n snowflake,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15, // 15 minutes\n },\n },\n eventSize: {\n type: \"integer\",\n label: \"Event Size\",\n description: \"The number of rows to include in a single event (by default, emits 1 event per row)\",\n default: 1,\n min: 1,\n },\n },\n methods: {\n async processCollection(statement, timestamp) {\n let lastResultId;\n let totalRowCount = 0;\n const rowCollectionStream = this.snowflake.collectRowsPaginated(statement, this.eventSize);\n for await (const rows of rowCollectionStream) {\n const rowCount = rows.length;\n if (rowCount <= 0) {\n break;\n }\n\n lastResultId = rows[rowCount-1][this.uniqueKey];\n totalRowCount += rowCount;\n const meta = this.generateMetaForCollection({\n lastResultId,\n rowCount,\n timestamp,\n });\n this.$emit({ rows }, meta);\n }\n return {\n lastResultId,\n rowCount: totalRowCount,\n }\n },\n async processSingle(statement, timestamp) {\n let lastResultId;\n let rowCount = 0;\n const rowStream = await this.snowflake.getRows(statement);\n for await (const row of rowStream) {\n const meta = this.generateMeta({\n row,\n timestamp,\n });\n this.$emit(row, meta);\n\n lastResultId = row[this.uniqueKey];\n ++rowCount;\n }\n\n return {\n lastResultId,\n rowCount,\n };\n },\n getStatement() {\n throw new Error('getStatement is not implemented');\n },\n generateMeta() {\n throw new Error('generateMeta is not implemented');\n },\n generateMetaForCollection() {\n throw new Error('generateMetaForCollection is not implemented');\n },\n processEvent() {\n throw new Error('processEvent is not implemented');\n },\n },\n async run(event) {\n const { timestamp } = event;\n const statement = this.getStatement(event);\n return (this.eventSize === 1) ?\n this.processSingle(statement, timestamp) :\n this.processCollection(statement, timestamp);\n },\n};\n\n\n<|start_filename|>components/stack_exchange/stack_exchange.app.js<|end_filename|>\nconst _ = require(\"lodash\");\nconst axios = require(\"axios\");\nconst he = require(\"he\");\n\nmodule.exports = {\n type: \"app\",\n app: \"stack_exchange\",\n propDefinitions: {\n siteId: {\n type: \"string\",\n label: \"Site\",\n description: \"The StackExchange site for which questions are of interest\",\n async options(context) {\n if (context.page !== 0) {\n // The `sites` API is not paginated:\n // https://api.stackexchange.com/docs/sites\n return {\n options: []\n };\n }\n\n const url = this._sitesUrl();\n const { data } = await axios.get(url);\n const rawOptions = data.items.map(site => ({\n label: site.name,\n value: site.api_site_parameter,\n }));\n const options = _.sortBy(rawOptions, ['label']);\n return {\n options,\n };\n },\n },\n keywords: {\n type: \"string[]\",\n label: \"Keywords\",\n description: \"Keywords to search for in questions\",\n },\n questionIds: {\n type: \"string[]\",\n label: \"Questions\",\n description: \"Questions to monitor (max: 100)\",\n useQuery: true,\n async options(context) {\n const q = context.query || '';\n const searchParams = {\n sort: 'relevance',\n order: 'desc',\n closed: false,\n q,\n };\n const url = this._advancedSearchUrl();\n const { items, hasMore } = await this._propDefinitionsOptions(url, searchParams, context);\n\n const options = items.map((question) => ({\n label: he.decode(question.title),\n value: question.question_id,\n }));\n return {\n options,\n context: {\n hasMore,\n },\n };\n },\n },\n userIds: {\n type: \"string[]\",\n label: \"Users\",\n description: \"Users to monitor (max: 100)\",\n useQuery: true,\n async options(context) {\n const inname = context.query || '';\n const searchParams = {\n sort: 'reputation',\n order: 'desc',\n inname,\n };\n const url = this._usersUrl();\n const { items, hasMore } = await this._propDefinitionsOptions(url, searchParams, context);\n\n const options = items.map((user) => ({\n label: user.display_name,\n value: user.user_id,\n }));\n return {\n options,\n context: {\n hasMore,\n },\n };\n },\n },\n },\n methods: {\n _apiUrl() {\n return \"https://api.stackexchange.com/2.2\";\n },\n _sitesUrl() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/sites`;\n },\n _advancedSearchUrl() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/search/advanced`;\n },\n _usersUrl() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/users`;\n },\n _answersForQuestionsUrl(questionIds) {\n const baseUrl = this._apiUrl();\n const ids = questionIds.join(';');\n return `${baseUrl}/questions/${ids}/answers`;\n },\n _answersFromUsersUrl(userIds) {\n const baseUrl = this._apiUrl();\n const ids = userIds.join(';');\n return `${baseUrl}/users/${ids}/answers`;\n },\n _authToken() {\n return this.$auth.oauth_access_token\n },\n async _propDefinitionsOptions(url, baseSearchParams, context) {\n const {\n hasMore = true,\n page,\n siteId,\n } = context;\n if (!hasMore) {\n return {\n items: [],\n hasMore: false,\n };\n }\n\n const searchParams = {\n ...baseSearchParams,\n site: siteId,\n };\n const searchPage = page + 1; // The StackExchange API pages are 1-indexed\n const {\n items,\n has_more: nextPageHasMore,\n } = await this.getItemsForPage(url, searchParams, searchPage);\n\n return {\n items,\n hasMore: nextPageHasMore,\n };\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `Bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n advancedSearch(searchParams) {\n const url = this._advancedSearchUrl();\n return this.getItems(url, searchParams);\n },\n answersForQuestions(questionIds, searchParams) {\n const url = this._answersForQuestionsUrl(questionIds);\n return this.getItems(url, searchParams);\n },\n answersFromUsers(userIds, searchParams) {\n const url = this._answersFromUsersUrl(userIds);\n return this.getItems(url, searchParams);\n },\n async *getItems(url, baseParams) {\n let page = 1;\n let hasMore = false;\n do {\n const data = await this.getItemsForPage(url, baseParams, page);\n const { items } = data;\n\n if (items === undefined) {\n console.warn(`\n Unexpected response from ${url} (page ${page}):\n \"items\" is undefined.\n Query parameters: ${JSON.stringify(baseParams, null, 2)}.\n `);\n return;\n }\n\n if (items.length === 0) {\n console.log(`\n No new items found in ${url} for the following parameters:\n ${JSON.stringify(baseParams, null, 2)}\n `);\n return;\n }\n\n console.log(`Found ${items.length} new item(s) in ${url}`);\n for (const item of items) {\n yield item;\n }\n hasMore = data.has_more;\n ++page;\n } while (hasMore);\n },\n async getItemsForPage(url, baseParams, page) {\n const baseRequestConfig = this._makeRequestConfig();\n const params = {\n ...baseParams,\n page,\n };\n const requestConfig = {\n ...baseRequestConfig,\n params,\n };\n const { data } = await axios.get(url, requestConfig);\n return data;\n },\n },\n};\n\n\n<|start_filename|>components/bitbucket/sources/new-branch/new-branch.js<|end_filename|>\nconst common = require(\"../../common\");\nconst { bitbucket } = common.props;\n\nconst EVENT_SOURCE_NAME = \"New Branch (Instant)\";\n\nmodule.exports = {\n ...common,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-branch\",\n description: \"Emits an event when a new branch is created\",\n version: \"0.0.2\",\n props: {\n ...common.props,\n repositoryId: {\n propDefinition: [\n bitbucket,\n \"repositoryId\",\n c => ({ workspaceId: c.workspaceId }),\n ],\n },\n },\n methods: {\n ...common.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return [\n \"repo:push\",\n ];\n },\n getHookPathProps() {\n return {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n };\n },\n isNewBranch(change) {\n const expectedChangeTypes = new Set([\n \"branch\",\n \"named_branch\",\n ]);\n return (\n change.created &&\n expectedChangeTypes.has(change.new.type)\n );\n },\n generateMeta(data) {\n const { headers, change } = data;\n const newBranchName = change.new.name;\n const summary = `New Branch: ${newBranchName}`;\n const ts = +new Date(headers[\"x-event-time\"]);\n const compositeId = `${newBranchName}-${ts}`;\n return {\n id: compositeId,\n summary,\n ts,\n };\n },\n async processEvent(event) {\n const { headers, body } = event;\n const { changes = [] } = body.push;\n changes\n .filter(this.isNewBranch)\n .forEach(change => {\n const data = {\n ...body,\n change,\n };\n const meta = this.generateMeta({\n headers,\n change,\n });\n this.$emit(data, meta);\n });\n },\n },\n};\n\n\n<|start_filename|>components/shopify/sources/new-cancelled-order/new-cancelled-order.js<|end_filename|>\nconst shopify = require(\"../../shopify.app.js\");\n\nmodule.exports = {\n key: \"shopify-new-cancelled-order\",\n name: \"New Cancelled Order\",\n description: \"Emits an event each time a new order is cancelled.\",\n version: \"0.0.3\",\n dedupe: \"unique\",\n props: {\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n shopify,\n },\n methods: {\n _getLastUpdatedDate() {\n return this.db.get(\"last_updated_at\") || null;\n },\n _setLastUpdatedDate(date) {\n this.db.set(\"last_updated_at\", date);\n },\n },\n async run() {\n const lastUpdatedAt = this._getLastUpdatedDate();\n let results = await this.shopify.getOrders(\n \"any\",\n true,\n null,\n lastUpdatedAt,\n \"cancelled\",\n );\n\n for (const order of results) {\n this.$emit(order, {\n id: order.id,\n summary: `Order cancelled: ${order.name}`,\n ts: Date.parse(order.updated_at),\n });\n }\n\n if (results[results.length - 1]) {\n this._setLastUpdatedDate(results[results.length - 1].updated_at);\n }\n },\n};\n\n\n<|start_filename|>components/eventbrite/actions/get-event-summary/get-event-summary.js<|end_filename|>\nconst eventbrite = require(\"../../eventbrite.app\");\n\nmodule.exports = {\n key: \"eventbrite-get-event-summary\",\n name: \"Get Event Summary\",\n description: \"Get event summary for a specified event.\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n eventbrite,\n eventId: {\n propDefinition: [\n eventbrite,\n \"eventId\",\n ],\n },\n },\n async run() {\n const { summary } = await this.eventbrite.getEvent(this.eventId);\n return summary;\n },\n};\n\n\n<|start_filename|>components/slack/actions/remove_star/remove_star.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-remove-star\",\n name: \"Remove Star\",\n description: \"Remove a star from an item on behalf of the authenticated user\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n optional: true,\n },\n timestamp: {\n propDefinition: [\n slack,\n \"timestamp\",\n ],\n optional: true,\n },\n file: {\n propDefinition: [\n slack,\n \"file\",\n ],\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().stars.remove({\n conversation: this.conversation,\n timestamp: this.timestamp,\n file: this.file,\n });\n },\n};\n\n\n<|start_filename|>components/zoom/zoom.app.js<|end_filename|>\nmodule.exports = {\n type: \"app\",\n app: \"zoom\",\n};\n\n<|start_filename|>components/bandwidth/sources/new-incoming-sms/new-incoming-sms.js<|end_filename|>\nconst bandwidth = require(\"../../bandwidth.app\");\n\nmodule.exports = {\n name: \"New Incoming SMS\",\n description: \"Emits an event each time a `message-received` event is received at the source url\",\n key: \"bandwidth-new-incoming-sms\",\n version: \"1.1.0\",\n props: {\n bandwidth,\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n\n async run(event) {\n const messageBody = event.body[0];\n this.http.respond({\n status: 204,\n });\n\n if (messageBody.message.direction == \"in\") {\n this.$emit(messageBody, {\n summary: \"Message Received\",\n id: messageBody.message.id,\n ts: +new Date(messageBody.time),\n });\n }\n },\n};\n\n\n<|start_filename|>components/webflow/sources/new-form-submission/new-form-submission.js<|end_filename|>\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-new-form-submission\",\n name: \"New Form Submission (Instant)\",\n description: \"Emit an event when a new form is submitted\",\n version: \"0.0.1\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"form_submission\";\n },\n generateMeta(data) {\n const {\n _id: id,\n d: date,\n } = data;\n const summary = \"New form submission\";\n const ts = Date.parse(date);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>examples/timer-interface-cron.js<|end_filename|>\nmodule.exports = {\n name: \"Cron Example\",\n version: \"0.1\",\n props: {\n timer: {\n type: \"$.interface.timer\",\n default: {\n cron: \"0 0 * * *\", // Run job once a day\n },\n },\n },\n async run() {\n console.log(\"hello world!\");\n },\n};\n\n\n<|start_filename|>components/github/sources/common-polling.js<|end_filename|>\nconst github = require(\"../github.app.js\");\n\nmodule.exports = {\n props: {\n github,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 5,\n },\n },\n db: \"$.service.db\",\n },\n methods: {\n async getFilteredNotifications(params, reason) {\n const notifications = await this.github.getNotifications(params);\n return notifications.filter(\n (notification) => notification.reason === reason\n );\n },\n },\n};\n\n<|start_filename|>components/twist/sources/new-channel/new-channel.js<|end_filename|>\nconst twist = require(\"../../twist.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Channel (Instant)\",\n version: \"0.0.1\",\n key: \"twist-new-channel\",\n description: \"Emits an event for any new channel added in a workspace\",\n methods: {\n getHookActivationData() {\n return {\n target_url: this.http.endpoint,\n event: \"channel_added\",\n workspace_id: this.workspace,\n };\n },\n getMeta(body) {\n const { id, name, created_ts } = body;\n return {\n id,\n summary: name,\n ts: Date.parse(created_ts),\n };\n },\n },\n};\n\n<|start_filename|>components/cliniko/package.json<|end_filename|>\n{\n \"name\": \"@pipedream/cliniko\",\n \"version\": \"0.0.1\",\n \"description\": \"Pipedream Cliniko Components\",\n \"main\": \"cliniko.app.js\",\n \"keywords\": [\n \"pipedream\",\n \"cliniko\"\n ],\n \"homepage\": \"https://pipedream.com/apps/cliniko\",\n \"author\": \" <> (https://ageuphealth.com.au/)\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@pipedreamhq/platform\": \"^0.8.1\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n\n\n<|start_filename|>components/github/sources/new-repository/new-repository.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\n\nmodule.exports = {\n ...common,\n key: \"github-new-repository\",\n name: \"New Repository\",\n description: \"Emit new events when new repositories are created\",\n version: \"0.0.4\",\n type: \"source\",\n dedupe: \"last\",\n methods: {\n generateMeta(data) {\n const ts = new Date(data.created_at).getTime();\n return {\n id: data.id,\n summary: data.full_name,\n ts,\n };\n },\n },\n async run() {\n let since = this.db.get(\"since\");\n\n const repos = await this.github.getRepos({\n sort: \"created\",\n direction: \"asc\",\n since,\n });\n\n let maxDate = since;\n for (const repo of repos) {\n if (!maxDate || new Date(repo.created_at) > new Date(maxDate)) {\n maxDate = repo.created_at;\n }\n const meta = this.generateMeta(repo);\n this.$emit(repo, meta);\n since = repo.created_at;\n }\n\n this.db.set(\"since\", since);\n },\n};\n\n\n<|start_filename|>components/stack_exchange/sources/new-question-for-keywords/new-question-for-keywords.js<|end_filename|>\nconst stack_exchange = require('../../stack_exchange.app');\n\nmodule.exports = {\n key: 'stack_exchange-new-question-for-specific-keywords',\n name: 'New Question for Specific Keywords',\n description:\n 'Emits an event when a new question is posted and related to a set of specific keywords',\n version: '0.0.2',\n dedupe: 'unique',\n props: {\n stack_exchange,\n db: '$.service.db',\n siteId: {propDefinition: [stack_exchange, 'siteId']},\n keywords: {propDefinition: [stack_exchange, 'keywords']},\n timer: {\n type: '$.interface.timer',\n default: {\n intervalSeconds: 60 * 15, // 15 minutes\n },\n },\n },\n hooks: {\n async activate() {\n const fromDate = this._getCurrentEpoch();\n this.db.set('fromDate', fromDate);\n },\n },\n methods: {\n _getCurrentEpoch() {\n // The StackExchange API works with Unix epochs in seconds.\n return Math.floor(Date.now() / 1000);\n },\n generateMeta(data) {\n const {question_id: id, creation_date: ts, title} = data;\n const summary = `New question: ${title}`;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run() {\n const fromDate = this.db.get('fromDate');\n const toDate = this._getCurrentEpoch();\n const keywordsQuery = this.keywords.join(',');\n const searchParams = {\n fromDate,\n toDate,\n sort: 'creation',\n order: 'asc',\n closed: false,\n site: this.siteId,\n q: keywordsQuery,\n };\n\n const items = this.stack_exchange.advancedSearch(searchParams);\n for await (const item of items) {\n const meta = this.generateMeta(item);\n this.$emit(item, meta);\n }\n\n this.db.set('fromDate', toDate);\n },\n};\n\n\n<|start_filename|>components/twist/sources/new-event/new-event.js<|end_filename|>\nconst twist = require(\"../../twist.app.js\");\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Event (Instant)\",\n version: \"0.0.1\",\n key: \"twist-new-event\",\n description: \"Emits an event for any new updates in a workspace\",\n props: {\n ...common.props,\n channel: {\n propDefinition: [twist, \"channel\", (c) => ({ workspace: c.workspace })],\n },\n thread: {\n propDefinition: [twist, \"thread\", (c) => ({ channel: c.channel })],\n },\n eventType: {\n propDefinition: [twist, \"eventType\"],\n },\n },\n methods: {\n getHookActivationData() {\n return {\n target_url: this.http.endpoint,\n event: this.eventType,\n workspace_id: this.workspace,\n channel_id: this.channel,\n thread_id: this.thread,\n };\n },\n getMeta(body) {\n const { name, id, created } = body;\n return {\n id,\n summary: name || \"New Event\",\n ts: Date.parse(created),\n };\n },\n },\n};\n\n<|start_filename|>components/todoist/sources/common-task.js<|end_filename|>\nconst todoist = require(\"../todoist.app.js\");\nconst common = require(\"./common.js\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n selectProjects: { propDefinition: [todoist, \"selectProjects\"] },\n },\n methods: {\n ...common.methods,\n isElementRelevant() {\n return true;\n },\n },\n async run(event) {\n const syncResult = await this.todoist.syncItems(this.db);\n\n Object.values(syncResult)\n .filter(Array.isArray)\n .flat()\n .filter(this.isElementRelevant)\n .filter((element) =>\n this.todoist.isProjectInList(element.project_id, this.selectProjects)\n )\n .forEach((element) => {\n element.summary = `Task: ${element.id}`;\n const meta = this.generateMeta(element);\n this.$emit(element, meta);\n });\n },\n};\n\n<|start_filename|>components/mercury/mercury.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"mercury\",\n propDefinitions: {\n account: {\n type: \"string\",\n label: \"Account\",\n async options() {\n const results = await this.getAccounts();\n const options = results.map((result) => {\n const { name, id } = result;\n return { label: name, value: id };\n });\n return options;\n },\n },\n },\n methods: {\n _getBaseURL() {\n return \"https://backend.mercury.com/api/v1\";\n },\n _getHeaders() {\n return {\n Authorization: `Bearer ${this.$auth.api_key}`,\n \"Content-Type\": \"application/json\",\n };\n },\n async _makeRequest(method, endpoint, params = null) {\n const config = {\n method,\n url: `${this._getBaseURL()}${endpoint}`,\n headers: this._getHeaders(),\n params,\n };\n return (await axios(config)).data;\n },\n daysAgo(days) {\n const daysAgo = new Date();\n daysAgo.setDate(daysAgo.getDate() - days);\n return daysAgo;\n },\n async getAccounts() {\n return (await this._makeRequest(\"GET\", \"/accounts\")).accounts;\n },\n async getTransactions(accountId, params) {\n return await this._makeRequest(\n \"GET\",\n `/account/${accountId}/transactions`,\n params\n );\n },\n },\n};\n\n<|start_filename|>components/slack/actions/list-channels/list-channels.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-list-channels\",\n name: \"List Channels\",\n description: \"Return a list of all channels in a workspace\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n },\n async run() {\n return await this.slack.sdk().conversations.list();\n },\n};\n\n\n<|start_filename|>docs/docs/.vuepress/enhanceApp.js<|end_filename|>\nimport VueGtm from \"vue-gtm\";\n\nexport default ({\n Vue, // the version of Vue being used in the VuePress app\n options, // the options for the root Vue instance\n router, // the router instance for the app\n siteData, // site metadata\n}) => {\n if (typeof window !== \"undefined\") {\n Vue.use(VueGtm, {\n id: \"GTM-KBDH3DB\",\n enabled: true,\n debug: false,\n vueRouter: router,\n });\n }\n\n router.addRoutes([\n { path: \"/cron\", redirect: \"/workflows/steps/triggers\" },\n { path: \"/notebook\", redirect: \"/workflows/steps\" },\n { path: \"/workflows/fork\", redirect: \"/workflows/copy\" },\n { path: \"/notebook/fork\", redirect: \"/workflows/copy\" },\n { path: \"/notebook/inspector/\", redirect: \"/workflows/events/inspect/\" },\n { path: \"/notebook/destinations/s3/\", redirect: \"/destinations/s3/\" },\n { path: \"/notebook/destinations/sse/\", redirect: \"/destinations/sse/\" },\n {\n path: \"/notebook/destinations/snowflake/\",\n redirect: \"/destinations/snowflake/\",\n },\n { path: \"/notebook/destinations/http/\", redirect: \"/destinations/http/\" },\n { path: \"/notebook/destinations/email/\", redirect: \"/destinations/email/\" },\n { path: \"/notebook/destinations/\", redirect: \"/destinations/\" },\n { path: \"/notebook/code/\", redirect: \"/workflows/steps/code/\" },\n {\n path: \"/notebook/observability/\",\n redirect: \"/workflows/events/inspect/\",\n },\n { path: \"/notebook/actions/\", redirect: \"/workflows/steps/actions/\" },\n { path: \"/notebook/sources/\", redirect: \"/workflows/steps/triggers/\" },\n { path: \"/notebook/sql/\", redirect: \"/destinations/triggers/\" },\n { path: \"/what-is-pipedream/\", redirect: \"/\" },\n {\n path: \"/docs/apps/all-apps\",\n redirect: \"https://pipedream.com/apps\",\n },\n ]);\n};\n\n\n<|start_filename|>interfaces/timer/examples/code.js<|end_filename|>\nconsole.log(\"Node code\");\n\n\n<|start_filename|>components/webflow/sources/new-ecomm-order/new-ecomm-order.js<|end_filename|>\nconst common = require(\"../common\");\n\nmodule.exports = {\n ...common,\n key: \"webflow-new-ecomm-order\",\n name: \"New E-commerce Order (Instant)\",\n description: \"Emit an event when an e-commerce order is created\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getWebhookTriggerType() {\n return \"ecomm_new_order\";\n },\n generateMeta(data) {\n const {\n acceptedOn,\n orderId: id,\n } = data;\n const summary = `New e-comm order: ${id}`;\n const ts = Date.parse(acceptedOn);\n return {\n id,\n summary,\n ts,\n };\n },\n },\n};\n\n\n<|start_filename|>components/calendly/calendly.app.js<|end_filename|>\nconst axios = require(\"axios\");\n\nmodule.exports = {\n type: \"app\",\n app: \"calendly\",\n methods: {\n _getAuthHeader() {\n return {\n \"X-TOKEN\": this.$auth.api_key,\n };\n },\n _getBaseURL() {\n return \"https://calendly.com/api/v1\";\n },\n monthAgo() {\n const now = new Date();\n const monthAgo = new Date(now.getTime());\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return Date.parse(monthAgo);\n },\n async getEventTypes() {\n return (\n await axios.get(`${this._getBaseURL()}/users/me/event_types`, {\n headers: this._getAuthHeader(),\n })\n ).data.data;\n },\n async getEvents() {\n return (\n await axios.get(`${this._getBaseURL()}/users/me/events`, {\n headers: this._getAuthHeader(),\n })\n ).data.data;\n },\n async createHook(data) {\n const config = {\n method: \"post\",\n url: `${this._getBaseURL()}/hooks`,\n headers: this._getAuthHeader(),\n data,\n };\n return await axios(config);\n },\n async deleteHook(hookId) {\n const config = {\n method: \"delete\",\n url: `${this._getBaseURL()}/hooks/${hookId}`,\n headers: this._getAuthHeader(),\n };\n await axios(config);\n },\n },\n};\n\n<|start_filename|>components/slack/actions/create-channel/create-channel.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-create-channel\",\n name: \"Create a Channel\",\n description: \"Create a new channel\",\n version: \"0.0.2\",\n type: \"action\",\n props: {\n slack,\n channelName: {\n label: \"Channel name\",\n description: \"Name of the public or private channel to create\",\n type: \"string\",\n },\n isPrivate: {\n label: \"Is private?\",\n type: \"boolean\",\n description: \"`false` by default. Pass `true` to create a private channel instead of a public one.\",\n default: false,\n optional: true,\n },\n },\n async run() {\n return await this.slack.sdk().conversations.create({\n name: this.channelName,\n is_private: this.isPrivate,\n });\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/campaign-starts-sending/campaign-starts-sending.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"Campaign Starts Sending (Instant)\",\n key: \"activecampaign-campaign-starts-sending\",\n description: \"Emits an event each time a campaign starts sending.\",\n version: \"0.0.1\",\n methods: {\n ...common.methods,\n getEvents() {\n return [\"sent\"];\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: body[\"campaign[id]\"],\n summary: body[\"campaign[name]\"],\n ts\n };\n },\n },\n};\n\n<|start_filename|>components/bitbucket/sources/new-commit/new-commit.js<|end_filename|>\nconst get = require(\"lodash/get\");\nconst common = require(\"../../common\");\nconst { bitbucket } = common.props;\n\nconst EVENT_SOURCE_NAME = \"New Commit (Instant)\";\n\nmodule.exports = {\n ...common,\n name: EVENT_SOURCE_NAME,\n key: \"bitbucket-new-commit\",\n description: \"Emits an event when a new commit is pushed to a branch\",\n version: \"0.0.2\",\n props: {\n ...common.props,\n repositoryId: {\n propDefinition: [\n bitbucket,\n \"repositoryId\",\n c => ({ workspaceId: c.workspaceId }),\n ],\n },\n branchName: {\n propDefinition: [\n bitbucket,\n \"branchName\",\n c => ({\n workspaceId: c.workspaceId,\n repositoryId: c.repositoryId,\n }),\n ],\n },\n },\n methods: {\n ...common.methods,\n getEventSourceName() {\n return EVENT_SOURCE_NAME;\n },\n getHookEvents() {\n return [\n \"repo:push\",\n ];\n },\n getHookPathProps() {\n return {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n };\n },\n isEventForThisBranch(change) {\n const expectedChangeTypes = new Set([\n \"branch\",\n \"named_branch\",\n ]);\n if (change.new) {\n const { name, type } = change.new;\n return name === this.branchName && expectedChangeTypes.has(type);\n }\n return false;\n },\n doesEventContainNewCommits(change) {\n return change.commits && change.commits.length > 0;\n },\n getBaseCommitHash(change) {\n return get(change, [\n \"old\",\n \"target\",\n \"hash\",\n ]);\n },\n generateMeta(commit) {\n const {\n hash,\n message,\n date,\n } = commit;\n const commitTitle = message\n .split(\"\\n\")\n .shift();\n const summary = `New commit: ${commitTitle} (${hash})`;\n const ts = +new Date(date);\n return {\n id: hash,\n summary,\n ts,\n };\n },\n async processEvent(event) {\n const { body } = event;\n const { changes = [] } = body.push;\n\n // Push events can be for different branches, tags and\n // causes. We need to make sure that we're only processing events\n // that are related to new commits in the particular branch\n // that the user indicated.\n const newCommitsInThisBranch = changes\n .filter(this.isEventForThisBranch)\n .filter(this.doesEventContainNewCommits);\n const isEventRelevant = newCommitsInThisBranch.length > 0;\n if (!isEventRelevant) {\n return;\n }\n\n // BitBucket events provide information about the state\n // of an entity before it was changed.\n // Based on that, we can extract the HEAD commit of\n // the relevant branch before new commits were pushed to it.\n const lastProcessedCommitHash = newCommitsInThisBranch\n .map(this.getBaseCommitHash)\n .shift();\n\n // The event payload contains some commits but it's not exhaustive,\n // so we need to explicitly fetch them just in case.\n const opts = {\n workspaceId: this.workspaceId,\n repositoryId: this.repositoryId,\n branchName: this.branchName,\n lastProcessedCommitHash,\n };\n const allCommits = this.bitbucket.getCommits(opts);\n\n // We need to collect all the relevant commits, sort\n // them in reverse order (since the BitBucket API sorts them\n // from most to least recent) and emit an event for each\n // one of them.\n const allCommitsCollected = [];\n for await (const commit of allCommits) {\n allCommitsCollected.push(commit);\n };\n\n allCommitsCollected.reverse().forEach(commit => {\n const meta = this.generateMeta(commit)\n this.$emit(commit, meta);\n });\n },\n },\n};\n\n\n<|start_filename|>components/twitter/sources/watch-retweets-of-user-tweet/watch-retweets-of-user-tweet.js<|end_filename|>\nconst base = require(\"../common/tweets\");\nconst baseRetweets = require(\"../watch-retweets-of-my-tweet/watch-retweets-of-my-tweet\");\n\nmodule.exports = {\n ...baseRetweets,\n key: \"twitter-watch-retweets-of-user-tweet\",\n name: \"Watch Retweets of User Tweet\",\n description: \"Emit an event when a specific Tweet from a user is retweeted\",\n version: \"0.0.1\",\n props: {\n ...base.props,\n screen_name: {\n propDefinition: [\n base.props.twitter,\n \"screen_name\",\n ],\n },\n tweetId: {\n type: \"string\",\n label: \"Tweet\",\n description: \"The Tweet to watch for retweets\",\n options(context) {\n return this.tweetIdOptions(context);\n },\n },\n },\n methods: {\n ...baseRetweets.methods,\n getScreenName() {\n return this.screen_name;\n },\n },\n};\n\n\n<|start_filename|>components/activecampaign/sources/new-event/new-event.js<|end_filename|>\nconst activecampaign = require(\"../../activecampaign.app.js\");\nconst common = require(\"../common-webhook.js\");\n\nmodule.exports = {\n ...common,\n name: \"New Event (Instant)\",\n key: \"activecampaign-new-event\",\n description:\n \"Emits an event for the specified event type from ActiveCampaign.\",\n version: \"0.0.1\",\n props: {\n ...common.props,\n eventType: { propDefinition: [activecampaign, \"eventType\"] },\n },\n methods: {\n ...common.methods,\n getEvents() {\n return [this.eventType];\n },\n getMeta(body) {\n const { date_time: dateTimeIso } = body;\n const ts = Date.parse(dateTimeIso);\n return {\n id: body.date_time,\n summary: `${body.type} initiated by ${body.initiated_by}`,\n ts\n };\n },\n },\n};\n\n<|start_filename|>examples/http.js<|end_filename|>\nmodule.exports = {\n name: \"HTTP Example\",\n version: \"0.0.1\",\n props: {\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n },\n async run(event) {\n this.http.respond({\n status: 200,\n body: {\n \"msg\": \"hello world!\",\n },\n headers: {\n \"content-type\": \"application/json\",\n },\n });\n console.log(event);\n },\n};\n\n\n<|start_filename|>components/calendly/sources/new-event-type/new-event-type.js<|end_filename|>\nconst common = require(\"../common-polling.js\");\nconst get = require(\"lodash/get\");\n\nmodule.exports = {\n ...common,\n key: \"calendly-new-event-type\",\n name: \"New Event Type\",\n description: \"Emits an event for each new event type\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n methods: {\n ...common.methods,\n async getResults() {\n return await this.calendly.getEventTypes();\n },\n isRelevant(eventType, lastEvent) {\n const createdAt = Date.parse(get(eventType, \"attributes.created_at\"));\n return createdAt > lastEvent;\n },\n generateMeta({ id, attributes }) {\n return {\n id,\n summary: attributes.name,\n ts: Date.now(),\n };\n },\n },\n};\n\n<|start_filename|>components/twitter/actions/retweet/retweet.js<|end_filename|>\nconst twitter = require(\"../../twitter.app.js\");\n\nmodule.exports = {\n key: \"twitter-retweet\",\n name: \"Retweet a tweet\",\n description: \"Retweets a specific tweet by ID\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n twitter,\n tweetID: {\n propDefinition: [\n twitter,\n \"tweetID\",\n ],\n description: \"The numerical ID of the tweet you'd like to retweet\",\n },\n },\n async run() {\n return await this.twitter.retweet({\n tweetID: this.tweetID,\n });\n },\n};\n\n\n<|start_filename|>components/twitch/sources/common-polling.js<|end_filename|>\nconst common = require(\"./common.js\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n },\n methods: {\n ...common.methods,\n getLastEvent(lastEvent) {\n return lastEvent ? new Date(lastEvent) : new Date();\n },\n },\n};\n\n<|start_filename|>components/datadog/sources/new-monitor-event/new-monitor-event.js<|end_filename|>\nconst datadog = require(\"../../datadog.app\");\nconst payloadFormat = require(\"../payload-format\");\n\nmodule.exports = {\n key: \"datadog-new-monitor-event\",\n name: \"New Monitor Event (Instant)\",\n description: \"Captures events emitted by a Datadog monitor\",\n dedupe: \"unique\",\n version: \"0.0.1\",\n props: {\n datadog,\n db: \"$.service.db\",\n http: {\n type: \"$.interface.http\",\n customResponse: true,\n },\n monitors: {\n type: \"string[]\",\n label: \"Monitors\",\n description: \"The monitors to observe for notifications\",\n optional: true,\n async options(context) {\n const { page } = context;\n const pageSize = 10;\n const monitors = await this.datadog.listMonitors(page, pageSize);\n const options = monitors.map(monitor => ({\n label: monitor.name,\n value: monitor.id,\n }));\n\n return {\n options,\n };\n },\n },\n },\n hooks: {\n async activate() {\n const {\n name: webhookName,\n secretKey: webhookSecretKey,\n } = await this.datadog.createWebhook(\n this.http.endpoint,\n payloadFormat,\n );\n\n console.log(`Created webhook \"${webhookName}\"`);\n this.db.set(\"webhookName\", webhookName);\n this.db.set(\"webhookSecretKey\", webhookSecretKey);\n\n await Promise.all(\n this.monitors.map(monitorId =>\n this.datadog.addWebhookNotification(webhookName, monitorId)\n )\n );\n },\n async deactivate() {\n const webhookName = this.db.get(\"webhookName\");\n await this.datadog.removeWebhookNotifications(webhookName);\n await this.datadog.deleteWebhook(webhookName);\n },\n },\n methods: {\n generateMeta(data) {\n const {\n id,\n eventTitle: summary,\n date: ts,\n } = data;\n return {\n id,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const webhookSecretKey = this.db.get(\"webhookSecretKey\");\n if (!this.datadog.isValidSource(event, webhookSecretKey)) {\n console.log(`Skipping event from unrecognized source`);\n this.http.respond({\n status: 404,\n });\n return;\n }\n\n // Acknowledge the event back to Datadog.\n this.http.respond({\n status: 200,\n });\n\n const { body } = event;\n const meta = this.generateMeta(body);\n this.$emit(body, meta);\n },\n};\n\n\n<|start_filename|>components/bandwidth/actions/send-sms/send-sms.js<|end_filename|>\nconst bandwidth = require(\"../../bandwidth.app.js\");\n\nmodule.exports = {\n key: \"bandwidth-send-sms\",\n name: \"Send SMS\",\n description: \"Send an SMS message using Bandwidth's Messaging API\",\n type: \"action\",\n version: \"1.0.0\",\n props: {\n bandwidth,\n messageTo: {\n propDefinition: [\n bandwidth,\n \"messageTo\",\n ],\n },\n from: {\n propDefinition: [\n bandwidth,\n \"from\",\n ],\n },\n message: {\n propDefinition: [\n bandwidth,\n \"message\",\n ],\n },\n messagingApplicationId: {\n propDefinition: [\n bandwidth,\n \"messagingApplicationId\",\n ],\n },\n },\n async run () {\n const response = await this.bandwidth.sendSms(\n this.messageTo,\n this.from,\n this.message,\n this.messagingApplicationId,\n );\n console.log(\"Status Code:\", response.statusCode);\n console.log(\"Message ID:\", response.result.id);\n return response;\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-task/new-task.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-task\",\n name: \"New Calendar Task\",\n description: \"Emits an event for each new task added.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(task) {\n const { id, name, eventType } = task;\n return {\n id,\n summary: `${name} - ${eventType}`,\n ts: Date.now(),\n };\n },\n },\n async run(event) {\n const yearFromNow = new Date();\n yearFromNow.setFullYear(yearFromNow.getFullYear() + 1);\n\n const results = await this.hubspot.getCalendarTasks(yearFromNow.getTime());\n for (const task of results) {\n const meta = this.generateMeta(task);\n this.$emit(task, meta);\n }\n },\n};\n\n<|start_filename|>components/google_drive/google_drive.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst { google } = require(\"googleapis\");\nconst { uuid } = require(\"uuidv4\");\n\nconst {\n GOOGLE_DRIVE_UPDATE_TYPES,\n MY_DRIVE_VALUE,\n WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS,\n} = require(\"./constants\");\n\nconst {\n isMyDrive,\n getDriveId,\n} = require(\"./utils\");\n\nmodule.exports = {\n type: \"app\",\n app: \"google_drive\",\n propDefinitions: {\n watchedDrive: {\n type: \"string\",\n label: \"Drive\",\n description: \"The drive you want to watch for changes\",\n async options({ prevContext }) {\n const { nextPageToken } = prevContext;\n return this._listDriveOptions(nextPageToken);\n },\n },\n updateTypes: {\n type: \"string[]\",\n label: \"Types of updates\",\n description:\n `The types of updates you want to watch for on these files. \n [See Google's docs]\n (https://developers.google.com/drive/api/v3/push#understanding-drive-api-notification-events).`,\n // https://developers.google.com/drive/api/v3/push#understanding-drive-api-notification-events\n default: GOOGLE_DRIVE_UPDATE_TYPES,\n options: GOOGLE_DRIVE_UPDATE_TYPES,\n },\n watchForPropertiesChanges: {\n type: \"boolean\",\n label: \"Watch for changes to file properties\",\n description:\n `Watch for changes to [file properties](https://developers.google.com/drive/api/v3/properties)\n in addition to changes to content. **Defaults to \\`false\\`, watching for only changes to content**.`,\n optional: true,\n default: false,\n },\n },\n methods: {\n // Static methods\n isMyDrive,\n getDriveId,\n\n // Returns a drive object authenticated with the user's access token\n drive() {\n const auth = new google.auth.OAuth2();\n auth.setCredentials({\n access_token: this.$auth.oauth_access_token,\n });\n return google.drive({\n version: \"v3\",\n auth,\n });\n },\n // Google's push notifications provide a URL to the resource that changed,\n // which we can use to fetch the file's metadata. So we use axios here\n // (vs. the Node client) to get that.\n async getFileMetadata(url) {\n return (\n await axios({\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${this.$auth.oauth_access_token}`,\n },\n url,\n })\n ).data;\n },\n /**\n * This method yields a list of changes that occurred to files in a\n * particular Google Drive. It is a wrapper around [the `drive.changes.list`\n * API](https://bit.ly/2SGb5M2) but defined as a generator to enable lazy\n * loading of multiple pages.\n *\n * @typedef {object} ChangesPage\n * @property {object[]} changedFiles - the list of file changes, as [defined\n * by the API](https://bit.ly/3h7WeUa). This list filters out any result\n * that is not a proper object.\n * @property {string} nextPageToken - the page token [returned by the last API\n * call](https://bit.ly/3h7WeUa). **Note that this generator keeps track of\n * this token internally, and the purpose of this value is to provide a way\n * for consumers of this method to handle checkpoints in case of an\n * unexpected halt.**\n *\n * @param {string} [pageToken] - the token for continuing a previous list\n * request on the next page. This must be a token that was previously\n * returned by this same method.\n * @param {string} [driveId] - the shared drive from which changes are\n * returned\n * @yields\n * @type {ChangesPage}\n */\n async *listChanges(pageToken, driveId) {\n const drive = this.drive();\n let changeRequest = {\n pageToken,\n pageSize: 1000,\n };\n\n // As with many of the methods for Google Drive, we must\n // pass a request of a different shape when we're requesting\n // changes for My Drive (null driveId) vs. a shared drive\n if (driveId) {\n changeRequest = {\n ...changeRequest,\n driveId,\n includeItemsFromAllDrives: true,\n supportsAllDrives: true,\n };\n }\n\n while (true) {\n const { data } = await drive.changes.list(changeRequest);\n const {\n changes = [],\n newStartPageToken,\n nextPageToken,\n } = data;\n\n // Some changes do not include an associated file object. Return only\n // those that do\n const changedFiles = changes\n .map((change) => change.file)\n .filter((f) => typeof f === \"object\");\n\n yield {\n changedFiles,\n nextPageToken: nextPageToken || newStartPageToken,\n };\n\n if (newStartPageToken) {\n // The 'newStartPageToken' field is only returned as part of the last\n // page from the API response: https://bit.ly/3jBEvWV\n break;\n }\n\n changeRequest.pageToken = nextPageToken;\n }\n },\n async getPageToken(driveId) {\n const drive = this.drive();\n const request = driveId\n ? {\n driveId,\n supportsAllDrives: true,\n }\n : {};\n const { data } = await drive.changes.getStartPageToken(request);\n return data.startPageToken;\n },\n checkHeaders(headers, subscription, channelID) {\n if (\n !headers[\"x-goog-resource-state\"] ||\n !headers[\"x-goog-resource-id\"] ||\n !headers[\"x-goog-resource-uri\"] ||\n !headers[\"x-goog-message-number\"]\n ) {\n console.log(\"Request missing necessary headers: \", headers);\n return false;\n }\n\n const incomingChannelID = headers[\"x-goog-channel-id\"];\n if (incomingChannelID !== channelID) {\n console.log(\n `Channel ID of ${incomingChannelID} not equal to deployed component channel of ${channelID}`,\n );\n return false;\n }\n\n if (headers[\"x-goog-resource-id\"] !== subscription.resourceId) {\n console.log(\n `Resource ID of ${subscription.resourceId} not currently being tracked. Exiting`,\n );\n return false;\n }\n return true;\n },\n\n /**\n * A utility method around [the `drive.drives.list`\n * API](https://bit.ly/3AiWE1x) but scoped to a specific page of the API\n * response\n *\n * @typedef {object} DriveListPage - an object representing a page that\n * lists GDrive drives, as defined by [the API](https://bit.ly/3jwxbvy)\n *\n * @param {string} [pageToken] - the page token for the next page of shared\n * drives\n * @param {number} [pageSize=10] - the number of records to retrieve as part\n * of the page\n *\n * @returns\n * @type {DriveListPage}\n */\n async listDrivesInPage(pageToken, pageSize = 10) {\n const drive = this.drive();\n const { data } = await drive.drives.list({\n pageSize,\n pageToken,\n });\n return data;\n },\n /**\n * This method yields the visible GDrive drives of the authenticated\n * account. It is a wrapper around [the `drive.drives.list`\n * API](https://bit.ly/3AiWE1x) but defined as a generator to enable lazy\n * loading of multiple pages.\n *\n * @typedef {object} Drive - an object representing a GDrive drive, as\n * defined by [the API](https://bit.ly/3ycifGY)\n *\n * @yields\n * @type {Drive}\n */\n async *listDrives() {\n let pageToken;\n\n while (true) {\n const {\n drives = [],\n nextPageToken,\n } = await this.listDrivesInPage(pageToken);\n\n for (const drive in drives) {\n yield drive;\n }\n\n if (!nextPageToken) {\n // The 'nextPageToken' field is only returned when there's still\n // comments to be retrieved (i.e. when the end of the list has not\n // been reached yet): https://bit.ly/3jwxbvy\n break;\n }\n\n pageToken = nextPageToken;\n }\n },\n async _listDriveOptions(pageToken) {\n const {\n drives,\n nextPageToken,\n } = await this.listDrivesInPage(pageToken);\n\n // \"My Drive\" isn't returned from the list of drives, so we add it to the\n // list and assign it a static ID that we can refer to when we need. We\n // only do this during the first page of options (i.e. when `pageToken` is\n // undefined).\n const options = pageToken !== undefined\n ? []\n : [\n {\n label: \"My Drive\",\n value: MY_DRIVE_VALUE,\n },\n ];\n for (const d of drives) {\n options.push({\n label: d.name,\n value: d.id,\n });\n }\n return {\n options,\n context: {\n nextPageToken,\n },\n };\n },\n /**\n * A utility method around [the `drive.files.list`\n * API](https://bit.ly/366CFVN) but scoped to a specific page of the API\n * response\n *\n * @typedef {object} FileListPage - an object representing a page that lists\n * GDrive files, as defined by [the API](https://bit.ly/3xdbAwc)\n *\n * @param {string} [pageToken] - the page token for the next page of shared\n * drives\n * @param {object} [extraOpts = {}] - an object containing extra/optional\n * parameters to be fed to the GDrive API call, as defined in [the API\n * docs](https://bit.ly/3AnQDR1)\n *\n * @returns\n * @type {FileListPage}\n */\n async listFilesInPage(pageToken, extraOpts = {}) {\n const drive = this.drive();\n const { data } = await drive.files.list({\n pageToken,\n ...extraOpts,\n });\n return data;\n },\n /**\n * A utility method around [the `drive.files.list`\n * API](https://bit.ly/366CFVN) but scoped to a specific page of the API\n * response, and intended to be used as a way for prop definitions to return\n * a list of options.\n *\n * @param {string} [pageToken] - the page token for the next page of shared\n * drives\n * @param {object} [extraOpts = {}] - an object containing extra/optional\n * parameters to be fed to the GDrive API call, as defined in [the API\n * docs](https://bit.ly/3AnQDR1)\n *\n * @returns a list of prop options\n */\n async listFilesOptions(pageToken, extraOpts = {}) {\n const {\n files,\n nextPageToken,\n } = await this.listFilesInPage(pageToken, extraOpts);\n const options = files.map((file) => ({\n label: file.name,\n value: file.id,\n }));\n return {\n options,\n context: {\n nextPageToken,\n },\n };\n },\n /**\n * Method returns a list of folder options\n *\n * @param {string} [pageToken] - the page token for the next page of shared\n * drives\n * @param {object} [opts = {}] - an object containing extra/optional\n * parameters to be fed to the GDrive API call, as defined in [the API\n * docs](https://bit.ly/3AnQDR1)\n *\n * @returns a list of prop options\n */\n async listFolderOptions(pageToken, opts = {}) {\n return await this.listFilesOptions(pageToken, {\n ...opts,\n q: \"mimeType = 'application/vnd.google-apps.folder'\",\n });\n },\n /**\n * Creates a new file in a drive\n *\n * @param {object} [opts = {}] - an object containing parameters to be fed to the GDrive\n * API call as defined in [the API docs](https://developers.google.com/drive/api/v3/reference/files/create)\n *\n * @returns a files resource\n */\n async createFile(opts = {}) {\n const drive = this.drive();\n return (await drive.files.create(opts)).data;\n },\n /**\n * This method yields comments made to a particular GDrive file. It is a\n * wrapper around [the `drive.comments.list` API](https://bit.ly/2UjYajv)\n * but defined as a generator to enable lazy loading of multiple pages.\n *\n * @typedef {object} Comment - an object representing a comment in a GDrive\n * file, as defined by [the API](https://bit.ly/3htAd12)\n *\n * @yields\n * @type {Comment}\n */\n async *listComments(fileId, startModifiedTime = null) {\n const drive = this.drive();\n const opts = {\n fileId,\n fields: \"*\",\n pageSize: 100,\n };\n\n if (startModifiedTime !== null) {\n opts.startModifiedTime = new Date(startModifiedTime).toISOString();\n }\n\n while (true) {\n const { data } = await drive.comments.list(opts);\n const {\n comments = [],\n nextPageToken,\n } = data;\n\n for (const comment of comments) {\n yield comment;\n }\n\n if (!nextPageToken) {\n // The 'nextPageToken' field is only returned when there's still\n // comments to be retrieved (i.e. when the end of the list has not\n // been reached yet): https://bit.ly/3w9ru9m\n break;\n }\n\n opts.pageToken = nextPageToken;\n }\n },\n _makeWatchRequestBody(id, address) {\n const expiration = Date.now() + WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS;\n return {\n id, // the component-specific channel ID, a UUID\n type: \"web_hook\",\n address, // the component-specific HTTP endpoint\n expiration,\n };\n },\n async watchDrive(id, address, pageToken, driveId) {\n const drive = this.drive();\n const requestBody = this._makeWatchRequestBody(id, address);\n let watchRequest = {\n pageToken,\n requestBody,\n };\n\n // Google expects an entirely different object to be passed\n // when you make a watch request for My Drive vs. a shared drive\n // \"My Drive\" doesn't have a driveId, so if this method is called\n // without a driveId, we make a watch request for My Drive\n if (driveId) {\n watchRequest = {\n ...watchRequest,\n driveId,\n includeItemsFromAllDrives: true,\n supportsAllDrives: true,\n };\n }\n\n // When watching for changes to an entire account, we must pass a pageToken,\n // which points to the moment in time we want to start watching for changes:\n // https://developers.google.com/drive/api/v3/manage-changes\n const {\n expiration,\n resourceId,\n } = (\n await drive.changes.watch(watchRequest)\n ).data;\n console.log(`Watch request for drive successful, expiry: ${expiration}`);\n return {\n expiration: parseInt(expiration),\n resourceId,\n };\n },\n async watchFile(id, address, fileId) {\n const drive = this.drive();\n const requestBody = this._makeWatchRequestBody(id, address);\n const {\n expiration,\n resourceId,\n } = (\n await drive.files.watch({\n fileId,\n requestBody,\n supportsAllDrives: true,\n })\n ).data;\n console.log(\n `Watch request for file ${fileId} successful, expiry: ${expiration}`,\n );\n return {\n expiration: parseInt(expiration),\n resourceId,\n };\n },\n async stopNotifications(id, resourceId) {\n // id = channelID\n // See https://github.com/googleapis/google-api-nodejs-client/issues/627\n const drive = this.drive();\n\n // If for some reason the channel doesn't exist, this throws an error\n // It's OK for this to fail in those cases, since we'll renew the channel\n // immediately after trying to stop it if we still want notifications,\n // so we squash the error, log it, and move on.\n try {\n await drive.channels.stop({\n resource: {\n id,\n resourceId,\n },\n });\n console.log(`Stopped push notifications on channel ${id}`);\n } catch (err) {\n console.error(\n `Failed to stop channel ${id} for resource ${resourceId}: ${err}`,\n );\n }\n },\n async getFile(fileId) {\n const drive = this.drive();\n return (\n await drive.files.get({\n fileId,\n fields: \"*\",\n supportsAllDrives: true,\n })\n ).data;\n },\n async getDrive(driveId) {\n const drive = this.drive();\n return (\n await drive.drives.get({\n driveId,\n })\n ).data;\n },\n async activateHook(channelID, url, drive) {\n const startPageToken = await this.getPageToken();\n const {\n expiration,\n resourceId,\n } = await this.watchDrive(\n channelID,\n url,\n startPageToken,\n drive,\n );\n return {\n startPageToken,\n expiration,\n resourceId,\n };\n },\n async deactivateHook(channelID, resourceId) {\n if (!channelID) {\n console.log(\n \"Channel not found, cannot stop notifications for non-existent channel\",\n );\n return;\n }\n\n if (!resourceId) {\n console.log(\n \"No resource ID found, cannot stop notifications for non-existent resource\",\n );\n return;\n }\n\n await this.stopNotifications(channelID, resourceId);\n },\n async invokedByTimer(drive, subscription, url, channelID, pageToken) {\n const newChannelID = channelID || uuid();\n const driveId = this.getDriveId(drive);\n const newPageToken = pageToken || await this.getPageToken(driveId);\n\n const {\n expiration,\n resourceId,\n } = await this.checkResubscription(\n subscription,\n newChannelID,\n newPageToken,\n url,\n drive,\n );\n\n return {\n newChannelID,\n newPageToken,\n expiration,\n resourceId,\n };\n },\n async checkResubscription(\n subscription,\n channelID,\n pageToken,\n endpoint,\n drive,\n ) {\n const driveId = this.getDriveId(drive);\n if (subscription && subscription.resourceId) {\n console.log(\n `Notifications for resource ${subscription.resourceId} are expiring at ${subscription.expiration}.\n Stopping existing sub`,\n );\n await this.stopNotifications(channelID, subscription.resourceId);\n }\n\n const {\n expiration,\n resourceId,\n } = await this.watchDrive(\n channelID,\n endpoint,\n pageToken,\n driveId,\n );\n return {\n expiration,\n resourceId,\n };\n },\n },\n};\n\n\n<|start_filename|>components/gorgias/gorgias.app.js<|end_filename|>\n// Gorgias app file\nmodule.exports = {\n type: \"app\",\n app: \"gorgias\",\n}\n\n\n<|start_filename|>components/slack/actions/upload-file/upload-file.js<|end_filename|>\nconst slack = require(\"../../slack.app.js\");\n\nmodule.exports = {\n key: \"slack-upload-file\",\n name: \"Upload File\",\n description: \"Upload a file\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n slack,\n content: {\n propDefinition: [\n slack,\n \"content\",\n ],\n },\n initial_comment: {\n propDefinition: [\n slack,\n \"initial_comment\",\n ],\n optional: true,\n },\n conversation: {\n propDefinition: [\n slack,\n \"conversation\",\n ],\n },\n },\n async run() {\n return await this.slack.sdk().files.upload({\n content: this.content,\n channel: this.conversation,\n initial_comment: this.initial_comment,\n });\n },\n};\n\n\n<|start_filename|>components/rss/rss.app.js<|end_filename|>\nmodule.exports = {\n type: 'app',\n app: 'rss',\n}\n\n<|start_filename|>components/eventbrite/sources/common/webhook.js<|end_filename|>\nconst common = require(\"./base.js\");\nconst get = require(\"lodash/get\");\n\nmodule.exports = {\n ...common,\n props: {\n ...common.props,\n http: \"$.interface.http\",\n },\n hooks: {\n ...common.hooks,\n async activate() {\n const data = {\n actions: this.getActions(),\n endpoint_url: this.http.endpoint,\n };\n const { id } = await this.eventbrite.createHook(this.organization, data);\n this._setHookId(id);\n },\n async deactivate() {\n const id = this._getHookId(\"hookId\");\n await this.eventbrite.deleteHook(id);\n },\n },\n methods: {\n ...common.methods,\n getData() {\n throw new Error(\"getData is not implemented\");\n },\n _getHookId() {\n return this.db.get(\"hookId\");\n },\n _setHookId(hookId) {\n this.db.set(\"hookId\", hookId);\n },\n },\n async run(event) {\n const url = get(event, \"body.api_url\");\n if (!url) return;\n\n const resource = await this.eventbrite.getResource(url);\n\n const data = await this.getData(resource);\n\n this.emitEvent(data);\n },\n};\n\n<|start_filename|>components/docusign/actions/create-signature-request/create-signature-request.js<|end_filename|>\nconst docusign = require(\"../../docusign.app.js\");\n\nmodule.exports = {\n key: \"docusign-create-signature-request\",\n name: \"Create Signature Request\",\n description: \"Creates a signature request from a template\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n docusign,\n account: {\n propDefinition: [\n docusign,\n \"account\",\n ],\n },\n template: {\n propDefinition: [\n docusign,\n \"template\",\n (c) => ({\n account: c.account,\n }),\n ],\n },\n emailSubject: {\n propDefinition: [\n docusign,\n \"emailSubject\",\n ],\n },\n emailBlurb: {\n propDefinition: [\n docusign,\n \"emailBlurb\",\n ],\n },\n recipientEmail: {\n propDefinition: [\n docusign,\n \"recipientEmail\",\n ],\n },\n recipientName: {\n propDefinition: [\n docusign,\n \"recipientName\",\n ],\n },\n role: {\n propDefinition: [\n docusign,\n \"role\",\n (c) => ({\n account: c.account,\n template: c.template,\n }),\n ],\n },\n },\n async run() {\n const baseUri = await this.docusign.getBaseUri(this.account);\n const data = {\n status: \"sent\",\n templateId: this.template,\n templateRoles: [\n {\n roleName: this.role,\n name: this.recipientName,\n email: this.recipientEmail,\n },\n ],\n emailSubject: this.emailSubject,\n };\n if (this.emailBlurb) data.emailBlurb = this.emailBlurb;\n try {\n return await this.docusign.createEnvelope(baseUri, data);\n } catch (err) {\n throw new Error(err.message);\n }\n },\n};\n\n\n<|start_filename|>components/docusign/sources/envelope-sent-or-complete/envelope-sent-or-complete.js<|end_filename|>\nconst docusign = require(\"../../docusign.app.js\");\n\nmodule.exports = {\n key: \"docusign-envelope-sent-or-complete\",\n name: \"Envelope Sent or Complete\",\n description:\n \"Emits an event when an envelope status is set to sent or complete\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n props: {\n docusign,\n db: \"$.service.db\",\n timer: {\n type: \"$.interface.timer\",\n default: {\n intervalSeconds: 60 * 15,\n },\n },\n account: {\n propDefinition: [\n docusign,\n \"account\",\n ],\n },\n status: {\n type: \"string[]\",\n label: \"Status\",\n description: \"The envelope status that you are checking for\",\n options: [\n \"sent\",\n \"completed\",\n ],\n default: [\n \"sent\",\n ],\n },\n },\n methods: {\n _getLastEvent() {\n return this.db.get(\"lastEvent\");\n },\n _setLastEvent(lastEvent) {\n this.db.set(\"lastEvent\", lastEvent);\n },\n monthAgo() {\n const monthAgo = new Date();\n monthAgo.setMonth(monthAgo.getMonth() - 1);\n return monthAgo;\n },\n generateMeta({\n envelopeId: id, emailSubject: summary, status,\n }, ts) {\n return {\n id: `${id}${status}`,\n summary,\n ts,\n };\n },\n },\n async run(event) {\n const { timestamp: ts } = event;\n const lastEvent = this._getLastEvent() || this.monthAgo().toISOString();\n const baseUri = await this.docusign.getBaseUri(this.account);\n let done = false;\n const params = {\n from_date: lastEvent,\n status: this.status.join(),\n };\n do {\n const {\n envelopes = [],\n nextUri,\n endPosition,\n } = await this.docusign.listEnvelopes(baseUri, params);\n if (nextUri) params.start_position += endPosition + 1;\n else done = true;\n\n for (const envelope of envelopes) {\n const meta = this.generateMeta(envelope, ts);\n this.$emit(envelope, meta);\n }\n } while (!done);\n this._setLastEvent(new Date(ts * 1000).toISOString());\n },\n};\n\n\n<|start_filename|>components/hubspot/sources/new-company/new-company.js<|end_filename|>\nconst common = require(\"../common.js\");\n\nmodule.exports = {\n ...common,\n key: \"hubspot-new-company\",\n name: \"New Companies\",\n description: \"Emits an event for each new company added.\",\n version: \"0.0.2\",\n dedupe: \"unique\",\n hooks: {},\n methods: {\n ...common.methods,\n generateMeta(company) {\n const { id, properties, createdAt } = company;\n const ts = Date.parse(createdAt);\n return {\n id,\n summary: properties.name,\n ts,\n };\n },\n isRelevant(company, createdAfter) {\n return Date.parse(company.createdAt) > createdAfter;\n },\n },\n async run(event) {\n const createdAfter = this._getAfter();\n const data = {\n limit: 100,\n sorts: [\n {\n propertyName: \"createdate\",\n direction: \"DESCENDING\",\n },\n ],\n object: \"companies\",\n };\n\n await this.paginate(\n data,\n this.hubspot.searchCRM.bind(this),\n \"results\",\n createdAfter\n );\n\n this._setAfter(Date.now());\n },\n};\n\n<|start_filename|>components/netlify/netlify.app.js<|end_filename|>\nconst axios = require(\"axios\");\nconst crypto = require(\"crypto\");\nconst jwt = require('jwt-simple');\nconst NetlifyAPI = require(\"netlify\");\nconst parseLinkHeader = require('parse-link-header');\n\nmodule.exports = {\n type: \"app\",\n app: \"netlify\",\n propDefinitions: {\n siteId: {\n type: \"string\",\n label: \"Site ID\",\n description: \"The site for which events must be captured\",\n async options(context) {\n // At the moment we need to \"manually\" query these items\n // instead of using the Netlify client, since it doesn't support\n // pagination.\n const url = this._sitesEndpoint();\n const params = {\n per_page: 10,\n };\n const { data, next } = await this._propDefinitionsOptions(url, params, context);\n\n const options = data.map(site => ({\n label: site.name,\n value: site.id,\n }));\n return {\n options,\n context: {\n nextPage: next,\n },\n };\n },\n },\n },\n methods: {\n _apiUrl() {\n return \"https://api.netlify.com/api/v1\";\n },\n _sitesEndpoint() {\n const baseUrl = this._apiUrl();\n return `${baseUrl}/sites`;\n },\n _authToken() {\n return this.$auth.oauth_access_token;\n },\n _makeRequestConfig() {\n const authToken = this._authToken();\n const headers = {\n \"Authorization\": `Bearer ${authToken}`,\n \"User-Agent\": \"@PipedreamHQ/pipedream v0.1\",\n };\n return {\n headers,\n };\n },\n async _propDefinitionsOptions(url, params, { page, prevContext }) {\n let requestConfig = this._makeRequestConfig(); // Basic axios request config\n if (page === 0) {\n // First time the options are being retrieved.\n // Include the parameters provided, which will be persisted\n // across the different pages.\n requestConfig = {\n ...requestConfig,\n params,\n };\n } else if (prevContext.nextPage) {\n // Retrieve next page of options.\n url = prevContext.nextPage.url;\n } else {\n // No more options available.\n return { data: [] };\n }\n\n const { data, headers } = await axios.get(url, requestConfig);\n // https://docs.netlify.com/api/get-started/#link-header\n const { next } = parseLinkHeader(headers.link);\n\n return {\n data,\n next,\n };\n },\n generateToken() {\n return crypto.randomBytes(32).toString(\"hex\");\n },\n createClient() {\n const opts = {\n userAgent: \"@PipedreamHQ/pipedream v0.1\",\n pathPrefix: \"/api/v1\",\n accessToken: this._authToken(),\n };\n return new NetlifyAPI(opts);\n },\n async createHook(opts) {\n const {\n event,\n url,\n siteId,\n } = opts;\n const token = this.generateToken();\n const hookOpts = {\n type: \"url\",\n event,\n data: {\n url,\n signature_secret: token,\n },\n };\n const requestParams = {\n site_id: siteId,\n body: hookOpts,\n };\n\n const netlifyClient = this.createClient();\n const { id } = await netlifyClient.createHookBySiteId(requestParams);\n console.log(\n `Created \"${event}\" webhook for site ID ${siteId}.\n (Hook ID: ${id}, endpoint: ${url})`\n );\n\n return {\n hookId: id,\n token,\n };\n },\n async deleteHook(opts) {\n const { hookId, siteId } = opts;\n const requestParams = {\n hook_id: hookId,\n };\n\n const netlifyClient = this.createClient();\n await netlifyClient.deleteHook(requestParams);\n console.log(\n `Deleted webhook for site ID ${siteId}.\n (Hook ID: ${hookId})`\n );\n },\n isValidSource(headers, bodyRaw, db) {\n // Verifies that the event is really coming from Netlify.\n // See https://docs.netlify.com/site-deploys/notifications/#payload-signature\n const signature = headers[\"x-webhook-signature\"];\n const token = db.get(\"token\");\n const { sha256 } = jwt.decode(signature, token);\n const encoded = crypto\n .createHash('sha256')\n .update(bodyRaw)\n .digest('hex');\n return sha256 === encoded;\n },\n },\n};\n\n\n<|start_filename|>components/ringcentral/sources/common/base.js<|end_filename|>\nconst ringcentral = require(\"../../ringcentral.app\");\n\nmodule.exports = {\n props: {\n ringcentral,\n db: \"$.service.db\",\n },\n methods: {\n /**\n * Given a phone number, return a masked version of it. The purpose of a\n * masked number is to avoid exposing it to an unintended audience.\n *\n * Example:\n *\n * - Input: +16505551234\n * - Output: ########1234\n *\n * @param {string} number The phone number to mask\n * @return {string} The masked phone number\n */\n getMaskedNumber(number) {\n const { length: numberLength } = number;\n return number\n .slice(numberLength - 4)\n .padStart(numberLength, \"#\");\n },\n generateMeta() {\n throw new Error(\"generateMeta is not implemented\");\n },\n processEvent() {\n throw new Error(\"processEvent is not implemented\");\n },\n },\n};\n\n\n<|start_filename|>components/eventbrite/actions/create-event/create-event.js<|end_filename|>\nconst eventbrite = require(\"../../eventbrite.app\");\nconst locales = require(\"../locales.js\");\n\nmodule.exports = {\n key: \"eventbrite-create-event\",\n name: \"Create Event\",\n description: \"Create a new Eventbrite event\",\n version: \"0.0.1\",\n type: \"action\",\n props: {\n eventbrite,\n organization: {\n propDefinition: [\n eventbrite,\n \"organization\",\n ],\n },\n name: {\n type: \"string\",\n label: \"Name\",\n description: \"Event name. Value cannot be empty nor whitespace\",\n },\n summary: {\n type: \"string\",\n label: \"Summary\",\n description:\n \"Event summary. This is a plaintext field and will have any supplied HTML removed from it. Maximum of 140 characters\",\n optional: true,\n },\n timezone: {\n propDefinition: [\n eventbrite,\n \"timezone\",\n ],\n },\n startTime: {\n type: \"string\",\n label: \"Start Time\",\n description:\n \"The event start time relative to UTC. (Ex. 2018-05-12T02:00:00Z).\",\n },\n endTime: {\n type: \"string\",\n label: \"End Time\",\n description:\n \"The event end time relative to UTC. (Ex. 2018-05-12T02:00:00Z)\",\n },\n hideStartDate: {\n type: \"boolean\",\n label: \"Hide Start Date\",\n description: \"Whether the start date should be hidden. Defaults to false if left blank.\",\n optional: true,\n },\n hideEndDate: {\n type: \"boolean\",\n label: \"Hide End Date\",\n description: \"Whether the end date should be hidden. Defaults to false if left blank.\",\n optional: true,\n },\n currency: {\n type: \"string\",\n label: \"Currency\",\n description: \"The ISO 4217 currency code for this event\",\n default: \"USD\",\n },\n onlineEvent: {\n type: \"boolean\",\n label: \"Online Event\",\n description: \"If this event doesn't have a venue and is only held online. Defaults to false if left blank.\",\n optional: true,\n },\n organizerId: {\n type: \"string\",\n label: \"Organizer ID\",\n description: \"ID of the event organizer\",\n optional: true,\n },\n logoId: {\n type: \"string\",\n label: \"Logo ID\",\n description: \"Image ID of the event logo\",\n optional: true,\n },\n venueId: {\n type: \"string\",\n label: \"Venue ID\",\n description: \"Event venue ID\",\n optional: true,\n },\n formatId: {\n type: \"string\",\n label: \"Format ID\",\n description: \"Event format\",\n optional: true,\n },\n categoryId: {\n type: \"string\",\n label: \"Category ID\",\n description: \"Event category\",\n optional: true,\n },\n subcategoryId: {\n type: \"string\",\n label: \"Subcategory ID\",\n description: \"Event subcategory (US only)\",\n optional: true,\n },\n listed: {\n type: \"boolean\",\n label: \"Listed\",\n description: \"Is this event publicly searchable on Eventbrite? Defaults to true.\",\n default: true,\n },\n shareable: {\n type: \"boolean\",\n label: \"Shareable\",\n description: \"Can this event show social sharing buttons? Defaults to false if left blank.\",\n optional: true,\n },\n inviteOnly: {\n type: \"boolean\",\n label: \"Invite Only\",\n description: \"Can only people with invites see the event page?. Defaults to false if left blank.\",\n optional: true,\n },\n showRemaining: {\n type: \"boolean\",\n label: \"Show Remaining\",\n description:\n \"If the remaining number of tickets is publicly visible on the event page. Defaults to false if left blank.\",\n optional: true,\n },\n password: {\n type: \"string\",\n label: \"Password\",\n description: \"Password needed to see the event in unlisted mode\",\n optional: true,\n },\n capacity: {\n type: \"integer\",\n label: \"Capacity\",\n description: \"Set specific capacity (if omitted, sums ticket capacities)\",\n optional: true,\n },\n isReservedSeating: {\n type: \"boolean\",\n label: \"Is Reserved Seating\",\n description: \"If the event is reserved seating. Defaults to false if left blank.\",\n optional: true,\n },\n isSeries: {\n type: \"boolean\",\n label: \"Is Series\",\n description:\n \"If the event is part of a series. Specifying this attribute as True during event creation will always designate the event as a series parent, never as a series occurrence. Series occurrences must be created through the schedules API and cannot be created using the events API. Defaults to false if left blank.\",\n optional: true,\n },\n showPickASeat: {\n type: \"boolean\",\n label: \"Show Pick A Seat\",\n description:\n \"For reserved seating event, if attendees can pick their seats. Defaults to false if left blank.\",\n optional: true,\n },\n showSeatmapThumbnail: {\n type: \"boolean\",\n label: \"Show Seatmap Thumbnail\",\n description:\n \"For reserved seating event, if venue map thumbnail visible on the event page. Defaults to false if left blank.\",\n optional: true,\n },\n showColorsInSeatmapThumbnail: {\n type: \"boolean\",\n label: \"Show Colors In Seatmap Thumbnail\",\n description:\n \"For reserved seating event, if venue map thumbnail should have colors on the event page. Defaults to false if left blank.\",\n optional: true,\n },\n source: {\n type: \"string\",\n label: \"Source\",\n description: \"Source of the event (defaults to API)\",\n optional: true,\n },\n locale: {\n type: \"string\",\n label: \"Locale\",\n description: \"Indicates event language on Event's listing page. Language options from Eventbrite documentation: https://www.eventbrite.com/platform/api#/reference/event/retrieve/create-an-event\",\n options: locales,\n default: \"en_US\",\n },\n },\n async run() {\n /* convert start and end time to UTC in case time was entered with timezone offset */\n const startTime = (new Date(this.startTime)).toISOString()\n .split(\".\")[0] + \"Z\";\n const endTime = (new Date(this.endTime)).toISOString()\n .split(\".\")[0] + \"Z\";\n\n let data = {\n event: {\n name: {\n html: this.name,\n },\n summary: this.summary,\n start: {\n timezone: this.timezone,\n utc: startTime,\n },\n end: {\n timezone: this.timezone,\n utc: endTime,\n },\n hide_start_date: this.hideStartDate,\n hide_end_date: this.hideEndDate,\n currency: this.currency,\n online_event: this.onlineEvent,\n organizer_id: this.organizerId,\n logo_id: this.logoId,\n venue_id: this.venueId,\n format_id: this.formatId,\n category_id: this.categoryId,\n subcategory_id: this.subcategoryId,\n listed: this.listed,\n shareable: this.shareable,\n invite_only: this.inviteOnly,\n show_remaining: this.showRemaining,\n password: ,\n capacity: this.capacity,\n is_reserved_seating: this.isReservedSeating,\n is_series: this.isSeries,\n show_pick_a_seat: this.showPickASeat,\n show_seatmap_thumbnail: this.showSeatmapThumbnail,\n show_colors_in_seatmap_thumbnail: this.showColorsInSeatmapThumbnail,\n source: this.source,\n locale: this.locale,\n },\n };\n data = JSON.parse(JSON.stringify(data));\n return await this.eventbrite.createEvent(this.organization, data);\n },\n};\n"},"max_stars_repo_name":{"kind":"string","value":"saikrishna169/pipedream"}}},{"rowIdx":226,"cells":{"content":{"kind":"string","value":"<|start_filename|>app/assets/javascripts/modules/teams/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport TeamsIndexPage from './pages/index';\nimport TeamsShowPage from './pages/show';\n\n$(() => {\n if (!$('body[data-controller=\"teams\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n TeamsIndexPage,\n TeamsShowPage,\n },\n });\n});\n\n\n<|start_filename|>spec/javascripts/utils/comparator.spec.js<|end_filename|>\nimport Comparator from '~/utils/comparator';\n\ndescribe('Comparator', () => {\n it('returns string comparator function', () => {\n expect(Comparator.of('string').name).toBe('stringComparator');\n });\n\n it('returns number comparator function', () => {\n expect(Comparator.of(1).name).toBe('numberComparator');\n });\n\n it('returns date comparator function', () => {\n expect(Comparator.of(new Date()).name).toBe('dateComparator');\n });\n\n it('returns string comparator function by default', () => {\n expect(Comparator.of(null).name).toBe('stringComparator');\n });\n\n describe('string comparator', () => {\n const comparator = Comparator.of('string');\n\n it('returns -1 if string a < b', () => {\n expect(comparator('a', 'b')).toBe(-1);\n });\n\n it('returns 0 if string a = b', () => {\n expect(comparator('a', 'a')).toBe(0);\n });\n\n it('returns 1 if string a > b', () => {\n expect(comparator('b', 'a')).toBe(1);\n });\n });\n\n describe('number comparator', () => {\n const comparator = Comparator.of(1);\n\n it('returns a negative number if a < b', () => {\n expect(comparator(1, 2)).toBeLessThanOrEqual(0);\n });\n\n it('returns 0 if number a = b', () => {\n expect(comparator(1, 1)).toBe(0);\n });\n\n it('returns a positive number > 0 if a > b', () => {\n expect(comparator(2, 1)).toBeGreaterThanOrEqual(0);\n });\n });\n\n describe('date comparator', () => {\n const comparator = Comparator.of(new Date());\n\n it('returns a negative number if date a < b', () => {\n const date1 = new Date('December 16, 1995 03:24:00');\n const date2 = new Date('December 17, 1995 03:24:00');\n\n expect(comparator(date1, date2)).toBeLessThanOrEqual(0);\n });\n\n it('returns 0 if date a = b', () => {\n const date1 = new Date('December 17, 1995 03:24:00');\n const date2 = new Date('December 17, 1995 03:24:00');\n\n expect(comparator(date1, date2)).toBe(0);\n });\n\n it('returns a positive number if date a > b', () => {\n const date1 = new Date('December 18, 1995 03:24:00');\n const date2 = new Date('December 17, 1995 03:24:00');\n\n expect(comparator(date1, date2)).toBeGreaterThanOrEqual(0);\n });\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/plugins/unauthenticated.js<|end_filename|>\nimport Vue from 'vue';\n\nimport Alert from '~/plugins/alert';\n\nVue.use(Alert);\n\n\n<|start_filename|>app/assets/javascripts/modules/webhooks/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport WebhooksIndexPage from './pages/index';\nimport WebhooksShowPage from './pages/show';\n\n$(() => {\n if (!$('body[data-controller=\"webhooks\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n WebhooksIndexPage,\n WebhooksShowPage,\n },\n });\n});\n\n\n<|start_filename|>spec/javascripts/modules/repositories/delete-tag-action.spec.js<|end_filename|>\nimport { mount } from '@vue/test-utils';\n\nimport DeleteTagAction from '~/modules/repositories/components/tags/delete-tag-action';\n\nimport sinon from 'sinon';\n\ndescribe('delete-tag-action', () => {\n let wrapper;\n\n beforeEach(() => {\n wrapper = mount(DeleteTagAction, {\n propsData: {\n state: {\n selectedTags: [],\n },\n },\n mocks: {\n $bus: {\n $emit: sinon.spy(),\n },\n },\n });\n });\n\n it('shows nothing if no tag is selected', () => {\n expect(wrapper.find('.label').exists()).toBe(false);\n });\n\n it('shows label in singular if only one tag is selected', () => {\n wrapper.setProps({ state: { selectedTags: [{}] } });\n\n expect(wrapper.text()).toBe('Delete tag');\n });\n\n it('shows label in plural if more than one tag is selected', () => {\n wrapper.setProps({ state: { selectedTags: [{}, {}] } });\n expect(wrapper.text()).toBe('Delete tags');\n });\n\n it('shows label in plural if more a tag with multiple labels is selected', () => {\n wrapper.setProps({ state: { selectedTags: [{ multiple: true }] } });\n expect(wrapper.text()).toBe('Delete tags');\n });\n\n it('emits deleteTags event if clicked', () => {\n wrapper.setProps({ state: { selectedTags: [{}] } });\n\n wrapper.find('.btn').trigger('click');\n expect(wrapper.vm.$bus.$emit.calledWith('deleteTags')).toBe(true);\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/dashboard/pages/dashboard.js<|end_filename|>\nimport BaseComponent from '~/base/component';\nimport TabbedWidget from '../components/tabbed_widget';\n\nconst TAB_WIDGET = '#sidebar-tabs';\n\nclass DashboardPage extends BaseComponent {\n elements() {\n this.$widget = this.$el.find(TAB_WIDGET);\n }\n\n mount() {\n this.tabbedWidget = new TabbedWidget(this.$widget);\n }\n}\n\nexport default DashboardPage;\n\n\n<|start_filename|>spec/javascripts/modules/repositories/vulnerabilities-parser.spec.js<|end_filename|>\nimport VulnerabilitiesParser from '~/modules/repositories/services/vulnerabilities-parser';\n\ndescribe('VulnerabilitiesParser', () => {\n describe('#countBySeverities', () => {\n const emptyVulnerabilities = [];\n const vulnerabilities = [\n { severity: 'Critical' },\n { severity: 'High' },\n { severity: 'High' },\n { severity: 'Medium' },\n { severity: 'Low' },\n { severity: 'Low' },\n { severity: 'Negligible' },\n ];\n const severitiesNames = ['Defcon1', 'Critical', 'High', 'Medium', 'Low', 'Unknown', 'Negligible'];\n\n it('returns object with severities categories', () => {\n const severities = VulnerabilitiesParser.countBySeverities(vulnerabilities);\n\n expect(Object.keys(severities)).toEqual(severitiesNames);\n });\n\n it('returns object with severities zero', () => {\n const severities = VulnerabilitiesParser.countBySeverities(emptyVulnerabilities);\n\n severitiesNames.forEach((s) => {\n expect(severities[s]).toBe(0);\n });\n });\n\n it('counts vulnerabilities by category', () => {\n const severities = VulnerabilitiesParser.countBySeverities(vulnerabilities);\n\n expect(severities.Critical).toBe(1);\n expect(severities.High).toBe(2);\n expect(severities.Medium).toBe(1);\n expect(severities.Low).toBe(2);\n expect(severities.Unknown).toBe(0);\n expect(severities.Negligible).toBe(1);\n });\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/utils/comparator.js<|end_filename|>\nimport dateutil from '~/utils/date';\n\nconst stringComparator = (a, b) => a.localeCompare(b);\n\nconst numberComparator = (a, b) => a - b;\n\nconst dateComparator = (a, b) => new Date(a) - new Date(b);\n\nfunction of(value) {\n let type = typeof value;\n\n if (dateutil.isISO8601(value)) {\n type = 'date';\n }\n\n switch (type) {\n case 'boolean':\n case 'number':\n return numberComparator;\n case 'date':\n return dateComparator;\n default:\n return stringComparator;\n }\n}\n\nexport default {\n of,\n};\n\n\n<|start_filename|>app/assets/javascripts/utils/alert.js<|end_filename|>\nconst ALERT_ELEMENT = '#float-alert';\nconst TEXT_ALERT_ELEMENT = '#float-alert p';\nconst HIDE_TIMEOUT = 5000;\nconst STORAGE_KEY = 'portus.alerts.schedule';\n\nconst storage = window.localStorage;\n\nconst $show = (text, autohide = true, timeout = HIDE_TIMEOUT) => {\n $(TEXT_ALERT_ELEMENT).html(text);\n $(ALERT_ELEMENT).fadeIn();\n\n if (autohide) {\n setTimeout(() => $(ALERT_ELEMENT).fadeOut(), timeout);\n }\n};\n\nconst scheduledMessages = () => JSON.parse(storage.getItem(STORAGE_KEY)) || [];\nconst storeMessages = messages => storage.setItem(STORAGE_KEY, JSON.stringify(messages));\n\n// the idea is to simulate the alert that is showed after a redirect\n// e.g.: something happened that requires a page reload/redirect and\n// we need to show this info to the user.\nconst $schedule = (text) => {\n const messages = scheduledMessages();\n messages.push(text);\n storeMessages(messages);\n};\n\nconst $process = () => {\n const messages = scheduledMessages();\n messages.forEach(m => $show(m, false));\n storage.clear(STORAGE_KEY);\n};\n\nexport default {\n $show,\n $schedule,\n $process,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/webhooks/services/webhooks.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst customActions = {\n toggleEnabled: {\n method: 'PUT',\n url: 'namespaces/{namespaceId}/webhooks/{id}/toggle_enabled.json',\n },\n};\n\nconst oldResource = Vue.resource('namespaces/{namespaceId}/webhooks{/id}.json', {}, customActions);\n\nfunction destroy(namespaceId, id) {\n return oldResource.delete({ namespaceId, id });\n}\n\nfunction save(namespaceId, webhook) {\n return oldResource.save({ namespaceId }, { webhook });\n}\n\nfunction toggleEnabled(namespaceId, id) {\n return oldResource.toggleEnabled({ namespaceId, id }, {});\n}\n\nfunction update(namespaceId, webhook) {\n return oldResource.update({ namespaceId, id: webhook.id }, { webhook });\n}\n\nexport default {\n destroy,\n save,\n toggleEnabled,\n update,\n};\n\n\n<|start_filename|>app/assets/javascripts/unauthenticated.js<|end_filename|>\n// Bootstrap\nimport 'bootstrap/js/tooltip';\n\n// misc\nimport './plugins/unauthenticated';\nimport './polyfill';\n\n// modules\nimport './modules/explore';\nimport './modules/users/unauthenticated';\n\nimport './bootstrap';\n\n\n<|start_filename|>app/assets/javascripts/modules/teams/service.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst customActions = {\n teamTypeahead: {\n method: 'GET',\n url: 'teams/typeahead/{teamName}',\n },\n};\n\nconst membersCustomActions = {\n memberTypeahead: {\n method: 'GET',\n url: 'teams/{teamId}/typeahead/{name}',\n },\n};\n\nconst resource = Vue.resource('api/v1/teams{/id}', {}, customActions);\nconst membersResource = Vue.resource('api/v1/teams{/teamId}/members{/id}', {}, membersCustomActions);\n\nfunction all(params = {}) {\n return resource.get({}, params);\n}\n\nfunction get(id) {\n return resource.get({ id });\n}\n\nfunction save(team) {\n return resource.save({}, team);\n}\n\nfunction update(team) {\n return resource.update({ id: team.id }, { team });\n}\n\nfunction remove(id, params) {\n return resource.delete({ id }, params);\n}\n\nfunction searchTeam(teamName, options = {}) {\n const params = Object.assign({ teamName }, options);\n\n return resource.teamTypeahead(params);\n}\n\nfunction exists(value, options) {\n return searchTeam(value, options)\n .then((response) => {\n const collection = response.data;\n\n if (Array.isArray(collection)) {\n return collection.some(e => e.name === value);\n }\n\n // some unexpected response from the api,\n // leave it for the back-end validation\n return null;\n })\n .catch(() => null);\n}\n\nfunction searchMember(teamId, name) {\n return membersResource.memberTypeahead({ teamId, name });\n}\n\nfunction destroyMember(member) {\n const teamId = member.team_id;\n const { id } = member;\n\n return membersResource.delete({ teamId, id });\n}\n\nfunction updateMember(member, role) {\n const teamId = member.team_id;\n const { id } = member;\n\n return membersResource.update({ teamId, id }, { role });\n}\n\nfunction saveMember(teamId, member) {\n return membersResource.save({ teamId }, member);\n}\n\nfunction memberExists(teamId, value) {\n return searchMember(teamId, value)\n .then((response) => {\n const collection = response.data;\n\n if (Array.isArray(collection)) {\n return collection.some(e => e.name === value);\n }\n\n // some unexpected response from the api,\n // leave it for the back-end validation\n return null;\n })\n .catch(() => null);\n}\n\nexport default {\n get,\n all,\n save,\n update,\n remove,\n exists,\n searchMember,\n destroyMember,\n updateMember,\n saveMember,\n memberExists,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/tags/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport TagsShowPage from './pages/show';\n\n$(() => {\n if (!$('body[data-controller=\"tags\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n TagsShowPage,\n },\n });\n});\n\n\n<|start_filename|>spec/javascripts/shared/toggle-link.spec.js<|end_filename|>\nimport { mount } from '@vue/test-utils';\n\nimport ToggleLink from '~/shared/components/toggle-link';\n\ndescribe('toggle-link', () => {\n let wrapper;\n\n beforeEach(() => {\n wrapper = mount(ToggleLink, {\n propsData: {\n state: {\n key: false,\n },\n stateKey: 'key',\n text: '',\n },\n });\n });\n\n it('shows the passed text', () => {\n wrapper.setProps({ text: 'Text xD' });\n\n expect(wrapper.html()).toContain('Text xD');\n });\n\n it('changes the state on user click', () => {\n wrapper.find('.btn').trigger('click');\n\n expect(wrapper.vm.state.key).toBe(true);\n });\n\n it('shows `trueIcon` when state is true', () => {\n const icon = wrapper.find('.fa');\n wrapper.setProps({\n trueIcon: 'fa-true',\n state: { key: true },\n });\n\n expect(icon.classes()).toContain('fa-true');\n });\n\n it('shows `falseIcon` when state is false', () => {\n const icon = wrapper.find('.fa');\n wrapper.setProps({\n falseIcon: 'fa-false',\n state: { key: false },\n });\n\n expect(icon.classes()).toContain('fa-false');\n });\n\n it('changes icon when state changes', () => {\n const icon = wrapper.find('.fa');\n wrapper.setProps({\n trueIcon: 'fa-true',\n falseIcon: 'fa-false',\n state: { key: false },\n });\n\n expect(icon.classes()).toContain('fa-false');\n\n wrapper.find('.btn').trigger('click');\n\n expect(icon.classes()).toContain('fa-true');\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/repositories/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport RepositoriesIndexPage from './pages/index';\nimport RepositoriesShowPage from './pages/show';\n\n$(() => {\n if (!$('body[data-controller=\"repositories\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n RepositoriesIndexPage,\n RepositoriesShowPage,\n },\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/namespaces/mixins/visibility.js<|end_filename|>\nexport default {\n props: ['namespace'],\n\n data() {\n return {\n onGoingRequest: false,\n };\n },\n\n computed: {\n isPrivate() {\n return this.namespace.visibility === 'private';\n },\n\n isProtected() {\n return this.namespace.visibility === 'protected';\n },\n\n isPublic() {\n return this.namespace.visibility === 'public';\n },\n\n canChangeVibisility() {\n return this.namespace.permissions.visibility\n && !this.onGoingRequest;\n },\n\n privateTitle() {\n if (this.namespace.global) {\n return 'The global namespace cannot be private';\n }\n\n return 'Team members can pull images from this namespace';\n },\n },\n};\n\n\n<|start_filename|>app/assets/javascripts/utils/effects.js<|end_filename|>\n// after jquery was upgraded this effect was conflicting\n// with lifeitup functions (probably layout_resizer)\n// so setTimeout was the workaround I found to solve the error\nexport const fadeIn = function ($el) {\n setTimeout(() => {\n $el.hide().fadeIn(1000);\n }, 0);\n};\n\n// openCloseIcon toggles the state of the given icon with the\n// 'fa-pencil'/'fa-close' classes.\nexport const openCloseIcon = function (icon) {\n if (icon.hasClass('fa-close')) {\n icon.removeClass('fa-close');\n icon.addClass('fa-pencil');\n } else {\n icon.removeClass('fa-pencil');\n icon.addClass('fa-close');\n }\n};\n\n// refreshFloatAlertPosition updates the position of a floating alert on scroll.\nexport const refreshFloatAlertPosition = function () {\n var box = $('.float-alert');\n\n if ($(this).scrollTop() < 60) {\n box.css('top', (72 - $(this).scrollTop()) + 'px');\n }\n\n $(window).scroll(() => {\n if ($(this).scrollTop() > 60) {\n box.css('top', '12px');\n } else {\n box.css('top', (72 - $(this).scrollTop()) + 'px');\n }\n });\n};\n\n// setTimeoutAlertDelay sets up the delay for hiding an alert.\n// IDEA: if alerts are put into a component, this hack will no longer be needed.\nexport const setTimeOutAlertDelay = function () {\n setTimeout(() => {\n $('.alert-hide').click();\n }, 4000);\n};\n\nexport default {\n fadeIn,\n openCloseIcon,\n refreshFloatAlertPosition,\n setTimeOutAlertDelay,\n};\n\n\n<|start_filename|>spec/javascripts/modules/repositories/tag.spec.js<|end_filename|>\nimport { mount } from '@vue/test-utils';\n\nimport Tag from '~/modules/repositories/components/tags/tag';\n\nimport sinon from 'sinon';\n\ndescribe('tag', () => {\n let wrapper;\n const commandToPull = 'docker pull localhost:5000/opensuse/portus:latest';\n\n beforeEach(() => {\n wrapper = mount(Tag, {\n propsData: {\n // not real data but the one used in the component\n tag: {\n name: 'latest',\n },\n repository: {\n registry_hostname: 'localhost:5000',\n full_name: 'opensuse/portus',\n },\n },\n mocks: {\n $alert: {\n $show: sinon.spy(),\n },\n },\n });\n });\n\n it('shows tag name', () => {\n expect(wrapper.find('.label').text()).toBe('latest');\n });\n\n it('computes command to pull properly', () => {\n expect(wrapper.vm.commandToPull).toBe(commandToPull);\n });\n\n it('copies command to pull to the clipboard', () => {\n // document in test env doesn't have execCommand\n document.execCommand = sinon.spy();\n\n wrapper.find('.label').trigger('click');\n expect(document.execCommand.calledWith('copy')).toBe(true);\n });\n\n it('calls $alert plugin notifying user', () => {\n const message = 'Copied pull command to clipboard';\n\n wrapper.find('.label').trigger('click');\n expect(wrapper.vm.$alert.$show.calledWith(message)).toBe(true);\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/repositories/services/vulnerabilities-parser.js<|end_filename|>\nconst countBySeverities = function (vulnerabilities) {\n const severities = {\n Defcon1: 0,\n Critical: 0,\n High: 0,\n Medium: 0,\n Low: 0,\n Unknown: 0,\n Negligible: 0,\n };\n\n if (vulnerabilities) {\n vulnerabilities.forEach((vul) => {\n severities[vul.severity] += 1;\n });\n }\n\n return severities;\n};\n\nexport default {\n countBySeverities,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/users/service.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst customActions = {\n createToken: {\n method: 'POST',\n url: 'api/v1/users/{userId}/application_tokens',\n },\n destroyToken: {\n method: 'DELETE',\n url: 'api/v1/users/application_tokens/{id}',\n },\n};\n\nconst oldCustomActions = {\n toggleAdmin: {\n method: 'PUT',\n url: 'admin/users/{id}/toggle_admin',\n },\n toggleEnabled: {\n method: 'PUT',\n url: 'toggle_enabled/{id}',\n },\n};\n\nconst resource = Vue.resource('api/v1/users{/id}', {}, customActions);\nconst oldResource = Vue.resource('admin/users{/id}', {}, oldCustomActions);\n\nfunction createToken(userId, appToken) {\n return resource.createToken({ userId }, appToken);\n}\n\nfunction destroyToken(id) {\n return resource.destroyToken({ id });\n}\n\nfunction save(user) {\n return oldResource.save({}, { user });\n}\n\nfunction update(user) {\n return resource.update({ id: user.id }, { user });\n}\n\nfunction destroy({ id }) {\n return resource.delete({ id });\n}\n\nfunction toggleAdmin({ id }) {\n return oldResource.toggleAdmin({ id }, {});\n}\n\nfunction toggleEnabled({ id }) {\n return oldResource.toggleEnabled({ id }, {});\n}\n\nexport default {\n save,\n destroy,\n update,\n toggleAdmin,\n toggleEnabled,\n createToken,\n destroyToken,\n};\n\n\n<|start_filename|>app/assets/javascripts/utils/csrf.js<|end_filename|>\nconst token = () => {\n const tokenEl = document.querySelector('meta[name=csrf-token]');\n\n if (tokenEl !== null) {\n return tokenEl.getAttribute('content');\n }\n\n return null;\n};\n\nexport default {\n token,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/dashboard/index.js<|end_filename|>\nimport SearchComponent from './components/search';\nimport DashboardPage from './pages/dashboard';\n\nconst DASHBOARD_INDEX = 'dashboard/index';\n\n$(() => {\n const $body = $('body');\n const route = $body.data('route');\n\n // Enable the search component globally if the HTML code is there.\n if ($('#search').length > 0) {\n // eslint-disable-next-line\n new SearchComponent($body);\n }\n\n if (route === DASHBOARD_INDEX) {\n // eslint-disable-next-line\n new DashboardPage($body);\n }\n});\n\n\n<|start_filename|>spec/javascripts/utils/date.spec.js<|end_filename|>\nimport DateUtil from '~/utils/date';\n\ndescribe('DateUtil', () => {\n it('returns false if it\\'s not a valid date string/object', () => {\n expect(DateUtil.isISO8601('asdasd')).toBe(false);\n expect(DateUtil.isISO8601(null)).toBe(false);\n expect(DateUtil.isISO8601('2018-222-222')).toBe(false);\n expect(DateUtil.isISO8601('')).toBe(false);\n expect(DateUtil.isISO8601('20180205T173027Z')).toBe(false);\n });\n\n it('returns true if it\\'s a valid date string/object', () => {\n expect(DateUtil.isISO8601('2018-07-20T18:14:43.000Z')).toBe(true);\n expect(DateUtil.isISO8601('2018-07-20T18:14:43Z')).toBe(true);\n expect(DateUtil.isISO8601('2018-02-05T17:14Z')).toBe(true);\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/users/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport DisableAccountPanel from './components/disable-account-panel';\nimport AppTokensWrapper from './components/application-tokens/wrapper';\n\nimport UsersIndexPage from './pages/index';\nimport UsersEditPage from './pages/edit';\nimport LegacyUsersEditPage from './pages/legacy/edit';\n\nconst USERS_SELF_EDIT_ROUTE = 'auth/registrations/edit';\n\n$(() => {\n const $body = $('body');\n const route = $body.data('route');\n const controller = $body.data('controller');\n\n if (controller === 'admin/users' || route === USERS_SELF_EDIT_ROUTE) {\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n AppTokensWrapper,\n DisableAccountPanel,\n UsersEditPage,\n UsersIndexPage,\n },\n\n mounted() {\n // eslint-disable-next-line\n new LegacyUsersEditPage($body);\n },\n });\n }\n});\n\n\n<|start_filename|>app/assets/javascripts/bootstrap.js<|end_filename|>\nimport Vue from 'vue';\n\nimport dayjs from 'dayjs';\nimport relativeTime from 'dayjs/plugin/relativeTime';\n\nimport Alert from './utils/alert';\n\nimport { setTimeOutAlertDelay, refreshFloatAlertPosition } from './utils/effects';\n\ndayjs.extend(relativeTime);\n\n$(function () {\n // this is a fallback to always instantiate a vue instance\n // useful for isolated shared components like \n // eslint-disable-next-line no-underscore-dangle\n if (!$('.vue-root')[0].__vue__) {\n // eslint-disable-next-line no-new\n new Vue({ el: '.vue-root' });\n }\n\n if ($.fn.popover) {\n $('a[rel~=popover], .has-popover').popover();\n }\n\n if ($.fn.tooltip) {\n $('a[rel~=tooltip], .has-tooltip').tooltip();\n }\n\n $('.alert .close').on('click', function () { $(this).closest('.alert-wrapper').fadeOut(); });\n\n // process scheduled alerts\n Alert.$process();\n\n refreshFloatAlertPosition();\n\n // disable effects during tests\n $.fx.off = $('body').data('disable-effects');\n});\n\n// necessary to be compatible with the js rendered\n// on the server-side via jquery-ujs\nwindow.setTimeOutAlertDelay = setTimeOutAlertDelay;\nwindow.refreshFloatAlertPosition = refreshFloatAlertPosition;\n\n// we are not a SPA and when user clicks on back/forward\n// we want the page to be fully reloaded to take advantage of\n// the url query params state\nwindow.onpopstate = function (e) {\n // phantomjs seems to trigger an oppopstate event\n // when visiting pages, e.state is always null and\n // in our component we set an empty string\n if (e.state !== null) {\n window.location.reload();\n }\n};\n\nVue.config.productionTip = process.env.NODE_ENV !== 'production';\n\n\n<|start_filename|>vendor/assets/javascripts/lifeitup_layout.js<|end_filename|>\n/* eslint-disable max-len, vars-on-top */\n\n// to render the layout correctly in every browser/screen\nvar alreadyResizing = false;\nwindow.$ = window.jQuery;\n\nwindow.layout_resizer = function layout_resizer() {\n alreadyResizing = true;\n\n var screenHeight = $(window).height();\n var headerHeight = $('header').outerHeight();\n var footerHeight = $('footer').outerHeight();\n var asideHeight = $('aside ul').outerHeight();\n var sectionHeight = $('section').outerHeight();\n\n\n if ((headerHeight + footerHeight + asideHeight) > screenHeight && asideHeight > sectionHeight) {\n $('.container-fluid').css({\n height: asideHeight + 'px',\n });\n } else if ((headerHeight + footerHeight + sectionHeight) > screenHeight && asideHeight < sectionHeight) {\n $('.container-fluid').css({\n height: sectionHeight + 'px',\n });\n } else {\n $('.container-fluid').css({\n height: screenHeight - headerHeight - footerHeight + 'px',\n });\n }\n\n alreadyResizing = false;\n};\n\n$(window).on('load', function () {\n layout_resizer();\n});\n\n$(window).on('resize', function () {\n layout_resizer();\n});\n\n$(document).bind('DOMSubtreeModified', function () {\n if (!alreadyResizing) {\n layout_resizer();\n }\n});\n\n// triger the function to resize and to get the images size when a panel has been displayed\n$(document).on('shown.bs.tab', 'a[data-toggle=\"tab\"]', function () {\n layout_resizer();\n});\n\n// BOOTSTRAP INITS\n$(function () {\n if ($.fn.popover) {\n $('body').popover({\n selector: '[data-toggle=\"popover\"]',\n trigger: 'focus',\n });\n // to destroy the popovers that are hidden\n $('[data-toggle=\"popover\"]').on('hidden.bs.popover', function () {\n var popover = $('.popover').not('.in');\n if (popover) {\n popover.remove();\n }\n });\n }\n});\n\n// init tooltip\n$(function () {\n if ($.fn.tooltip) {\n $('[data-toggle=\"tooltip\"]').tooltip();\n }\n});\n\n// Hide alert box instead of closing it\n$(document).on('click', '.alert-hide', function () {\n $(this).parent().parent().fadeOut();\n});\n\n\n<|start_filename|>spec/javascripts/modules/teams/form.spec.js<|end_filename|>\nimport { mount } from '@vue/test-utils';\n\nimport Vue from 'vue';\nimport Vuelidate from 'vuelidate';\nimport sinon from 'sinon';\n\nimport NewTeamForm from '~/modules/teams/components/new-form';\n\nVue.use(Vuelidate);\n\ndescribe('new-team-form', () => {\n let wrapper;\n\n const submitButton = () => wrapper.find('button[type=\"submit\"]');\n const teamNameInput = () => wrapper.find('#team_name');\n\n beforeEach(() => {\n wrapper = mount(NewTeamForm, {\n propsData: {\n isAdmin: false,\n currentUserId: 0,\n owners: [{}],\n },\n mocks: {\n $bus: {\n $emit: sinon.spy(),\n },\n },\n });\n });\n\n context('when current user is admin', () => {\n beforeEach(() => {\n wrapper.setProps({\n isAdmin: true,\n });\n });\n\n it('shows owner select field', () => {\n expect(wrapper.text()).toContain('Owner');\n });\n });\n\n context('when current user is not admin', () => {\n beforeEach(() => {\n wrapper.setProps({\n isAdmin: false,\n });\n });\n\n it('hides owner select field', () => {\n expect(wrapper.text()).not.toContain('Owner');\n });\n });\n\n it('disables submit button if form is invalid', () => {\n expect(submitButton().attributes().disabled).toBe('disabled');\n });\n\n it('enables submit button if form is valid', () => {\n // there's a custom validation the involves a Promise and an ajax request.\n // this was the simpler way to bypass that validation.\n // tried to stub/mock/fake with sinon but wasn't able to make it work.\n // another solution would be using vue resource interceptors but that would\n // add unecessary complexity for the moment.\n // maybe when we move to axios we could use moxios for that which is much simpler.\n Object.defineProperty(wrapper.vm.$v.team.name, 'available', {\n value: true,\n writable: false,\n });\n\n teamNameInput().element.value = 'test';\n teamNameInput().trigger('input');\n expect(submitButton().attributes().disabled).toBeUndefined();\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/polyfill.js<|end_filename|>\nimport 'core-js/fn/array/some';\nimport 'core-js/fn/array/from';\nimport 'core-js/fn/array/find';\nimport 'core-js/fn/array/find-index';\nimport 'core-js/fn/object/assign';\n\n\n<|start_filename|>app/assets/javascripts/modules/namespaces/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport NamespacesIndexPage from './pages/index';\nimport NamespacesShowPage from './pages/show';\n\n$(() => {\n if (!$('body[data-controller=\"namespaces\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n NamespacesIndexPage,\n NamespacesShowPage,\n },\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/users/pages/sign-in.js<|end_filename|>\nimport BaseComponent from '~/base/component';\n\nimport { fadeIn } from '~/utils/effects';\n\n// UsersSignInPage component responsible to instantiate\n// the user's sign in page components and handle interactions.\nclass UsersSignInPage extends BaseComponent {\n mount() {\n fadeIn(this.$el.find('> .container-fluid'));\n }\n}\n\nexport default UsersSignInPage;\n\n\n<|start_filename|>app/assets/javascripts/modules/users/components/password-form.js<|end_filename|>\nimport BaseComponent from '~/base/component';\n\nconst CURRENT_PASSWORD_FIELD = ';\nconst NEW_PASSWORD_FIELD = ';\nconst NEW_CONFIRMATION_PASSWORD_FIELD = ';\nconst SUBMIT_BUTTON = 'input[type=submit]';\n\n// UsersPasswordForm component that handles user password form\n// interactions.\nclass UsersPasswordForm extends BaseComponent {\n elements() {\n this.$currentPassword = this.$el.find(CURRENT_PASSWORD_FIELD);\n this.$newPassword = this.$el.find(NEW_PASSWORD_FIELD);\n this.$newPasswordConfirmation = this.$el.find(NEW_CONFIRMATION_PASSWORD_FIELD);\n this.$submit = this.$el.find(SUBMIT_BUTTON);\n }\n\n events() {\n this.$el.on('keyup', CURRENT_PASSWORD_FIELD, e => this.onKeyup(e));\n this.$el.on('keyup', NEW_PASSWORD_FIELD, e => this.onKeyup(e));\n this.$el.on('keyup', NEW_CONFIRMATION_PASSWORD_FIELD, e => this.onKeyup(e));\n }\n\n onKeyup() {\n const currentPassword = this.$currentPassword.val();\n const newPassword = this.$.val();\n const newPasswordConfirmation = this.$newPasswordConfirmation.val();\n\n const currentPasswordInvalid = !currentPassword;\n const newPasswordInvalid = !newPassword;\n const newPasswordConfirmationInvalid = !newPasswordConfirmation\n || newPassword !== Confirmation;\n\n if (currentPasswordInvalid || newPasswordInvalid || newPasswordConfirmationInvalid) {\n this.$submit.attr('disabled', 'disabled');\n } else {\n this.$submit.removeAttr('disabled');\n }\n }\n}\n\nexport default UsersPasswordForm;\n\n\n<|start_filename|>app/assets/javascripts/modules/webhooks/store.js<|end_filename|>\nimport Vue from 'vue';\n\nconst { set } = Vue;\n\nclass WebhooksStore {\n constructor() {\n this.state = {\n newFormVisible: false,\n editFormVisible: false,\n newHeaderFormVisible: false,\n };\n }\n\n set(key, value) {\n set(this.state, key, value);\n }\n}\n\nexport default new WebhooksStore();\n\n\n<|start_filename|>app/assets/javascripts/config.js<|end_filename|>\nexport default {\n pagination: window.PAGINATION,\n apiUrl: window.API_URL,\n};\n\n\n<|start_filename|>spec/javascripts/utils/range.spec.js<|end_filename|>\nimport range from '~/utils/range';\n\ndescribe('Range', () => {\n it('returns throws exception if start > end', () => {\n expect(() => {\n range(1, -2);\n }).toThrowError();\n });\n\n it('returns an array of integers', () => {\n expect(range(-1, 1)).toEqual([-1, 0, 1]);\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/webhooks/services/deliveries.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst oldResource = Vue.resource('namespaces/{namespaceId}/webhooks/{webhookId}/deliveries{/id}.json');\n\nfunction retrigger(namespaceId, webhookId, id) {\n return oldResource.update({ namespaceId, webhookId, id }, {});\n}\n\nexport default {\n retrigger,\n};\n\n\n<|start_filename|>spec/javascripts/modules/repositories/vulnerabilities-preview.spec.js<|end_filename|>\nimport { mount } from '@vue/test-utils';\n\nimport VulnerabilitiesPreview from '~/modules/vulnerabilities/components/preview';\n\ndescribe('vulnerabilities-preview', () => {\n let wrapper;\n\n beforeEach(() => {\n wrapper = mount(VulnerabilitiesPreview, {\n propsData: {\n vulnerabilities: [],\n },\n });\n });\n\n context('when no vulnerabilities', () => {\n it('shows passed', () => {\n expect(wrapper.find('.severity-passed').text()).toBe('Passed');\n });\n });\n\n context('when vulnerabilities', () => {\n it('shows highest severity and total number', () => {\n const vulnerabilities = [\n { severity: 'High' },\n { severity: 'High' },\n { severity: 'Low' },\n { severity: 'Low' },\n ];\n\n wrapper.setProps({ vulnerabilities });\n expect(wrapper.find('.severity-high').text()).toBe('2 High');\n expect(wrapper.find('.total').text()).toBe('4 total');\n });\n\n it('shows highest severity and total number [2]', () => {\n const vulnerabilities = [\n { severity: 'Critical' },\n { severity: 'High' },\n { severity: 'High' },\n { severity: 'Low' },\n { severity: 'Low' },\n ];\n\n wrapper.setProps({ vulnerabilities });\n expect(wrapper.find('.severity-critical').text()).toBe('1 Critical');\n expect(wrapper.find('.total').text()).toBe('5 total');\n });\n });\n});\n\n\n<|start_filename|>spec/javascripts/setup.js<|end_filename|>\nrequire('jsdom-global')();\n\nconst dayjs = require('dayjs');\nconst relativeTime = require('dayjs/plugin/relativeTime');\n\nglobal.expect = require('expect');\n\ndayjs.extend(relativeTime);\n\n\n<|start_filename|>app/assets/javascripts/modules/users/store.js<|end_filename|>\nclass UsersStore {\n constructor() {\n this.state = {\n newFormVisible: false,\n };\n }\n}\n\nexport default new UsersStore();\n\n\n<|start_filename|>app/assets/javascripts/modules/admin/registries/service.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst customActions = {\n validate: {\n method: 'GET',\n url: 'api/v1/registries/validate',\n },\n};\n\nconst resource = Vue.resource('api/v1/registries/{/id}.json', {}, customActions);\n\nfunction validate(registry, field = null) {\n const data = registry;\n\n if (field) {\n data['only[]'] = field;\n }\n\n return resource.validate(data)\n .then(response => response.data)\n .catch(() => null);\n}\n\nexport default {\n validate,\n};\n\n\n<|start_filename|>app/assets/javascripts/main.js<|end_filename|>\n// Bootstrap\nimport 'bootstrap/js/transition';\nimport 'bootstrap/js/tab';\nimport 'bootstrap/js/tooltip';\nimport 'bootstrap/js/popover';\nimport 'bootstrap/js/dropdown';\nimport 'bootstrap/js/button';\nimport 'bootstrap/js/collapse';\n\n// Life it up\nimport 'vendor/lifeitup_layout';\n\n// misc\nimport './plugins';\nimport './polyfill';\n\n// modules\nimport './modules/admin/registries';\nimport './modules/users';\nimport './modules/dashboard';\nimport './modules/repositories';\nimport './modules/namespaces';\nimport './modules/tags';\nimport './modules/teams';\nimport './modules/webhooks';\n\nimport './bootstrap';\nimport './globals';\n\n\n<|start_filename|>app/assets/javascripts/modules/repositories/services/comments.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst oldResource = Vue.resource('repositories/{repositoryId}/comments{/id}.json');\n\nfunction save(repositoryId, comment) {\n return oldResource.save({ repositoryId }, { comment });\n}\n\nfunction remove(repositoryId, id) {\n return oldResource.delete({ repositoryId, id });\n}\n\nexport default {\n save,\n remove,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/explore/pages/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport Result from '../components/result';\n\n$(() => {\n if (!$('body[data-route=\"explore/index\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: 'body[data-route=\"explore/index\"] .vue-root',\n\n components: {\n Result,\n },\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/admin/registries/index.js<|end_filename|>\nimport Vue from 'vue';\n\nimport AdminRegistriesNewPage from './pages/new';\nimport AdminRegistriesEditPage from './pages/edit';\n\n$(() => {\n if (!$('body[data-controller=\"admin/registries\"]').length) {\n return;\n }\n\n // eslint-disable-next-line no-new\n new Vue({\n el: '.vue-root',\n\n components: {\n AdminRegistriesNewPage,\n AdminRegistriesEditPage,\n },\n });\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/dashboard/components/search.js<|end_filename|>\nimport BaseComponent from '~/base/component';\n\nconst SEARCH_FIELD = '#search';\nconst CTRL = 17;\nconst SPACE = 32;\n\n// SearchComponent handles the state and the dynamic behavior of the\n// search input.\nclass SearchComponent extends BaseComponent {\n elements() {\n // Instance variables.\n this.keys = [\n { key: CTRL, pressed: false },\n { key: SPACE, pressed: false },\n ];\n this.keypressed = void 0;\n\n // UI elements.\n this.$search = this.$el.find(SEARCH_FIELD);\n }\n\n events() {\n this.$el.on('keydown', e => this.onKey(e, true));\n this.$el.on('keyup', e => this.onKey(e, false));\n }\n\n // onKey is a callback that should be executed on key events. The first\n // parameter is the event object, and `down` is a boolean specifying whether\n // this is a \"keydown\" event or not.\n onKey(e, down) {\n if (e.keyCode === CTRL || e.keyCode === SPACE) {\n // If we are on a key down event and ctrl is currently pressed, the\n // spacebar default action wont be triggered\n if (down && this.keys[0].v) {\n e.preventDefault();\n }\n\n this.keypressed = e.keyCode;\n this.searchKey(this.keypressed, down);\n }\n }\n\n // openSearch scrolls to the top if needed and focuses the search input.\n openSearch() {\n if ($(window).scrollTop() > 0) {\n $('html,body').unbind().animate({ scrollTop: 0 }, 500);\n }\n this.$search.val('').focus();\n }\n\n // activateSearch calls openSearch if both keys are pressed at the same time.\n activateSearch() {\n var performSearch = 0;\n\n $.each(this.keys, (i) => {\n if (this.keys[i].pressed) {\n performSearch++;\n }\n if (performSearch === 2) {\n this.openSearch();\n }\n });\n }\n\n // searchKey sets the given key as pressed/unpressed if it's one of the two\n // keys.\n searchKey(key, pressed) {\n $.each(this.keys, (i) => {\n if (this.keys[i].key === key) {\n this.keys[i].pressed = pressed;\n }\n });\n this.activateSearch();\n }\n}\n\nexport default SearchComponent;\n\n\n<|start_filename|>app/assets/javascripts/plugins/config.js<|end_filename|>\nimport config from '~/config';\n\nexport default function install(Vue) {\n Object.defineProperties(Vue.prototype, {\n $config: {\n get() {\n return config;\n },\n },\n });\n}\n\n\n<|start_filename|>app/assets/javascripts/modules/namespaces/store.js<|end_filename|>\nclass RepositoriesStore {\n constructor() {\n this.state = {\n newFormVisible: false,\n editFormVisible: false,\n isDeleting: false,\n isLoading: false,\n notLoaded: false,\n onGoingVisibilityRequest: false,\n };\n }\n}\n\nexport default new RepositoriesStore();\n\n\n<|start_filename|>app/assets/javascripts/plugins/index.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\nimport Vuelidate from 'vuelidate';\n\nimport EventBus from '~/plugins/eventbus';\nimport Alert from '~/plugins/alert';\nimport Config from '~/plugins/config';\n\nimport CSRF from '~/utils/csrf';\n\nimport configObj from '~/config';\n\nVue.use(Vuelidate);\nVue.use(VueResource);\nVue.use(EventBus);\nVue.use(Alert);\nVue.use(Config);\n\nVue.http.options.root = configObj.apiUrl;\n\nVue.http.interceptors.push((_request) => {\n window.$.active = window.$.active || 0;\n window.$.active += 1;\n\n return function () {\n window.$.active -= 1;\n };\n});\n\nVue.http.interceptors.push((request) => {\n const token = CSRF.token();\n\n if (token !== null) {\n request.headers.set('X-CSRF-Token', token);\n }\n});\n\n\n<|start_filename|>app/assets/javascripts/modules/dashboard/components/tabbed_widget.js<|end_filename|>\nimport BaseComponent from '~/base/component';\n\nclass TabbedWidget extends BaseComponent {\n elements() {\n this.$links = this.$el.find('a');\n }\n\n events() {\n this.$links.on('click', (e) => {\n e.preventDefault();\n $(this).tab('show');\n });\n }\n}\n\nexport default TabbedWidget;\n\n\n<|start_filename|>config/webpack.js<|end_filename|>\n/* eslint-disable quote-props, comma-dangle, import/no-extraneous-dependencies */\n// This file was based on Gitlab's config/webpack.config.js file.\n\nconst path = require('path');\nconst webpack = require('webpack');\nconst CompressionPlugin = require('compression-webpack-plugin');\nconst StatsPlugin = require('stats-webpack-plugin');\nconst VueLoaderPlugin = require('vue-loader/lib/plugin');\nconst UglifyJSPlugin = require('uglifyjs-webpack-plugin');\nconst { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');\n\nconst ROOT_PATH = path.resolve(__dirname, '..');\nconst CACHE_PATH = path.join(ROOT_PATH, 'tmp/cache');\nconst IS_PRODUCTION = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging';\nconst IS_TEST = process.env.NODE_ENV === 'test';\nconst { WEBPACK_REPORT } = process.env;\n\nconst VUE_VERSION = require('vue/package.json').version;\nconst VUE_LOADER_VERSION = require('vue-loader/package.json').version;\n\nconst devtool = IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map';\n\nvar config = {\n mode: IS_PRODUCTION ? 'production' : 'development',\n\n context: path.join(ROOT_PATH, 'app/assets/javascripts'),\n\n entry: {\n application: './main.js',\n unauthenticated: './unauthenticated.js',\n },\n\n output: {\n path: path.join(ROOT_PATH, 'public/assets/webpack'),\n publicPath: '/assets/webpack/',\n filename: IS_PRODUCTION ? '[name]-[chunkhash].js' : '[name].js',\n chunkFilename: IS_PRODUCTION ? '[name]-[chunkhash].chunk.js' : '[name].chunk.js',\n },\n\n resolve: {\n extensions: ['.js', '.vue'],\n mainFields: ['jsnext', 'main', 'browser'],\n alias: {\n '~': path.join(ROOT_PATH, 'app/assets/javascripts'),\n 'bootstrap/js': 'bootstrap-sass/assets/javascripts/bootstrap',\n 'vendor': path.join(ROOT_PATH, 'vendor/assets/javascripts'),\n 'vue$': 'vue/dist/vue.esm.js',\n },\n },\n\n devtool,\n\n module: {\n rules: [\n {\n test: /\\.js$/,\n exclude: file => /node_modules|vendor[\\\\/]assets/.test(file) && !/\\.vue\\.js/.test(file),\n loader: 'babel-loader',\n options: {\n cacheDirectory: path.join(CACHE_PATH, 'babel-loader'),\n },\n },\n {\n test: /\\.vue$/,\n exclude: /(node_modules|vendor\\/assets)/,\n loader: 'vue-loader',\n options: {\n cacheDirectory: path.join(CACHE_PATH, 'vue-loader'),\n cacheIdentifier: [\n process.env.NODE_ENV || 'development',\n webpack.version,\n VUE_VERSION,\n VUE_LOADER_VERSION,\n ].join('|'),\n },\n },\n {\n test: /\\.css$/,\n use: [\n 'vue-style-loader',\n 'css-loader',\n ],\n },\n ],\n },\n\n optimization: {\n splitChunks: {\n chunks: 'all',\n cacheGroups: {\n default: false,\n vendors: {\n priority: 10,\n test: /[\\\\/](node_modules|vendor[\\\\/]assets[\\\\/]javascripts)[\\\\/]/,\n },\n },\n },\n },\n\n plugins: [\n // Manifest filename must match config.webpack.manifest_filename\n // webpack-rails only needs assetsByChunkName to function properly\n new StatsPlugin('manifest.json', {\n chunkModules: false,\n source: false,\n chunks: false,\n modules: false,\n assets: true,\n }),\n\n new VueLoaderPlugin(),\n\n // fix legacy jQuery plugins which depend on globals\n new webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery',\n }),\n\n new webpack.IgnorePlugin(/^\\.\\/jquery$/, /jquery-ujs$/),\n\n WEBPACK_REPORT && new BundleAnalyzerPlugin({\n analyzerMode: 'static',\n generateStatsFile: true,\n openAnalyzer: false,\n reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'),\n statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'),\n }),\n ].filter(Boolean),\n};\n\nif (IS_PRODUCTION) {\n config.optimization.minimizer = [\n new UglifyJSPlugin({\n sourceMap: true,\n cache: true,\n parallel: true,\n uglifyOptions: {\n output: {\n comments: false\n }\n }\n })\n ];\n\n config.plugins.push(\n new webpack.NoEmitOnErrorsPlugin(),\n\n new webpack.LoaderOptionsPlugin({\n minimize: true,\n debug: false,\n }),\n\n new webpack.DefinePlugin({\n 'process.env': { NODE_ENV: JSON.stringify('production') },\n }),\n\n new CompressionPlugin()\n );\n}\n\nif (IS_TEST) {\n // eslint-disable-next-line\n config.externals = [require('webpack-node-externals')()];\n config.devtool = 'eval-source-map';\n}\n\nmodule.exports = config;\n\n\n<|start_filename|>app/assets/javascripts/utils/date.js<|end_filename|>\nimport dayjs from 'dayjs';\n\nconst isISO8601 = (date) => {\n const type = typeof date;\n const regex = /(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))/;\n\n if (type === 'object') {\n return dayjs(date).isValid();\n }\n\n if (type !== 'string'\n || !regex.test(date)) {\n return false;\n }\n\n return dayjs(date).isValid();\n};\n\nexport default {\n isISO8601,\n};\n\n\n<|start_filename|>app/assets/javascripts/modules/webhooks/services/headers.js<|end_filename|>\nimport Vue from 'vue';\nimport VueResource from 'vue-resource';\n\nVue.use(VueResource);\n\nconst oldResource = Vue.resource('namespaces/{namespaceId}/webhooks/{webhookId}/headers{/id}.json');\n\nfunction destroy(namespaceId, webhookId, id) {\n return oldResource.delete({ namespaceId, webhookId, id });\n}\n\nfunction save(namespaceId, webhookId, webhook_header) {\n return oldResource.save({ namespaceId, webhookId }, { webhook_header });\n}\n\nexport default {\n destroy,\n save,\n};\n"},"max_stars_repo_name":{"kind":"string","value":"xybots/Portus"}}},{"rowIdx":227,"cells":{"content":{"kind":"string","value":"<|start_filename|>.vscode/settings.json<|end_filename|>\n{\n \"editor.formatOnSave\": true,\n \"yaml.schemas\": {\n \"https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/github-workflow.json\": \".github/workflows/**\"\n }\n}\n\n<|start_filename|>src/JsonRpc.fs<|end_filename|>\nmodule Ionide.LanguageServerProtocol.JsonRpc\n\nopen Newtonsoft.Json\nopen Newtonsoft.Json.Linq\n\ntype MessageTypeTest =\n { []\n Version: string\n Id: int option\n Method: string option }\n\n[]\ntype MessageType =\n | Notification\n | Request\n | Response\n | Error\n\nlet getMessageType messageTest =\n match messageTest with\n | { Version = \"2.0\"; Id = Some _; Method = Some _ } -> MessageType.Request\n | { Version = \"2.0\"; Id = Some _; Method = None } -> MessageType.Response\n | { Version = \"2.0\"; Id = None; Method = Some _ } -> MessageType.Notification\n | _ -> MessageType.Error\n\ntype Request =\n { []\n Version: string\n Id: int\n Method: string\n Params: JToken option }\n static member Create(id: int, method': string, rpcParams: JToken option) =\n { Version = \"2.0\"; Id = id; Method = method'; Params = rpcParams }\n\ntype Notification =\n { []\n Version: string\n Method: string\n Params: JToken option }\n static member Create(method': string, rpcParams: JToken option) =\n { Version = \"2.0\"; Method = method'; Params = rpcParams }\n\nmodule ErrorCodes =\n let parseError = -32700\n let invalidRequest = -32600\n let methodNotFound = -32601\n let invalidParams = -32602\n let internalError = -32603\n let serverErrorStart = -32000\n let serverErrorEnd = -32099\n\ntype Error =\n { Code: int\n Message: string\n Data: JToken option }\n static member Create(code: int, message: string) = { Code = code; Message = message; Data = None }\n static member ParseError = Error.Create(ErrorCodes.parseError, \"Parse error\")\n static member InvalidRequest = Error.Create(ErrorCodes.invalidRequest, \"Invalid Request\")\n static member MethodNotFound = Error.Create(ErrorCodes.methodNotFound, \"Method not found\")\n static member InvalidParams = Error.Create(ErrorCodes.invalidParams, \"Invalid params\")\n static member InternalError = Error.Create(ErrorCodes.internalError, \"Internal error\")\n static member InternalErrorMessage message = Error.Create(ErrorCodes.internalError, message)\n\ntype Response =\n { []\n Version: string\n Id: int option\n Error: Error option\n []\n Result: JToken option }\n /// Json.NET conditional property serialization, controlled by naming convention\n member x.ShouldSerializeResult() = x.Error.IsNone\n\n static member Success(id: int, result: JToken option) =\n { Version = \"2.0\"; Id = Some id; Result = result; Error = None }\n\n static member Failure(id: int, error: Error) = { Version = \"2.0\"; Id = Some id; Result = None; Error = Some error }\n\n<|start_filename|>src/Server.fs<|end_filename|>\nnamespace Ionide.LanguageServerProtocol\n\nopen Ionide.LanguageServerProtocol.Types\n\nmodule private ServerUtil =\n /// Return the JSON-RPC \"not implemented\" error\n let notImplemented<'t> = async.Return LspResult.notImplemented<'t>\n\n /// Do nothing and ignore the notification\n let ignoreNotification = async.Return(())\n\nopen ServerUtil\n\n[]\ntype LspServer() =\n interface System.IDisposable with\n member x.Dispose() = x.Dispose()\n\n abstract member Dispose: unit -> unit\n\n /// The initialize request is sent as the first request from the client to the server.\n /// The initialize request may only be sent once.\n abstract member Initialize: InitializeParams -> AsyncLspResult\n\n default __.Initialize(_) = notImplemented\n\n /// The initialized notification is sent from the client to the server after the client received the result\n /// of the initialize request but before the client is sending any other request or notification to the server.\n /// The server can use the initialized notification for example to dynamically register capabilities.\n /// The initialized notification may only be sent once.\n abstract member Initialized: InitializedParams -> Async\n\n default __.Initialized(_) = ignoreNotification\n\n /// The shutdown request is sent from the client to the server. It asks the server to shut down, but to not\n /// exit (otherwise the response might not be delivered correctly to the client). There is a separate exit\n /// notification that asks the server to exit.\n abstract member Shutdown: unit -> Async\n\n default __.Shutdown() = ignoreNotification\n\n /// A notification to ask the server to exit its process.\n abstract member Exit: unit -> Async\n default __.Exit() = ignoreNotification\n\n /// The hover request is sent from the client to the server to request hover information at a given text\n /// document position.\n abstract member TextDocumentHover: TextDocumentPositionParams -> AsyncLspResult\n\n default __.TextDocumentHover(_) = notImplemented\n\n /// The document open notification is sent from the client to the server to signal newly opened text\n /// documents.\n ///\n /// The document’s truth is now managed by the client and the server must not try to read the document’s\n /// truth using the document’s uri. Open in this sense means it is managed by the client. It doesn't\n /// necessarily mean that its content is presented in an editor. An open notification must not be sent\n /// more than once without a corresponding close notification send before. This means open and close\n /// notification must be balanced and the max open count for a particular textDocument is one.\n abstract member TextDocumentDidOpen: DidOpenTextDocumentParams -> Async\n\n default __.TextDocumentDidOpen(_) = ignoreNotification\n\n /// The document change notification is sent from the client to the server to signal changes to a text document.\n abstract member TextDocumentDidChange: DidChangeTextDocumentParams -> Async\n default __.TextDocumentDidChange(_) = ignoreNotification\n\n /// The Completion request is sent from the client to the server to compute completion items at a given\n /// cursor position. Completion items are presented in the IntelliSense user interface.\n ///\n /// If computing full completion items is expensive, servers can additionally provide a handler for the\n /// completion item resolve request (‘completionItem/resolve’). This request is sent when a completion\n /// item is selected in the user interface. A typical use case is for example: the ‘textDocument/completion’\n /// request doesn’t fill in the documentation property for returned completion items since it is expensive\n /// to compute. When the item is selected in the user interface then a ‘completionItem/resolve’ request is\n /// sent with the selected completion item as a param. The returned completion item should have the\n /// documentation property filled in. The request can delay the computation of the detail and documentation\n /// properties. However, properties that are needed for the initial sorting and filtering, like sortText,\n /// filterText, insertText, and textEdit must be provided in the textDocument/completion request and must\n /// not be changed during resolve.\n abstract member TextDocumentCompletion: CompletionParams -> AsyncLspResult\n\n default __.TextDocumentCompletion(_) = notImplemented\n\n /// The request is sent from the client to the server to resolve additional information for a given\n /// completion item.\n abstract member CompletionItemResolve: CompletionItem -> AsyncLspResult\n\n default __.CompletionItemResolve(_) = notImplemented\n\n /// The rename request is sent from the client to the server to perform a workspace-wide rename of a symbol.\n abstract member TextDocumentRename: RenameParams -> AsyncLspResult\n default __.TextDocumentRename(_) = notImplemented\n\n /// The goto definition request is sent from the client to the server to resolve the definition location of\n /// a symbol at a given text document position.\n abstract member TextDocumentDefinition: TextDocumentPositionParams -> AsyncLspResult\n\n default __.TextDocumentDefinition(_) = notImplemented\n\n /// The references request is sent from the client to the server to resolve project-wide references for\n /// the symbol denoted by the given text document position.\n abstract member TextDocumentReferences: ReferenceParams -> AsyncLspResult\n\n default __.TextDocumentReferences(_) = notImplemented\n\n /// The document highlight request is sent from the client to the server to resolve a document highlights\n /// for a given text document position. For programming languages this usually highlights all references\n /// to the symbol scoped to this file.\n ///\n /// However we kept `textDocument/documentHighlight` and `textDocument/references` separate requests since\n /// the first one is allowed to be more fuzzy. Symbol matches usually have a DocumentHighlightKind of Read\n /// or Write whereas fuzzy or textual matches use Text as the kind.\n abstract member TextDocumentDocumentHighlight:\n TextDocumentPositionParams -> AsyncLspResult\n\n default __.TextDocumentDocumentHighlight(_) = notImplemented\n\n /// The document links request is sent from the client to the server to request the location of links\n /// in a document.\n abstract member TextDocumentDocumentLink: DocumentLinkParams -> AsyncLspResult\n\n default __.TextDocumentDocumentLink(_) = notImplemented\n\n /// The goto type definition request is sent from the client to the server to resolve the type definition\n /// location of a symbol at a given text document position.\n abstract member TextDocumentTypeDefinition: TextDocumentPositionParams -> AsyncLspResult\n\n default __.TextDocumentTypeDefinition(_) = notImplemented\n\n /// The goto implementation request is sent from the client to the server to resolve the implementation\n /// location of a symbol at a given text document position.\n abstract member TextDocumentImplementation: TextDocumentPositionParams -> AsyncLspResult\n\n default __.TextDocumentImplementation(_) = notImplemented\n\n /// The code action request is sent from the client to the server to compute commands for a given text\n /// document and range. These commands are typically code fixes to either fix problems or to\n /// beautify/refactor code. The result of a textDocument/codeAction request is an array of Command literals\n /// which are typically presented in the user interface. When the command is selected the server should be\n /// contacted again (via the workspace/executeCommand) request to execute the command.\n abstract member TextDocumentCodeAction: CodeActionParams -> AsyncLspResult\n\n default __.TextDocumentCodeAction(_) = notImplemented\n\n /// The code action request is sent from the client to the server to compute commands for a given text\n /// document and range. These commands are typically code fixes to either fix problems or to\n /// beautify/refactor code. The result of a textDocument/codeAction request is an array of Command literals\n /// which are typically presented in the user interface. When the command is selected the server should be\n /// contacted again (via the workspace/executeCommand) request to execute the command.\n abstract member CodeActionResolve: CodeAction -> AsyncLspResult\n\n default __.CodeActionResolve(_) = notImplemented\n\n /// The code lens request is sent from the client to the server to compute code lenses for a given\n /// text document.\n abstract member TextDocumentCodeLens: CodeLensParams -> AsyncLspResult\n\n default __.TextDocumentCodeLens(_) = notImplemented\n\n /// The code lens resolve request is sent from the client to the server to resolve the command for\n /// a given code lens item.\n abstract member CodeLensResolve: CodeLens -> AsyncLspResult\n\n default __.CodeLensResolve(_) = notImplemented\n\n /// The signature help request is sent from the client to the server to request signature information at\n /// a given cursor position.\n abstract member TextDocumentSignatureHelp: SignatureHelpParams -> AsyncLspResult\n\n default __.TextDocumentSignatureHelp(_) = notImplemented\n\n /// The document link resolve request is sent from the client to the server to resolve the target of\n /// a given document link.\n abstract member DocumentLinkResolve: DocumentLink -> AsyncLspResult\n\n default __.DocumentLinkResolve(_) = notImplemented\n\n /// The document color request is sent from the client to the server to list all color references\n /// found in a given text document. Along with the range, a color value in RGB is returned.\n abstract member TextDocumentDocumentColor: DocumentColorParams -> AsyncLspResult\n\n default __.TextDocumentDocumentColor(_) = notImplemented\n\n /// The color presentation request is sent from the client to the server to obtain a list of\n /// presentations for a color value at a given location. Clients can use the result to\n abstract member TextDocumentColorPresentation: ColorPresentationParams -> AsyncLspResult\n\n default __.TextDocumentColorPresentation(_) = notImplemented\n\n /// The document formatting request is sent from the client to the server to format a whole document.\n abstract member TextDocumentFormatting: DocumentFormattingParams -> AsyncLspResult\n default __.TextDocumentFormatting(_) = notImplemented\n\n /// The document range formatting request is sent from the client to the server to format a given\n /// range in a document.\n abstract member TextDocumentRangeFormatting: DocumentRangeFormattingParams -> AsyncLspResult\n\n default __.TextDocumentRangeFormatting(_) = notImplemented\n\n /// The document on type formatting request is sent from the client to the server to format parts\n /// of the document during typing.\n abstract member TextDocumentOnTypeFormatting: DocumentOnTypeFormattingParams -> AsyncLspResult\n\n default __.TextDocumentOnTypeFormatting(_) = notImplemented\n\n /// The document symbol request is sent from the client to the server to return a flat list of all symbols\n /// found in a given text document. Neither the symbol’s location range nor the symbol’s container name\n /// should be used to infer a hierarchy.\n abstract member TextDocumentDocumentSymbol:\n DocumentSymbolParams -> AsyncLspResult option>\n\n default __.TextDocumentDocumentSymbol(_) = notImplemented\n\n /// The watched files notification is sent from the client to the server when the client detects changes\n /// to files watched by the language client. It is recommended that servers register for these file\n /// events using the registration mechanism. In former implementations clients pushed file events without\n /// the server actively asking for it.\n abstract member WorkspaceDidChangeWatchedFiles: DidChangeWatchedFilesParams -> Async\n\n default __.WorkspaceDidChangeWatchedFiles(_) = ignoreNotification\n\n /// The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server to inform\n /// the server about workspace folder configuration changes. The notification is sent by default if both\n /// *ServerCapabilities/workspace/workspaceFolders* and *ClientCapabilities/workapce/workspaceFolders* are\n /// true; or if the server has registered to receive this notification it first.\n abstract member WorkspaceDidChangeWorkspaceFolders: DidChangeWorkspaceFoldersParams -> Async\n\n default __.WorkspaceDidChangeWorkspaceFolders(_) = ignoreNotification\n\n /// A notification sent from the client to the server to signal the change of configuration settings.\n abstract member WorkspaceDidChangeConfiguration: DidChangeConfigurationParams -> Async\n default __.WorkspaceDidChangeConfiguration(_) = ignoreNotification\n\n /// The will create files request is sent from the client to the server before files are actually created\n /// as long as the creation is triggered from within the client either by a user action or by applying a\n /// workspace edit\n abstract member WorkspaceWillCreateFiles: CreateFilesParams -> AsyncLspResult\n\n default __.WorkspaceWillCreateFiles(_) = notImplemented\n\n /// The did create files notification is sent from the client to the server when files were created\n /// from within the client.\n abstract member WorkspaceDidCreateFiles: CreateFilesParams -> Async\n\n default __.WorkspaceDidCreateFiles(_) = ignoreNotification\n\n /// The will rename files request is sent from the client to the server before files are actually renamed\n /// as long as the rename is triggered from within the client either by a user action or by applying a\n /// workspace edit.\n abstract member WorkspaceWillRenameFiles: RenameFilesParams -> AsyncLspResult\n\n default __.WorkspaceWillRenameFiles(_) = notImplemented\n\n /// The did rename files notification is sent from the client to the server when files were renamed from\n /// within the client.\n abstract member WorkspaceDidRenameFiles: RenameFilesParams -> Async\n\n default __.WorkspaceDidRenameFiles(_) = ignoreNotification\n\n /// The will delete files request is sent from the client to the server before files are actually deleted\n /// as long as the deletion is triggered from within the client either by a user action or by applying a\n /// workspace edit.\n abstract member WorkspaceWillDeleteFiles: DeleteFilesParams -> AsyncLspResult\n\n default __.WorkspaceWillDeleteFiles(_) = notImplemented\n\n /// The did delete files notification is sent from the client to the server when files were deleted from\n /// within the client.\n abstract member WorkspaceDidDeleteFiles: DeleteFilesParams -> Async\n\n default __.WorkspaceDidDeleteFiles(_) = ignoreNotification\n\n /// The workspace symbol request is sent from the client to the server to list project-wide symbols matching\n /// the query string.\n abstract member WorkspaceSymbol: WorkspaceSymbolParams -> AsyncLspResult\n\n default __.WorkspaceSymbol(_) = notImplemented\n\n /// The `workspace/executeCommand` request is sent from the client to the server to trigger command execution\n /// on the server. In most cases the server creates a `WorkspaceEdit` structure and applies the changes to the\n /// workspace using the request `workspace/applyEdit` which is sent from the server to the client.\n abstract member WorkspaceExecuteCommand: ExecuteCommandParams -> AsyncLspResult\n\n default __.WorkspaceExecuteCommand(_) = notImplemented\n\n /// The document will save notification is sent from the client to the server before the document is\n /// actually saved.\n abstract member TextDocumentWillSave: WillSaveTextDocumentParams -> Async\n\n default __.TextDocumentWillSave(_) = ignoreNotification\n\n /// The document will save request is sent from the client to the server before the document is actually saved.\n /// The request can return an array of TextEdits which will be applied to the text document before it is saved.\n /// Please note that clients might drop results if computing the text edits took too long or if a server\n /// constantly fails on this request. This is done to keep the save fast and reliable.\n abstract member TextDocumentWillSaveWaitUntil: WillSaveTextDocumentParams -> AsyncLspResult\n\n default __.TextDocumentWillSaveWaitUntil(_) = notImplemented\n\n /// The document save notification is sent from the client to the server when the document was saved\n /// in the client.\n abstract member TextDocumentDidSave: DidSaveTextDocumentParams -> Async\n\n default __.TextDocumentDidSave(_) = ignoreNotification\n\n /// The document close notification is sent from the client to the server when the document got closed in the\n /// client. The document’s truth now exists where the document’s uri points to (e.g. if the document’s uri is\n /// a file uri the truth now exists on disk). As with the open notification the close notification is about\n /// managing the document’s content. Receiving a close notification doesn't mean that the document was open in\n /// an editor before. A close notification requires a previous open notification to be sent.\n abstract member TextDocumentDidClose: DidCloseTextDocumentParams -> Async\n\n default __.TextDocumentDidClose(_) = ignoreNotification\n\n /// The folding range request is sent from the client to the server to return all folding ranges found in a given text document.\n abstract member TextDocumentFoldingRange: FoldingRangeParams -> AsyncLspResult\n default __.TextDocumentFoldingRange(_) = notImplemented\n\n /// The selection range request is sent from the client to the server to return suggested selection ranges at an array of given positions.\n /// A selection range is a range around the cursor position which the user might be interested in selecting.\n abstract member TextDocumentSelectionRange: SelectionRangeParams -> AsyncLspResult\n\n default __.TextDocumentSelectionRange(_) = notImplemented\n\n abstract member TextDocumentSemanticTokensFull: SemanticTokensParams -> AsyncLspResult\n default __.TextDocumentSemanticTokensFull(_) = notImplemented\n\n abstract member TextDocumentSemanticTokensFullDelta:\n SemanticTokensDeltaParams -> AsyncLspResult option>\n\n default __.TextDocumentSemanticTokensFullDelta(_) = notImplemented\n\n abstract member TextDocumentSemanticTokensRange: SemanticTokensRangeParams -> AsyncLspResult\n default __.TextDocumentSemanticTokensRange(_) = notImplemented\n\n /// The inlay hints request is sent from the client to the server to compute inlay hints for a given [text document, range] tuple\n /// that may be rendered in the editor in place with other text.\n abstract member TextDocumentInlayHint: InlayHintParams -> AsyncLspResult\n\n default __.TextDocumentInlayHint(_) = notImplemented\n\n /// The request is sent from the client to the server to resolve additional information for a given inlay hint.\n /// This is usually used to compute the `tooltip`, `location` or `command` properties of a inlay hint’s label part\n /// to avoid its unnecessary computation during the `textDocument/inlayHint` request.\n ///\n /// Consider the clients announces the `label.location` property as a property that can be resolved lazy using the client capability\n /// ```typescript\n /// textDocument.inlayHint.resolveSupport = { properties: ['label.location'] };\n /// ```\n /// then an inlay hint with a label part without a location needs to be resolved using the `inlayHint/resolve` request before it can be used.\n abstract member InlayHintResolve: InlayHint -> AsyncLspResult\n\n default __.InlayHintResolve(_) = notImplemented\n\n<|start_filename|>src/Client.fs<|end_filename|>\nnamespace Ionide.LanguageServerProtocol\n\nopen Ionide.LanguageServerProtocol.Types\n\nmodule private ClientUtil =\n /// Return the JSON-RPC \"not implemented\" error\n let notImplemented<'t> = async.Return LspResult.notImplemented<'t>\n\n /// Do nothing and ignore the notification\n let ignoreNotification = async.Return(())\n\nopen ClientUtil\n\n[]\ntype LspClient() =\n\n /// The show message notification is sent from a server to a client to ask the client to display\n /// a particular message in the user interface.\n abstract member WindowShowMessage: ShowMessageParams -> Async\n\n default __.WindowShowMessage(_) = ignoreNotification\n\n /// The show message request is sent from a server to a client to ask the client to display\n /// a particular message in the user interface. In addition to the show message notification the\n /// request allows to pass actions and to wait for an answer from the client.\n abstract member WindowShowMessageRequest: ShowMessageRequestParams -> AsyncLspResult\n\n default __.WindowShowMessageRequest(_) = notImplemented\n\n /// The log message notification is sent from the server to the client to ask the client to log\n ///a particular message.\n abstract member WindowLogMessage: LogMessageParams -> Async\n\n default __.WindowLogMessage(_) = ignoreNotification\n\n /// The telemetry notification is sent from the server to the client to ask the client to log\n /// a telemetry event.\n abstract member TelemetryEvent: Newtonsoft.Json.Linq.JToken -> Async\n\n default __.TelemetryEvent(_) = ignoreNotification\n\n /// The `client/registerCapability` request is sent from the server to the client to register for a new\n /// capability on the client side. Not all clients need to support dynamic capability registration.\n /// A client opts in via the dynamicRegistration property on the specific client capabilities. A client\n /// can even provide dynamic registration for capability A but not for capability B.\n abstract member ClientRegisterCapability: RegistrationParams -> AsyncLspResult\n\n default __.ClientRegisterCapability(_) = notImplemented\n\n /// The `client/unregisterCapability` request is sent from the server to the client to unregister a previously\n /// registered capability.\n abstract member ClientUnregisterCapability: UnregistrationParams -> AsyncLspResult\n\n default __.ClientUnregisterCapability(_) = notImplemented\n\n /// Many tools support more than one root folder per workspace. Examples for this are VS Code’s multi-root\n /// support, Atom’s project folder support or Sublime’s project support. If a client workspace consists of\n /// multiple roots then a server typically needs to know about this. The protocol up to know assumes one root\n /// folder which is announce to the server by the rootUri property of the InitializeParams.\n /// If the client supports workspace folders and announces them via the corresponding workspaceFolders client\n /// capability the InitializeParams contain an additional property workspaceFolders with the configured\n /// workspace folders when the server starts.\n ///\n /// The workspace/workspaceFolders request is sent from the server to the client to fetch the current open\n /// list of workspace folders. Returns null in the response if only a single file is open in the tool.\n /// Returns an empty array if a workspace is open but no folders are configured.\n abstract member WorkspaceWorkspaceFolders: unit -> AsyncLspResult\n\n default __.WorkspaceWorkspaceFolders() = notImplemented\n\n /// The workspace/configuration request is sent from the server to the client to fetch configuration\n /// settings from the client.\n ///\n /// The request can fetch n configuration settings in one roundtrip. The order of the returned configuration\n /// settings correspond to the order of the passed ConfigurationItems (e.g. the first item in the response\n /// is the result for the first configuration item in the params).\n abstract member WorkspaceConfiguration: ConfigurationParams -> AsyncLspResult\n\n default __.WorkspaceConfiguration(_) = notImplemented\n\n abstract member WorkspaceApplyEdit: ApplyWorkspaceEditParams -> AsyncLspResult\n default __.WorkspaceApplyEdit(_) = notImplemented\n\n /// The workspace/semanticTokens/refresh request is sent from the server to the client.\n /// Servers can use it to ask clients to refresh the editors for which this server provides semantic tokens.\n /// As a result the client should ask the server to recompute the semantic tokens for these editors.\n /// This is useful if a server detects a project wide configuration change which requires a re-calculation\n /// of all semantic tokens. Note that the client still has the freedom to delay the re-calculation of\n /// the semantic tokens if for example an editor is currently not visible.\n abstract member WorkspaceSemanticTokensRefresh: unit -> Async\n\n default __.WorkspaceSemanticTokensRefresh() = ignoreNotification\n\n /// The `workspace/inlayHint/refresh` request is sent from the server to the client.\n /// Servers can use it to ask clients to refresh the inlay hints currently shown in editors.\n /// As a result the client should ask the server to recompute the inlay hints for these editors.\n /// This is useful if a server detects a configuration change which requires a re-calculation\n /// of all inlay hints. Note that the client still has the freedom to delay the re-calculation of the inlay hints\n /// if for example an editor is currently not visible.\n abstract member WorkspaceInlayHintRefresh: unit -> Async\n\n default __.WorkspaceInlayHintRefresh() = ignoreNotification\n\n /// Diagnostics notification are sent from the server to the client to signal results of validation runs.\n ///\n /// Diagnostics are “owned” by the server so it is the server’s responsibility to clear them if necessary.\n /// The following rule is used for VS Code servers that generate diagnostics:\n ///\n /// * if a language is single file only (for example HTML) then diagnostics are cleared by the server when\n /// the file is closed.\n /// * if a language has a project system (for example C#) diagnostics are not cleared when a file closes.\n /// When a project is opened all diagnostics for all files are recomputed (or read from a cache).\n ///\n /// When a file changes it is the server’s responsibility to re-compute diagnostics and push them to the\n /// client. If the computed set is empty it has to push the empty array to clear former diagnostics.\n /// Newly pushed diagnostics always replace previously pushed diagnostics. There is no merging that happens\n /// on the client side.\n abstract member TextDocumentPublishDiagnostics: PublishDiagnosticsParams -> Async\n\n default __.TextDocumentPublishDiagnostics(_) = ignoreNotification"},"max_stars_repo_name":{"kind":"string","value":"baronfel/LanguageServerProtocol"}}},{"rowIdx":228,"cells":{"content":{"kind":"string","value":"<|start_filename|>Hashids/Classes/Hashids.h<|end_filename|>\n//\n// Hashids.h\n// Hashids\n//\n// Created by on 7/13/13.\n// Copyright (c) 2013 . All rights reserved.\n//\n\n#import \n\n#define HASHID_MIN_ALPHABET_LENGTH 4\n#define HASHID_SEP_DIV 3.5\n#define HASHID_GUARD_DIV 12\n#define HASHID_MAX_INT_VALUE 1000000000\n\n@interface HashidsException : NSException\n@end\n\n@interface NSMutableString (Hashids)\n\n- (NSString *) replaceIndex:(NSInteger)index withString:(NSString *)replaceString;\n\n@end\n\n@interface Hashids : NSObject\n\n+ (id)hashidWithSalt:(NSString *) salt;\n\n+ (id)hashidWithSalt:(NSString *) salt\n andMinLength:(NSInteger)minLength;\n\n+ (id)hashidWithSalt:(NSString *) salt\n minLength:(NSInteger) minLength\n andAlpha:(NSString *) alphabet;\n\n- (id)initWithSalt:(NSString *) salt\n minLength:(NSInteger) minLength\n andAlpha:(NSString *) alphabet;\n\n- (NSString *) encode:(NSNumber *)firstEntry, ... NS_REQUIRES_NIL_TERMINATION;\n- (NSArray *) decode:(NSString *) encoded;\n\n\n@end\n"},"max_stars_repo_name":{"kind":"string","value":"jofell/hashids-objc"}}},{"rowIdx":229,"cells":{"content":{"kind":"string","value":"<|start_filename|>test/vary.test.js<|end_filename|>\n'use strict'\n\nconst { test } = require('tap')\nconst vary = require('../vary')\n\ntest('Should not set reply header if none is passed', t => {\n t.plan(1)\n\n const replyMock = {\n getHeader (name) {\n return []\n },\n header (name, value) {\n t.fail('Should not be here')\n }\n }\n\n vary(replyMock, [])\n t.pass()\n})\n"},"max_stars_repo_name":{"kind":"string","value":"mikemaccana/fastify-cors"}}},{"rowIdx":230,"cells":{"content":{"kind":"string","value":"<|start_filename|>packages/p/pcre2/xmake.lua<|end_filename|>\npackage(\"pcre2\")\n\n set_homepage(\"https://www.pcre.org/\")\n set_description(\"A Perl Compatible Regular Expressions Library\")\n\n set_urls(\"https://ftp.pcre.org/pub/pcre/pcre2-$(version).zip\",\n \"ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre2-$(version).zip\")\n\n add_versions(\"10.23\", \"6301a525a8a7e63a5fac0c2fbfa0374d3eb133e511d886771e097e427707094a\")\n add_versions(\"10.30\", \"3677ce17854fffa68fce6b66442858f48f0de1f537f18439e4bd2771f8b4c7fb\")\n add_versions(\"10.31\", \"b4b40695a5347a770407d492c1749e35ba3970ca03fe83eb2c35d44343a5a444\")\n\n if is_host(\"windows\") then\n add_deps(\"cmake\")\n end\n\n add_configs(\"jit\", {description = \"Enable jit.\", default = true, type = \"boolean\"})\n add_configs(\"bitwidth\", {description = \"Set the code unit width.\", default = \"8\", values = {\"8\", \"16\", \"32\"}})\n\n on_load(function (package)\n local bitwidth = package:config(\"bitwidth\") or \"8\"\n package:add(\"links\", \"pcre2-\" .. bitwidth)\n package:add(\"defines\", \"PCRE2_CODE_UNIT_WIDTH=\" .. bitwidth)\n if not package:config(\"shared\") then\n package:add(\"defines\", \"PCRE2_STATIC\")\n end\n end)\n\n on_install(\"windows\", function (package)\n if package:version():lt(\"10.21\") then\n io.replace(\"CMakeLists.txt\", [[SET(CMAKE_C_FLAGS -I${PROJECT_SOURCE_DIR}/src)]], [[SET(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -I${PROJECT_SOURCE_DIR}/src\")]], {plain = true})\n end\n local configs = {\"-DPCRE2_BUILD_TESTS=OFF\", \"-DPCRE2_BUILD_PCRE2GREP=OFF\"}\n table.insert(configs, \"-DBUILD_SHARED_LIBS=\" .. (package:config(\"shared\") and \"ON\" or \"OFF\"))\n table.insert(configs, \"-DPCRE2_SUPPORT_JIT=\" .. (package:config(\"jit\") and \"ON\" or \"OFF\"))\n local bitwidth = package:config(\"bitwidth\") or \"8\"\n if bitwidth ~= \"8\" then\n table.insert(configs, \"-DPCRE2_BUILD_PCRE2_8=OFF\")\n table.insert(configs, \"-DPCRE2_BUILD_PCRE2_\" .. bitwidth .. \"=ON\")\n end\n if package:debug() then\n table.insert(configs, \"-DPCRE2_DEBUG=ON\")\n end\n if package:is_plat(\"windows\") then\n table.insert(configs, \"-DPCRE2_STATIC_RUNTIME=\" .. (package:config(\"vs_runtime\"):startswith(\"MT\") and \"ON\" or \"OFF\"))\n end\n import(\"package.tools.cmake\").install(package, configs)\n end)\n\n on_install(\"macosx\", \"linux\", \"mingw\", function (package)\n local configs = {}\n table.insert(configs, \"--enable-shared=\" .. (package:config(\"shared\") and \"yes\" or \"no\"))\n table.insert(configs, \"--enable-static=\" .. (package:config(\"shared\") and \"no\" or \"yes\"))\n if package:debug() then\n table.insert(configs, \"--enable-debug\")\n end\n if package:config(\"pic\") ~= false then\n table.insert(configs, \"--with-pic\")\n end\n if package:config(\"jit\") then\n table.insert(configs, \"--enable-jit\")\n end\n local bitwidth = package:config(\"bitwidth\") or \"8\"\n if bitwidth ~= \"8\" then\n table.insert(configs, \"--disable-pcre2-8\")\n table.insert(configs, \"--enable-pcre2-\" .. bitwidth)\n end\n import(\"package.tools.autoconf\").install(package, configs)\n end)\n\n on_test(function (package)\n assert(package:has_cfuncs(\"pcre2_compile\", {includes = \"pcre2.h\"}))\n end)\n"},"max_stars_repo_name":{"kind":"string","value":"wsw0108/xmake-repo"}}},{"rowIdx":231,"cells":{"content":{"kind":"string","value":"<|start_filename|>main.go<|end_filename|>\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/bendahl/uinput\"\n\t\"github.com/godbus/dbus\"\n\tevdev \"github.com/gvalkov/golang-evdev\"\n)\n\nvar (\n\tconfig Config\n\n\tdbusConn *dbus.Conn\n\tkeyboard uinput.Keyboard\n\tthreshold time.Time\n\n\tpressed = make(map[uint16]struct{})\n\n\tconfigFile = flag.String(\"config\", \"config.json\", \"path to config file\")\n\tdebug = flag.Bool(\"debug\", false, \"enables debug output\")\n\ttimeout = flag.Uint(\"threshold\", 200, \"threshold in ms between wheel events\")\n)\n\ntype Event struct {\n\t*evdev.InputEvent\n\tDevice Device\n}\n\n// logs if debug is enabled\nfunc dLog(a ...interface{}) {\n\tif !*debug {\n\t\treturn\n\t}\n\n\tlog.Println(a...)\n}\n\n// prints all detected input devices\nfunc listDevices() error {\n\tdevs, err := evdev.ListInputDevices()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't find input devices\")\n\t}\n\n\tfor _, val := range devs {\n\t\tdLog(\"ID->\", val.File.Name(), \"Device->\", val.Name)\n\t}\n\n\treturn nil\n}\n\n// findDevice returns the device file matching an input device's name\nfunc findDevice(s string) (string, error) {\n\tdevs, err := evdev.ListInputDevices()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, val := range devs {\n\t\tif strings.Contains(val.Name, s) {\n\t\t\treturn val.File.Name(), nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"No such device\")\n}\n\n// emulates a (multi-)key press\nfunc emulateKeyPress(keys string) {\n\tkk := strings.Split(keys, \"-\")\n\tfor i, k := range kk {\n\t\tkc, err := strconv.Atoi(k)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"%s is not a valid keycode: %s\", k, err)\n\t\t}\n\n\t\tif i+1 < len(kk) {\n\t\t\tkeyboard.KeyDown(kc)\n\t\t\tdefer keyboard.KeyUp(kc)\n\t\t} else {\n\t\t\tkeyboard.KeyPress(kc)\n\t\t}\n\t}\n}\n\n// executes a dbus method\nfunc executeDBusMethod(object, path, method, args string) {\n\tcall := dbusConn.Object(object, dbus.ObjectPath(path)).Call(method, 0)\n\tif call.Err != nil {\n\t\tlog.Printf(\"dbus call failed: %s\", call.Err)\n\t}\n}\n\n// executes a command\nfunc executeCommand(cmd string) {\n\targs := strings.Split(cmd, \" \")\n\tc := exec.Command(args[0], args[1:]...)\n\tif err := c.Start(); err != nil {\n\t\tpanic(err)\n\t}\n\terr := c.Wait()\n\tif err != nil {\n\t\tlog.Printf(\"command failed: %s\", err)\n\t}\n}\n\n// executes an action\nfunc executeAction(a Action) {\n\tdLog(fmt.Sprintf(\"Executing action: %+v\", a))\n\n\tif a.Keycode != \"\" {\n\t\temulateKeyPress(a.Keycode)\n\t}\n\tif a.DBus.Method != \"\" {\n\t\texecuteDBusMethod(a.DBus.Object, a.DBus.Path, a.DBus.Method, a.DBus.Value)\n\t}\n\tif a.Exec != \"\" {\n\t\texecuteCommand(a.Exec)\n\t}\n}\n\n// handles mouse wheel events\nfunc mouseWheelEvent(ev Event, activeWindow Window) {\n\trel := evdev.RelEvent{}\n\trel.New(ev.InputEvent)\n\n\tif ev.Code != evdev.REL_HWHEEL && ev.Code != evdev.REL_DIAL {\n\t\treturn\n\t}\n\n\tif time.Since(threshold) < time.Millisecond*time.Duration(*timeout) {\n\t\tdLog(\"Discarding wheel event below threshold\")\n\t\treturn\n\t}\n\tthreshold = time.Now()\n\n\tswitch ev.Code {\n\tcase evdev.REL_HWHEEL:\n\t\trr := config.Rules.\n\t\t\tFilterByDevice(ev.Device).\n\t\t\tFilterByDial(0).\n\t\t\tFilterByHWheel(ev.Value).\n\t\t\tFilterByKeycodes(pressed).\n\t\t\tFilterByApplication(activeWindow.Class)\n\t\tif len(rr) == 0 {\n\t\t\treturn\n\t\t}\n\n\t\texecuteAction(rr[0].Action)\n\n\tcase evdev.REL_DIAL:\n\t\trr := config.Rules.\n\t\t\tFilterByDevice(ev.Device).\n\t\t\tFilterByDial(ev.Value).\n\t\t\tFilterByHWheel(0).\n\t\t\tFilterByKeycodes(pressed).\n\t\t\tFilterByApplication(activeWindow.Class)\n\t\tif len(rr) == 0 {\n\t\t\treturn\n\t\t}\n\n\t\texecuteAction(rr[0].Action)\n\n\tdefault:\n\t\t// dLog(rel.String())\n\t}\n}\n\n// handles key events\nfunc keyEvent(ev Event, activeWindow Window) {\n\tkev := evdev.KeyEvent{}\n\tkev.New(ev.InputEvent)\n\n\tpressed[ev.Code] = struct{}{}\n\tif kev.State != evdev.KeyUp {\n\t\treturn\n\t}\n\n\trr := config.Rules.\n\t\tFilterByDevice(ev.Device).\n\t\tFilterByHWheel(0).\n\t\tFilterByDial(0).\n\t\tFilterByKeycodes(pressed).\n\t\tFilterByApplication(activeWindow.Class)\n\tdelete(pressed, ev.Code)\n\n\tif len(rr) == 0 {\n\t\treturn\n\t}\n\n\texecuteAction(rr[0].Action)\n}\n\nfunc handleEvent(ev Event, win Window) {\n\tswitch ev.Type {\n\tcase evdev.EV_KEY:\n\t\t// dLog(\"Key event:\", ev.String())\n\t\tkeyEvent(ev, win)\n\tcase evdev.EV_REL:\n\t\t// dLog(\"Rel event:\", ev.String())\n\t\tmouseWheelEvent(ev, win)\n\tcase evdev.EV_ABS:\n\tcase evdev.EV_SYN:\n\tcase evdev.EV_MSC:\n\tcase evdev.EV_LED:\n\tcase evdev.EV_SND:\n\tcase evdev.EV_SW:\n\tcase evdev.EV_PWR:\n\tcase evdev.EV_FF:\n\tcase evdev.EV_FF_STATUS:\n\tdefault:\n\t\tlog.Println(\"Unexpected event type:\", ev.String())\n\t}\n}\n\nfunc subscribeToDevice(dev Device, keychan chan Event) {\n\tgo func(dev Device) {\n\t\tfor {\n\t\t\tvar err error\n\t\t\tdf := dev.Dev\n\t\t\tif df == \"\" {\n\t\t\t\tdf, err = findDevice(dev.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Could not find device for %s\", dev.Name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ted, err := evdev.Open(df)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdLog(ed.String())\n\n\t\t\tfor {\n\t\t\t\tev, eerr := ed.ReadOne()\n\t\t\t\tif eerr != nil {\n\t\t\t\t\tlog.Printf(\"Error reading from device: %v\", eerr)\n\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tkeychan <- Event{\n\t\t\t\t\tInputEvent: ev,\n\t\t\t\t\tDevice: dev,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}(dev)\n}\n\nfunc main() {\n\tvar err error\n\tflag.Parse()\n\tconfig, err = LoadConfig(*configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdbusConn, err = dbus.SessionBus()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tx := Connect(os.Getenv(\"DISPLAY\"))\n\tdefer x.Close()\n\n\ttracker := make(chan Window)\n\tx.TrackActiveWindow(tracker, time.Second)\n\tgo func() {\n\t\tfor w := range tracker {\n\t\t\tdLog(fmt.Sprintf(\"Active window changed to %s (%s)\", w.Class, w.Name))\n\t\t}\n\t}()\n\n\tkeyboard, err = uinput.CreateKeyboard(\"/dev/uinput\", []byte(\"Virtual Wand\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create virtual input device (/dev/uinput): %s\", err)\n\t}\n\tdefer keyboard.Close()\n\n\terr = listDevices()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkeychan := make(chan Event)\n\tfor _, dev := range config.Devices {\n\t\tsubscribeToDevice(dev, keychan)\n\t}\n\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, os.Interrupt, syscall.SIGTERM)\n\tvar quit bool\n\n\tfor {\n\t\tselect {\n\t\tcase <-sigchan:\n\t\t\tquit = true\n\t\tcase ev := <-keychan:\n\t\t\thandleEvent(ev, x.ActiveWindow())\n\t\t}\n\n\t\tif quit {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"Shutting down...\")\n\tif *debug {\n\t\terr = config.Save(*configFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\n\n<|start_filename|>config.go<|end_filename|>\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype DBus struct {\n\tObject string `json:\"object,omitempty\"`\n\tPath string `json:\"path,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tValue string `json:\"value,omitempty\"`\n}\n\ntype Action struct {\n\tKeycode string `json:\"keycode,omitempty\"`\n\tExec string `json:\"exec,omitempty\"`\n\tDBus DBus `json:\"dbus,omitempty\"`\n}\n\ntype Rule struct {\n\tDevice *Device `json:\"device,omitempty\"`\n\tApplication string `json:\"application,omitempty\"`\n\tKeycode string `json:\"keycode,omitempty\"`\n\tHWheel int32 `json:\"hwheel\"`\n\tDial int32 `json:\"dial\"`\n\tAction Action `json:\"action\"`\n}\ntype Rules []Rule\n\ntype Device struct {\n\tName string `json:\"name,omitempty\"`\n\tDev string `json:\"dev,omitempty\"`\n}\ntype Devices []Device\n\ntype Config struct {\n\tDevices Devices `json:\"devices\"`\n\tRules Rules `json:\"rules\"`\n}\n\n// LoadConfig loads config from filename\nfunc LoadConfig(filename string) (Config, error) {\n\tconfig := Config{}\n\n\tj, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.Unmarshal(j, &config)\n\treturn config, err\n}\n\n// Save writes config as json to filename\nfunc (c Config) Save(filename string) error {\n\tj, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filename, j, 0644)\n}\n\nfunc (r Rules) FilterByDevice(dev Device) Rules {\n\tvar res Rules\n\tfor _, v := range r {\n\t\tif v.Device == nil ||\n\t\t\t(len(dev.Name) > 0 && v.Device.Name == dev.Name) ||\n\t\t\t(len(dev.Dev) > 0 && v.Device.Dev == dev.Dev) {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (r Rules) FilterByApplication(name string) Rules {\n\tvar res Rules\n\tfor _, v := range r {\n\t\tif v.Application == \"\" || v.Application == name {\n\t\t\tres = append(res, v)\n\t\t}\n\t\tif len(v.Application) > 0 && v.Application[0] == '!' {\n\t\t\tif v.Application[1:] != name {\n\t\t\t\tres = append(res, v)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (r Rules) FilterByHWheel(wheel int32) Rules {\n\tvar res Rules\n\tfor _, v := range r {\n\t\tif v.HWheel == 0 || v.HWheel == wheel {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (r Rules) FilterByDial(dial int32) Rules {\n\tvar res Rules\n\tfor _, v := range r {\n\t\tif v.Dial == 0 || v.Dial == dial {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (r Rules) FilterByKeycodes(pressed map[uint16]struct{}) Rules {\n\tvar res Rules\n\tfor _, v := range r {\n\t\tkk := strings.Split(v.Keycode, \"-\")\n\t\tmatch := true\n\t\tfor _, k := range kk {\n\t\t\tif k == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkc, err := strconv.Atoi(k)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"%s is not a valid keycode: %s\", k, err)\n\t\t\t}\n\n\t\t\tif _, ok := pressed[uint16(kc)]; !ok {\n\t\t\t\tmatch = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif match {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn res\n}\n"},"max_stars_repo_name":{"kind":"string","value":"muesli/magicwand"}}},{"rowIdx":232,"cells":{"content":{"kind":"string","value":"<|start_filename|>ReliableNetcode/Utils/DateTimeEx.cs<|end_filename|>\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ReliableNetcode.Utils\n{\n\tinternal static class DateTimeEx\n\t{\n\t\tpublic static double GetTotalSeconds(this DateTime time)\n\t\t{\n\t\t\treturn (time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;\n\t\t}\n\n\t\t/// \n\t\t/// Gets the Unix timestamp of the DateTime object\n\t\t/// \n\t\tpublic static ulong ToUnixTimestamp(this DateTime time)\n\t\t{\n\t\t\treturn (ulong)Math.Truncate(time.GetTotalSeconds());\n\t\t}\n\t}\n}\n\n\n<|start_filename|>ReliableNetcode/Utils/ObjPool.cs<|end_filename|>\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ReliableNetcode.Utils\n{\n\tinternal static class ObjPool where T : new()\n\t{\n\t\tprivate static Queue pool = new Queue();\n\n\t\tpublic static T Get()\n\t\t{\n lock (pool) {\n if (pool.Count > 0)\n return pool.Dequeue();\n }\n\n\t\t\treturn new T();\n\t\t}\n\n\t\tpublic static void Return(T val)\n\t\t{\n lock (pool) {\n pool.Enqueue(val);\n }\n\t\t}\n\t}\n}\n\n\n<|start_filename|>ReliableNetcode/Utils/IO/ByteArrayReader.cs<|end_filename|>\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace ReliableNetcode.Utils\n{\n\t/// \n\t/// Helper class for a quick non-allocating way to read or write from/to temporary byte arrays as streams\n\t/// \n\tpublic class ByteArrayReaderWriter : IDisposable\n\t{\n\t\tprotected static Queue readerPool = new Queue();\n\n\t\t/// \n\t\t/// Get a reader/writer for the given byte array\n\t\t/// \n\t\tpublic static ByteArrayReaderWriter Get(byte[] byteArray)\n\t\t{\n\t\t\tByteArrayReaderWriter reader = null;\n\n lock (readerPool) {\n if (readerPool.Count > 0) {\n reader = readerPool.Dequeue();\n }\n else {\n reader = new ByteArrayReaderWriter();\n }\n }\n\n\t\t\treader.SetStream(byteArray);\n\t\t\treturn reader;\n\t\t}\n\n\t\t/// \n\t\t/// Release a reader/writer to the pool\n\t\t/// \n\t\tpublic static void Release(ByteArrayReaderWriter reader)\n\t\t{\n lock (readerPool) {\n readerPool.Enqueue(reader);\n }\n\t\t}\n\n\t\tpublic long ReadPosition\n\t\t{\n\t\t\tget { return readStream.Position; }\n\t\t}\n\n\t\tpublic bool IsDoneReading\n\t\t{\n\t\t\tget { return readStream.Position >= readStream.Length; }\n\t\t}\n\n\t\tpublic long WritePosition\n\t\t{\n\t\t\tget { return writeStream.Position; }\n\t\t}\n\n\t\tprotected ByteStream readStream;\n\t\tprotected ByteStream writeStream;\n\n\t\tpublic ByteArrayReaderWriter()\n\t\t{\n\t\t\tthis.readStream = new ByteStream();\n\t\t\tthis.writeStream = new ByteStream();\n\t\t}\n\n\t\tpublic void SetStream(byte[] byteArray)\n\t\t{\n\t\t\tthis.readStream.SetStreamSource(byteArray);\n\t\t\tthis.writeStream.SetStreamSource(byteArray);\n\t\t}\n\n\t\tpublic void SeekRead(long pos)\n\t\t{\n\t\t\tthis.readStream.Seek(pos, SeekOrigin.Begin);\n\t\t}\n\n\t\tpublic void SeekWrite(long pos)\n\t\t{\n\t\t\tthis.writeStream.Seek(pos, SeekOrigin.Begin);\n\t\t}\n\n\t\tpublic void Write(byte val) { writeStream.Write(val); }\n\t\tpublic void Write(byte[] val) { writeStream.Write(val); }\n\t\tpublic void Write(char val) { writeStream.Write(val); }\n\t\tpublic void Write(char[] val) { writeStream.Write(val); }\n\t\tpublic void Write(string val) { writeStream.Write(val); }\n\t\tpublic void Write(short val) { writeStream.Write(val); }\n\t\tpublic void Write(int val) { writeStream.Write(val); }\n\t\tpublic void Write(long val) { writeStream.Write(val); }\n\t\tpublic void Write(ushort val) { writeStream.Write(val); }\n\t\tpublic void Write(uint val) { writeStream.Write(val); }\n\t\tpublic void Write(ulong val) { writeStream.Write(val); }\n\t\tpublic void Write(float val) { writeStream.Write(val); }\n\t\tpublic void Write(double val) { writeStream.Write(val); }\n\n\t\tpublic void WriteASCII(char[] chars)\n\t\t{\n\t\t\tfor (int i = 0; i < chars.Length; i++)\n\t\t\t{\n\t\t\t\tbyte asciiCode = (byte)(chars[i] & 0xFF);\n\t\t\t\tWrite(asciiCode);\n\t\t\t}\n\t\t}\n\n\t\tpublic void WriteASCII(string str)\n\t\t{\n\t\t\tfor (int i = 0; i < str.Length; i++)\n\t\t\t{\n\t\t\t\tbyte asciiCode = (byte)(str[i] & 0xFF);\n\t\t\t\tWrite(asciiCode);\n\t\t\t}\n\t\t}\n\n\t\tpublic void WriteBuffer(byte[] buffer, int length)\n\t\t{\n\t\t\tfor (int i = 0; i < length; i++)\n\t\t\t\tWrite(buffer[i]);\n\t\t}\n\n\t\tpublic byte ReadByte() { return readStream.ReadByte(); }\n\t\tpublic byte[] ReadBytes(int length) { return readStream.ReadBytes(length); }\n\t\tpublic char ReadChar() { return readStream.ReadChar(); }\n\t\tpublic char[] ReadChars(int length) { return readStream.ReadChars(length); }\n\t\tpublic string ReadString() { return readStream.ReadString(); }\n\t\tpublic short ReadInt16() { return readStream.ReadInt16(); }\n\t\tpublic int ReadInt32() { return readStream.ReadInt32(); }\n\t\tpublic long ReadInt64() { return readStream.ReadInt64(); }\n\t\tpublic ushort ReadUInt16() { return readStream.ReadUInt16(); }\n\t\tpublic uint ReadUInt32() { return readStream.ReadUInt32(); }\n\t\tpublic ulong ReadUInt64() { return readStream.ReadUInt64(); }\n\n\t\tpublic float ReadSingle() { return readStream.ReadSingle(); }\n\t\tpublic double ReadDouble() { return readStream.ReadDouble(); }\n\n\t\tpublic void ReadASCIICharsIntoBuffer(char[] buffer, int length)\n\t\t{\n\t\t\tfor (int i = 0; i < length; i++)\n\t\t\t\tbuffer[i] = (char)ReadByte();\n\t\t}\n\n\t\tpublic void ReadBytesIntoBuffer(byte[] buffer, int length)\n\t\t{\n\t\t\tfor (int i = 0; i < length; i++)\n\t\t\t\tbuffer[i] = ReadByte();\n\t\t}\n\n\t\tpublic void Dispose()\n\t\t{\n\t\t\tRelease(this);\n\t\t}\n\t}\n}\n\n\n<|start_filename|>ReliableNetcode/Utils/ByteBuffer.cs<|end_filename|>\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ReliableNetcode.Utils\n{\n\tinternal class ByteBuffer\n\t{\n\t\tpublic int Length\n\t\t{\n\t\t\tget { return size; }\n\t\t}\n\n\t\tpublic byte[] InternalBuffer\n\t\t{\n\t\t\tget { return _buffer; }\n\t\t}\n\n\t\tprotected byte[] _buffer;\n\t\tprotected int size;\n\n\t\tpublic ByteBuffer()\n\t\t{\n\t\t\t_buffer = null;\n\t\t\tthis.size = 0;\n\t\t}\n\n\t\tpublic ByteBuffer(int size = 0)\n\t\t{\n\t\t\t_buffer = new byte[size];\n\t\t\tthis.size = size;\n\t\t}\n\n\t\tpublic void SetSize(int newSize)\n\t\t{\n\t\t\tif (_buffer == null || _buffer.Length < newSize)\n\t\t\t{\n\t\t\t\tbyte[] newBuffer = new byte[newSize];\n\n\t\t\t\tif (_buffer != null)\n\t\t\t\t\tSystem.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _buffer.Length);\n\n\t\t\t\t_buffer = newBuffer;\n\t\t\t}\n\n\t\t\tsize = newSize;\n\t\t}\n\n\t\tpublic void BufferCopy(byte[] source, int src, int dest, int length)\n\t\t{\n\t\t\tSystem.Buffer.BlockCopy(source, src, _buffer, dest, length);\n\t\t}\n\n\t\tpublic void BufferCopy(ByteBuffer source, int src, int dest, int length)\n {\n System.Buffer.BlockCopy(source._buffer, src, _buffer, dest, length);\n }\n\n\t\tpublic byte this[int index]\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tif (index < 0 || index > size) throw new System.IndexOutOfRangeException();\n\t\t\t\treturn _buffer[index];\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tif (index < 0 || index > size) throw new System.IndexOutOfRangeException();\n\t\t\t\t_buffer[index] = value;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n<|start_filename|>ReliableNetcode/PacketHeader.cs<|end_filename|>\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing ReliableNetcode.Utils;\n\nnamespace ReliableNetcode\n{\n internal class SentPacketData\n {\n public double time;\n public bool acked;\n public uint packetBytes;\n }\n\n internal class ReceivedPacketData\n {\n public double time;\n public uint packetBytes;\n }\n\n internal class FragmentReassemblyData\n {\n public ushort Sequence;\n public ushort Ack;\n public uint AckBits;\n public int NumFragmentsReceived;\n public int NumFragmentsTotal;\n public ByteBuffer PacketDataBuffer = new ByteBuffer();\n public int PacketBytes;\n public int HeaderOffset;\n public bool[] FragmentReceived = new bool[256];\n\n public void StoreFragmentData(byte channelID, ushort sequence, ushort ack, uint ackBits, int fragmentID, int fragmentSize, byte[] fragmentData, int fragmentBytes)\n {\n int copyOffset = 0;\n\n if (fragmentID == 0) {\n byte[] packetHeader = BufferPool.GetBuffer(Defines.MAX_PACKET_HEADER_BYTES);\n int headerBytes = PacketIO.WritePacketHeader(packetHeader, channelID, sequence, ack, ackBits);\n this.HeaderOffset = Defines.MAX_PACKET_HEADER_BYTES - headerBytes;\n\n if (this.PacketDataBuffer.Length < (Defines.MAX_PACKET_HEADER_BYTES + fragmentSize))\n this.PacketDataBuffer.SetSize(Defines.MAX_PACKET_HEADER_BYTES + fragmentSize);\n\n this.PacketDataBuffer.BufferCopy(packetHeader, 0, this.HeaderOffset, headerBytes);\n copyOffset = headerBytes;\n\n fragmentBytes -= headerBytes;\n\n BufferPool.ReturnBuffer(packetHeader);\n }\n\n int writePos = Defines.MAX_PACKET_HEADER_BYTES + fragmentID * fragmentSize;\n int end = writePos + fragmentBytes;\n\n if (this.PacketDataBuffer.Length < end)\n this.PacketDataBuffer.SetSize(end);\n\n if (fragmentID == NumFragmentsTotal - 1) {\n this.PacketBytes = (this.NumFragmentsTotal - 1) * fragmentSize + fragmentBytes;\n }\n\n this.PacketDataBuffer.BufferCopy(fragmentData, copyOffset, Defines.MAX_PACKET_HEADER_BYTES + fragmentID * fragmentSize, fragmentBytes);\n }\n }\n}\n"},"max_stars_repo_name":{"kind":"string","value":"gresolio/ReliableNetcode.NET"}}},{"rowIdx":233,"cells":{"content":{"kind":"string","value":"<|start_filename|>sources/converter.cpp<|end_filename|>\n#include \"converter.hpp\"\r\n\r\nint32_t* cvtMat2Int32(const cv::Mat& srcImage)\r\n{\r\n\tint32_t *result = new int32_t[srcImage.cols*srcImage.rows];\r\n\tint offset = 0;\r\n\r\n\tfor (int i = 0; i> 8) & 0xff);\r\n\t\tint32_t red = ((a >> 16) & 0xff);\r\n\t\toutImage.data[i] = blue;\r\n\t\toutImage.data[i + 1] = green;\r\n\t\toutImage.data[i + 2] = red;\r\n\t}\r\n\treturn;\r\n}\n\n<|start_filename|>sources/resizeOMP.cpp<|end_filename|>\n#include \"resizeOMP.hpp\"\r\n//#include \"omp.h\"\r\n\r\nint* resizeBilinear_omp(int* pixels, int w, int h, int w2, int h2)\r\n{\r\n\tint32_t* temp = new int32_t[w2*h2];\r\n\tfloat x_ratio = ((float)(w - 1)) / w2;\r\n\tfloat y_ratio = ((float)(h - 1)) / h2;\r\n\tomp_set_num_threads(24);\r\n#pragma omp parallel //num_threads(8)\r\n\t{\r\n#pragma omp for //schedule(static, w /24)\r\n\t\tfor (int i = 0; i < h2; i++)\r\n\t\t{\r\n\t\t\tint32_t a, b, c, d, x, y, index;\r\n\t\t\tfloat x_diff, y_diff, blue, red, green;\r\n\t\t\tint offset = i*w2;\r\n\t\t\tfor (int j = 0; j < w2; j++)\r\n\t\t\t{\r\n\t\t\t\tx = (int)(x_ratio * j);\r\n\t\t\t\ty = (int)(y_ratio * i);\r\n\t\t\t\tx_diff = (x_ratio * j) - x;\r\n\t\t\t\ty_diff = (y_ratio * i) - y;\r\n\t\t\t\tindex = (y*w + x);\r\n\t\t\t\ta = pixels[index];\r\n\t\t\t\tb = pixels[index + 1];\r\n\t\t\t\tc = pixels[index + w];\r\n\t\t\t\td = pixels[index + w + 1];\r\n\r\n\t\t\t\t// blue element\r\n\t\t\t\t// Yb = Ab(1-w)(1-h) + Bb(w)(1-h) + Cb(h)(1-w) + Db(wh)\r\n\t\t\t\tblue = (a & 0xff)*(1 - x_diff)*(1 - y_diff) + (b & 0xff)*(x_diff)*(1 - y_diff) +\r\n\t\t\t\t\t(c & 0xff)*(y_diff)*(1 - x_diff) + (d & 0xff)*(x_diff*y_diff);\r\n\r\n\t\t\t\t// green element\r\n\t\t\t\t// Yg = Ag(1-w)(1-h) + Bg(w)(1-h) + Cg(h)(1-w) + Dg(wh)\r\n\t\t\t\tgreen = ((a >> 8) & 0xff)*(1 - x_diff)*(1 - y_diff) + ((b >> 8) & 0xff)*(x_diff)*(1 - y_diff) +\r\n\t\t\t\t\t((c >> 8) & 0xff)*(y_diff)*(1 - x_diff) + ((d >> 8) & 0xff)*(x_diff*y_diff);\r\n\r\n\t\t\t\t// red element\r\n\t\t\t\t// Yr = Ar(1-w)(1-h) + Br(w)(1-h) + Cr(h)(1-w) + Dr(wh)\r\n\t\t\t\tred = ((a >> 16) & 0xff)*(1 - x_diff)*(1 - y_diff) + ((b >> 16) & 0xff)*(x_diff)*(1 - y_diff) +\r\n\t\t\t\t\t((c >> 16) & 0xff)*(y_diff)*(1 - x_diff) + ((d >> 16) & 0xff)*(x_diff*y_diff);\r\n\r\n\t\t\t\ttemp[offset++] =\r\n\t\t\t\t\t0xff000000 |\r\n\t\t\t\t\t((((int32_t)red) << 16) & 0xff0000) |\r\n\t\t\t\t\t((((int32_t)green) << 8) & 0xff00) |\r\n\t\t\t\t\t((int32_t)blue);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn temp;\r\n}\n\n<|start_filename|>include/converter.hpp<|end_filename|>\n#include \r\n#include \r\n\r\nint32_t* cvtMat2Int32(const cv::Mat& srcImage);\r\nvoid cvtInt322Mat(int32_t *pxArray, cv::Mat& outImage);\n\n<|start_filename|>include/resizeOMP.hpp<|end_filename|>\n#include \r\n#include \r\n#include \r\n\r\nint* resizeBilinear_omp(int* pixels, int w, int h, int w2, int h2);\n\n<|start_filename|>include/resizeGPU.cuh<|end_filename|>\n#include \r\n#include \r\n#include \r\n\r\nint* resizeBilinear_gpu(int w, int h, int w2, int h2);\r\n\r\nvoid initGPU(const int maxResolutionX, const int maxResolutionY);\r\nvoid deinitGPU();\r\n\r\nvoid reAllocPinned(int w, int h, int w2, int h2, int32_t* dataSource);\r\nvoid freePinned();\n\n<|start_filename|>include/resizeCPU.hpp<|end_filename|>\n#include \r\n\r\nint* resizeBilinear_cpu(int* pixels, int w, int h, int w2, int h2);"},"max_stars_repo_name":{"kind":"string","value":"royinx/BilinearImageResize"}}},{"rowIdx":234,"cells":{"content":{"kind":"string","value":"<|start_filename|>css/osgh.user.css<|end_filename|>\n\n/* ==UserStyle==\n@name Old School GitHub\n@version 1.8.0\n@description Reverts most of GitHub to its classic look\n@license MIT\n@author daattali\n@homepageURL https://github.com/daattali/oldschool-github-extension\n@namespace daattali\n==/UserStyle== */\n\n@-moz-document url-prefix(\"https://github.com/\"), url-prefix(\"https://gist.github.com/\") {\n /* Move page headers to the middle */\n@media (min-width: 1280px) {\n main > div.color-bg-secondary,\n main > div.hx_page-header-bg {\n box-shadow: inset 0 -1px 0 #e1e4e8;\n }\n main > div.color-bg-secondary > div,\n main > div.color-bg-secondary > nav,\n main > div.hx_page-header-bg > div, \n main > div.hx_page-header-bg > nav {\n max-width: 1280px;\n margin-left: auto;\n margin-right: auto;\n }\n main > div.color-bg-secondary > nav > ul > li > a,\n main > div.hx_page-header-bg > nav > ul > li > a {\n visibility: visible !important;\n }\n main > div.color-bg-secondary > nav .js-responsive-underlinenav-overflow,\n main > div.hx_page-header-bg > nav .js-responsive-underlinenav-overflow {\n display: none;\n }\n}\n\n/* Slightly more compact header tabs (excluding sticky header on user profile page) */\nbody:not(.page-profile) .UnderlineNav-body .UnderlineNav-item {\n padding: 5px 14px 3px;\n}\n\n/* Highlight the selected page in the header (excluding sticky header on user profile page) */\nbody:not(.page-profile) .UnderlineNav-item.selected {\n border-radius: 3px 3px 0 0;\n background: #fff;\n border-left: 1px solid #e1e4e8;\n border-right: 1px solid #e1e4e8;\n border-bottom: none;\n border-top: 3px solid #e36209;\n padding-top: 0;\n}\n\n/* Add the row separators in the list of files on a repo's main page */\n.js-active-navigation-container .Box-row + .Box-row {\n border-top: 1px solid #eaecef !important;\n}\n\n/* Slightly more compact file list rows and box headers */\n.js-active-navigation-container .Box-row {\n padding-top: 6px !important;\n padding-bottom: 6px !important;\n}\n.js-active-navigation-container .Box-row.p-0 {\n padding-top: 0 !important;\n padding-bottom: 0 !important;\n}\n.repository-content .gutter-condensed .Box .Box-header {\n padding-top: 10px;\n padding-bottom: 10px;\n}\n\n/* Content boxes border radius revert */\nbody .Box {\n border-radius: 3px;\n}\nbody .Box .Box-header, body .Box-row:first-of-type {\n border-top-left-radius: 3px;\n border-top-right-radius: 3px;\n}\n\n/* Buttons border radius revert - excluding button groups and other special buttons */\n/* \n By chaining all these :not() selectors this rule is very specific and hard to override.\n So it will need to grown even longer as more button types need to be excluded.\n It's possible that setting all button border radiuses to 3px and then overriding where they\n should be square would be a better approach.\n*/\n:not(.input-group-button) > :not(.BtnGroup):not(.subnav-search-context):not(.input-group-button)\n> .btn:not(.BtnGroup-item):not(.btn-with-count):not(.get-repo-btn) {\n border-radius: 3px; \n}\n\n/* Button groups & special buttons border radius revert - only affects specific corners */\nbody .BtnGroup-item:first-child,\nbody .BtnGroup-parent:first-child .BtnGroup-item,\n.input-group .input-group-button:first-child .btn,\nbody .subnav-item:first-child,\n.subnav-search-context .btn,\nbody .btn.btn-with-count {\n border-radius: 3px 0 0 3px;\n}\nbody .BtnGroup-item:last-child, \nbody .BtnGroup-parent:last-child .BtnGroup-item,\n.input-group .input-group-button:last-child .btn,\nbody .subnav-item:last-child,\n.subnav-search-context + .subnav-search .subnav-search-input,\nbody .social-count {\n border-radius: 0 3px 3px 0;\n}\n\n/* Status/state and issue labels border radius revert */\nbody .IssueLabel {\n border-radius: 2px;\n}\nbody .IssueLabel--big.lh-condensed, \nbody .State {\n border-radius: 3px;\n}\n\n/* Remove the circular user images */\nbody .avatar-user {\n border-radius: 3px !important;\n}\n\n/* Box border was slightly darker in classic design */\nbody .Box:not(.Box--danger), body .Box-header {\n border-color: #d1d5da;\n}\n/* Hide duplicated red top border of danger boxes - probably a github oversight */\nbody .Box--danger .Box-row:first-of-type {\n border-top-color: transparent;\n}\n\n/* Form field borders were slightly darker in classic design */\nbody .form-control {\n border-color: #d1d5da;\n}\n\n/* README should have a slight background */\n#readme .Box-header {\n background: #f6f8fa !important;\n border: 1px solid #d1d5da !important;\n}\n\n/* Font weight revert for issue counters and labels */\nmain > div.bg-gray-light > nav .Counter,\nbody .IssueLabel--big.lh-condensed,\n.IssueLabel {\n font-weight: 600;\n}\n\n/* Rows in Issues page have way too much whitespace */\n\n.js-issue-row.Box-row {\n padding-top: 0 !important;\n padding-bottom: 0 !important;\n}\n\n/* Classic buttons */\n\nbody .btn {\n transition: none !important;\n font-weight: 600;\n background-image: linear-gradient(-180deg, #fafbfc 0%, #eff3f6 90%);\n /* Set only border color here (not width) to avoid adding extra borders that shouldn't exists */\n border-color: rgba(27,31,35,0.2);\n /* these three background properties help the border color blend in better with the button color*/\n background-repeat: repeat-x;\n background-position: -1px -1px;\n background-size: 110% 110%;\n box-shadow: none;\n}\nbody .btn:hover {\n background-image: linear-gradient(-180deg, #f0f3f6 0%, #e6ebf1 90%);\n border-color: rgba(27,31,35,0.35);\n}\n\nbody [open] > .btn, body [open] > summary > .btn, body .btn:active {\n background: #e9ecef;\n border-color: rgba(27,31,35,0.35);\n box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15);\n}\n/* \n The github stylesheet contains this rule: body.intent-mouse a:focus { box-shadow: none }\n It overrides the rule above and removes the inset shadow. This extra rule has higher specificity\n to beat it and put the shadow back. Adding !important to box-shadow above could also do the trick.\n*/\nhtml > body.intent-mouse [open] > .btn, html > body.intent-mouse .btn:active {\n box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15);\n}\nbody .btn[disabled] {\n cursor: not-allowed;\n color: #959da5;\n background: #fafbfc;\n border-color: rgba(27,31,35,.15);\n}\n\n/* Revert button icon colors/opacity */\nbody .btn .octicon {\n color: #24292e;\n}\nbody .btn .dropdown-caret {\n opacity: 1;\n}\nbody .btn-primary .octicon {\n color: #fff;\n}\n\n/* Match social count boxes to button styles */\nbody .social-count {\n border-color: rgba(27,31,35,0.2);\n box-shadow: none;\n}\n\nbody .btn-primary {\n background-image: linear-gradient(-180deg, #34d058 0%, #28a745 90%);\n}\nbody .btn-primary:hover {\n background-image: linear-gradient(-180deg, #2fcb53 0%, #269f42 90%);\n border-color: rgba(27,31,35,0.5);\n}\nbody [open]>.btn-primary, body .btn-primary:active {\n background: #279f43;\n border-color: rgba(27,31,35,0.5);\n box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15);\n}\nbody .btn-primary[disabled] {\n color: hsla(0,0%,100%,.8);\n background: #94d3a2;\n border-color: rgba(27,31,35,.1);\n box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03);\n}\n\nbody .btn-danger {\n color: #cb2431;\n}\nbody .btn-danger:hover {\n color: #fff;\n background: #cb2431;\n border-color: rgba(27,31,35,.15);\n box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03);\n}\nbody [open]>.btn-danger, body .btn-danger:active { \n color: #fff;\n background: #be222e;\n border-color: rgba(27,31,35,.15);\n box-shadow: inset 0 1px 0 rgba(134,24,29,.2);\n}\nbody .btn-danger[disabled] {\n color: rgba(203,36,49,.5);\n background: #fafbfc;\n border-color: rgba(27,31,35,.15);\n box-shadow: 0 1px 0 rgba(27,31,35,.04), inset 0 1px 0 hsla(0,0%,100%,.25);\n}\n\nbody .btn-outline {\n color: #0366d6;\n background: #fff;\n}\nbody .btn-outline:hover, body .full-commit .btn-outline:not(:disabled):hover {\n color: #fff; \n background: #0366d6;\n border-color: rgba(27,31,35,.15);\n box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03);\n}\nbody [open]>.btn-outline, body .btn-outline:active { \n color: #fff; \n background: #035fc7;\n border-color: rgba(27,31,35,.15);\n box-shadow: inset 0 1px 0 rgba(5,38,76,.2);\n}\nbody .btn-outline[disabled] {\n color: rgba(3,102,214,.5);\n background: #fafbfc;\n border-color: rgba(27,31,35,.15);\n box-shadow: 0 1px 0 rgba(27,31,35,.04), inset 0 1px 0 hsla(0,0%,100%,.25);\n}\n\n/* User profile page: move status badge back below avatar image */\n.user-status-container .user-status-circle-badge-container {\n position: unset;\n width: auto;\n height: auto;\n margin: 4px 0 0;\n}\n.user-status-circle-badge-container .user-status-circle-badge {\n border-radius: 3px;\n width: 100%;\n}\nbody .user-status-circle-badge .user-status-message-wrapper {\n width: 100%;\n opacity: 1;\n}\nbody .user-status-circle-badge-container .user-status-emoji-container {\n margin-right: 8px !important;\n}\nbody .user-status-circle-badge-container .user-status-circle-badge,\nbody .user-status-circle-badge-container:hover .user-status-circle-badge {\n box-shadow: none; \n}\n.user-status-message-wrapper .css-truncate.css-truncate-target {\n white-space: auto;\n}\n.user-status-message-wrapper.no-wrap {\n white-space: normal !important;\n}\n\n}\n\n<|start_filename|>manifest.json<|end_filename|>\n{\n \"name\": \"Old School GitHub\",\n \"version\": \"1.8.0\",\n \"manifest_version\": 2,\n \"description\": \"Revert GitHub's UI back to its classic look (before the June 23, 2020 update that has a flat, rounded and more whitespaced design).\",\n \"icons\": {\n \"16\": \"img/icon-16.png\",\n \"48\": \"img/icon-48.png\",\n \"128\": \"img/icon-128.png\"\n },\n \"content_scripts\": [\n {\n \"matches\": [\n \"https://github.com/*\",\n \"https://gist.github.com/*\"\n ],\n \"css\": [\"css/osgh.css\"],\n \"run_at\": \"document_start\"\n }\n ],\n \"homepage_url\": \"https://github.com/daattali/oldschool-github-extension\"\n}\n"},"max_stars_repo_name":{"kind":"string","value":"daattali/oldschool-github-extension"}}},{"rowIdx":235,"cells":{"content":{"kind":"string","value":"<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserLoginLogQueryReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.QueryByPage;\n\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-21 22:12
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserLoginLogQueryReq extends QueryByPage {\n\n @ApiModelProperty(\"用户登录名\")\n private String username;\n\n @ApiModelProperty(\"系统名称\")\n private String sysName;\n\n @ApiModelProperty(\"登录时间 - 开始\")\n private Date loginTimeStart;\n\n @ApiModelProperty(\"登录时间 - 结束\")\n private Date loginTimeEnd;\n\n @ApiModelProperty(\"登录状态,0:未知;1:已登录;2:登录已过期\")\n private Integer loginState;\n\n @ApiModelProperty(\"手机号\")\n private String telephone;\n\n @ApiModelProperty(\"邮箱\")\n private String email;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/BadLoginTypeException.java<|end_filename|>\npackage org.clever.security.exception;\n\nimport org.springframework.security.core.AuthenticationException;\n\n/**\n * 不支持的登录类型\n *

\n * 作者: lzw
\n * 创建时间:2018-09-24 12:51
\n */\npublic class BadLoginTypeException extends AuthenticationException {\n\n public BadLoginTypeException(String msg) {\n super(msg);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/Constant.java<|end_filename|>\npackage org.clever.security;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-25 19:57
\n */\npublic class Constant {\n\n /**\n * 配置文件前缀\n */\n public static final String ConfigPrefix = \"clever.security\";\n\n /**\n * 登录请求数据 Key\n */\n public static final String Login_Data_Body_Request_Key = \"Login_Data_Body_Request_Key\";\n\n /**\n * 请求登录用户名 Key\n */\n public static final String Login_Username_Request_Key = \"Login_Username_Request_Key\";\n\n /**\n * 登录验证码 Key\n */\n public static final String Login_Captcha_Session_Key = \"Login_Captcha_Session_Key\";\n\n /**\n * 登录失败次数 Key\n */\n public static final String Login_Fail_Count_Session_Key = \"Login_Fail_Count_Session_Key\";\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ServiceSysService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.mapper.ServiceSysMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.List;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-22 20:36
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ServiceSysService {\n\n @Autowired\n private ServiceSysMapper serviceSysMapper;\n\n public List selectAll() {\n return serviceSysMapper.selectList(null);\n }\n\n @Transactional\n public ServiceSys registerSys(ServiceSys serviceSys) {\n ServiceSys existsSys = serviceSysMapper.getByUnique(serviceSys.getSysName(), serviceSys.getRedisNameSpace());\n if (existsSys != null) {\n if (!Objects.equals(existsSys.getSysName(), serviceSys.getSysName())\n || !Objects.equals(existsSys.getRedisNameSpace(), serviceSys.getRedisNameSpace())\n || !Objects.equals(existsSys.getLoginModel(), serviceSys.getLoginModel())) {\n throw new BusinessException(\n \"服务系统注册失败,存在冲突(SysName: \"\n + existsSys.getSysName()\n + \", redisNameSpace: \"\n + existsSys.getRedisNameSpace()\n + \", loginModel: \"\n + existsSys.getLoginModel()\n + \")\"\n );\n }\n return existsSys;\n }\n // 注册系统\n serviceSysMapper.insert(serviceSys);\n return serviceSysMapper.selectById(serviceSys.getId());\n }\n\n @Transactional\n public ServiceSys delServiceSys(String sysName) {\n ServiceSys existsSys = serviceSysMapper.getBySysName(sysName);\n if (existsSys == null) {\n throw new BusinessException(\"系统不存在:\" + sysName);\n }\n serviceSysMapper.deleteById(existsSys.getId());\n return existsSys;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/UsernamePasswordToken.java<|end_filename|>\npackage org.clever.security.token.login;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport lombok.Getter;\nimport lombok.Setter;\nimport lombok.ToString;\nimport org.clever.security.LoginTypeConstant;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-27 21:19
\n */\n@ToString\npublic class UsernamePasswordToken extends BaseLoginToken {\n\n /**\n * 用户名\n */\n @JsonProperty(value = \"principal\", access = JsonProperty.Access.WRITE_ONLY)\n @Setter\n @Getter\n private String username;\n /**\n * 密码\n */\n @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)\n @Setter\n @Getter\n private String password;\n\n public UsernamePasswordToken() {\n super(LoginTypeConstant.UsernamePassword);\n }\n\n public UsernamePasswordToken(String username, String password) {\n this();\n this.username = username;\n this.password = password;\n }\n\n /**\n * 擦除密码\n */\n @Override\n public void eraseCredentials() {\n super.eraseCredentials();\n password = \"\";\n }\n\n /**\n * 返回密码\n */\n @Override\n public Object getCredentials() {\n return password;\n }\n\n /**\n * 返回用户登录唯一ID\n */\n @Override\n public Object getPrincipal() {\n return username;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLoginSuccessHandler.java<|end_filename|>\npackage org.clever.security.handler;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.utils.CookieUtils;\nimport org.clever.common.utils.mapper.JacksonMapper;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.client.UserLoginLogClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.dto.request.UserLoginLogAddReq;\nimport org.clever.security.dto.response.JwtLoginRes;\nimport org.clever.security.dto.response.LoginRes;\nimport org.clever.security.dto.response.UserRes;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.repository.LoginFailCountRepository;\nimport org.clever.security.repository.RedisJwtRepository;\nimport org.clever.security.token.JwtAccessToken;\nimport org.clever.security.utils.AuthenticationUtils;\nimport org.clever.security.utils.HttpRequestUtils;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextImpl;\nimport org.springframework.security.web.DefaultRedirectStrategy;\nimport org.springframework.security.web.RedirectStrategy;\nimport org.springframework.security.web.WebAttributes;\nimport org.springframework.security.web.authentication.AuthenticationSuccessHandler;\nimport org.springframework.security.web.authentication.WebAuthenticationDetails;\nimport org.springframework.security.web.savedrequest.HttpSessionRequestCache;\nimport org.springframework.security.web.savedrequest.NullRequestCache;\nimport org.springframework.security.web.savedrequest.RequestCache;\nimport org.springframework.security.web.savedrequest.SavedRequest;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.List;\n\n/**\n * 自定义登录成功处理类\n *

\n * 作者: lzw
\n * 创建时间:2018-03-16 11:06
\n */\n@Component\n@Slf4j\npublic class UserLoginSuccessHandler implements AuthenticationSuccessHandler {\n\n private final String defaultRedirectUrl = \"/home.html\";\n private SecurityConfig securityConfig;\n private RequestCache requestCache;\n private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n @Autowired\n private LoginFailCountRepository loginFailCountRepository;\n @Autowired\n private UserLoginLogClient userLoginLogClient;\n\n public UserLoginSuccessHandler(SecurityConfig securityConfig) {\n this.securityConfig = securityConfig;\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n requestCache = new NullRequestCache();\n } else {\n requestCache = new HttpSessionRequestCache();\n }\n }\n\n @Override\n public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {\n SavedRequest savedRequest = null;\n if (LoginModel.session.equals(securityConfig.getLoginModel())) {\n savedRequest = requestCache.getRequest(request, response);\n }\n requestCache.removeRequest(request, response);\n clearAuthenticationAttributes(request, authentication.getName());\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // 登录成功保存 JwtAccessToken JwtRefreshToken\n JwtAccessToken jwtAccessToken = redisJwtRepository.saveJwtToken(AuthenticationUtils.getSecurityContextToken(authentication));\n redisJwtRepository.saveSecurityContext(new SecurityContextImpl(authentication));\n log.info(\"### 已保存 JWT Token 和 SecurityContext\");\n // 写入登录成功日志\n addLoginLog(authentication, jwtAccessToken);\n // 登录成功 - 返回JSon数据\n sendJsonData(response, authentication, jwtAccessToken);\n return;\n }\n LoginConfig login = securityConfig.getLogin();\n if (login.getLoginSuccessNeedRedirect() != null) {\n if (login.getLoginSuccessNeedRedirect()) {\n // 跳转\n sendRedirect(request, response, getRedirectUrl(savedRequest, login.getLoginSuccessRedirectPage()));\n } else {\n // 不跳转\n sendJsonData(response, authentication, null);\n }\n return;\n }\n // 根据当前请求类型判断是否需要跳转页面\n if (HttpRequestUtils.isJsonResponseByLogin(request)) {\n sendJsonData(response, authentication, null);\n return;\n }\n // 根据savedRequest判断是否需要跳转 (之前访问的Url是一个页面才跳转)\n if (savedRequest != null && isJsonResponseBySavedRequest(savedRequest)) {\n sendJsonData(response, authentication, null);\n return;\n }\n sendRedirect(request, response, getRedirectUrl(savedRequest, login.getLoginSuccessRedirectPage()));\n }\n\n /**\n * 清除登录异常信息\n */\n private void clearAuthenticationAttributes(HttpServletRequest request, String username) {\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n loginFailCountRepository.deleteLoginFailCount(username);\n }\n HttpSession session = request.getSession(false);\n if (session == null) {\n return;\n }\n session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);\n session.removeAttribute(Constant.Login_Captcha_Session_Key);\n session.removeAttribute(Constant.Login_Fail_Count_Session_Key);\n }\n\n /**\n * 写入登录成功日志(JwtToken日志)\n */\n @SuppressWarnings(\"Duplicates\")\n private void addLoginLog(Authentication authentication, JwtAccessToken jwtAccessToken) {\n String JwtTokenId = jwtAccessToken.getClaims().getId();\n String loginIp = null;\n if (authentication.getDetails() instanceof WebAuthenticationDetails) {\n WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();\n loginIp = webAuthenticationDetails.getRemoteAddress();\n }\n UserLoginLogAddReq userLoginLog = new UserLoginLogAddReq();\n userLoginLog.setSysName(securityConfig.getSysName());\n userLoginLog.setUsername(authentication.getName());\n userLoginLog.setLoginTime(new Date());\n userLoginLog.setLoginIp(StringUtils.trimToEmpty(loginIp));\n userLoginLog.setAuthenticationInfo(JacksonMapper.nonEmptyMapper().toJson(authentication));\n userLoginLog.setLoginModel(EnumConstant.ServiceSys_LoginModel_1);\n userLoginLog.setSessionId(StringUtils.trimToEmpty(JwtTokenId));\n userLoginLog.setLoginState(EnumConstant.UserLoginLog_LoginState_1);\n try {\n userLoginLogClient.addUserLoginLog(userLoginLog);\n log.info(\"### 写入登录成功日志 [{}]\", authentication.getName());\n } catch (Exception e) {\n log.error(\"写入登录成功日志失败 [{}]\", authentication.getName(), e);\n }\n }\n\n /**\n * 根据savedRequest判断是否需要跳转\n */\n private boolean isJsonResponseBySavedRequest(SavedRequest savedRequest) {\n if (savedRequest == null) {\n return true;\n }\n boolean jsonFlag = false;\n boolean ajaxFlag = false;\n List acceptHeaders = savedRequest.getHeaderValues(\"Accept\");\n if (acceptHeaders != null) {\n for (String accept : acceptHeaders) {\n if (\"application/json\".equalsIgnoreCase(accept)) {\n jsonFlag = true;\n break;\n }\n }\n }\n List ajaxHeaders = savedRequest.getHeaderValues(\"X-Requested-With\");\n if (ajaxHeaders != null) {\n for (String ajax : ajaxHeaders) {\n if (\"XMLHttpRequest\".equalsIgnoreCase(ajax)) {\n ajaxFlag = true;\n break;\n }\n }\n }\n return jsonFlag || ajaxFlag;\n }\n\n /**\n * 获取需要跳转的Url\n */\n private String getRedirectUrl(SavedRequest savedRequest, String defaultUrl) {\n String url = null;\n if (savedRequest != null && !isJsonResponseBySavedRequest(savedRequest)) {\n url = savedRequest.getRedirectUrl();\n }\n if (StringUtils.isBlank(url)) {\n url = defaultUrl;\n }\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n return url;\n }\n\n /**\n * 直接返回Json数据\n */\n private void sendJsonData(HttpServletResponse response, Authentication authentication, JwtAccessToken jwtAccessToken) {\n Object resData;\n if (jwtAccessToken == null) {\n UserRes userRes = AuthenticationUtils.getUserRes(authentication);\n resData = new LoginRes(true, \"登录成功\", userRes);\n } else {\n if (securityConfig.getTokenConfig().isUseCookie()) {\n CookieUtils.setRooPathCookie(response, securityConfig.getTokenConfig().getJwtTokenKey(), jwtAccessToken.getToken());\n }\n response.setHeader(securityConfig.getTokenConfig().getJwtTokenKey(), jwtAccessToken.getToken());\n UserRes userRes = AuthenticationUtils.getUserRes(authentication);\n resData = new JwtLoginRes(true, \"登录成功\", userRes, jwtAccessToken.getToken(), jwtAccessToken.getRefreshToken());\n }\n HttpResponseUtils.sendJsonBy200(response, resData);\n log.info(\"### 登录成功不需要跳转 -> [{}]\", resData);\n }\n\n /**\n * 页面跳转 (重定向)\n */\n private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n log.info(\"### 登录成功跳转Url(重定向) -> {}\", url);\n if (!response.isCommitted()) {\n redirectStrategy.sendRedirect(request, response, url);\n }\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByRoleService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.RoleQueryPageReq;\nimport org.clever.security.dto.request.RoleUpdateReq;\nimport org.clever.security.dto.response.RoleInfoRes;\nimport org.clever.security.entity.Role;\nimport org.clever.security.mapper.PermissionMapper;\nimport org.clever.security.mapper.RoleMapper;\nimport org.clever.security.service.internal.ReLoadSessionService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 23:52
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ManageByRoleService {\n\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private PermissionMapper permissionMapper;\n @Autowired\n private ReLoadSessionService reLoadSessionService;\n\n public IPage findByPage(RoleQueryPageReq roleQueryPageReq) {\n Page page = new Page<>(roleQueryPageReq.getPageNo(), roleQueryPageReq.getPageSize());\n page.setRecords(roleMapper.findByPage(roleQueryPageReq, page));\n return page;\n }\n\n @Transactional\n public Role addRole(Role role) {\n Role oldRole = roleMapper.getByName(role.getName());\n if (oldRole != null) {\n throw new BusinessException(\"角色[\" + role.getName() + \"]已经存在\");\n }\n roleMapper.insert(role);\n return roleMapper.selectById(role.getId());\n }\n\n @Transactional\n public Role updateRole(String name, RoleUpdateReq roleUpdateReq) {\n Role oldRole = roleMapper.getByName(name);\n if (oldRole == null) {\n throw new BusinessException(\"角色[\" + roleUpdateReq.getName() + \"]不存在\");\n }\n Role update = new Role();\n update.setId(oldRole.getId());\n if (StringUtils.isNotBlank(roleUpdateReq.getName()) && !Objects.equals(roleUpdateReq.getName(), oldRole.getName())) {\n update.setName(roleUpdateReq.getName());\n }\n update.setDescription(roleUpdateReq.getDescription());\n roleMapper.updateById(update);\n if (update.getName() != null) {\n roleMapper.updateUserRoleByRoleName(oldRole.getName(), roleUpdateReq.getName());\n roleMapper.updateRolePermissionByRoleName(oldRole.getName(), roleUpdateReq.getName());\n // 更新受影响用户的Session\n reLoadSessionService.onChangeRole(update.getName());\n }\n return roleMapper.getByName(roleUpdateReq.getName());\n }\n\n @Transactional\n public Role delRole(String name) {\n Role oldRole = roleMapper.getByName(name);\n if (oldRole == null) {\n throw new BusinessException(\"角色[\" + name + \"]不存在\");\n }\n int count = roleMapper.deleteById(oldRole.getId());\n if (count > 0) {\n roleMapper.delUserRoleByRoleName(oldRole.getName());\n roleMapper.delRolePermissionByRoleName(oldRole.getName());\n // 更新受影响用户的Session\n reLoadSessionService.onChangeRole(name);\n }\n return oldRole;\n }\n\n public RoleInfoRes getRoleInfo(String name) {\n Role role = roleMapper.getByName(name);\n if (role == null) {\n return null;\n }\n RoleInfoRes roleInfoRes = BeanMapper.mapper(role, RoleInfoRes.class);\n roleInfoRes.setPermissionList(permissionMapper.findByRoleName(role.getName()));\n return roleInfoRes;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RoleUpdateReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 9:30
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class RoleUpdateReq extends BaseRequest {\n\n @ApiModelProperty(\"角色名称\")\n @Length(max = 63)\n private String name;\n\n @ApiModelProperty(\"角色说明\")\n @Length(max = 1023)\n private String description;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserBindSysRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 21:44
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserBindSysRes extends BaseResponse {\n\n @ApiModelProperty(\"用户名\")\n private String username;\n\n @ApiModelProperty(\"系统名集合\")\n private List sysNameList;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/RoleMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.dto.request.RoleQueryPageReq;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.Role;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:11
\n */\n@Repository\n@Mapper\npublic interface RoleMapper extends BaseMapper {\n\n Role getByName(@Param(\"name\") String name);\n\n List findByUsername(@Param(\"username\") String username);\n\n List findByPage(@Param(\"query\") RoleQueryPageReq query, IPage page);\n\n int updateUserRoleByRoleName(@Param(\"oldName\") String oldName, @Param(\"newName\") String newName);\n\n int updateRolePermissionByRoleName(@Param(\"oldName\") String oldName, @Param(\"newName\") String newName);\n\n int updateRolePermissionByPermissionStr(@Param(\"oldPermissionStr\") String oldPermissionStr, @Param(\"newPermissionStr\") String newPermissionStr);\n\n int delUserRoleByRoleName(@Param(\"name\") String name);\n\n int delRolePermissionByRoleName(@Param(\"name\") String name);\n\n int addPermission(@Param(\"roleName\") String roleName, @Param(\"permissionStr\") String permissionStr);\n\n int delPermission(@Param(\"roleName\") String roleName, @Param(\"permissionStr\") String permissionStr);\n\n int existsByRole(@Param(\"roleName\") String roleName);\n\n List findPermissionByRoleName(@Param(\"roleName\") String roleName);\n\n int existsRolePermission(@Param(\"roleName\") String roleName, @Param(\"permissionStr\") String permissionStr);\n\n List findUsernameByRoleName(@Param(\"roleName\") String roleName);\n\n List findRoleNameByPermissionStr(@Param(\"permissionStr\") String permissionStr);\n\n List findRoleNameByPermissionStrList(@Param(\"permissionStrList\") Set permissionStrList);\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeRepository.java<|end_filename|>\npackage org.clever.security.rememberme;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.client.RememberMeTokenClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.RememberMeTokenAddReq;\nimport org.clever.security.dto.request.RememberMeTokenUpdateReq;\nimport org.clever.security.entity.RememberMeToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;\nimport org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;\nimport org.springframework.stereotype.Component;\n\nimport java.util.Date;\n\n/**\n * 存储“记住我”功能产生的Token\n * 作者: lzw
\n * 创建时间:2018-09-21 19:52
\n */\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n@Component\n@Slf4j\npublic class RememberMeRepository implements PersistentTokenRepository {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private RememberMeTokenClient rememberMeTokenClient;\n\n @Override\n public void createNewToken(PersistentRememberMeToken token) {\n RememberMeTokenAddReq req = new RememberMeTokenAddReq();\n req.setSysName(securityConfig.getSysName());\n req.setSeries(token.getSeries());\n req.setUsername(token.getUsername());\n req.setToken(token.getTokenValue());\n req.setLastUsed(token.getDate());\n rememberMeTokenClient.addRememberMeToken(req);\n }\n\n @Override\n public void updateToken(String series, String tokenValue, Date lastUsed) {\n RememberMeTokenUpdateReq req = new RememberMeTokenUpdateReq();\n req.setToken(tokenValue);\n req.setLastUsed(lastUsed);\n rememberMeTokenClient.updateRememberMeToken(series, req);\n }\n\n @Override\n public PersistentRememberMeToken getTokenForSeries(String seriesId) {\n RememberMeToken rememberMeToken = rememberMeTokenClient.getRememberMeToken(seriesId);\n if (rememberMeToken == null) {\n return null;\n }\n return new PersistentRememberMeToken(\n rememberMeToken.getUsername(),\n rememberMeToken.getSeries(),\n rememberMeToken.getToken(),\n rememberMeToken.getLastUsed()\n );\n }\n\n @Override\n public void removeUserTokens(String username) {\n rememberMeTokenClient.delRememberMeToken(username);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserAuthenticationRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-24 11:06
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserAuthenticationRes extends BaseResponse {\n\n @ApiModelProperty(\"登录是否成功\")\n private Boolean success = false;\n\n @ApiModelProperty(\"登录失败消息\")\n private String failMessage;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeUserDetailsChecker.java<|end_filename|>\npackage org.clever.security.rememberme;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.exception.CanNotLoginSysException;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsChecker;\nimport org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-22 15:50
\n */\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n@Component\n@Slf4j\npublic class RememberMeUserDetailsChecker implements UserDetailsChecker {\n\n @Autowired\n @Qualifier(\"DefaultPreAuthenticationChecks\")\n private UserDetailsChecker preAuthenticationChecks;\n @Autowired\n @Qualifier(\"DefaultPostAuthenticationChecks\")\n private UserDetailsChecker postAuthenticationChecks;\n\n /**\n * {@link org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#autoLogin}只处理一下异常\n * 1.CookieTheftException
\n * 2.UsernameNotFoundException
\n * 3.InvalidCookieException
\n * 4.AccountStatusException
\n * 5.RememberMeAuthenticationException
\n * 由于使用自定义UserDetailsService会抛出其他异常,所以包装处理\n */\n @Override\n public void check(UserDetails toCheck) {\n try {\n preAuthenticationChecks.check(toCheck);\n postAuthenticationChecks.check(toCheck);\n } catch (CanNotLoginSysException e) {\n throw new RememberMeAuthenticationException(e.getMessage(), e);\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/CollectLoginToken.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.springframework.security.core.AuthenticationException;\n\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\n\n/**\n * 收集用户登录认证信息接口\n *

\n * 作者: lzw
\n * 创建时间:2019-04-26 16:36
\n * @see org.clever.security.authentication.collect.CollectUsernamePasswordToken\n */\npublic interface CollectLoginToken {\n\n String LOGIN_TYPE_PARAM = \"loginType\";\n String CAPTCHA_PARAM = \"captcha\";\n String CAPTCHA_DIGEST_PARAM = \"captchaDigest\";\n String REMEMBER_ME_PARAM = \"rememberMe\";\n\n /**\n * 是否支持收集当前请求的登录信息\n *\n * @param request 请求对象\n * @param isSubmitBody 提交数据是否是JsonBody格式\n * @return 支持解析返回true\n */\n boolean supports(HttpServletRequest request, boolean isSubmitBody) throws IOException;\n\n /**\n * 收集用户登录认证信息\n *\n * @param request 请求对象\n * @param isSubmitBody 提交数据是否是JsonBody格式\n * @return 返回Authentication子类\n */\n BaseLoginToken attemptAuthentication(HttpServletRequest request, boolean isSubmitBody) throws AuthenticationException, IOException;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionQueryReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.QueryByPage;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 12:55
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class PermissionQueryReq extends QueryByPage {\n\n @ApiModelProperty(\"系统(或服务)名称\")\n private String sysName;\n\n @ApiModelProperty(\"资源标题(模糊匹配)\")\n private String title;\n\n @ApiModelProperty(\"资源访问所需要的权限标识字符串(模糊匹配)\")\n private String permissionStr;\n\n @ApiModelProperty(\"资源类型(1:请求URL地址, 2:其他资源)\")\n private Integer resourcesType;\n\n @ApiModelProperty(\"Spring Controller类名称(模糊匹配)\")\n private String targetClass;\n\n @ApiModelProperty(\"Spring Controller类的方法名称\")\n private String targetMethod;\n\n @ApiModelProperty(\"资源URL地址(模糊匹配)\")\n private String resourcesUrl;\n\n @ApiModelProperty(\"需要授权才允许访问(1:需要;2:不需要)\")\n private Integer needAuthorization;\n\n @ApiModelProperty(\"Spring Controller路由资源是否存在,0:不存在;1:存在\")\n private Integer targetExist;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/config/GlobalConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.Data;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2017-12-04 12:44
\n */\n@Component\n@ConfigurationProperties(prefix = \"clever.config\")\n@Data\npublic class GlobalConfig {\n\n /**\n * 请求数据AES加密 key(Hex编码)\n */\n private String reqAesKey = \"\";\n\n /**\n * 请求数据AES加密 iv(Hex编码)\n */\n private String reqAesIv = \"f0021ea5a06d5a7bade961afe47e9ad9\";\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageBySecurityController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.security.dto.request.*;\nimport org.clever.security.dto.response.RoleBindPermissionRes;\nimport org.clever.security.dto.response.UserBindRoleRes;\nimport org.clever.security.dto.response.UserBindSysRes;\nimport org.clever.security.service.ManageBySecurityService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 21:22
\n */\n@Api(\"系统、角色、权限分配管理\")\n@RestController\n@RequestMapping(\"/api/manage/security\")\npublic class ManageBySecurityController extends BaseController {\n\n @Autowired\n private ManageBySecurityService manageBySecurityService;\n\n @ApiOperation(\"为用户设置登录的系统(批量)\")\n @PostMapping(\"/user_sys\")\n public List userBindSys(@RequestBody @Validated UserBindSysReq userBindSysReq) {\n return manageBySecurityService.userBindSys(userBindSysReq);\n }\n\n @ApiOperation(\"为用户分配角色(批量)\")\n @PostMapping(\"/user_role\")\n public List userBindRole(@RequestBody @Validated UserBindRoleReq userBindSysReq) {\n return manageBySecurityService.userBindRole(userBindSysReq);\n }\n\n @ApiOperation(\"为角色分配权限(批量)\")\n @PostMapping(\"/role_permission\")\n public List roleBindPermission(@RequestBody @Validated RoleBindPermissionReq roleBindPermissionReq) {\n return manageBySecurityService.roleBindPermission(roleBindPermissionReq);\n }\n\n @ApiOperation(\"为用户添加登录的系统(单个)\")\n @PostMapping(\"/user_sys/bind\")\n public UserBindSysRes userBindSys(@RequestBody @Validated UserSysReq userSysReq) {\n return manageBySecurityService.userBindSys(userSysReq);\n }\n\n @ApiOperation(\"为用户删除登录的系统(单个)\")\n @PostMapping(\"/user_sys/un_bind\")\n public UserBindSysRes userUnBindSys(@RequestBody @Validated UserSysReq userSysReq) {\n return manageBySecurityService.userUnBindSys(userSysReq);\n }\n\n @ApiOperation(\"为用户添加角色(单个)\")\n @PostMapping(\"/user_role/bind\")\n public UserBindRoleRes userBindRole(@RequestBody @Validated UserRoleReq userRoleReq) {\n return manageBySecurityService.userBindRole(userRoleReq);\n }\n\n @ApiOperation(\"为用户删除角色(单个)\")\n @PostMapping(\"/user_role/un_bind\")\n public UserBindRoleRes userUnBindRole(@RequestBody @Validated UserRoleReq userRoleReq) {\n return manageBySecurityService.userUnBindRole(userRoleReq);\n }\n\n @ApiOperation(\"为角色添加权限(单个)\")\n @PostMapping(\"/role_permission/bind\")\n public RoleBindPermissionRes roleBindPermission(@RequestBody @Validated RolePermissionReq rolePermissionReq) {\n return manageBySecurityService.roleBindPermission(rolePermissionReq);\n }\n\n @ApiOperation(\"为角色删除权限(单个)\")\n @PostMapping(\"/role_permission/un_bind\")\n public RoleBindPermissionRes roleUnBindPermission(@RequestBody @Validated RolePermissionReq rolePermissionReq) {\n return manageBySecurityService.roleUnBindPermission(rolePermissionReq);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/HttpResponseUtils.java<|end_filename|>\npackage org.clever.security.utils;\n\nimport org.clever.common.utils.StringUtils;\nimport org.clever.common.utils.mapper.JacksonMapper;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-29 09:19
\n */\npublic class HttpResponseUtils {\n\n private static void sendJson(HttpServletResponse response, Object resData, int status) {\n if (!response.isCommitted()) {\n String json;\n if (resData instanceof String\n || resData instanceof Byte\n || resData instanceof Short\n || resData instanceof Integer\n || resData instanceof Float\n || resData instanceof Long\n || resData instanceof Double\n || resData instanceof Boolean) {\n json = String.valueOf(resData);\n } else {\n json = JacksonMapper.nonEmptyMapper().toJson(resData);\n }\n response.setStatus(status);\n response.setCharacterEncoding(\"UTF-8\");\n response.setContentType(\"application/json;charset=utf-8\");\n try {\n response.getWriter().print(json);\n } catch (IOException e) {\n throw new InternalAuthenticationServiceException(\"返回数据写入响应流失败\", e);\n }\n }\n }\n\n /**\n * 写入响应Json数据\n */\n public static void sendJsonBy200(HttpServletResponse response, Object resData) {\n sendJson(response, resData, HttpServletResponse.SC_OK);\n }\n\n /**\n * 写入响应Json数据\n */\n public static void sendJsonBy401(HttpServletResponse response, Object resData) {\n sendJson(response, resData, HttpServletResponse.SC_UNAUTHORIZED);\n }\n\n /**\n * 写入响应Json数据\n */\n public static void sendJsonBy403(HttpServletResponse response, Object resData) {\n sendJson(response, resData, HttpServletResponse.SC_FORBIDDEN);\n }\n\n /**\n * 重定向页面(客户端跳转)\n *\n * @param redirectUrl 跳转地址\n */\n public static void sendRedirect(HttpServletResponse response, String redirectUrl) throws IOException {\n if (StringUtils.isNotBlank(redirectUrl)) {\n response.sendRedirect(redirectUrl);\n }\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ISecurityContextService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport org.springframework.security.core.context.SecurityContext;\n\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-22 19:32
\n */\npublic interface ISecurityContextService {\n\n /**\n * 读取用户 SecurityContext\n *\n * @param sysName 系统名\n * @param userName 用户名\n * @return 不存在返回null\n */\n Map getSecurityContext(String sysName, String userName);\n\n /**\n * 读取用户 SecurityContext\n *\n * @param sessionId Session ID\n */\n SecurityContext getSecurityContext(String sessionId);\n\n /**\n * 重新加载所有系统用户权限信息(sessionAttr:SPRING_SECURITY_CONTEXT)\n *\n * @param sysName 系统名\n * @param userName 用户名\n */\n List reloadSecurityContext(String sysName, String userName);\n\n /**\n * 重新加载所有系统用户权限信息(sessionAttr:SPRING_SECURITY_CONTEXT)\n *\n * @param userName 用户名\n */\n Map> reloadSecurityContext(String userName);\n\n /**\n * 踢出用户(强制下线)\n *\n * @param sysName 系统名\n * @param userName 用户名\n * @return 下线Session数量\n */\n int forcedOffline(String sysName, String userName);\n\n /**\n * 删除用户Session(所有的系统)\n *\n * @param userName 用户信息\n */\n void delSession(String userName);\n\n /**\n * 删除用户Session\n *\n * @param sysName 系统名\n * @param userName 用户名\n */\n void delSession(String sysName, String userName);\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/RolePermission.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 角色-权限(RolePermission)实体类\n *\n * @author lizw\n * @since 2018-09-16 21:24:44\n */\n@Data\npublic class RolePermission implements Serializable {\n private static final long serialVersionUID = 148599893038494346L;\n /** 角色名称 */ \n private String roleName;\n \n /** 资源访问所需要的权限标识字符串 */ \n private String permissionStr;\n \n /** 创建时间 */ \n private Date createAt;\n \n /** 更新时间 */ \n private Date updateAt;\n \n}\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserAddRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 20:57
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserAddRes extends BaseResponse {\n /** 主键id */\n private Long id;\n\n /** 登录名 */\n private String username;\n\n /** 用户类型,0:系统内建,1:外部系统用户 */\n private Integer userType;\n\n /** 手机号 */\n private String telephone;\n\n /** 邮箱 */\n private String email;\n\n /** 帐号过期时间 */\n private Date expiredTime;\n\n /** 帐号是否锁定,0:未锁定;1:锁定 */\n private Integer locked;\n\n /** 是否启用,0:禁用;1:启用 */\n private Integer enabled;\n\n /** 说明 */\n private String description;\n\n /** 创建时间 */\n private Date createAt;\n\n /** 更新时间 */\n private Date updateAt;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/CleverSecurityJackson2Module.java<|end_filename|>\npackage org.clever.security.jackson2;\n\nimport com.fasterxml.jackson.core.Version;\nimport com.fasterxml.jackson.databind.module.SimpleModule;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.model.UserAuthority;\nimport org.clever.security.token.SecurityContextToken;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-22 21:21
\n */\npublic class CleverSecurityJackson2Module extends SimpleModule {\n\n public CleverSecurityJackson2Module() {\n super(CleverSecurityJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));\n }\n\n @Override\n public void setupModule(SetupContext context) {\n context.setMixInAnnotations(SecurityContextToken.class, SecurityContextTokenMixin.class);\n context.setMixInAnnotations(LoginUserDetails.class, LoginUserDetailsMixin.class);\n context.setMixInAnnotations(UserAuthority.class, UserAuthorityMixin.class);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserAddReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\nimport org.hibernate.validator.constraints.Range;\n\nimport javax.validation.constraints.Email;\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.Pattern;\nimport javax.validation.constraints.Size;\nimport java.util.Date;\nimport java.util.Set;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 20:57
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserAddReq extends BaseRequest {\n\n @ApiModelProperty(\"登录名\")\n @NotBlank\n @Pattern(regexp = \"[a-zA-Z0-9_-]{3,16}\")\n private String username;\n\n @ApiModelProperty(\"密码\")\n @NotBlank\n @Length(min = 6, max = 127)\n private String password;\n\n @ApiModelProperty(\"用户类型,0:系统内建,1:外部系统用户\")\n @Range(min = 0, max = 1)\n private Integer userType;\n\n @ApiModelProperty(\"手机号\")\n @Pattern(regexp = \"1[0-9]{10}\")\n private String telephone;\n\n @ApiModelProperty(\"邮箱\")\n @Email\n private String email;\n\n @ApiModelProperty(\"帐号过期时间\")\n private Date expiredTime;\n\n @ApiModelProperty(\"帐号是否锁定,0:未锁定;1:锁定\")\n @Range(min = 0, max = 1)\n private Integer locked;\n\n @ApiModelProperty(\"是否启用,0:禁用;1:启用\")\n @Range(min = 0, max = 1)\n private Integer enabled;\n\n @ApiModelProperty(\"说明\")\n @Length(max = 511)\n private String description;\n\n @ApiModelProperty(\"系统名称列表\")\n @Size(max = 100)\n private Set sysNameList;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/JwtRedisSecurityContextRepository.java<|end_filename|>\npackage org.clever.security.repository;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.token.JwtAccessToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.AuthenticationTrustResolver;\nimport org.springframework.security.authentication.AuthenticationTrustResolverImpl;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.context.HttpRequestResponseHolder;\nimport org.springframework.security.web.context.SecurityContextRepository;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-18 17:27
\n */\n@Component\n@Slf4j\npublic class JwtRedisSecurityContextRepository implements SecurityContextRepository {\n private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();\n\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n\n /**\n * 从Redis读取Jwt Token\n */\n @Override\n public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {\n HttpServletRequest request = requestResponseHolder.getRequest();\n JwtAccessToken jwtAccessToken;\n try {\n jwtAccessToken = redisJwtRepository.getJwtToken(request);\n log.info(\"### JwtToken 验证成功\");\n } catch (Throwable e) {\n if (e instanceof BusinessException) {\n log.warn(\"### JwtToken 验证失败: {}\", e.getMessage());\n } else {\n log.warn(\"### JwtToken 验证失败\", e);\n }\n return SecurityContextHolder.createEmptyContext();\n }\n // 读取 context\n SecurityContext securityContext;\n try {\n securityContext = redisJwtRepository.getSecurityContext(jwtAccessToken);\n log.info(\"### 读取SecurityContext成功\");\n } catch (Throwable e) {\n throw new InternalAuthenticationServiceException(\"读取SecurityContext失败\", e);\n }\n return securityContext;\n }\n\n /**\n * 保存Jwt Token到Redis\n */\n @Override\n public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {\n final Authentication authentication = context.getAuthentication();\n // 认证信息不存在或者是匿名认证不保存\n if (authentication == null || trustResolver.isAnonymous(authentication)) {\n return;\n }\n // 验证当前请求 JWT Token\n if (redisJwtRepository.validationToken(request)) {\n return;\n }\n // 保存 context\n redisJwtRepository.saveSecurityContext(context);\n log.info(\"### 已保存SecurityContext\");\n }\n\n @Override\n public boolean containsContext(HttpServletRequest request) {\n // 验证 JWT Token\n return redisJwtRepository.validationToken(request);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RememberMeTokenAddReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 16:39
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class RememberMeTokenAddReq extends BaseRequest {\n\n @NotBlank\n @Length(max = 127)\n @ApiModelProperty(\"系统(或服务)名称\")\n private String sysName;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"token序列号\")\n private String series;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"用户登录名\")\n private String username;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"token数据\")\n private String token;\n\n @NotNull\n @ApiModelProperty(\"最后使用时间\")\n private Date lastUsed;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/LogoutRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-21 10:22
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LogoutRes extends BaseResponse {\n /**\n * 是否登出成功\n */\n private Boolean success;\n\n /**\n * 错误消息\n */\n private String message;\n\n /**\n * 时间戳\n */\n private Long timestamp = System.currentTimeMillis();\n\n /**\n * 当前登出用户信息\n */\n private UserRes user;\n\n public LogoutRes(Boolean success, String message) {\n this.success = success;\n this.message = message;\n }\n\n public LogoutRes(Boolean success, String message, UserRes user) {\n this.success = success;\n this.message = message;\n this.user = user;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/GlobalUserDetailsService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.User;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.model.UserAuthority;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-16 10:54
\n */\n@Component\n@Slf4j\npublic class GlobalUserDetailsService implements UserDetailsService {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserClient userClient;\n\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n log.info(\"### 开始加载用户信息 [usernameOrTelephone={}]\", username);\n // 从本地数据库查询\n User user = userClient.getUser(username);\n if (user == null) {\n log.info(\"### 用户不存在 [usernameOrTelephone={}]\", username);\n throw new UsernameNotFoundException(\"用户不存在,usernameOrTelephone=\" + username);\n }\n // 获取用户所有权限\n List permissionList = userClient.findAllPermission(user.getUsername(), securityConfig.getSysName());\n // 获取用所有权限\n LoginUserDetails userDetails = new LoginUserDetails(user);\n for (Permission permission : permissionList) {\n userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle()));\n }\n // TODO 加载角色信息\n // userDetails.getRoles().add()\n return userDetails;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RefreshTokenReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\n\nimport javax.validation.constraints.NotBlank;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-19 21:23
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class RefreshTokenReq extends BaseRequest {\n\n /**\n * JWT 刷新 Token 字符串\n */\n @NotBlank\n private String refreshToken;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/AuthenticationLoginToken.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport org.clever.security.service.RequestCryptoService;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\n\n/**\n * 认证登录用户信息接口\n *

\n * 作者: lzw
\n * 创建时间:2019-04-26 16:45
\n */\npublic interface AuthenticationLoginToken {\n\n /**\n * 是否支持验证此身份类型(BaseLoginToken.class.isAssignableFrom(loginToken))\n *\n * @param loginToken Token类型\n * @return 返回true表示支持认证\n */\n boolean supports(Class loginToken);\n\n /**\n * loginToken 数据完整性校验(登录认证之前的校验 BadCredentialsException)\n */\n void preAuthenticationCheck(BaseLoginToken loginToken) throws AuthenticationException;\n\n /**\n * Token验证(密码验证等)\n *\n * @param loginToken 登录Token\n * @param loadedUser 数据库中的数据\n * @param requestCryptoService 请求参数加密/解密\n * @param bCryptPasswordEncoder 密码匹配\n * @throws AuthenticationException (BadCredentialsException)\n */\n void mainAuthenticationChecks(\n BaseLoginToken loginToken,\n UserDetails loadedUser,\n RequestCryptoService requestCryptoService,\n BCryptPasswordEncoder bCryptPasswordEncoder) throws AuthenticationException;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/WebPermissionServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.client.WebPermissionClient;\nimport org.clever.security.dto.request.WebPermissionInitReq;\nimport org.clever.security.dto.request.WebPermissionModelGetReq;\nimport org.clever.security.dto.response.WebPermissionInitRes;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.service.WebPermissionService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-11 19:30
\n */\n@Component\n@Slf4j\npublic class WebPermissionServiceProxy implements WebPermissionClient {\n @Autowired\n private WebPermissionService webPermissionService;\n\n @Override\n public WebPermissionModel getWebPermissionModel(WebPermissionModelGetReq req) {\n return webPermissionService.getWebPermissionModel(req);\n }\n\n @Override\n public List findAllWebPermissionModel(String sysName) {\n return webPermissionService.findAllWebPermissionModel(sysName);\n }\n\n @Override\n public WebPermissionInitRes initWebPermission(String sysName, WebPermissionInitReq req) {\n return webPermissionService.initWebPermission(sysName, req);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/AuthenticationUtils.java<|end_filename|>\npackage org.clever.security.utils;\n\nimport org.clever.security.dto.response.UserRes;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.token.SecurityContextToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.context.SecurityContextHolder;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 15:26
\n */\npublic class AuthenticationUtils {\n\n public static SecurityContextToken getSecurityContextToken() {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n return getSecurityContextToken(authentication);\n }\n\n public static SecurityContextToken getSecurityContextToken(Authentication authentication) {\n if (authentication == null) {\n return null;\n }\n if (!(authentication instanceof SecurityContextToken)) {\n throw new ClassCastException(String.format(\"Authentication类型错误,%s | %s\", authentication.getClass(), authentication));\n }\n return (SecurityContextToken) authentication;\n }\n\n public static UserRes getUserRes() {\n SecurityContextToken securityContextToken = getSecurityContextToken();\n return getUserRes(securityContextToken);\n }\n\n public static UserRes getUserRes(Authentication authentication) {\n SecurityContextToken securityContextToken = getSecurityContextToken(authentication);\n return getUserRes(securityContextToken);\n }\n\n public static UserRes getUserRes(SecurityContextToken securityContextToken) {\n if (securityContextToken == null) {\n return null;\n }\n LoginUserDetails loginUserDetails = securityContextToken.getUserDetails();\n if (loginUserDetails == null) {\n return null;\n }\n UserRes userRes = new UserRes();\n userRes.setUsername(loginUserDetails.getUsername());\n userRes.setTelephone(loginUserDetails.getTelephone());\n userRes.setEmail(loginUserDetails.getEmail());\n userRes.setUserType(loginUserDetails.getUserType());\n // 读取角色信息\n userRes.getRoleNames().addAll(loginUserDetails.getRoles());\n // 读取权限信息\n if (loginUserDetails.getAuthorities() != null) {\n for (GrantedAuthority grantedAuthority : loginUserDetails.getAuthorities()) {\n userRes.getAuthorities().add(grantedAuthority.getAuthority());\n }\n }\n return userRes;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/CaptchaInfoRepository.java<|end_filename|>\npackage org.clever.security.repository;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.model.CaptchaInfo;\nimport org.clever.security.service.GenerateKeyService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.stereotype.Component;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-20 19:57
\n */\n@Component\n@Slf4j\npublic class CaptchaInfoRepository {\n\n @Autowired\n private RedisTemplate redisTemplate;\n @Autowired\n private GenerateKeyService generateKeyService;\n\n public void saveCaptchaInfo(CaptchaInfo captchaInfo) {\n String captchaInfoKey = generateKeyService.getCaptchaInfoKey(captchaInfo.getCode().toUpperCase(), captchaInfo.getImageDigest());\n redisTemplate.opsForValue().set(captchaInfoKey, captchaInfo, captchaInfo.getEffectiveTime(), TimeUnit.MILLISECONDS);\n }\n\n /**\n * 读取验证码,不存在返回null\n */\n public CaptchaInfo getCaptchaInfo(String code, String imageDigest) {\n String captchaInfoKey = generateKeyService.getCaptchaInfoKey(code.toUpperCase(), imageDigest);\n Object object = redisTemplate.opsForValue().get(captchaInfoKey);\n if (object instanceof CaptchaInfo) {\n return (CaptchaInfo) object;\n }\n return null;\n }\n\n public void deleteCaptchaInfo(String code, String imageDigest) {\n String captchaInfoKey = generateKeyService.getCaptchaInfoKey(code.toUpperCase(), imageDigest);\n redisTemplate.delete(captchaInfoKey);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/HttpRequestUtils.java<|end_filename|>\npackage org.clever.security.utils;\n\nimport org.apache.commons.lang3.StringUtils;\n\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-17 21:38
\n */\npublic class HttpRequestUtils {\n\n /**\n * 判断是否要返回Json\n */\n public static boolean isJsonResponse(HttpServletRequest request) {\n String getFlag = request.getMethod();\n String jsonFlag = StringUtils.trimToEmpty(request.getHeader(\"Accept\"));\n String ajaxFlag = request.getHeader(\"X-Requested-With\");\n return !getFlag.equalsIgnoreCase(\"GET\") || jsonFlag.contains(\"application/json\") || Objects.equals(\"XMLHttpRequest\", ajaxFlag);\n }\n\n /**\n * 判断是否要返回Json (只用用于判断登录请求)\n */\n public static boolean isJsonResponseByLogin(HttpServletRequest request) {\n String jsonFlag = StringUtils.trimToEmpty(request.getHeader(\"Accept\"));\n String ajaxFlag = request.getHeader(\"X-Requested-With\");\n return jsonFlag.contains(\"application/json\") || Objects.equals(\"XMLHttpRequest\", ajaxFlag);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/JwtLoginRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-19 11:56
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class JwtLoginRes extends LoginRes {\n\n /**\n * JWT Token 字符串\n */\n private String token;\n\n /**\n * JWT 刷新 Token 字符串\n */\n private String refreshToken;\n\n public JwtLoginRes(Boolean success, String message, String token, String refreshToken) {\n super(success, message);\n this.token = token;\n this.refreshToken = refreshToken;\n }\n\n public JwtLoginRes(Boolean success, String message, UserRes user, String token, String refreshToken) {\n super(success, message, user);\n this.token = token;\n this.refreshToken = refreshToken;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/collect/CollectUsernamePasswordToken.java<|end_filename|>\npackage org.clever.security.authentication.collect;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.io.IOUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginTypeConstant;\nimport org.clever.security.authentication.CollectLoginToken;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.clever.security.token.login.UsernamePasswordToken;\nimport org.json.JSONObject;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\n\n/**\n * 收集用户信息 UsernamePasswordToken\n *

\n * 作者: lzw
\n * 创建时间:2019-04-28 15:59
\n */\n@Component\n@Slf4j\npublic class CollectUsernamePasswordToken implements CollectLoginToken {\n\n private static final String USERNAME_PARAM = \"username\";\n private static final String PASSWORD_PARAM = \"password\";\n\n private UsernamePasswordToken readUsernamePasswordToken(HttpServletRequest request, boolean isSubmitBody) throws IOException {\n String loginType;\n String username;\n String password;\n String captcha;\n String captchaDigest;\n boolean rememberMe;\n if (isSubmitBody) {\n // 使用Json方式提交数据\n Object json = request.getAttribute(Constant.Login_Data_Body_Request_Key);\n if (json == null) {\n json = IOUtils.toString(request.getReader());\n request.setAttribute(Constant.Login_Data_Body_Request_Key, json);\n }\n JSONObject object = new JSONObject(json.toString());\n loginType = StringUtils.trimToEmpty(object.optString(LOGIN_TYPE_PARAM));\n username = StringUtils.trimToEmpty(object.optString(USERNAME_PARAM));\n password = StringUtils.trimToEmpty(object.optString(PASSWORD_PARAM));\n captcha = StringUtils.trimToEmpty(object.optString(CAPTCHA_PARAM));\n captchaDigest = StringUtils.trimToEmpty(object.optString(CAPTCHA_DIGEST_PARAM));\n rememberMe = Boolean.parseBoolean(StringUtils.trimToEmpty(object.optString(REMEMBER_ME_PARAM)));\n } else {\n // 使用Parameter提交数据\n loginType = StringUtils.trimToEmpty(request.getParameter(LOGIN_TYPE_PARAM));\n username = StringUtils.trimToEmpty(request.getParameter(USERNAME_PARAM));\n password = StringUtils.trimToEmpty(request.getParameter(PASSWORD_PARAM));\n captcha = StringUtils.trimToEmpty(request.getParameter(CAPTCHA_PARAM));\n captchaDigest = StringUtils.trimToEmpty(request.getParameter(CAPTCHA_DIGEST_PARAM));\n rememberMe = Boolean.parseBoolean(StringUtils.trimToEmpty(request.getParameter(REMEMBER_ME_PARAM)));\n }\n // 创建Token\n UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);\n usernamePasswordToken.setLoginType(loginType);\n usernamePasswordToken.setCaptcha(captcha);\n usernamePasswordToken.setCaptchaDigest(captchaDigest);\n usernamePasswordToken.setRememberMe(rememberMe);\n return usernamePasswordToken;\n }\n\n @Override\n public boolean supports(HttpServletRequest request, boolean isSubmitBody) throws IOException {\n UsernamePasswordToken usernamePasswordToken = readUsernamePasswordToken(request, isSubmitBody);\n if (StringUtils.isNotBlank(usernamePasswordToken.getLoginType())) {\n return LoginTypeConstant.UsernamePassword.equalsIgnoreCase(usernamePasswordToken.getLoginType());\n }\n return StringUtils.isNotBlank(usernamePasswordToken.getUsername()) && StringUtils.isNotBlank(usernamePasswordToken.getPassword());\n }\n\n\n @Override\n public BaseLoginToken attemptAuthentication(HttpServletRequest request, boolean isSubmitBody) throws AuthenticationException, IOException {\n return readUsernamePasswordToken(request, isSubmitBody);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserLoginLogAddReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.clever.common.validation.ValidIntegerStatus;\nimport org.hibernate.validator.constraints.Length;\nimport org.hibernate.validator.constraints.Range;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 19:57
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserLoginLogAddReq extends BaseRequest {\n\n @NotBlank\n @Length(max = 127)\n @ApiModelProperty(\"系统(或服务)名称\")\n private String sysName;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"用户登录名\")\n private String username;\n\n @NotNull\n @ApiModelProperty(\"登录时间\")\n private Date loginTime;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"登录IP\")\n private String loginIp;\n\n @NotBlank\n @ApiModelProperty(\"登录的用户信息\")\n private String authenticationInfo;\n\n @ApiModelProperty(\"登录类型,0:sesion-cookie,1:jwt-token\")\n @NotNull\n @ValidIntegerStatus({0, 1})\n private Integer loginModel;\n\n @NotBlank\n @Length(max = 63)\n @ApiModelProperty(\"登录SessionID\")\n private String sessionId;\n\n @NotNull\n @Range(min = 0, max = 2)\n @ApiModelProperty(\"登录状态,0:未知;1:已登录;2:登录已过期\")\n private Integer loginState;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-20 16:13
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserRes extends BaseResponse {\n\n /**\n * 登录名\n */\n private String username;\n\n /**\n * 手机号\n */\n private String telephone;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * 用户类型,0:系统内建,1:外部系统用户\n */\n private Integer userType;\n\n /**\n * 用户有角色名\n */\n private List roleNames = new ArrayList<>();\n\n /**\n * 拥有的权限字符串\n */\n private List authorities = new ArrayList<>();\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/HttpSessionDestroyedListener.java<|end_filename|>\npackage org.clever.security.event;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.LoginModel;\nimport org.clever.security.client.UserLoginLogClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.UserLoginLogUpdateReq;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.UserLoginLog;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.core.session.SessionDestroyedEvent;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-23 19:33
\n */\n@Component\n@Slf4j\npublic class HttpSessionDestroyedListener implements ApplicationListener {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserLoginLogClient userLoginLogClient;\n\n @SuppressWarnings(\"NullableProblems\")\n @Override\n public void onApplicationEvent(SessionDestroyedEvent event) {\n // org.springframework.session.events.SessionDestroyedEvent;\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n log.error(\"### 注销Session [{}] -> 不应该创建HttpSession\", event.getId());\n } else {\n try {\n log.info(\"### 注销Session [{}]\", event.getId());\n UserLoginLog userLoginLog = userLoginLogClient.getUserLoginLog(event.getId());\n if (userLoginLog == null) {\n log.warn(\"### 注销Session未能找到对应的登录日志 [{}]\", event.getId());\n return;\n }\n // 设置登录过期\n UserLoginLogUpdateReq req = new UserLoginLogUpdateReq();\n req.setLoginState(EnumConstant.UserLoginLog_LoginState_2);\n userLoginLogClient.updateUserLoginLog(event.getId(), req);\n } catch (Exception e) {\n log.error(\"更新Session注销信息失败\", e);\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/PermissionMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.dto.request.PermissionQueryReq;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:13
\n */\n@Repository\n@Mapper\npublic interface PermissionMapper extends BaseMapper {\n\n List findByUsername(@Param(\"username\") String username);\n\n List findByRoleName(@Param(\"roleName\") String roleName);\n\n List findByPage(@Param(\"query\") PermissionQueryReq query, IPage page);\n\n int existsPermission(@Param(\"permissionStr\") String permissionStr);\n\n WebPermissionModel getByPermissionStr(@Param(\"permissionStr\") String permissionStr);\n\n int delRolePermission(@Param(\"permissionStr\") String permissionStr);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/UserBindRoleService.java<|end_filename|>\npackage org.clever.security.service.internal;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.mapper.QueryMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.service.ISecurityContextService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-11 20:39
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class UserBindRoleService {\n\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private QueryMapper queryMapper;\n @Autowired\n private ISecurityContextService sessionService;\n\n /**\n * 重新为用户分配角色\n *\n * @param userName 用户登录名\n * @param roleNameList 角色名称集合\n */\n @Transactional\n public void resetUserBindRole(String userName, Collection roleNameList) {\n if (roleNameList == null) {\n roleNameList = new ArrayList<>();\n }\n // 获取关联角色列表\n List oldRoleNameList = queryMapper.findRoleNameByUser(userName);\n Set addRoleName = new HashSet<>(roleNameList);\n addRoleName.removeAll(oldRoleNameList);\n Set delRoleName = new HashSet<>(oldRoleNameList);\n delRoleName.removeAll(roleNameList);\n // 新增\n for (String roleName : addRoleName) {\n userMapper.addRole(userName, roleName);\n }\n // 删除\n for (String roleName : delRoleName) {\n userMapper.delRole(userName, roleName);\n }\n // 更新Session\n sessionService.reloadSecurityContext(userName);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/JwtWebSecurityConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.authentication.UserLoginEntryPoint;\nimport org.clever.security.authentication.filter.UserLoginFilter;\nimport org.clever.security.handler.UserAccessDeniedHandler;\nimport org.clever.security.handler.UserLogoutHandler;\nimport org.clever.security.handler.UserLogoutSuccessHandler;\nimport org.clever.security.repository.SecurityContextRepositoryProxy;\nimport org.clever.security.service.GlobalUserDetailsService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.access.AccessDecisionManager;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.AuthenticationProvider;\nimport org.springframework.security.config.BeanIds;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;\nimport org.springframework.security.web.context.SecurityContextRepository;\nimport org.springframework.security.web.savedrequest.NullRequestCache;\nimport org.springframework.security.web.savedrequest.RequestCache;\n\nimport java.util.List;\n\n/**\n * Jwt Token 登录配置\n * 作者: lzw
\n * 创建时间:2018-03-14 14:45
\n */\n@Configuration\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"jwt\")\n@Slf4j\npublic class JwtWebSecurityConfig extends BaseWebSecurityConfig {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserLoginFilter userLoginFilter;\n @Autowired\n private GlobalUserDetailsService globalUserDetailsService;\n @Autowired\n private List authenticationProviderList;\n @Autowired\n private UserLoginEntryPoint userLoginEntryPoint;\n @Autowired\n private UserLogoutHandler userLogoutHandler;\n @Autowired\n private UserLogoutSuccessHandler userLogoutSuccessHandler;\n @Autowired\n private UserAccessDeniedHandler userAccessDeniedHandler;\n @Autowired\n private AccessDecisionManager accessDecisionManager;\n @Autowired\n private BCryptPasswordEncoder bCryptPasswordEncoder;\n @Autowired\n private SecurityContextRepositoryProxy securityContextRepositoryProxy;\n\n @Override\n PasswordEncoder getPasswordEncoder() {\n return bCryptPasswordEncoder;\n }\n\n @Override\n UserDetailsService getUserDetailsService() {\n return globalUserDetailsService;\n }\n\n @Override\n List getAuthenticationProviderList() {\n return authenticationProviderList;\n }\n\n @Override\n SecurityConfig getSecurityConfig() {\n return securityConfig;\n }\n\n /**\n * 在Spring容器中注册 AuthenticationManager\n */\n @Bean(name = BeanIds.AUTHENTICATION_MANAGER)\n @Override\n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean();\n }\n\n /**\n * 具体的权限控制规则配置\n */\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n // Jwt Token不需要使用HttpSession\n http.setSharedObject(SecurityContextRepository.class, securityContextRepositoryProxy);\n http.setSharedObject(RequestCache.class, new NullRequestCache());\n\n // 自定义登录 Filter --> UserLoginFilter\n http.addFilterAt(userLoginFilter, UsernamePasswordAuthenticationFilter.class);\n\n// http\n// .csrf().and()\n// .addFilter(new WebAsyncManagerIntegrationFilter())\n// .exceptionHandling().and()\n// .headers().and()\n// .sessionManagement().and()\n// .securityContext().and()\n// .requestCache().and()\n// .anonymous().and()\n// .servletApi().and()\n// .apply(new DefaultLoginPageConfigurer<>()).and()\n// .logout();\n// ClassLoader classLoader = this.getApplicationContext().getClassLoader();\n// List defaultHttpConfigurers = SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);\n// for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) {\n// http.apply(configurer);\n// }\n\n // 过滤器配置\n http\n .csrf().disable()\n .sessionManagement().disable()\n .exceptionHandling().authenticationEntryPoint(userLoginEntryPoint).accessDeniedHandler(userAccessDeniedHandler)\n .and()\n .authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager)\n .and()\n .formLogin().disable()\n .logout().logoutUrl(securityConfig.getLogout().getLogoutUrl()).addLogoutHandler(userLogoutHandler).logoutSuccessHandler(userLogoutSuccessHandler).permitAll()\n ;\n // 禁用\"记住我功能配置\"(Token的记住我功能仅仅只是Token过期时间加长)\n http.rememberMe().disable();\n log.info(\"### HttpSecurity 配置完成!\");\n }\n}\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/RememberMeConfig.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\nimport java.time.Duration;\n\n/**\n * 记住我功能配置\n * 作者: lzw
\n * 创建时间:2019-04-25 19:26
\n */\n@Data\npublic class RememberMeConfig {\n /**\n * 启用\"记住我\"功能\n */\n private Boolean enable = true;\n\n /**\n * 总是\"记住我\"\n */\n private Boolean alwaysRemember = false;\n\n /**\n * \"记住我\"有效时间(单位秒,默认一个月)\n */\n private Duration validity = Duration.ofDays(30);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/UserLoginLogServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.client.UserLoginLogClient;\nimport org.clever.security.dto.request.UserLoginLogAddReq;\nimport org.clever.security.dto.request.UserLoginLogUpdateReq;\nimport org.clever.security.entity.UserLoginLog;\nimport org.clever.security.service.UserLoginLogService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n/**\n * 参考 UserLoginLogController\n *

\n * 作者: lzw
\n * 创建时间:2018-11-11 19:30
\n */\n@Component\n@Slf4j\npublic class UserLoginLogServiceProxy implements UserLoginLogClient {\n @Autowired\n private UserLoginLogService userLoginLogService;\n\n @Override\n public UserLoginLog addUserLoginLog(UserLoginLogAddReq req) {\n UserLoginLog userLoginLog = BeanMapper.mapper(req, UserLoginLog.class);\n return userLoginLogService.addUserLoginLog(userLoginLog);\n }\n\n @Override\n public UserLoginLog getUserLoginLog(String sessionId) {\n return userLoginLogService.getUserLoginLog(sessionId);\n }\n\n @Override\n public UserLoginLog updateUserLoginLog(String sessionId, UserLoginLogUpdateReq req) {\n UserLoginLog update = BeanMapper.mapper(req, UserLoginLog.class);\n return userLoginLogService.updateUserLoginLog(sessionId, update);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/ReLoadSessionService.java<|end_filename|>\npackage org.clever.security.service.internal;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.mapper.RoleMapper;\nimport org.clever.security.service.ISecurityContextService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * 重新加载Session\n * 作者: lzw
\n * 创建时间:2018-11-16 11:54
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ReLoadSessionService {\n\n // @Autowired\n // private UserMapper userMapper;\n // @Autowired\n // private RedisOperationsSessionRepository sessionRepository;\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private ISecurityContextService sessionService;\n\n /**\n * 角色所拥有的权限发生变化 - 重新加载Session\n */\n public void onChangeRole(String roleName) {\n List usernameList = roleMapper.findUsernameByRoleName(roleName);\n for (String username : usernameList) {\n sessionService.reloadSecurityContext(username);\n }\n }\n\n /**\n * 角色所拥有的权限发生变化 - 重新加载Session\n */\n public void onChangeRole(Collection roleNameList) {\n Set usernameList = new HashSet<>();\n for (String roleName : roleNameList) {\n usernameList.addAll(roleMapper.findUsernameByRoleName(roleName));\n }\n for (String username : usernameList) {\n sessionService.reloadSecurityContext(username);\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/LoginSuccessListener.java<|end_filename|>\npackage org.clever.security.event;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.utils.mapper.JacksonMapper;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.client.UserLoginLogClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.UserLoginLogAddReq;\nimport org.clever.security.entity.EnumConstant;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.authentication.event.AuthenticationSuccessEvent;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.web.authentication.WebAuthenticationDetails;\nimport org.springframework.stereotype.Component;\n\nimport java.util.Date;\n\n/**\n * 登录事件监听(写入登录成功的SessionID日志)\n * 作者: lzw
\n * 创建时间:2018-09-18 13:55
\n */\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n@Component\n@Slf4j\npublic class LoginSuccessListener implements ApplicationListener {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserLoginLogClient userLoginLogClient;\n\n @SuppressWarnings(\"Duplicates\")\n @Override\n public void onApplicationEvent(AuthenticationSuccessEvent event) {\n Authentication authentication = event.getAuthentication();\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n log.info(\"### 登录成功 -> {}\", authentication);\n } else {\n String loginIp = null;\n String sessionId = null;\n if (authentication.getDetails() != null && authentication.getDetails() instanceof WebAuthenticationDetails) {\n WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();\n loginIp = webAuthenticationDetails.getRemoteAddress();\n sessionId = webAuthenticationDetails.getSessionId();\n } else {\n log.warn(\"### 登录成功未能得到SessionID [{}]\", authentication.getName());\n }\n UserLoginLogAddReq userLoginLog = new UserLoginLogAddReq();\n userLoginLog.setSysName(securityConfig.getSysName());\n userLoginLog.setUsername(authentication.getName());\n userLoginLog.setLoginTime(new Date());\n userLoginLog.setLoginIp(StringUtils.trimToEmpty(loginIp));\n userLoginLog.setAuthenticationInfo(JacksonMapper.nonEmptyMapper().toJson(authentication));\n userLoginLog.setLoginModel(EnumConstant.ServiceSys_LoginModel_0);\n userLoginLog.setSessionId(StringUtils.trimToEmpty(sessionId));\n userLoginLog.setLoginState(EnumConstant.UserLoginLog_LoginState_1);\n try {\n userLoginLogClient.addUserLoginLog(userLoginLog);\n log.info(\"### 写入登录成功日志 [{}]\", authentication.getName());\n } catch (Exception e) {\n log.error(\"写入登录成功日志失败 [{}]\", authentication.getName(), e);\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/model/LoginUserDetails.java<|end_filename|>\npackage org.clever.security.model;\n\nimport lombok.Getter;\nimport lombok.ToString;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.User;\nimport org.springframework.security.core.CredentialsContainer;\nimport org.springframework.security.core.userdetails.UserDetails;\n\nimport java.util.*;\n\n/**\n * 登录的用户信息\n *

\n * 作者: lzw
\n * 创建时间:2018-03-16 17:41
\n */\n@ToString(includeFieldNames = false, of = {\"username\"})\npublic class LoginUserDetails implements UserDetails, CredentialsContainer {\n\n /**\n * 主键id\n */\n @Getter\n private final Long id;\n /**\n * 登录名(一条记录的手机号不能当另一条记录的用户名用)\n */\n private final String username;\n /**\n * 密码\n */\n private String password;\n /**\n * 用户类型,0:系统内建,1:外部系统用户\n */\n @Getter\n private final Integer userType;\n /**\n * 手机号\n */\n @Getter\n private final String telephone;\n /**\n * 邮箱\n */\n @Getter\n private final String email;\n /**\n * 帐号过期时间\n */\n @Getter\n private final Date expiredTime;\n /**\n * 帐号锁定标识\n */\n private final boolean locked;\n /**\n * 是否启用\n */\n private final boolean enabled;\n /**\n * 说明\n */\n @Getter\n private String description;\n /**\n * 创建时间\n */\n @Getter\n private Date createAt;\n /**\n * 更新时间\n */\n @Getter\n private Date updateAt;\n\n /**\n * 凭证过期标识\n */\n private final boolean credentialsNonExpired;\n /**\n * 帐号过期标识\n */\n private final boolean accountNonExpired;\n /**\n * 用户权限信息\n */\n private final Set authorities = new HashSet<>();\n /**\n * 角色信息\n */\n @Getter\n private final Set roles = new HashSet<>();\n\n public LoginUserDetails(User user) {\n this.id = user.getId();\n this.username = user.getUsername();\n this.password = ();\n this.userType = user.getUserType();\n this.telephone = user.getTelephone();\n this.email = user.getEmail();\n this.expiredTime = user.getExpiredTime();\n this.locked = Objects.equals(user.getLocked(), EnumConstant.User_Locked_0);\n this.enabled = Objects.equals(user.getEnabled(), EnumConstant.User_Enabled_1);\n this.description = user.getDescription();\n this.createAt = user.getCreateAt();\n this.updateAt = user.getUpdateAt();\n\n this.credentialsNonExpired = true;\n this.accountNonExpired = user.getExpiredTime() == null || user.getExpiredTime().compareTo(new Date()) > 0;\n }\n\n /**\n * 用于反序列化构造\n */\n public LoginUserDetails(\n Long id,\n String username,\n String password,\n Integer userType,\n String telephone,\n String email,\n Date expiredTime,\n boolean locked,\n boolean enabled,\n String description,\n Date createAt,\n Date updateAt) {\n this.id = id;\n this.username = username;\n this.password = password;\n this.userType = userType;\n this.telephone = telephone;\n this.email = email;\n this.expiredTime = expiredTime;\n this.locked = locked;\n this.enabled = enabled;\n this.description = description;\n this.createAt = createAt;\n this.updateAt = updateAt;\n\n this.credentialsNonExpired = true;\n this.accountNonExpired = expiredTime == null || expiredTime.compareTo(new Date()) > 0;\n }\n\n @Override\n public void eraseCredentials() {\n this.password = \"\";\n }\n\n @Override\n public Collection getAuthorities() {\n return authorities;\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n @Override\n public String getUsername() {\n return username;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return accountNonExpired;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return locked;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return credentialsNonExpired;\n }\n\n @Override\n public boolean isEnabled() {\n return enabled;\n }\n\n @Override\n public int hashCode() {\n if (username == null) {\n return super.hashCode();\n }\n return username.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (!(obj instanceof LoginUserDetails)) {\n return false;\n }\n LoginUserDetails objTmp = (LoginUserDetails) obj;\n if (this.username == null) {\n return objTmp.username == null;\n }\n return this.username.equals(objTmp.username);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/LoginUserDetailsMixin.java<|end_filename|>\npackage org.clever.security.jackson2;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-22 21:28
\n */\n//@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY)\n@JsonAutoDetect\n@JsonIgnoreProperties(ignoreUnknown = true)\nclass LoginUserDetailsMixin {\n\n @JsonCreator\n public LoginUserDetailsMixin(\n @JsonProperty(\"id\") Long id,\n @JsonProperty(\"username\") String username,\n @JsonProperty(\"password\") String password,\n @JsonProperty(\"userType\") Integer userType,\n @JsonProperty(\"telephone\") String telephone,\n @JsonProperty(\"email\") String email,\n @JsonProperty(\"expiredTime\") Date expiredTime,\n @JsonProperty(\"accountNonLocked\") boolean locked,\n @JsonProperty(\"enabled\") boolean enabled,\n @JsonProperty(\"description\") String description,\n @JsonProperty(\"createAt\") Date createAt,\n @JsonProperty(\"updateAt\") Date updateAt) {\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/UserService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.server.service.BaseService;\nimport org.clever.security.dto.request.UserAuthenticationReq;\nimport org.clever.security.dto.response.UserAuthenticationRes;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.User;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.service.internal.ManageCryptoService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:20
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class UserService extends BaseService {\n\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private ManageCryptoService manageCryptoService;\n\n public User getUser(String unique) {\n return userMapper.getByUnique(unique);\n }\n\n public List findAllPermission(String username, String sysName) {\n return userMapper.findByUsername(username, sysName);\n }\n\n public Boolean canLogin(String username, String sysName) {\n return userMapper.existsUserBySysName(username, sysName) >= 1;\n }\n\n // TODO 认证\n public Boolean authentication(UserAuthenticationReq req) {\n User user = userMapper.getByUnique(req.getLoginName());\n if (user == null) {\n throw new BusinessException(\"用户不存在\");\n }\n// if (!user.isCredentialsNonExpired()) {\n// log.info(\"帐号密码已过期 [username={}]\", user.getUsername());\n// throw new CredentialsExpiredException(\"帐号密码已过期\");\n// }\n if (!Objects.equals(user.getLocked(), EnumConstant.User_Locked_0)) {\n log.info(\"帐号已锁定 [username={}]\", user.getUsername());\n throw new BusinessException(\"帐号已锁定\");\n }\n if (!Objects.equals(user.getEnabled(), EnumConstant.User_Enabled_1)) {\n log.info(\"帐号已禁用 [username={}]\", user.getUsername());\n throw new BusinessException(\"帐号已禁用\");\n }\n if (!(user.getExpiredTime() == null || user.getExpiredTime().compareTo(new Date()) > 0)) {\n log.info(\"帐号已过期 [username={}]\", user.getUsername());\n throw new BusinessException(\"帐号已过期\");\n }\n // 校验用户是否有权登录当前系统\n if (StringUtils.isNotBlank(req.getSysName())) {\n if (!canLogin(user.getUsername(), req.getSysName())) {\n throw new BusinessException(\"您无权登录当前系统,请联系管理员授权\");\n }\n }\n // 校验密码\n if (UserAuthenticationReq.LoginType_Username.equals(req.getLoginType())) {\n // 密码先解密再加密\n req.setPassword(manageCryptoService.reqAesDecrypt(req.getPassword()));\n req.setPassword(manageCryptoService.dbEncode(req.getPassword()));\n // 用户名、密码校验\n if (!req.getLoginName().equals(user.getUsername()) || !manageCryptoService.dbMatches(req.getPassword(), user.getPassword())) {\n log.info(\"### 用户名密码验证失败 [{}]\", req.toString());\n throw new BusinessException(\"用户名密码验证失败\");\n }\n log.info(\"### 用户名密码验证成功 [{}]\", req.toString());\n } else if (UserAuthenticationReq.LoginType_Telephone.equals(req.getLoginType())) {\n // TODO 手机号验证码登录\n throw new BusinessException(\"暂不支持手机号验证码登录\");\n } else {\n throw new BusinessException(\"不支持的登录类型\");\n }\n return true;\n }\n\n public UserAuthenticationRes authenticationAndRes(UserAuthenticationReq req) {\n UserAuthenticationRes userAuthenticationRes = new UserAuthenticationRes();\n if (StringUtils.isBlank(req.getLoginType())) {\n req.setLoginType(\"username\");\n }\n try {\n userAuthenticationRes.setSuccess(authentication(req));\n } catch (Exception e) {\n userAuthenticationRes.setSuccess(false);\n userAuthenticationRes.setFailMessage(e.getMessage());\n }\n return userAuthenticationRes;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/JwtRefreshToken.java<|end_filename|>\npackage org.clever.security.token;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-20 9:11
\n */\n@Data\npublic class JwtRefreshToken implements Serializable {\n\n /**\n * 用户名\n */\n private String username;\n\n /**\n * Token ID\n */\n private String tokenId;\n\n public JwtRefreshToken() {\n }\n\n public JwtRefreshToken(String username, String tokenId) {\n this.username = username;\n this.tokenId = tokenId;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByUserService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.UserAddReq;\nimport org.clever.security.dto.request.UserQueryPageReq;\nimport org.clever.security.dto.request.UserUpdateReq;\nimport org.clever.security.dto.response.UserInfoRes;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.User;\nimport org.clever.security.mapper.PermissionMapper;\nimport org.clever.security.mapper.RememberMeTokenMapper;\nimport org.clever.security.mapper.RoleMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.service.internal.ManageCryptoService;\nimport org.clever.security.service.internal.UserBindSysNameService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 20:53
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ManageByUserService {\n\n @Autowired\n private ManageCryptoService manageCryptoService;\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private PermissionMapper permissionMapper;\n @Autowired\n private RememberMeTokenMapper rememberMeTokenMapper;\n @Autowired\n private UserBindSysNameService userBindSysNameService;\n @Autowired\n private ISecurityContextService sessionService;\n\n public IPage findByPage(UserQueryPageReq userQueryPageReq) {\n Page page = new Page<>(userQueryPageReq.getPageNo(), userQueryPageReq.getPageSize());\n page.setRecords(userMapper.findByPage(userQueryPageReq, page));\n return page;\n }\n\n public UserInfoRes getUserInfo(String username) {\n User user = userMapper.getByUsername(username);\n if (user == null) {\n return null;\n }\n UserInfoRes userInfoRes = BeanMapper.mapper(user, UserInfoRes.class);\n userInfoRes.setRoleList(roleMapper.findByUsername(user.getUsername()));\n userInfoRes.setPermissionList(permissionMapper.findByUsername(user.getUsername()));\n userInfoRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername()));\n return userInfoRes;\n }\n\n @Transactional\n public User addUser(UserAddReq userAddReq) {\n User user = BeanMapper.mapper(userAddReq, User.class);\n final Date now = new Date();\n if (user.getExpiredTime() != null && now.compareTo(user.getExpiredTime()) >= 0) {\n throw new BusinessException(\"设置过期时间小于当前时间\");\n }\n if (userMapper.existsByUserName(user.getUsername()) > 0) {\n throw new BusinessException(\"用户名已经存在\");\n }\n if (StringUtils.isNotBlank(user.getTelephone()) && userMapper.existsByTelephone(user.getTelephone()) > 0) {\n throw new BusinessException(\"手机号已经被绑定\");\n }\n if (StringUtils.isNotBlank(user.getEmail()) && userMapper.existsByEmail(user.getEmail()) > 0) {\n throw new BusinessException(\"邮箱已经被绑定\");\n }\n // 登录名(一条记录的手机号不能当另一条记录的用户名用)\n if (StringUtils.isNotBlank(user.getTelephone()) && userMapper.existsByUserName(user.getTelephone()) > 0) {\n // 手机号不能是已存在用户的登录名\n throw new BusinessException(\"手机号已经被绑定\");\n }\n if (user.getUsername().matches(\"1[0-9]{10}\") && userMapper.existsByTelephone(user.getUsername()) > 0) {\n // 登录名符合手机号格式,而且该手机号已经存在\n throw new BusinessException(\"手机号已经被绑定\");\n }\n // 密码先解密再加密\n user.setPassword(manageCryptoService.reqAesDecrypt(user.getPassword()));\n user.setPassword(manageCryptoService.dbEncode(user.getPassword()));\n userMapper.insert(user);\n if (userAddReq.getSysNameList() != null) {\n for (String sysName : userAddReq.getSysNameList()) {\n userMapper.addUserSys(user.getUsername(), sysName);\n }\n }\n return userMapper.selectById(user.getId());\n }\n\n @Transactional\n public User updateUser(String username, UserUpdateReq req) {\n User oldUser = userMapper.getByUsername(username);\n if (oldUser == null) {\n throw new BusinessException(\"用户不存在\");\n }\n boolean delRememberMeToken = false;\n // Session 操作标识,0 不操作;1 更新;2 删除\n int sessionFlag = 0;\n // 修改了密码\n if (StringUtils.isNotBlank(req.getPassword())) {\n // 密码先解密再加密\n req.setPassword(manageCryptoService.reqAesDecrypt(req.getPassword()));\n req.setPassword(manageCryptoService.dbEncode(req.getPassword()));\n // 设置删除 RememberMeToken\n delRememberMeToken = true;\n // 更新Session\n sessionFlag = 1;\n } else {\n req.setPassword(null);\n }\n // 修改了手机号\n if (StringUtils.isNotBlank(req.getTelephone()) && !req.getTelephone().equals(oldUser.getTelephone())) {\n if (userMapper.existsByTelephone(req.getTelephone()) > 0 || userMapper.existsByUserName(req.getTelephone()) > 0) {\n throw new BusinessException(\"手机号已经被绑定\");\n }\n } else {\n req.setTelephone(null);\n }\n // 修改了邮箱\n if (StringUtils.isNotBlank(req.getEmail()) && !req.getEmail().equals(oldUser.getEmail())) {\n if (userMapper.existsByEmail(req.getEmail()) > 0) {\n throw new BusinessException(\"邮箱已经被绑定\");\n }\n } else {\n req.setEmail(null);\n }\n // 设置了过期、锁定、禁用\n if ((req.getExpiredTime() != null && req.getExpiredTime().compareTo(new Date()) <= 0)\n || Objects.equals(req.getLocked(), EnumConstant.User_Locked_1)\n || Objects.equals(req.getEnabled(), EnumConstant.User_Enabled_0)) {\n // 设置删除 RememberMeToken\n delRememberMeToken = true;\n // 删除Session\n sessionFlag = 2;\n }\n User user = BeanMapper.mapper(req, User.class);\n user.setId(oldUser.getId());\n userMapper.updateById(user);\n user = userMapper.selectById(oldUser.getId());\n // 更新关联系统\n if (req.getSysNameList() == null) {\n req.setSysNameList(new HashSet<>());\n }\n userBindSysNameService.resetUserBindSys(user.getUsername(), req.getSysNameList());\n if (delRememberMeToken) {\n // 删除RememberMe Token\n rememberMeTokenMapper.deleteByUsername(user.getUsername());\n }\n if (sessionFlag == 1) {\n // 更新Session\n sessionService.reloadSecurityContext(user.getUsername());\n }\n if (sessionFlag == 2) {\n // 删除Session\n sessionService.delSession(user.getUsername());\n }\n return user;\n }\n\n @Transactional\n public User deleteUser(String username) {\n User user = userMapper.getByUsername(username);\n if (user == null) {\n throw new BusinessException(\"用户不存在\");\n }\n userMapper.deleteById(user.getId());\n userMapper.delUserRole(user.getUsername());\n userMapper.delAllUserSys(user.getUsername());\n rememberMeTokenMapper.deleteByUsername(user.getUsername());\n // 删除Session\n sessionService.delSession(user.getUsername());\n return user;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByQueryService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.dto.request.RememberMeTokenQueryReq;\nimport org.clever.security.dto.request.ServiceSysQueryReq;\nimport org.clever.security.dto.request.UserLoginLogQueryReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.entity.model.UserLoginLogModel;\nimport org.clever.security.entity.model.UserRememberMeToken;\nimport org.clever.security.mapper.QueryMapper;\nimport org.clever.security.mapper.ServiceSysMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-07 19:38
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ManageByQueryService {\n\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private QueryMapper queryMapper;\n @Autowired\n private ServiceSysMapper serviceSysMapper;\n\n public Boolean existsUserByUsername(String username) {\n return userMapper.existsByUserName(username) > 0;\n }\n\n public Boolean existsUserByTelephone(String telephone) {\n return userMapper.existsByTelephone(telephone) > 0;\n }\n\n public Boolean existsUserByEmail(String email) {\n return userMapper.existsByEmail(email) > 0;\n }\n\n public List allSysName() {\n List sysNameList = serviceSysMapper.allSysName();\n List tmp = queryMapper.allSysName();\n for (String sysName : tmp) {\n if (!sysNameList.contains(sysName)) {\n sysNameList.add(sysName);\n }\n }\n return sysNameList;\n }\n\n public List findSysNameByUser(String username) {\n return userMapper.findSysNameByUsername(username);\n }\n\n public List allRoleName() {\n return queryMapper.allRoleName();\n }\n\n public List findRoleNameByUser(String username) {\n return queryMapper.findRoleNameByUser(username);\n }\n\n public List findPermissionStrByRole(String roleName) {\n return queryMapper.findPermissionStrByRole(roleName);\n }\n\n public IPage findRememberMeToken(RememberMeTokenQueryReq req) {\n Page page = new Page<>(req.getPageNo(), req.getPageSize());\n page.setRecords(queryMapper.findRememberMeToken(req, page));\n return page;\n }\n\n public IPage findUserLoginLog(UserLoginLogQueryReq req) {\n Page page = new Page<>(req.getPageNo(), req.getPageSize());\n page.setRecords(queryMapper.findUserLoginLog(req, page));\n return page;\n }\n\n public IPage findServiceSys(ServiceSysQueryReq req) {\n Page page = new Page<>(req.getPageNo(), req.getPageSize());\n page.setRecords(queryMapper.findServiceSys(req, page));\n return page;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByQueryController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.model.response.AjaxMessage;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.security.dto.request.RememberMeTokenQueryReq;\nimport org.clever.security.dto.request.ServiceSysQueryReq;\nimport org.clever.security.dto.request.UserLoginLogQueryReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.entity.model.UserLoginLogModel;\nimport org.clever.security.entity.model.UserRememberMeToken;\nimport org.clever.security.service.ManageByQueryService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 20:50
\n */\n@Api(\"管理页面查询\")\n@RestController\n@RequestMapping(\"/api/manage\")\npublic class ManageByQueryController extends BaseController {\n\n @Autowired\n private ManageByQueryService manageByQueryService;\n\n @ApiOperation(\"查询username是否存在\")\n @GetMapping(\"/user/username/{username}/exists\")\n public AjaxMessage existsUserByUsername(@PathVariable(\"username\") String username) {\n return new AjaxMessage<>(manageByQueryService.existsUserByUsername(username), \"查询成功\");\n }\n\n @ApiOperation(\"查询telephone是否存在\")\n @GetMapping(\"/user/telephone/{telephone}/exists\")\n public AjaxMessage existsUserByTelephone(@PathVariable(\"telephone\") String telephone) {\n return new AjaxMessage<>(manageByQueryService.existsUserByTelephone(telephone), \"查询成功\");\n }\n\n @ApiOperation(\"查询email是否存在\")\n @GetMapping(\"/user/email/{email}/exists\")\n public AjaxMessage existsUserByEmail(@PathVariable(\"email\") String email) {\n return new AjaxMessage<>(manageByQueryService.existsUserByEmail(email), \"查询成功\");\n }\n\n @ApiOperation(\"查询所有系统名称\")\n @GetMapping(\"/sys_name\")\n public List allSysName() {\n return manageByQueryService.allSysName();\n }\n\n @ApiOperation(\"查询用户绑定的系统\")\n @GetMapping(\"/sys_name/{username}\")\n public List findSysNameByUser(@PathVariable(\"username\") String username) {\n return manageByQueryService.findSysNameByUser(username);\n }\n\n @ApiOperation(\"查询所有角色名称\")\n @GetMapping(\"/role_name\")\n public List allRoleName() {\n return manageByQueryService.allRoleName();\n }\n\n @ApiOperation(\"查询用户拥有的角色\")\n @GetMapping(\"/role_name/{username}\")\n public List findRoleNameByUser(@PathVariable(\"username\") String username) {\n return manageByQueryService.findRoleNameByUser(username);\n }\n\n @ApiOperation(\"查询角色拥有的权限字符串\")\n @GetMapping(\"/permission_str/{roleName}\")\n public List findPermissionStrByRole(@PathVariable(\"roleName\") String roleName) {\n return manageByQueryService.findPermissionStrByRole(roleName);\n }\n\n @ApiOperation(\"分页查询“记住我”功能的Token\")\n @GetMapping(\"/remember_me_token\")\n public IPage findRememberMeToken(RememberMeTokenQueryReq req) {\n return manageByQueryService.findRememberMeToken(req);\n }\n\n @ApiOperation(\"分页查询用户登录日志\")\n @GetMapping(\"/user_login_log\")\n public IPage findUserLoginLog(UserLoginLogQueryReq req) {\n return manageByQueryService.findUserLoginLog(req);\n }\n\n @ApiOperation(\"分页查询接入系统\")\n @GetMapping(\"/service_sys\")\n public IPage findServiceSys(ServiceSysQueryReq req) {\n return manageByQueryService.findServiceSys(req);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/provider/AuthenticationUsernamePasswordToken.java<|end_filename|>\npackage org.clever.security.authentication.provider;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.authentication.AuthenticationLoginToken;\nimport org.clever.security.exception.BadLoginTypeException;\nimport org.clever.security.service.RequestCryptoService;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.clever.security.token.login.UsernamePasswordToken;\nimport org.springframework.security.authentication.BadCredentialsException;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.stereotype.Component;\n\n/**\n * UsernamePasswordToken 验证逻辑\n * 作者: lzw
\n * 创建时间:2019-04-28 15:21
\n */\n@Component\n@Slf4j\npublic class AuthenticationUsernamePasswordToken implements AuthenticationLoginToken {\n\n private UsernamePasswordToken getUsernamePasswordToken(BaseLoginToken loginToken) {\n if (!(loginToken instanceof UsernamePasswordToken)) {\n throw new BadLoginTypeException(String.format(\"loginToken类型错误,%s | %s\", loginToken.getClass(), loginToken.toString()));\n }\n return (UsernamePasswordToken) loginToken;\n }\n\n @Override\n public boolean supports(Class loginToken) {\n return UsernamePasswordToken.class.isAssignableFrom(loginToken);\n }\n\n @Override\n public void preAuthenticationCheck(BaseLoginToken loginToken) throws AuthenticationException {\n UsernamePasswordToken usernamePasswordToken = getUsernamePasswordToken(loginToken);\n if (StringUtils.isBlank(usernamePasswordToken.getUsername())) {\n throw new BadCredentialsException(\"用户名不能为空\");\n }\n if (StringUtils.isBlank(usernamePasswordToken.getPassword())) {\n throw new BadCredentialsException(\"密码不能为空\");\n }\n }\n\n @Override\n public void mainAuthenticationChecks(BaseLoginToken loginToken, UserDetails loadedUser, RequestCryptoService requestCryptoService, BCryptPasswordEncoder bCryptPasswordEncoder) throws AuthenticationException {\n UsernamePasswordToken usernamePasswordToken = getUsernamePasswordToken(loginToken);\n // 用户密码需要AES对称加解密 网络密文传输\n usernamePasswordToken.setPassword(requestCryptoService.reqAesDecrypt(usernamePasswordToken.getPassword()));\n // 用户名、密码校验\n if (!usernamePasswordToken.getUsername().equals(loadedUser.getUsername()) || !bCryptPasswordEncoder.matches(usernamePasswordToken.getPassword(), loadedUser.getPassword())) {\n log.info(\"### 用户名密码验证失败 [{}]\", loginToken.toString());\n throw new BadCredentialsException(\"用户名密码验证失败\");\n }\n log.info(\"### 用户名密码验证成功 [{}]\", loginToken.toString());\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/UserLoginLog.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 用户登录日志(UserLoginLog)实体类\n *\n * @author lizw\n * @since 2018-09-23 19:55:43\n */\n@Data\npublic class UserLoginLog implements Serializable {\n private static final long serialVersionUID = -11162979906700377L;\n /**\n * 主键id\n */\n private Long id;\n\n /**\n * 系统(或服务)名称\n */\n private String sysName;\n\n /**\n * 用户登录名\n */\n private String username;\n\n /**\n * 登录时间\n */\n private Date loginTime;\n\n /**\n * 登录IP\n */\n private String loginIp;\n\n /**\n * 登录的用户信息\n */\n private String authenticationInfo;\n\n /**\n * 登录类型,0:sesion-cookie,1:jwt-token\n */\n private Integer loginModel;\n\n /**\n * 登录SessionID\n */\n private String sessionId;\n\n /**\n * 登录状态,0:未知;1:已登录;2:登录已过期\n */\n private Integer loginState;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n\n}\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/BadCaptchaException.java<|end_filename|>\npackage org.clever.security.exception;\n\n\nimport org.springframework.security.core.AuthenticationException;\n\n/**\n * 验证码错误\n *

\n * 作者: lzw
\n * 创建时间:2018-09-19 22:33
\n */\npublic class BadCaptchaException extends AuthenticationException {\n\n public BadCaptchaException(String msg) {\n super(msg);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/Role.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 角色表(Role)实体类\n *\n * @author lizw\n * @since 2018-09-16 21:24:44\n */\n@Data\npublic class Role implements Serializable {\n private static final long serialVersionUID = -72497893232578795L;\n /** 主键id */ \n private Long id;\n \n /** 角色名称 */ \n private String name;\n \n /** 角色说明 */ \n private String description;\n \n /** 创建时间 */ \n private Date createAt;\n \n /** 更新时间 */ \n private Date updateAt;\n \n}\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLoginFailureHandler.java<|end_filename|>\npackage org.clever.security.handler;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.dto.response.LoginRes;\nimport org.clever.security.exception.BadCaptchaException;\nimport org.clever.security.exception.BadLoginTypeException;\nimport org.clever.security.exception.CanNotLoginSysException;\nimport org.clever.security.exception.ConcurrentLoginException;\nimport org.clever.security.repository.LoginFailCountRepository;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.*;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.security.web.DefaultRedirectStrategy;\nimport org.springframework.security.web.RedirectStrategy;\nimport org.springframework.security.web.WebAttributes;\nimport org.springframework.security.web.authentication.AuthenticationFailureHandler;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * 自定义登录失败处理类\n *

\n * 作者: lzw
\n * 创建时间:2018-03-17 23:04
\n */\n@Component\n@Slf4j\npublic class UserLoginFailureHandler implements AuthenticationFailureHandler {\n\n private final String defaultRedirectUrl = \"/index.html\";\n private final Map failureMessageMap = new HashMap<>();\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private LoginFailCountRepository loginFailCountRepository;\n @Autowired\n private UserClient userClient;\n private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();\n private boolean hideUserNotFoundExceptions = true;\n\n public UserLoginFailureHandler(SecurityConfig securityConfig) {\n failureMessageMap.put(UsernameNotFoundException.class.getName(), \"用户不存在\");\n failureMessageMap.put(BadCredentialsException.class.getName(), \"用户名或密码错误\");\n failureMessageMap.put(AccountStatusException.class.getName(), \"账户状态异常\");\n failureMessageMap.put(AccountExpiredException.class.getName(), \"账户已过期\");\n failureMessageMap.put(LockedException.class.getName(), \"账户被锁定\");\n failureMessageMap.put(DisabledException.class.getName(), \"账户被禁用\");\n failureMessageMap.put(CredentialsExpiredException.class.getName(), \"密码已过期\");\n failureMessageMap.put(BadCaptchaException.class.getName(), \"验证码错误\");\n failureMessageMap.put(BadLoginTypeException.class.getName(), \"不支持的登录类型\");\n failureMessageMap.put(CanNotLoginSysException.class.getName(), \"您无权登录当前系统,请联系管理员授权\");\n failureMessageMap.put(ConcurrentLoginException.class.getName(), \"并发登录数量超限\");\n if (securityConfig.getHideUserNotFoundExceptions() != null) {\n hideUserNotFoundExceptions = securityConfig.getHideUserNotFoundExceptions();\n }\n }\n\n @Override\n public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {\n Integer loginFailCount = null;\n LoginConfig login = securityConfig.getLogin();\n if (login.getNeedCaptcha()) {\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // JwtToken 记录登录失败次数\n Object object = request.getAttribute(Constant.Login_Username_Request_Key);\n if (object != null && StringUtils.isNotBlank(object.toString()) && userClient.canLogin(object.toString(), securityConfig.getSysName())) {\n loginFailCount = Long.valueOf(loginFailCountRepository.incrementLoginFailCount(object.toString())).intValue();\n }\n } else {\n // Session 记录登录次数\n Object loginFailCountStr = request.getSession().getAttribute(Constant.Login_Fail_Count_Session_Key);\n loginFailCount = 1;\n if (loginFailCountStr != null) {\n loginFailCount = NumberUtils.toInt(loginFailCountStr.toString(), 0) + 1;\n }\n request.getSession().setAttribute(Constant.Login_Fail_Count_Session_Key, loginFailCount);\n }\n }\n // 登录失败 - 是否需要跳转\n if (login.getLoginFailureNeedRedirect() != null && login.getLoginFailureNeedRedirect()) {\n // 跳转\n HttpSession session = request.getSession(false);\n if (session != null) {\n request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);\n }\n sendRedirect(request, response, login.getLoginFailureRedirectPage());\n return;\n }\n // 请求转发\n if (login.getLoginFailureNeedForward() != null && login.getLoginFailureNeedForward()) {\n request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);\n sendForward(request, response, login.getLoginFailureRedirectPage());\n return;\n }\n // 不需要跳转\n sendJsonData(response, exception, login, loginFailCount);\n }\n\n /**\n * 直接返回Json数据\n */\n private void sendJsonData(HttpServletResponse response, AuthenticationException exception, LoginConfig login, Integer loginFailCount) {\n String message = failureMessageMap.get(exception.getClass().getName());\n if (hideUserNotFoundExceptions && exception instanceof UsernameNotFoundException) {\n message = failureMessageMap.get(BadCredentialsException.class.getName());\n }\n if (StringUtils.isBlank(message)) {\n message = \"登录失败\";\n }\n LoginRes loginRes = new LoginRes(false, message);\n if (loginFailCount != null) {\n if (login.getNeedCaptcha() && login.getNeedCaptchaByLoginFailCount() <= loginFailCount) {\n // 下次登录需要验证码\n loginRes.setNeedCaptcha(true);\n }\n }\n log.info(\"### 登录失败不需要跳转 -> [{}]\", loginRes);\n HttpResponseUtils.sendJsonBy401(response, loginRes);\n }\n\n /**\n * 页面跳转 (重定向)\n */\n private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n log.info(\"### 登录失败跳转Url(重定向) -> {}\", url);\n if (!response.isCommitted()) {\n redirectStrategy.sendRedirect(request, response, url);\n }\n }\n\n /**\n * 页面跳转 (请求转发)\n */\n private void sendForward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n log.info(\"### 登录失败跳转Url(请求转发) -> {}\", url);\n request.getRequestDispatcher(url).forward(request, response);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/UserBindSysNameService.java<|end_filename|>\npackage org.clever.security.service.internal;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.service.ISecurityContextService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 操作用户系统绑定的Service\n *

\n * 作者: lzw
\n * 创建时间:2018-10-11 9:44
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class UserBindSysNameService {\n\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private ISecurityContextService sessionService;\n\n /**\n * 重置用户系统绑定\n *\n * @param userName 用户登录名\n * @param sysNameList 系统名称集合\n */\n @Transactional\n public void resetUserBindSys(String userName, Collection sysNameList) {\n if (sysNameList == null) {\n sysNameList = new ArrayList<>();\n }\n // 获取关联系统列表\n List oldSysNameList = userMapper.findSysNameByUsername(userName);\n Set addSysName = new HashSet<>(sysNameList);\n addSysName.removeAll(oldSysNameList);\n Set delSysName = new HashSet<>(oldSysNameList);\n delSysName.removeAll(sysNameList);\n // 新增\n for (String sysName : addSysName) {\n userMapper.addUserSys(userName, sysName);\n }\n // 删除\n for (String sysName : delSysName) {\n userMapper.delUserSys(userName, sysName);\n // 删除Session\n sessionService.delSession(sysName, userName);\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/RedisJwtRepository.java<|end_filename|>\npackage org.clever.security.repository;\n\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.Jws;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.CookieUtils;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.TokenConfig;\nimport org.clever.security.service.GenerateKeyService;\nimport org.clever.security.service.JwtTokenService;\nimport org.clever.security.token.JwtAccessToken;\nimport org.clever.security.token.JwtRefreshToken;\nimport org.clever.security.token.SecurityContextToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport java.time.Duration;\nimport java.util.HashSet;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-20 11:12
\n */\n@Component\n@Slf4j\npublic class RedisJwtRepository {\n\n /**\n * 刷新令牌有效时间\n */\n private final Duration refreshTokenValidity;\n /**\n * JWT Token配置\n */\n private final TokenConfig tokenConfig;\n\n @Autowired\n private JwtTokenService jwtTokenService;\n @Autowired\n private RedisTemplate redisTemplate;\n @Autowired\n private GenerateKeyService generateKeyService;\n\n protected RedisJwtRepository(SecurityConfig securityConfig) {\n tokenConfig = securityConfig.getTokenConfig();\n if (tokenConfig == null || tokenConfig.getRefreshTokenValidity() == null) {\n throw new IllegalArgumentException(\"未配置TokenConfig\");\n }\n refreshTokenValidity = tokenConfig.getRefreshTokenValidity();\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------- JwtAccessToken\n\n public JwtAccessToken saveJwtToken(SecurityContextToken securityContextToken) {\n boolean rememberMe = securityContextToken.getLoginToken().isRememberMe();\n // 保存 JwtAccessToken\n JwtAccessToken jwtAccessToken = jwtTokenService.createToken(securityContextToken, rememberMe);\n String JwtTokenKey = generateKeyService.getJwtTokenKey(jwtAccessToken.getClaims());\n if (jwtAccessToken.getClaims().getExpiration() == null) {\n redisTemplate.opsForValue().set(JwtTokenKey, jwtAccessToken);\n } else {\n long timeout = jwtAccessToken.getClaims().getExpiration().getTime() - System.currentTimeMillis();\n redisTemplate.opsForValue().set(JwtTokenKey, jwtAccessToken, timeout, TimeUnit.MILLISECONDS);\n }\n // 保存 JwtRefreshToken\n String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(jwtAccessToken.getRefreshToken());\n JwtRefreshToken jwtRefreshToken = new JwtRefreshToken(securityContextToken.getName(), jwtAccessToken.getClaims().getId());\n if (refreshTokenValidity.getSeconds() <= 0) {\n redisTemplate.opsForValue().set(jwtRefreshTokenKey, jwtRefreshToken);\n } else {\n redisTemplate.opsForValue().set(jwtRefreshTokenKey, jwtRefreshToken, refreshTokenValidity.getSeconds(), TimeUnit.SECONDS);\n }\n return jwtAccessToken;\n }\n\n public void deleteJwtTokenByKey(String JwtTokenKey) {\n JwtAccessToken jwtAccessToken = getJwtTokenByKey(JwtTokenKey);\n deleteJwtToken(jwtAccessToken);\n }\n\n public void deleteJwtToken(JwtAccessToken jwtAccessToken) {\n // 删除 JwtAccessToken\n String JwtTokenKey = generateKeyService.getJwtTokenKey(jwtAccessToken.getClaims());\n redisTemplate.delete(JwtTokenKey);\n // 删除 JwtRefreshToken\n String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(jwtAccessToken.getRefreshToken());\n redisTemplate.delete(jwtRefreshTokenKey);\n }\n\n public JwtAccessToken getJwtToken(HttpServletRequest request) {\n String token;\n if (Objects.equals(tokenConfig.isUseCookie(), true)) {\n token = CookieUtils.getCookie(request, tokenConfig.getJwtTokenKey());\n } else {\n token = request.getHeader(tokenConfig.getJwtTokenKey());\n }\n if (StringUtils.isBlank(token)) {\n throw new BusinessException(\"Token不存在\");\n }\n return getJwtToken(token);\n }\n\n public JwtAccessToken getJwtToken(String token) {\n Jws claimsJws = jwtTokenService.getClaimsJws(token);\n return getJwtToken(claimsJws.getBody());\n }\n\n public JwtAccessToken getJwtToken(Claims claims) {\n return getJwtToken(claims.getSubject(), claims.getId());\n }\n\n public JwtAccessToken getJwtToken(String username, String tokenId) {\n String JwtTokenKey = generateKeyService.getJwtTokenKey(username, tokenId);\n return getJwtTokenByKey(JwtTokenKey);\n }\n\n public JwtAccessToken getJwtTokenByKey(String JwtTokenKey) {\n Object object = redisTemplate.opsForValue().get(JwtTokenKey);\n if (object == null) {\n throw new BusinessException(\"JwtToken已过期\");\n }\n if (!(object instanceof JwtAccessToken)) {\n throw new BusinessException(\"JwtToken类型错误\");\n }\n return (JwtAccessToken) object;\n }\n\n public Set getJwtTokenPatternKey(String username) {\n Set ketSet = redisTemplate.keys(generateKeyService.getJwtTokenPatternKey(username));\n if (ketSet == null) {\n ketSet = new HashSet<>(0);\n }\n return ketSet;\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------- JwtRefreshToken\n\n public JwtRefreshToken getRefreshToken(String refreshToken) {\n String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(refreshToken);\n Object object = redisTemplate.opsForValue().get(jwtRefreshTokenKey);\n if (object == null) {\n throw new BusinessException(\"刷新令牌错误或已过期\");\n }\n if (!(object instanceof JwtRefreshToken)) {\n throw new BusinessException(\"刷新令牌类型错误\");\n }\n return (JwtRefreshToken) object;\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------- SecurityContext\n\n public void saveSecurityContext(SecurityContext context) {\n String securityContextKey = generateKeyService.getSecurityContextKey(context.getAuthentication().getName());\n redisTemplate.opsForValue().set(securityContextKey, context);\n }\n\n public void deleteSecurityContext(String username) {\n String securityContextKey = generateKeyService.getSecurityContextKey(username);\n redisTemplate.delete(securityContextKey);\n }\n\n public SecurityContext getSecurityContext(JwtAccessToken jwtAccessToken) {\n return getSecurityContext(jwtAccessToken.getClaims().getSubject());\n }\n\n public SecurityContext getSecurityContext(Claims claims) {\n return getSecurityContext(claims.getSubject());\n }\n\n public SecurityContext getSecurityContext(String username) {\n String securityContextKey = generateKeyService.getSecurityContextKey(username);\n Object object = redisTemplate.opsForValue().get(securityContextKey);\n if (object == null) {\n throw new BusinessException(\"SecurityContext不存在\");\n }\n if (!(object instanceof SecurityContext)) {\n throw new BusinessException(\"SecurityContext类型错误\");\n }\n return (SecurityContext) object;\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------- validationToken\n\n /**\n * 验证令牌 (不会抛出异常)\n */\n public boolean validationToken(HttpServletRequest request) {\n String token = request.getHeader(tokenConfig.getJwtTokenKey());\n if (StringUtils.isBlank(token) && tokenConfig.isUseCookie()) {\n token = CookieUtils.getCookie(request, tokenConfig.getJwtTokenKey());\n }\n if (StringUtils.isBlank(token)) {\n return false;\n }\n return validationToken(token);\n }\n\n /**\n * 验证令牌 (不会抛出异常)\n */\n public boolean validationToken(String token) {\n try {\n Jws claimsJws = jwtTokenService.getClaimsJws(token);\n if (claimsJws != null) {\n return true;\n }\n } catch (Throwable ignored) {\n }\n return false;\n }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/config/CleverSecurityFeignConfiguration.java<|end_filename|>\npackage org.clever.security.config;\n\nimport feign.RequestInterceptor;\nimport feign.RequestTemplate;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.spring.SpringContextHolder;\n\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-05-15 17:58
\n */\n@Slf4j\npublic class CleverSecurityFeignConfiguration implements RequestInterceptor {\n\n /**\n * 服务访问Token\n */\n private CleverSecurityAccessTokenConfig accessTokenConfig;\n\n @Override\n public void apply(RequestTemplate template) {\n if (accessTokenConfig == null) {\n accessTokenConfig = SpringContextHolder.getBean(CleverSecurityAccessTokenConfig.class);\n // log.debug(\"读取访问clever-security-server服务API的授权Token请求头: {}\", accessTokenConfig.getAccessTokenHeads());\n }\n if (accessTokenConfig.getAccessTokenHeads() != null && accessTokenConfig.getAccessTokenHeads().size() > 0) {\n // log.debug(\"[访问clever-security-server的AccessToken请求头] --> {}\", accessTokenConfig.getAccessTokenHeads());\n for (Map.Entry entry : accessTokenConfig.getAccessTokenHeads().entrySet()) {\n template.header(entry.getKey(), entry.getValue());\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/HttpSessionCreatedListener.java<|end_filename|>\npackage org.clever.security.event;//package org.clever.security.event;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.LoginModel;\nimport org.clever.security.config.SecurityConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.security.web.session.HttpSessionCreatedEvent;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpSession;\n\n/**\n * Session 创建监听\n *

\n * 作者: lzw
\n * 创建时间:2018-09-23 19:28
\n */\n@Component\n@Slf4j\npublic class HttpSessionCreatedListener implements ApplicationListener {\n\n @Autowired\n private SecurityConfig securityConfig;\n\n @Override\n public void onApplicationEvent(HttpSessionCreatedEvent event) {\n HttpSession session = event.getSession();\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n log.error(\"### 新建Session [{}] -> JWT Token 不应该创建HttpSession\", session.getId());\n } else {\n log.info(\"### 新建Session [{}]\", session.getId());\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/RememberMeToken.java<|end_filename|>\npackage org.clever.security.token.login;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport lombok.Getter;\nimport lombok.Setter;\nimport org.clever.security.LoginTypeConstant;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-28 18:25
\n */\npublic class RememberMeToken extends BaseLoginToken {\n\n /**\n * 用户名\n */\n @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)\n @Setter\n @Getter\n private String username;\n\n public RememberMeToken() {\n super(LoginTypeConstant.RememberMe);\n }\n\n /**\n * 返回密码\n */\n @Override\n public Object getCredentials() {\n return null;\n }\n\n /**\n * 返回用户登录唯一ID\n */\n @Override\n public Object getPrincipal() {\n return username;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/RoleBindPermissionRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\nimport org.clever.security.entity.Permission;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-04 12:56
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class RoleBindPermissionRes extends BaseResponse {\n\n @ApiModelProperty(\"角色名称\")\n private String roleName;\n\n @ApiModelProperty(\"权限列表\")\n private List permissionList;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageBySessionController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.security.dto.response.ForcedOfflineRes;\nimport org.clever.security.service.ISecurityContextService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-12 10:21
\n */\n@Api(\"Session管理\")\n@RestController\n@RequestMapping(\"/api/manage\")\npublic class ManageBySessionController {\n\n @Autowired\n private ISecurityContextService sessionService;\n\n @ApiOperation(\"重新加载用户SessionSecurityContext\")\n @GetMapping(\"/reload_session_security_context/{username}\")\n public Map> reloadSessionSecurityContext(@PathVariable(\"username\") String username) {\n return sessionService.reloadSecurityContext(username);\n }\n\n @ApiOperation(\"读取用户SessionSecurityContext\")\n @GetMapping(\"/session_security_context/{sysName}/{username}\")\n public Map getSessionSecurityContext(@PathVariable(\"sysName\") String sysName, @PathVariable(\"username\") String username) {\n return sessionService.getSecurityContext(sysName, username);\n }\n\n @ApiOperation(\"读取用户SessionSecurityContext\")\n @GetMapping(\"/session_security_context/{sessionId}\")\n public SecurityContext getSessionSecurityContext(@PathVariable(\"sessionId\") String sessionId) {\n return sessionService.getSecurityContext(sessionId);\n }\n\n @ApiOperation(\"踢出用户(强制下线)\")\n @GetMapping(\"/forced_offline/{sysName}/{username}\")\n public ForcedOfflineRes forcedOffline(@PathVariable(\"sysName\") String sysName, @PathVariable(\"username\") String username) {\n int count = sessionService.forcedOffline(sysName, username);\n ForcedOfflineRes forcedOfflineRes = new ForcedOfflineRes();\n forcedOfflineRes.setCount(count);\n forcedOfflineRes.setSysName(sysName);\n forcedOfflineRes.setUsername(username);\n return forcedOfflineRes;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/RoleBindPermissionService.java<|end_filename|>\npackage org.clever.security.service.internal;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.mapper.QueryMapper;\nimport org.clever.security.mapper.RoleMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-19 19:30
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class RoleBindPermissionService {\n\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private QueryMapper queryMapper;\n @Autowired\n private ReLoadSessionService reLoadSessionService;\n\n /**\n * 重新为角色分配权限\n *\n * @param roleName 角色名称\n * @param permissionStrList 权限名称集合\n */\n @Transactional\n public void resetRoleBindPermission(String roleName, Collection permissionStrList) {\n if (permissionStrList == null) {\n permissionStrList = new ArrayList<>();\n }\n // 获取关联角色列表\n List oldPermissionStrList = queryMapper.findPermissionStrByRole(roleName);\n Set addPermissionStr = new HashSet<>(permissionStrList);\n addPermissionStr.removeAll(oldPermissionStrList);\n Set delPermissionStr = new HashSet<>(oldPermissionStrList);\n delPermissionStr.removeAll(permissionStrList);\n // 新增\n for (String permissionStr : addPermissionStr) {\n roleMapper.addPermission(roleName, permissionStr);\n }\n // 删除\n for (String permissionStr : delPermissionStr) {\n roleMapper.delPermission(roleName, permissionStr);\n }\n // 分析受影响的用户并更新对应的Session\n reLoadSessionService.onChangeRole(roleName);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/LoadThirdUser.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport org.clever.security.client.ManageByUserClient;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.token.login.BaseLoginToken;\n\n/**\n * 加载第三方用户信息\n *

\n * 作者: lzw
\n * 创建时间:2019-04-28 18:55
\n */\npublic interface LoadThirdUser {\n\n /**\n * 是否支持当前loginToken从第三方加载用户信息\n *\n * @param loginToken 当前登录Token\n * @return 支持返回true\n */\n boolean supports(BaseLoginToken loginToken);\n\n /**\n * 从第三方系统加载用户信息\n *\n * @param loginToken 当前登录Token\n * @param userClient 读取系统用户\n * @param manageByUserClient 新增系统用户\n * @return 如仍需从权限系统读取用户信息则返回null,如果不需要则返回LoginUserDetails实体(建议把三方系统用户同步到当前系统并返回null)\n */\n LoginUserDetails loadUser(BaseLoginToken loginToken, UserClient userClient, ManageByUserClient manageByUserClient);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/UserLoginLogMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.entity.UserLoginLog;\nimport org.springframework.stereotype.Repository;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-23 16:02
\n */\n@Repository\n@Mapper\npublic interface UserLoginLogMapper extends BaseMapper {\n\n UserLoginLog getBySessionId(@Param(\"sessionId\") String sessionId);\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/model/UserAuthority.java<|end_filename|>\npackage org.clever.security.model;\n\nimport lombok.Getter;\nimport org.springframework.security.core.GrantedAuthority;\n\n/**\n * 权限信息\n *

\n * 作者: lzw
\n * 创建时间:2018-03-18 14:05
\n */\n@Getter\npublic final class UserAuthority implements GrantedAuthority {\n\n /** 权限字符串 */\n private final String authority;\n /** 权限标题 */\n private final String title;\n\n public UserAuthority(String authority, String title) {\n this.authority = authority;\n this.title = title;\n }\n\n @Override\n public String getAuthority() {\n return authority;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByRoleController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.RoleAddReq;\nimport org.clever.security.dto.request.RoleQueryPageReq;\nimport org.clever.security.dto.request.RoleUpdateReq;\nimport org.clever.security.dto.response.RoleInfoRes;\nimport org.clever.security.entity.Role;\nimport org.clever.security.service.ManageByRoleService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 20:47
\n */\n@Api(\"角色管理\")\n@RestController\n@RequestMapping(\"/api/manage\")\npublic class ManageByRoleController extends BaseController {\n\n @Autowired\n private ManageByRoleService manageByRoleService;\n\n @ApiOperation(\"查询权限列表\")\n @GetMapping(\"/role\")\n public IPage findByPage(RoleQueryPageReq roleQueryPageReq) {\n return manageByRoleService.findByPage(roleQueryPageReq);\n }\n\n @ApiOperation(\"新增权限\")\n @PostMapping(\"/role\")\n public Role addRole(@RequestBody @Validated RoleAddReq roleAddReq) {\n Role role = BeanMapper.mapper(roleAddReq, Role.class);\n return manageByRoleService.addRole(role);\n }\n\n @ApiOperation(\"更新权限\")\n @PutMapping(\"/role/{name}\")\n public Role updateRole(@PathVariable(\"name\") String name, @RequestBody @Validated RoleUpdateReq roleUpdateReq) {\n return manageByRoleService.updateRole(name, roleUpdateReq);\n }\n\n @ApiOperation(\"删除权限\")\n @DeleteMapping(\"/role/{name}\")\n public Role delRole(@PathVariable(\"name\") String name) {\n return manageByRoleService.delRole(name);\n }\n\n @ApiOperation(\"获取权限信息\")\n @GetMapping(\"/role/{name}\")\n public RoleInfoRes getRoleInfo(@PathVariable(\"name\") String name) {\n return manageByRoleService.getRoleInfo(name);\n }\n}\n\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/TokenAuthenticationManager.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.LoginModel;\nimport org.clever.security.client.ManageByUserClient;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.exception.BadLoginTypeException;\nimport org.clever.security.exception.ConcurrentLoginException;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.repository.RedisJwtRepository;\nimport org.clever.security.service.GlobalUserDetailsService;\nimport org.clever.security.service.RequestCryptoService;\nimport org.clever.security.token.JwtAccessToken;\nimport org.clever.security.token.SecurityContextToken;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.security.authentication.AuthenticationProvider;\nimport org.springframework.security.authentication.AuthenticationTrustResolver;\nimport org.springframework.security.authentication.AuthenticationTrustResolverImpl;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.core.userdetails.UserCache;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsChecker;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.security.core.userdetails.cache.NullUserCache;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * 登录Token认证 BaseLoginToken\n *

\n * 作者: lzw
\n * 创建时间:2018-03-15 17:41
\n */\n@Component\n@Slf4j\npublic class TokenAuthenticationManager implements AuthenticationProvider {\n\n /**\n * 登入模式\n */\n private LoginModel loginModel;\n /**\n * 同一个用户并发登录次数限制(-1表示不限制)\n */\n private final int concurrentLoginCount;\n /**\n * 同一个用户并发登录次数达到最大值之后,是否不允许之后的登录(false 之后登录的把之前登录的挤下来)\n */\n private final boolean notAllowAfterLogin;\n /**\n * 密码处理\n */\n @Autowired\n private BCryptPasswordEncoder bCryptPasswordEncoder;\n /**\n * 加载用户信息\n */\n @Autowired\n private GlobalUserDetailsService globalUserDetailsService;\n /**\n * 读取系统用户\n */\n @Autowired\n private UserClient userClient;\n /**\n * 新增系统用户\n */\n @Autowired\n private ManageByUserClient manageByUserClient;\n /**\n * 从第三方加载用户信息支持\n */\n @Autowired(required = false)\n private List loadThirdUserList;\n /**\n * 帐号校验(密码认证之前)\n */\n @Autowired\n @Qualifier(\"DefaultPreAuthenticationChecks\")\n private UserDetailsChecker preAuthenticationChecks;\n /**\n * 帐号校验(密码认证之后)\n */\n @Autowired\n @Qualifier(\"DefaultPostAuthenticationChecks\")\n private UserDetailsChecker postAuthenticationChecks;\n /**\n * 请求参数加密/解密\n */\n @Autowired\n private RequestCryptoService requestCryptoService;\n /**\n * JwtToken数据存取操作组件\n */\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n /**\n * Token认证登录\n */\n @Autowired\n private List authenticationLoginTokenList;\n /**\n * 用户数据本地缓存\n */\n private UserCache userCache = new NullUserCache();\n /**\n * 解析授权信息\n */\n private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();\n\n public TokenAuthenticationManager(SecurityConfig securityConfig) {\n LoginConfig login = securityConfig.getLogin();\n if (login == null) {\n throw new BusinessException(\"未配置Login配置\");\n }\n concurrentLoginCount = login.getConcurrentLoginCount();\n notAllowAfterLogin = login.getNotAllowAfterLogin();\n loginModel = securityConfig.getLoginModel();\n }\n\n /**\n * 是否支持验证此身份类型\n */\n @Override\n public boolean supports(Class authentication) {\n if (BaseLoginToken.class.isAssignableFrom(authentication)) {\n if (authenticationLoginTokenList == null) {\n log.warn(\"未注入Token认证登录组件\");\n } else {\n for (AuthenticationLoginToken authenticationLoginToken : authenticationLoginTokenList) {\n if (authenticationLoginToken.supports(authentication)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n * 认证用户登录\n */\n @Override\n public Authentication authenticate(Authentication authentication) throws AuthenticationException {\n Authentication currentLogined = SecurityContextHolder.getContext().getAuthentication();\n if (currentLogined != null && currentLogined.isAuthenticated() && !authenticationTrustResolver.isRememberMe(currentLogined)) {\n log.info(\"### 当前用户已登录拦截 [{}]\", currentLogined.toString());\n return currentLogined;\n }\n if (authentication.isAuthenticated()) {\n log.info(\"### 取消认证,Authentication已经认证成功 [{}]\", authentication.toString());\n return authentication;\n }\n log.info(\"### 开始验证用户[{}]\", authentication.toString());\n if (!(authentication instanceof BaseLoginToken)) {\n throw new BadLoginTypeException(String.format(\"不支持的登录信息,%s | %s\", authentication.getClass(), authentication.toString()));\n }\n // 获取对应的认证组件\n AuthenticationLoginToken authenticationLoginToken = null;\n for (AuthenticationLoginToken tmp : authenticationLoginTokenList) {\n if (tmp.supports(authentication.getClass())) {\n authenticationLoginToken = tmp;\n break;\n }\n }\n if (authenticationLoginToken == null) {\n throw new InternalAuthenticationServiceException(\"找不到Token认证登录组件\");\n }\n BaseLoginToken loginToken = (BaseLoginToken) authentication;\n authenticationLoginToken.preAuthenticationCheck(loginToken);\n // 查询帐号信息\n boolean cacheWasUsed = true;\n UserDetails loadedUser = this.userCache.getUserFromCache(loginToken.getName());\n if (loadedUser == null) {\n cacheWasUsed = false;\n try {\n loadedUser = retrieveUser(loginToken);\n } catch (UsernameNotFoundException notFound) {\n log.info(\"### 用户不存在[username={}]\", loginToken.getName());\n throw notFound;\n }\n log.info(\"### 已查询到用户信息[{}]\", loadedUser.toString());\n }\n // 验证帐号信息\n try {\n preAuthenticationChecks.check(loadedUser);\n authenticationLoginToken.mainAuthenticationChecks(loginToken, loadedUser, requestCryptoService, bCryptPasswordEncoder);\n } catch (AuthenticationException exception) {\n if (cacheWasUsed) {\n // 缓存中的数据不一定准确,如果使用缓存数据身份认证异常,则直接使用数据库的数据\n cacheWasUsed = false;\n // 检查此处的 hideUserNotFoundExceptions 是否需要判断\n loadedUser = retrieveUser(loginToken);\n preAuthenticationChecks.check(loadedUser);\n authenticationLoginToken.mainAuthenticationChecks(loginToken, loadedUser, requestCryptoService, bCryptPasswordEncoder);\n } else {\n throw exception;\n }\n }\n postAuthenticationChecks.check(loadedUser);\n log.info(\"### 用户认证成功 [{}]\", loadedUser.toString());\n // 帐号信息存入缓存\n if (!cacheWasUsed) {\n this.userCache.putUserInCache(loadedUser);\n }\n // 返回认证成功的 Authentication\n Authentication successAuthentication = createSuccessAuthentication(loginToken, loadedUser);\n // JwtToken 并发登录控制\n if (LoginModel.jwt.equals(loginModel)) {\n concurrentLogin(loadedUser.getUsername());\n }\n return successAuthentication;\n }\n\n /**\n * 查询用户\n */\n private UserDetails retrieveUser(BaseLoginToken loginToken) {\n UserDetails loadedUser = null;\n try {\n // 从第三方加载用户数据\n LoadThirdUser loadThirdUser = null;\n if (loadThirdUserList != null) {\n for (LoadThirdUser tmp : loadThirdUserList) {\n if (tmp.supports(loginToken)) {\n loadThirdUser = tmp;\n break;\n }\n }\n }\n if (loadThirdUser != null) {\n loadedUser = loadThirdUser.loadUser(loginToken, userClient, manageByUserClient);\n }\n if (loadedUser == null) {\n loadedUser = globalUserDetailsService.loadUserByUsername(loginToken.getName());\n }\n } catch (UsernameNotFoundException notFound) {\n throw notFound;\n } catch (Exception repositoryProblem) {\n throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);\n }\n return loadedUser;\n }\n\n /**\n * 创建认证成功的Authentication\n */\n private SecurityContextToken createSuccessAuthentication(BaseLoginToken loginToken, UserDetails userDetails) {\n LoginUserDetails loginUserDetails;\n if (!(userDetails instanceof LoginUserDetails)) {\n throw new InternalAuthenticationServiceException(String.format(\"加载的用户类型不正确,%s | %s\", userDetails.getClass(), userDetails.toString()));\n }\n loginUserDetails = (LoginUserDetails) userDetails;\n return new SecurityContextToken(loginToken, loginUserDetails);\n }\n\n /**\n * JwtToken 并发登录控制\n */\n private void concurrentLogin(String username) {\n if (concurrentLoginCount <= 0) {\n return;\n }\n Set ketSet = redisJwtRepository.getJwtTokenPatternKey(username);\n if (ketSet != null && ketSet.size() >= concurrentLoginCount) {\n if (notAllowAfterLogin) {\n throw new ConcurrentLoginException(\"并发登录数量超限\");\n }\n // 删除之前登录的Token 和 刷新令牌\n List list = ketSet.stream().sorted().collect(Collectors.toList());\n int delCount = list.size() - concurrentLoginCount + 1;\n for (int i = 0; i < delCount; i++) {\n String JwtTokenKey = list.get(i);\n JwtAccessToken jwtAccessToken = null;\n try {\n jwtAccessToken = redisJwtRepository.getJwtTokenByKey(JwtTokenKey);\n } catch (Throwable ignored) {\n }\n assert jwtAccessToken != null;\n redisJwtRepository.deleteJwtToken(jwtAccessToken);\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/DefaultPostAuthenticationChecks.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.security.authentication.CredentialsExpiredException;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsChecker;\nimport org.springframework.stereotype.Component;\n\n/**\n * 验证帐号信息成功之后的校验\n *

\n * 作者: lzw
\n * 创建时间:2018-09-19 16:33
\n */\n@Component(\"DefaultPostAuthenticationChecks\")\n@Slf4j\npublic class DefaultPostAuthenticationChecks implements UserDetailsChecker {\n\n @Override\n public void check(UserDetails user) {\n if (!user.isCredentialsNonExpired()) {\n log.info(\"帐号密码已过期 [username={}]\", user.getUsername());\n throw new CredentialsExpiredException(\"帐号密码已过期\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/UserServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.dto.request.UserAuthenticationReq;\nimport org.clever.security.dto.response.UserAuthenticationRes;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.User;\nimport org.clever.security.service.UserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-11 19:29
\n */\n@Component\n@Slf4j\npublic class UserServiceProxy implements UserClient {\n @Autowired\n private UserService userService;\n\n @Override\n public User getUser(String unique) {\n return userService.getUser(unique);\n }\n\n @Override\n public List findAllPermission(String username, String sysName) {\n return userService.findAllPermission(username, sysName);\n }\n\n @Override\n public Boolean canLogin(String username, String sysName) {\n return userService.canLogin(username, sysName);\n }\n\n @Override\n public UserAuthenticationRes authentication(UserAuthenticationReq req) {\n return userService.authenticationAndRes(req);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/BaseWebSecurityConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.security.authentication.AuthenticationProvider;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.WebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.password.PasswordEncoder;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-26 10:06
\n */\n@Slf4j\npublic abstract class BaseWebSecurityConfig extends WebSecurityConfigurerAdapter {\n\n public BaseWebSecurityConfig() {\n super(false);\n }\n\n /**\n * 密码编码码器\n */\n abstract PasswordEncoder getPasswordEncoder();\n\n /**\n * 获取用户信息组件\n */\n abstract UserDetailsService getUserDetailsService();\n\n /**\n * 用户认证组件\n */\n abstract List getAuthenticationProviderList();\n\n /**\n * 配置信息\n */\n abstract SecurityConfig getSecurityConfig();\n\n /**\n * 设置AuthenticationManager组件配置\n */\n @Override\n protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n super.configure(auth);\n // 添加认证组件\n List authenticationProviderList = getAuthenticationProviderList();\n if (authenticationProviderList == null || authenticationProviderList.size() <= 0) {\n throw new RuntimeException(\"缺少认证组件\");\n }\n for (AuthenticationProvider authenticationProvider : authenticationProviderList) {\n auth.authenticationProvider(authenticationProvider);\n }\n auth\n // 设置认证事件发布组件\n // .authenticationEventPublisher(null)\n // 是否擦除认证凭证\n .eraseCredentials(true)\n // 设置获取用户认证信息和授权信息组件\n .userDetailsService(getUserDetailsService())\n // 设置密码编码码器\n .passwordEncoder(getPasswordEncoder());\n }\n\n /**\n * 使用自定义的 UserDetailsService\n */\n @Override\n protected UserDetailsService userDetailsService() {\n return getUserDetailsService();\n }\n\n /**\n * 全局请求忽略规则配置(比如说静态文件,比如说注册页面)
\n * 全局HttpFirewall配置
\n * 是否debug配置
\n * 全局SecurityFilterChain配置
\n * privilegeEvaluator、expressionHandler、securityInterceptor、
\n */\n @Override\n public void configure(WebSecurity web) {\n SecurityConfig securityConfig = getSecurityConfig();\n // 设置调试\n if (securityConfig.getEnableDebug() != null) {\n web.debug(securityConfig.getEnableDebug());\n }\n // 配置忽略的路径\n if (securityConfig.getIgnoreUrls() == null) {\n securityConfig.setIgnoreUrls(new ArrayList<>());\n }\n // 加入 /403.html\n if (StringUtils.isNotBlank(securityConfig.getForbiddenForwardPage())\n && !securityConfig.getIgnoreUrls().contains(securityConfig.getForbiddenForwardPage())) {\n securityConfig.getIgnoreUrls().add(securityConfig.getForbiddenForwardPage());\n }\n // 加入 /login.html\n if (StringUtils.isNotBlank(securityConfig.getLogin().getLoginPage())\n && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogin().getLoginPage())) {\n securityConfig.getIgnoreUrls().add(securityConfig.getLogin().getLoginPage());\n }\n // 加入 login-failure-redirect-page\n if (StringUtils.isNotBlank(securityConfig.getLogin().getLoginFailureRedirectPage())\n && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogin().getLoginFailureRedirectPage())) {\n securityConfig.getIgnoreUrls().add(securityConfig.getLogin().getLoginFailureRedirectPage());\n }\n // 加入 logout-success-redirect-page\n if (StringUtils.isNotBlank(securityConfig.getLogout().getLogoutSuccessRedirectPage())\n && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogout().getLogoutSuccessRedirectPage())) {\n securityConfig.getIgnoreUrls().add(securityConfig.getLogout().getLogoutSuccessRedirectPage());\n }\n if (securityConfig.getIgnoreUrls().size() > 0) {\n web.ignoring().antMatchers(securityConfig.getIgnoreUrls().toArray(new String[0]));\n // 打印相应的日志\n if (log.isInfoEnabled()) {\n StringBuilder strTmp = new StringBuilder();\n strTmp.append(\"\\r\\n\");\n strTmp.append(\"#=======================================================================================================================#\\r\\n\");\n strTmp.append(\"不需要登录认证的资源:\\r\\n\");\n for (String url : securityConfig.getIgnoreUrls()) {\n strTmp.append(\"\\t\").append(url).append(\"\\r\\n\");\n }\n strTmp.append(\"#=======================================================================================================================#\");\n log.info(strTmp.toString());\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/LoginFailCountRepository.java<|end_filename|>\npackage org.clever.security.repository;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.service.GenerateKeyService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.stereotype.Component;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-20 21:41
\n */\n@Component\n@Slf4j\npublic class LoginFailCountRepository {\n\n @Autowired\n private RedisTemplate redisTemplate;\n @Autowired\n private GenerateKeyService generateKeyService;\n\n public long incrementLoginFailCount(String username) {\n String loginFailCountKey = generateKeyService.getLoginFailCountKey(username);\n Long count = redisTemplate.boundValueOps(loginFailCountKey).increment(1);\n redisTemplate.expire(loginFailCountKey, 30, TimeUnit.MINUTES);\n return count == null ? 0 : count;\n }\n\n public void deleteLoginFailCount(String username) {\n String loginFailCountKey = generateKeyService.getLoginFailCountKey(username);\n redisTemplate.delete(loginFailCountKey);\n }\n\n public long getLoginFailCount(String username) {\n String loginFailCountKey = generateKeyService.getLoginFailCountKey(username);\n Boolean exists = redisTemplate.hasKey(loginFailCountKey);\n if (exists != null && !exists) {\n return 0L;\n }\n Long count = redisTemplate.boundValueOps(loginFailCountKey).increment(0);\n return count == null ? 0 : count;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/TokenConfig.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\nimport java.time.Duration;\n\n/**\n * JWT Token配置\n * 作者: lzw
\n * 创建时间:2019-04-25 19:04
\n */\n@Data\npublic class TokenConfig {\n /**\n * Token Redis前缀\n */\n private String redisNamespace = \"jwt\";\n\n /**\n * Token签名密钥\n */\n private String secretKey = \"clever-security-jwt\";\n\n /**\n * Token有效时间(默认:7天)\n */\n private Duration tokenValidity = Duration.ofDays(7);\n\n /**\n * Token记住我有效时间(默认:15天)\n */\n private Duration tokenValidityForRememberMe = Duration.ofDays(15);\n\n /**\n * 刷新令牌有效时间\n */\n private Duration refreshTokenValidity = Duration.ofDays(30);\n\n /**\n * 设置密钥过期时间 (格式 HH:mm:ss)\n */\n private String hoursInDay = \"03:45:00\";\n\n /**\n * iss(签发者)\n */\n private String issuer = \"clever-security-jwt\";\n\n /**\n * aud(接收方)\n */\n private String audience = \"clever-*\";\n\n /**\n * 使用Cookie读写JWT Token\n */\n private boolean useCookie = false;\n\n /**\n * Head或者Cookie中的JwtToken的key值\n */\n private String jwtTokenKey = \"Authorization\";\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserAccessDeniedHandler.java<|end_filename|>\npackage org.clever.security.handler;\n\nimport lombok.Getter;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.response.AccessDeniedRes;\nimport org.clever.security.utils.HttpRequestUtils;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.access.AccessDeniedException;\nimport org.springframework.security.web.WebAttributes;\nimport org.springframework.security.web.access.AccessDeniedHandler;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n/**\n * 拒绝访问处理器\n * 作者: lzw
\n * 创建时间:2018-03-18 15:09
\n */\n@Component\n@Getter\n@Slf4j\npublic class UserAccessDeniedHandler implements AccessDeniedHandler {\n\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final String defaultRedirectUrl = \"/403.html\";\n\n @Autowired\n private SecurityConfig securityConfig;\n\n @Override\n public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {\n // 不需要跳转\n if (securityConfig.getForbiddenNeedForward() != null && !securityConfig.getForbiddenNeedForward()) {\n sendJsonData(response);\n return;\n }\n // 需要跳转 - 判断请求是否需要跳转\n if (HttpRequestUtils.isJsonResponse(request)) {\n sendJsonData(response);\n return;\n }\n // 需要跳转\n String url = securityConfig.getForbiddenForwardPage();\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);\n response.setStatus(HttpServletResponse.SC_FORBIDDEN);\n RequestDispatcher dispatcher = request.getRequestDispatcher(url);\n dispatcher.forward(request, response);\n }\n\n /**\n * 直接返回Json数据\n */\n private void sendJsonData(HttpServletResponse response) {\n AccessDeniedRes accessDeniedRes = new AccessDeniedRes(\"没有访问权限\");\n HttpResponseUtils.sendJsonBy403(response, accessDeniedRes);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/job/CheckUserLoginLogJob.java<|end_filename|>\npackage org.clever.security.job;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.GlobalJob;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-12 12:49
\n */\n@Component\n@Slf4j\npublic class CheckUserLoginLogJob extends GlobalJob {\n\n @Override\n protected void internalExecute() {\n // TODO 检查登录状态-校正Session状态\n // TODO Token 状态\n }\n\n @Override\n protected void exceptionHandle(Throwable e) {\n\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/SessionRedisSecurityContextRepository.java<|end_filename|>\n//package org.clever.security.repository;\n//\n//import org.springframework.security.web.context.HttpSessionSecurityContextRepository;\n//\n///**\n// * 作者: lzw
\n// * 创建时间:2019-05-16 14:26
\n// */\n//public class SessionRedisSecurityContextRepository extends HttpSessionSecurityContextRepository {\n//\n//}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/ServiceSysServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.client.ServiceSysClient;\nimport org.clever.security.dto.request.ServiceSysAddReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.service.ServiceSysService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n/**\n * 参考 ServiceSysController\n *

\n * 作者: lzw
\n * 创建时间:2018-11-11 19:28
\n */\n@Component\n@Slf4j\npublic class ServiceSysServiceProxy implements ServiceSysClient {\n @Autowired\n private ServiceSysService serviceSysService;\n\n @Override\n public List allSysName() {\n return serviceSysService.selectAll();\n }\n\n @Override\n public ServiceSys registerSys(ServiceSysAddReq serviceSysAddReq) {\n ServiceSys serviceSys = BeanMapper.mapper(serviceSysAddReq, ServiceSys.class);\n return serviceSysService.registerSys(serviceSys);\n }\n\n @Override\n public ServiceSys delServiceSys(String sysName) {\n return serviceSysService.delServiceSys(sysName);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/test/java/org/clever/security/test/CryptoUtilsTest.java<|end_filename|>\npackage org.clever.security.test;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.codec.CryptoUtils;\nimport org.clever.common.utils.codec.EncodeDecodeUtils;\nimport org.junit.Test;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-08 10:25
\n */\n@Slf4j\npublic class CryptoUtilsTest {\n\n @Test\n public void t01() {\n log.info(\"{}\",EncodeDecodeUtils.encodeHex(\"clever-security-server李志伟\".getBytes()));\n\n\n String str = \"李志伟123abc!@#$\";\n byte[] key = EncodeDecodeUtils.decodeHex(\"\");\n byte[] iv = EncodeDecodeUtils.decodeHex(\"f0021ea5a06d5a7bade961afe47e9ad9\");\n\n byte[] data = CryptoUtils.aesEncrypt(str.getBytes(), key, iv);\n\n String str2 = EncodeDecodeUtils.encodeBase64(data);\n log.info(\"加密 {}\", str2);\n log.info(\"解密 {}\", CryptoUtils.aesDecrypt(data, key, iv));\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/filter/UserLoginFilter.java<|end_filename|>\npackage org.clever.security.authentication.filter;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.authentication.CollectLoginToken;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.dto.response.JwtLoginRes;\nimport org.clever.security.dto.response.LoginRes;\nimport org.clever.security.dto.response.UserRes;\nimport org.clever.security.exception.BadCaptchaException;\nimport org.clever.security.exception.BadLoginTypeException;\nimport org.clever.security.handler.UserLoginFailureHandler;\nimport org.clever.security.handler.UserLoginSuccessHandler;\nimport org.clever.security.model.CaptchaInfo;\nimport org.clever.security.repository.CaptchaInfoRepository;\nimport org.clever.security.repository.LoginFailCountRepository;\nimport org.clever.security.repository.RedisJwtRepository;\nimport org.clever.security.token.JwtAccessToken;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.clever.security.utils.AuthenticationUtils;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.AuthenticationServiceException;\nimport org.springframework.security.authentication.AuthenticationTrustResolver;\nimport org.springframework.security.authentication.AuthenticationTrustResolverImpl;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;\nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher;\nimport org.springframework.stereotype.Component;\n\nimport javax.annotation.PostConstruct;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.List;\n\n/**\n * 收集用户登录信息\n * 作者: lzw
\n * 创建时间:2018-03-15 12:48
\n */\n@Component\n@Slf4j\npublic class UserLoginFilter extends AbstractAuthenticationProcessingFilter {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserLoginSuccessHandler userLoginSuccessHandler;\n @Autowired\n private UserLoginFailureHandler userLoginFailureHandler;\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n @Autowired\n private CaptchaInfoRepository captchaInfoRepository;\n @Autowired\n private LoginFailCountRepository loginFailCountRepository;\n @Autowired\n private List collectLoginTokenList;\n private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();\n private boolean postOnly = true;\n /**\n * 登录是否需要验证码\n */\n private Boolean needCaptcha = true;\n /**\n * 登录失败多少次才需要验证码(小于等于0,总是需要验证码)\n */\n private Integer needCaptchaByLoginFailCount = 3;\n\n public UserLoginFilter(SecurityConfig securityConfig) {\n super(new AntPathRequestMatcher(securityConfig.getLogin().getLoginUrl()));\n }\n\n @Autowired\n @Override\n public void setAuthenticationManager(AuthenticationManager authenticationManager) {\n super.setAuthenticationManager(authenticationManager);\n }\n\n @PostConstruct\n public void init() {\n log.info(\"### UserLoginFilter 初始化配置\");\n this.setBeanName(this.toString());\n // 初始化配置\n LoginConfig login = securityConfig.getLogin();\n if (login != null) {\n if (login.getPostOnly() != null) {\n postOnly = login.getPostOnly();\n }\n if (login.getNeedCaptcha() != null) {\n needCaptcha = login.getNeedCaptcha();\n }\n if (login.getNeedCaptchaByLoginFailCount() != null) {\n needCaptchaByLoginFailCount = login.getNeedCaptchaByLoginFailCount();\n }\n }\n if (collectLoginTokenList == null || this.collectLoginTokenList.size() <= 0) {\n throw new RuntimeException(\"未注入收集用户登录信息组件\");\n }\n this.setAuthenticationSuccessHandler(userLoginSuccessHandler);\n this.setAuthenticationFailureHandler(userLoginFailureHandler);\n }\n\n /**\n * 收集认证信息\n */\n @Override\n public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {\n if (postOnly && !request.getMethod().equalsIgnoreCase(\"POST\")) {\n throw new AuthenticationServiceException(\"Authentication method not supported: \" + request.getMethod());\n }\n // 需要防止用户重复登录\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (authentication != null && authentication.isAuthenticated() && !authenticationTrustResolver.isRememberMe(authentication)) {\n // 已经登录成功了\n UserRes userRes = AuthenticationUtils.getUserRes(authentication);\n Object resData;\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // JWT\n JwtAccessToken jwtAccessToken = redisJwtRepository.getJwtToken(request);\n resData = new JwtLoginRes(true, \"您已经登录成功了无须多次登录\", userRes, jwtAccessToken.getToken(), jwtAccessToken.getRefreshToken());\n } else {\n // Session\n resData = new LoginRes(true, \"您已经登录成功了无须多次登录\", userRes);\n }\n HttpResponseUtils.sendJsonBy200(response, resData);\n log.info(\"### 当前用户已登录 [{}]\", authentication.toString());\n return null;\n }\n // 获取用户登录信息\n boolean isSubmitBody = securityConfig.getLogin().getJsonDataSubmit();\n BaseLoginToken loginToken = null;\n for (CollectLoginToken collectLoginToken : collectLoginTokenList) {\n if (collectLoginToken.supports(request, isSubmitBody)) {\n loginToken = collectLoginToken.attemptAuthentication(request, isSubmitBody);\n break;\n }\n }\n if (loginToken == null) {\n throw new BadLoginTypeException(\"不支持的登录请求\");\n }\n // 设置用户 \"details\" 属性(设置请求IP和SessionID) -- 需要提前创建Session\n if (LoginModel.session.equals(securityConfig.getLoginModel())) {\n request.getSession();\n }\n loginToken.setDetails(authenticationDetailsSource.buildDetails(request));\n log.info(\"### 用户登录开始,构建LoginToken [{}]\", loginToken.toString());\n request.setAttribute(Constant.Login_Username_Request_Key, loginToken.getName());\n // 读取验证码 - 验证\n if (needCaptcha) {\n long loginFailCount = 0;\n CaptchaInfo captchaInfo;\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // JWT\n loginFailCount = loginFailCountRepository.getLoginFailCount(loginToken.getName());\n if (loginFailCount >= needCaptchaByLoginFailCount) {\n captchaInfo = captchaInfoRepository.getCaptchaInfo(loginToken.getCaptcha(), loginToken.getCaptchaDigest());\n verifyCaptchaInfo(captchaInfo, loginToken.getCaptcha());\n captchaInfoRepository.deleteCaptchaInfo(loginToken.getCaptcha(), loginToken.getCaptchaDigest());\n }\n } else {\n // Session\n Object loginFailCountStr = request.getSession().getAttribute(Constant.Login_Fail_Count_Session_Key);\n if (loginFailCountStr != null) {\n loginFailCount = NumberUtils.toInt(loginFailCountStr.toString(), 0);\n }\n if (loginFailCount >= needCaptchaByLoginFailCount) {\n captchaInfo = (CaptchaInfo) request.getSession().getAttribute(Constant.Login_Captcha_Session_Key);\n verifyCaptchaInfo(captchaInfo, loginToken.getCaptcha());\n request.getSession().removeAttribute(Constant.Login_Captcha_Session_Key);\n }\n }\n log.info(\"### 验证码校验通过\");\n }\n // 验证登录\n return this.getAuthenticationManager().authenticate(loginToken);\n }\n\n /**\n * 校验验证码\n */\n private void verifyCaptchaInfo(CaptchaInfo captchaInfo, String captcha) {\n if (captchaInfo == null) {\n throw new BadCaptchaException(\"验证码不存在\");\n }\n if (captchaInfo.getEffectiveTime() > 0 && System.currentTimeMillis() - captchaInfo.getCreateTime() >= captchaInfo.getEffectiveTime()) {\n throw new BadCaptchaException(\"验证码已过期\");\n }\n if (!captchaInfo.getCode().equalsIgnoreCase(captcha)) {\n throw new BadCaptchaException(\"验证码不匹配\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLogoutSuccessHandler.java<|end_filename|>\npackage org.clever.security.handler;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.LogoutConfig;\nimport org.clever.security.dto.response.LogoutRes;\nimport org.clever.security.dto.response.UserRes;\nimport org.clever.security.utils.AuthenticationUtils;\nimport org.clever.security.utils.HttpRequestUtils;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.web.DefaultRedirectStrategy;\nimport org.springframework.security.web.RedirectStrategy;\nimport org.springframework.security.web.authentication.logout.LogoutSuccessHandler;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-21 10:21
\n */\n@Component\n@Slf4j\npublic class UserLogoutSuccessHandler implements LogoutSuccessHandler {\n\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final String defaultRedirectUrl = \"/index.html\";\n @Autowired\n private SecurityConfig securityConfig;\n private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();\n\n @Override\n public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {\n if (authentication == null) {\n log.info(\"### 登出无效(还未登录)\");\n } else {\n log.info(\"### 用户登出成功 [username={}]\", authentication.getPrincipal().toString());\n }\n LogoutConfig logout = securityConfig.getLogout();\n if (logout.getLogoutSuccessNeedRedirect() != null && logout.getLogoutSuccessNeedRedirect()) {\n sendRedirect(request, response, logout.getLogoutSuccessRedirectPage());\n return;\n }\n // 判断是否需要跳转到页面\n if (HttpRequestUtils.isJsonResponse(request)) {\n sendJsonData(response, authentication);\n return;\n }\n sendRedirect(request, response, logout.getLogoutSuccessRedirectPage());\n }\n\n /**\n * 页面跳转 (重定向)\n */\n private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {\n if (StringUtils.isBlank(url)) {\n url = defaultRedirectUrl;\n }\n log.info(\"### 登出成功跳转Url(重定向) -> {}\", url);\n if (!response.isCommitted()) {\n redirectStrategy.sendRedirect(request, response, url);\n }\n }\n\n /**\n * 直接返回Json数据\n */\n private void sendJsonData(HttpServletResponse response, Authentication authentication) {\n UserRes userRes = AuthenticationUtils.getUserRes(authentication);\n LogoutRes logoutRes = new LogoutRes(true, \"登出成功\", userRes);\n HttpResponseUtils.sendJsonBy200(response, logoutRes);\n log.info(\"### 登出成功不需要跳转 -> [{}]\", logoutRes);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/WebPermissionModelGetReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 19:03
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class WebPermissionModelGetReq extends BaseRequest {\n\n @NotBlank\n @Length(max = 127)\n @ApiModelProperty(\"系统名称\")\n private String sysName;\n\n @NotBlank\n @Length(max = 255)\n @ApiModelProperty(\"Controller Class\")\n private String targetClass;\n\n @NotBlank\n @Length(max = 255)\n @ApiModelProperty(\"Controller Method\")\n private String targetMethod;\n\n @NotNull\n @Length(max = 255)\n @ApiModelProperty(\"Controller Method Params\")\n private String targetMethodParams;\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/ServiceSysClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.ServiceSysAddReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-23 10:23
\n */\n@FeignClient(\n contextId = \"org.clever.security.client.ServiceSysClient\",\n name = \"clever-security-server\",\n path = \"/api\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface ServiceSysClient {\n\n /**\n * 查询所有系统信息\n */\n @GetMapping(\"/service_sys\")\n List allSysName();\n\n /**\n * 注册系统\n */\n @PostMapping(\"/service_sys\")\n ServiceSys registerSys(@RequestBody ServiceSysAddReq serviceSysAddReq);\n\n /**\n * 删除系统\n */\n @DeleteMapping(\"/service_sys/{sysName}\")\n ServiceSys delServiceSys(@PathVariable(\"sysName\") String sysName);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/UserMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.dto.request.UserQueryPageReq;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.Role;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.entity.User;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:08
\n */\n@Repository\n@Mapper\npublic interface UserMapper extends BaseMapper {\n\n User getByUnique(@Param(\"unique\") String unique);\n\n User getByUsername(@Param(\"username\") String username);\n\n User getByTelephone(@Param(\"telephone\") String telephone);\n\n List findByUsername(@Param(\"username\") String username, @Param(\"sysName\") String sysName);\n\n int existsUserBySysName(@Param(\"username\") String username, @Param(\"sysName\") String sysName);\n\n List findByPage(@Param(\"query\") UserQueryPageReq query, IPage page);\n\n List findSysNameByUsername(@Param(\"username\") String username);\n\n List findSysByUsername(@Param(\"username\") String username);\n\n int addUserSys(@Param(\"username\") String username, @Param(\"sysName\") String sysName);\n\n int delUserSys(@Param(\"username\") String username, @Param(\"sysName\") String sysName);\n\n int existsByUserName(@Param(\"username\") String username);\n\n int existsByTelephone(@Param(\"telephone\") String telephone);\n\n int existsByEmail(@Param(\"email\") String email);\n\n int addRole(@Param(\"username\") String username, @Param(\"roleName\") String roleName);\n\n int delRole(@Param(\"username\") String username, @Param(\"roleName\") String roleName);\n\n List findRoleByUsername(@Param(\"username\") String username);\n\n int existsUserRole(@Param(\"username\") String username, @Param(\"roleName\") String roleName);\n\n int delUserRole(@Param(\"username\") String username);\n\n int delAllUserSys(@Param(\"username\") String username);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/config/BeanConfiguration.java<|end_filename|>\npackage org.clever.security.config;\n\nimport com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;\nimport com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;\nimport com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.server.config.CustomPaginationInterceptor;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\n\nimport java.security.SecureRandom;\n\n/**\n * 作者: lzw
\n * 创建时间:2017-12-04 10:37
\n */\n@Configuration\n@Slf4j\npublic class BeanConfiguration {\n\n /**\n * 密码处理\n */\n @Bean\n protected BCryptPasswordEncoder bCryptPasswordEncoder() {\n return new BCryptPasswordEncoder(10, new SecureRandom());\n }\n\n// /**\n// * 使用 GenericJackson2JsonRedisSerializer 替换默认序列化\n// */\n// @Bean(\"redisTemplate\")\n// public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {\n// // 自定义 ObjectMapper\n// ObjectMapper objectMapper = new ObjectMapper();\n// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);\n// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);\n//// objectMapper.setDateFormat();\n//// objectMapper.setDefaultMergeable()\n//// objectMapper.setDefaultPropertyInclusion()\n//// objectMapper.setDefaultSetterInfo()\n//// objectMapper.setDefaultVisibility()\n// // 查看Spring的实现 SecurityJackson2Modules\n// List modules = SecurityJackson2Modules.getModules(getClass().getClassLoader());\n// objectMapper.findAndRegisterModules();\n// objectMapper.registerModules(modules);\n// objectMapper.registerModule(new CleverSecurityJackson2Module());\n// // 创建 RedisTemplate\n// RedisTemplate template = new RedisTemplate<>();\n// template.setConnectionFactory(redisConnectionFactory);\n// // 设置value的序列化规则和 key的序列化规则\n// template.setKeySerializer(new StringRedisSerializer());\n// template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));\n// template.afterPropertiesSet();\n// return template;\n// }\n\n /**\n * 分页插件\n */\n @SuppressWarnings(\"UnnecessaryLocalVariable\")\n @Bean\n public CustomPaginationInterceptor paginationInterceptor() {\n CustomPaginationInterceptor paginationInterceptor = new CustomPaginationInterceptor();\n// paginationInterceptor.setSqlParser()\n// paginationInterceptor.setDialectClazz()\n// paginationInterceptor.setOverflow()\n// paginationInterceptor.setProperties();\n return paginationInterceptor;\n }\n\n /**\n * 乐观锁插件
\n * 取出记录时,获取当前version
\n * 更新时,带上这个version
\n * 执行更新时, set version = yourVersion+1 where version = yourVersion
\n * 如果version不对,就更新失败
\n */\n @Bean\n public OptimisticLockerInterceptor optimisticLockerInterceptor() {\n return new OptimisticLockerInterceptor();\n }\n\n// /**\n// * 逻辑删除
\n// */\n// @Bean\n// public ISqlInjector sqlInjector() {\n// return new LogicSqlInjector();\n// }\n\n /**\n * SQL执行效率插件\n */\n @SuppressWarnings(\"UnnecessaryLocalVariable\")\n @Bean\n @Profile({\"dev\", \"test\"})\n public PerformanceInterceptor performanceInterceptor() {\n PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();\n// performanceInterceptor.setFormat(true);\n// performanceInterceptor.setMaxTime();\n// performanceInterceptor.setWriteInLog();\n return performanceInterceptor;\n }\n\n /**\n * 执行分析插件
\n * SQL 执行分析拦截器【 目前只支持 MYSQL-5.6.3 以上版本 】\n * 作用是分析 处理 DELETE UPDATE 语句\n * 防止小白或者恶意 delete update 全表操作!\n */\n @SuppressWarnings(\"UnnecessaryLocalVariable\")\n @Bean\n @Profile({\"dev\", \"test\"})\n public SqlExplainInterceptor sqlExplainInterceptor() {\n SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();\n// sqlExplainInterceptor.stopProceed\n return sqlExplainInterceptor;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/RememberMeTokenServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.client.RememberMeTokenClient;\nimport org.clever.security.dto.request.RememberMeTokenAddReq;\nimport org.clever.security.dto.request.RememberMeTokenUpdateReq;\nimport org.clever.security.entity.RememberMeToken;\nimport org.clever.security.service.RememberMeTokenService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * 参考 RememberMeTokenController\n *

\n * 作者: lzw
\n * 创建时间:2018-11-11 19:21
\n */\n@Component\n@Slf4j\npublic class RememberMeTokenServiceProxy implements RememberMeTokenClient {\n\n @Autowired\n private RememberMeTokenService rememberMeTokenService;\n\n @Override\n public RememberMeToken addRememberMeToken(RememberMeTokenAddReq req) {\n RememberMeToken rememberMeToken = BeanMapper.mapper(req, RememberMeToken.class);\n return rememberMeTokenService.addRememberMeToken(rememberMeToken);\n }\n\n @Override\n public RememberMeToken getRememberMeToken(String series) {\n return rememberMeTokenService.getRememberMeToken(series);\n }\n\n @Override\n public Map delRememberMeToken(String username) {\n Map map = new HashMap<>();\n Integer delCount = rememberMeTokenService.delRememberMeToken(username);\n map.put(\"delCount\", delCount);\n return map;\n }\n\n @Override\n public RememberMeToken updateRememberMeToken(String series, RememberMeTokenUpdateReq req) {\n return rememberMeTokenService.updateRememberMeToken(series, req.getToken(), req.getLastUsed());\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/DefaultPreAuthenticationChecks.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.client.UserClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.exception.CanNotLoginSysException;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.AccountExpiredException;\nimport org.springframework.security.authentication.DisabledException;\nimport org.springframework.security.authentication.LockedException;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsChecker;\nimport org.springframework.stereotype.Component;\n\n/**\n * 验证帐号信息之前的校验\n *

\n * 作者: lzw
\n * 创建时间:2018-09-19 16:32
\n */\n@Component(\"DefaultPreAuthenticationChecks\")\n@Slf4j\npublic class DefaultPreAuthenticationChecks implements UserDetailsChecker {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserClient userClient;\n\n @Override\n public void check(UserDetails user) {\n if (!user.isAccountNonLocked()) {\n log.info(\"帐号已锁定 [username={}]\", user.getUsername());\n throw new LockedException(\"帐号已锁定\");\n }\n if (!user.isEnabled()) {\n log.info(\"帐号已禁用 [username={}]\", user.getUsername());\n throw new DisabledException(\"帐号已禁用\");\n }\n if (!user.isAccountNonExpired()) {\n log.info(\"帐号已过期 [username={}]\", user.getUsername());\n throw new AccountExpiredException(\"帐号已过期\");\n }\n // 校验用户是否有权登录当前系统\n Boolean canLogin = userClient.canLogin(user.getUsername(), securityConfig.getSysName());\n if (!canLogin) {\n throw new CanNotLoginSysException(\"您无权登录当前系统,请联系管理员授权\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/SecurityContextTokenMixin.java<|end_filename|>\npackage org.clever.security.jackson2;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.token.login.BaseLoginToken;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-22 21:14
\n */\n//@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY)\n@JsonAutoDetect\n@JsonIgnoreProperties(ignoreUnknown = true)\nclass SecurityContextTokenMixin {\n\n @JsonCreator\n public SecurityContextTokenMixin(@JsonProperty(\"credentials\") BaseLoginToken loginToken, @JsonProperty(\"principal\") LoginUserDetails userDetails) {\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/LogoutConfig.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\n/**\n * 用户登出配置\n * 作者: lzw
\n * 创建时间:2019-04-25 19:02
\n */\n@Data\npublic class LogoutConfig {\n\n /**\n * 登出请求URL\n */\n private String logoutUrl = \"/logout\";\n\n /**\n * 登出成功 - 是否需要跳转\n */\n private Boolean logoutSuccessNeedRedirect = false;\n\n /**\n * 登出成功默认跳转的页面\n */\n private String logoutSuccessRedirectPage = \"/index.html\";\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/CanNotLoginSysException.java<|end_filename|>\npackage org.clever.security.exception;\n\nimport org.springframework.security.core.AuthenticationException;\n\n/**\n * 无权登录系统\n *

\n * 作者: lzw
\n * 创建时间:2018-10-01 22:01
\n */\npublic class CanNotLoginSysException extends AuthenticationException {\n\n public CanNotLoginSysException(String msg) {\n super(msg);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/UserController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.security.dto.request.UserAuthenticationReq;\nimport org.clever.security.dto.response.UserAuthenticationRes;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.User;\nimport org.clever.security.service.UserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:21
\n */\n@Api(\"用户信息\")\n@RestController\n@RequestMapping(\"/api\")\npublic class UserController extends BaseController {\n\n @Autowired\n private UserService userService;\n\n @ApiOperation(\"获取用户(登录名、手机、邮箱)\")\n @GetMapping(\"/user/{unique}\")\n public User getUser(@PathVariable(\"unique\") String unique) {\n return userService.getUser(unique);\n }\n\n @ApiOperation(\"获取某个用户在某个系统下的所有权限\")\n @GetMapping(\"/user/{username}/{sysName}/permission\")\n public List findAllPermission(@PathVariable(\"username\") String username, @PathVariable(\"sysName\") String sysName) {\n return userService.findAllPermission(username, sysName);\n }\n\n @ApiOperation(\"用户是否有权登录某个系统\")\n @GetMapping(\"/user/{username}/{sysName}\")\n public Boolean canLogin(@PathVariable(\"username\") String username, @PathVariable(\"sysName\") String sysName) {\n return userService.canLogin(username, sysName);\n }\n\n @ApiOperation(\"用户登录认证\")\n @PostMapping(\"/user/authentication\")\n public UserAuthenticationRes authentication(@RequestBody @Validated UserAuthenticationReq req) {\n return userService.authenticationAndRes(req);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/ApplicationSecurityBean.java<|end_filename|>\npackage org.clever.security.config;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo;\nimport com.fasterxml.jackson.annotation.PropertyAccessor;\nimport com.fasterxml.jackson.databind.Module;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.authentication.CollectLoginToken;\nimport org.clever.security.authorization.RequestAccessDecisionVoter;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.config.model.RememberMeConfig;\nimport org.clever.security.jackson2.CleverSecurityJackson2Module;\nimport org.clever.security.rememberme.RememberMeRepository;\nimport org.clever.security.rememberme.RememberMeServices;\nimport org.clever.security.rememberme.RememberMeUserDetailsChecker;\nimport org.clever.security.service.GlobalUserDetailsService;\nimport org.clever.security.strategy.SessionExpiredStrategy;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.data.redis.connection.RedisConnectionFactory;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;\nimport org.springframework.data.redis.serializer.RedisSerializer;\nimport org.springframework.data.redis.serializer.StringRedisSerializer;\nimport org.springframework.security.access.AccessDecisionManager;\nimport org.springframework.security.access.AccessDecisionVoter;\nimport org.springframework.security.access.vote.AffirmativeBased;\nimport org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.core.session.SessionRegistry;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.jackson2.SecurityJackson2Modules;\nimport org.springframework.security.web.authentication.NullRememberMeServices;\nimport org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;\nimport org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;\nimport org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;\nimport org.springframework.security.web.session.HttpSessionEventPublisher;\nimport org.springframework.security.web.session.SessionInformationExpiredStrategy;\nimport org.springframework.session.data.redis.RedisOperationsSessionRepository;\nimport org.springframework.session.security.SpringSessionBackedSessionRegistry;\n\nimport java.security.SecureRandom;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:49
\n */\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true)\n@Configuration\n@Slf4j\npublic class ApplicationSecurityBean {\n\n @Autowired\n private SecurityConfig securityConfig;\n\n /**\n * 密码处理\n */\n @ConditionalOnMissingBean(BCryptPasswordEncoder.class)\n @Bean\n protected BCryptPasswordEncoder bCryptPasswordEncoder() {\n return new BCryptPasswordEncoder(10, new SecureRandom());\n }\n\n /**\n * 使用 GenericJackson2JsonRedisSerializer 替换默认序列化\n */\n // @ConditionalOnMissingBean(RedisTemplate.class)\n @Bean(\"redisTemplate\")\n public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {\n // 自定义 ObjectMapper\n ObjectMapper objectMapper = newObjectMapper();\n // 创建 RedisTemplate\n RedisTemplate template = new RedisTemplate<>();\n template.setConnectionFactory(redisConnectionFactory);\n // 设置value的序列化规则和 key的序列化规则\n template.setKeySerializer(new StringRedisSerializer());\n template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));\n template.afterPropertiesSet();\n return template;\n }\n\n /**\n * 授权校验
\n *

\n     * {@code\n     *   AffirmativeBased (有一个允许访问就有权访问)\n     *     1. 只要有AccessDecisionVoter的投票为ACCESS_GRANTED则同意用户进行访问\n     *     2. 如果全部弃权也表示通过\n     *     3. 如果没有一个人投赞成票,但是有人投反对票,则将抛出AccessDeniedException\n     *   ConsensusBased (大多数允许访问才有权访问)\n     *     1. 如果赞成票多于反对票则表示通过\n     *     2. 反过来,如果反对票多于赞成票则将抛出AccessDeniedException\n     *     3. 如果赞成票与反对票相同且不等于0,并且属性allowIfEqualGrantedDeniedDecisions的值为true,则表示通过,否则将抛出异常AccessDeniedException。参数allowIfEqualGrantedDeniedDecisions的值默认为true\n     *     4. 如果所有的AccessDecisionVoter都弃权了,则将视参数allowIfAllAbstainDecisions的值而定,如果该值为true则表示通过,否则将抛出异常AccessDeniedException。参数allowIfAllAbstainDecisions的值默认为false\n     *   UnanimousBased\n     *     逻辑与另外两种实现有点不一样,\n     *     另外两种会一次性把受保护对象的配置属性全部传递给AccessDecisionVoter进行投票,\n     *     而UnanimousBased会一次只传递一个ConfigAttribute给AccessDecisionVoter进行投票。\n     *     这也就意味着如果我们的AccessDecisionVoter的逻辑是只要传递进来的ConfigAttribute中有一个能够匹配则投赞成票,\n     *     但是放到UnanimousBased中其投票结果就不一定是赞成了\n     *     1. 如果受保护对象配置的某一个ConfigAttribute被任意的AccessDecisionVoter反对了,则将抛出AccessDeniedException\n     *     2. 如果没有反对票,但是有赞成票,则表示通过\n     *     3. 如果全部弃权了,则将视参数allowIfAllAbstainDecisions的值而定,true则通过,false则抛出AccessDeniedException\n     * }\n     * 
\n */\n @Bean\n protected AccessDecisionManager accessDecisionManager(@Autowired RequestAccessDecisionVoter requestAccessDecisionVoter) {\n // WebExpressionVoter RoleVoter AuthenticatedVoter\n List> decisionVoters = Collections.singletonList(requestAccessDecisionVoter);\n // AffirmativeBased accessDecisionManager = new AffirmativeBased(decisionVoters);\n // accessDecisionManager.\n // TODO 支持注解权限校验\n return new AffirmativeBased(decisionVoters);\n }\n\n /**\n * 登录并发处理(使用session登录时才需要)\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean\n protected SessionAuthenticationStrategy sessionAuthenticationStrategy(@Autowired SessionRegistry sessionRegistry) {\n LoginConfig login = securityConfig.getLogin();\n if (login.getConcurrentLoginCount() == null) {\n return new NullAuthenticatedSessionStrategy();\n }\n int concurrentLoginCount = login.getConcurrentLoginCount() <= 0 ? -1 : login.getConcurrentLoginCount();\n boolean notAllowAfterLogin = false;\n if (login.getNotAllowAfterLogin() != null) {\n notAllowAfterLogin = login.getNotAllowAfterLogin();\n }\n ConcurrentSessionControlAuthenticationStrategy sessionAuthenticationStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);\n sessionAuthenticationStrategy.setMaximumSessions(concurrentLoginCount);\n sessionAuthenticationStrategy.setExceptionIfMaximumExceeded(notAllowAfterLogin);\n // sessionAuthenticationStrategy.setMessageSource();\n return sessionAuthenticationStrategy;\n }\n\n /**\n * Session过期处理(使用session登录时才需要)\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean\n protected SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {\n SessionExpiredStrategy sessionExpiredStrategy = new SessionExpiredStrategy();\n sessionExpiredStrategy.setNeedRedirect(StringUtils.isNotBlank(securityConfig.getSessionExpiredRedirectUrl()));\n sessionExpiredStrategy.setDestinationUrl(securityConfig.getSessionExpiredRedirectUrl());\n return sessionExpiredStrategy;\n }\n\n /**\n * 实现的记住我的功能,不使用SpringSession提供的SpringSessionRememberMeServices(使用session登录时才需要)\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean\n protected org.springframework.security.web.authentication.RememberMeServices rememberMeServices(\n @Autowired RememberMeUserDetailsChecker rememberMeUserDetailsChecker,\n @Autowired GlobalUserDetailsService userDetailsService,\n @Autowired RememberMeRepository rememberMeRepository) {\n RememberMeConfig rememberMe = securityConfig.getRememberMe();\n if (rememberMe == null || rememberMe.getEnable() == null || !rememberMe.getEnable()) {\n return new NullRememberMeServices();\n }\n RememberMeServices rememberMeServices = new RememberMeServices(\n RememberMeServices.REMEMBER_ME_KEY,\n userDetailsService,\n rememberMeRepository,\n rememberMeUserDetailsChecker);\n rememberMeServices.setAlwaysRemember(rememberMe.getAlwaysRemember());\n rememberMeServices.setParameter(CollectLoginToken.REMEMBER_ME_PARAM);\n rememberMeServices.setTokenValiditySeconds((int) rememberMe.getValidity().getSeconds());\n rememberMeServices.setCookieName(RememberMeServices.REMEMBER_ME_COOKIE_NAME);\n// rememberMeServices.setTokenLength();\n// rememberMeServices.setSeriesLength();\n// rememberMeServices.setUserDetailsChecker();\n// rememberMeServices.setUseSecureCookie();\n// rememberMeServices.setCookieDomain();\n return rememberMeServices;\n }\n\n /**\n * 替换Spring Session Redis默认的序列化方式 JdkSerializationRedisSerializer
\n *\n * @see org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration#setDefaultRedisSerializer\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean(\"springSessionDefaultRedisSerializer\")\n protected RedisSerializer springSessionDefaultRedisSerializer() {\n //解决查询缓存转换异常的问题\n ObjectMapper objectMapper = newObjectMapper();\n return new GenericJackson2JsonRedisSerializer(objectMapper);\n }\n\n /**\n * 监听 HttpSession 事件\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean\n public HttpSessionEventPublisher httpSessionEventPublisher() {\n return new HttpSessionEventPublisher();\n }\n\n /**\n * 集成Spring Session所需的Bean\n */\n @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n @Bean\n protected SpringSessionBackedSessionRegistry sessionRegistry(@Autowired RedisOperationsSessionRepository sessionRepository) {\n return new SpringSessionBackedSessionRegistry<>(sessionRepository);\n }\n\n private ObjectMapper newObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);\n objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);\n// objectMapper.setDateFormat();\n// objectMapper.setDefaultMergeable()\n// objectMapper.setDefaultPropertyInclusion()\n// objectMapper.setDefaultSetterInfo()\n// objectMapper.setDefaultVisibility()\n // 查看Spring的实现 SecurityJackson2Modules\n List modules = SecurityJackson2Modules.getModules(getClass().getClassLoader());\n objectMapper.findAndRegisterModules();\n objectMapper.registerModules(modules);\n objectMapper.registerModule(new CleverSecurityJackson2Module());\n return objectMapper;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/CaptchaController.java<|end_filename|>\npackage org.clever.security.embed.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.codec.DigestUtils;\nimport org.clever.common.utils.codec.EncodeDecodeUtils;\nimport org.clever.common.utils.imgvalidate.ImageValidateCageUtils;\nimport org.clever.common.utils.imgvalidate.ValidateCodeSourceUtils;\nimport org.clever.common.utils.reflection.ReflectionsUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.model.CaptchaInfo;\nimport org.clever.security.repository.CaptchaInfoRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-19 21:21
\n */\n@Api(\"验证码\")\n@RestController\n@Slf4j\npublic class CaptchaController {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private CaptchaInfoRepository captchaInfoRepository;\n\n @ApiOperation(\"获取登录验证码(请求头包含文件SHA1签名)\")\n @GetMapping(\"/login/captcha.png\")\n public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {\n String code = ValidateCodeSourceUtils.getRandString(4);\n byte[] image = ImageValidateCageUtils.createImage(code);\n // 3分钟有效\n Long captchaEffectiveTime = 180000L;\n String imageDigestHeader = \"ImageDigest\";\n if (securityConfig.getLogin() != null && securityConfig.getLogin().getCaptchaEffectiveTime() != null) {\n captchaEffectiveTime = securityConfig.getLogin().getCaptchaEffectiveTime().toMillis();\n }\n CaptchaInfo captchaInfo;\n setContentTypeNoCharset(response, \"image/png\");\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // JWT Token\n String imageDigest = EncodeDecodeUtils.encodeHex(DigestUtils.sha1(image));\n captchaInfo = new CaptchaInfo(code, captchaEffectiveTime, imageDigest);\n // 验证码放在Redis\n captchaInfoRepository.saveCaptchaInfo(captchaInfo);\n // 写入图片数据\n response.setHeader(imageDigestHeader, imageDigest);\n log.info(\"### 获取验证码[{}]\", captchaInfo);\n } else {\n // Session\n captchaInfo = new CaptchaInfo(code, captchaEffectiveTime);\n request.getSession().setAttribute(Constant.Login_Captcha_Session_Key, captchaInfo);\n log.info(\"### 客户端[SessionID={}] 获取验证码[{}]\", request.getSession().getId(), captchaInfo);\n }\n response.getOutputStream().write(image);\n }\n\n @SuppressWarnings(\"SameParameterValue\")\n private static void setContentTypeNoCharset(HttpServletResponse response, String contentType) {\n boolean flag = false;\n Object object = response;\n while (true) {\n try {\n object = ReflectionsUtils.getFieldValue(object, \"response\");\n } catch (Throwable e) {\n break;\n }\n if (object instanceof org.apache.catalina.connector.Response) {\n break;\n }\n }\n if (object instanceof org.apache.catalina.connector.Response) {\n org.apache.catalina.connector.Response connectorResponse = (org.apache.catalina.connector.Response) object;\n object = ReflectionsUtils.getFieldValue(connectorResponse, \"coyoteResponse\");\n if (object instanceof org.apache.coyote.Response) {\n org.apache.coyote.Response coyoteResponse = (org.apache.coyote.Response) object;\n coyoteResponse.setContentTypeNoCharset(contentType);\n ReflectionsUtils.setFieldValue(coyoteResponse, \"charset\", null);\n flag = true;\n }\n }\n if (!flag) {\n response.setContentType(contentType);\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionUpdateReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\nimport org.hibernate.validator.constraints.Range;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 19:05
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class PermissionUpdateReq extends BaseRequest {\n\n @ApiModelProperty(\"权限标题\")\n @Length(max = 255)\n private String title;\n\n @ApiModelProperty(\"唯一权限标识字符串\")\n @Length(min = 6, max = 255)\n private String permissionStr;\n\n @ApiModelProperty(\"权限类型,1:web资源权限, 2:菜单权限,3:ui权限,4:自定义\")\n @Range(min = 1, max = 4)\n private Integer resourcesType;\n\n @ApiModelProperty(\"权限说明\")\n @Length(max = 127)\n private String description;\n\n @ApiModelProperty(\"需要授权才允许访问(1:需要;2:不需要)\")\n @Range(min = 1, max = 2)\n private Integer needAuthorization;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserBindRoleReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\n\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Size;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 21:53
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserBindRoleReq extends BaseRequest {\n\n @ApiModelProperty(\"用户名集合\")\n @Size(min = 1, max = 100)\n @NotNull\n private List usernameList;\n\n @ApiModelProperty(\"角色集合\")\n @NotNull\n private List roleNameList;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/ServiceSysMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.entity.ServiceSys;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-22 15:23
\n */\n@Repository\n@Mapper\npublic interface ServiceSysMapper extends BaseMapper {\n\n int existsSysName(@Param(\"sysName\") String sysName);\n\n int existsRedisNameSpace(@Param(\"redisNameSpace\") String redisNameSpace);\n\n ServiceSys getByUnique(@Param(\"sysName\") String sysName, @Param(\"redisNameSpace\") String redisNameSpace);\n\n ServiceSys getBySysName(@Param(\"sysName\") String sysName);\n\n List allSysName();\n}\n\n\n<|start_filename|>Dockerfile<|end_filename|>\nFROM 172.18.1.1:15000/java:8u111-jre-alpine as dev\nADD clever-security-server/target/clever-security-server-*-SNAPSHOT.jar app.jar\nENTRYPOINT [\"java\", \"-jar\", \"app.jar\", \"--server.port=9066\", \"--server.address=0.0.0.0\"]\nEXPOSE 9066\n\nFROM 172.18.1.1:15000/java:8u111-jre-alpine as prod\nADD clever-security-server/target/clever-security-server-*-SNAPSHOT.jar app.jar\nENTRYPOINT [\"java\", \"-jar\", \"app.jar\", \"--server.port=9066\", \"--server.address=0.0.0.0\"]\nEXPOSE 9066\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionAddReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.hibernate.validator.constraints.Length;\nimport org.hibernate.validator.constraints.Range;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 16:29
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class PermissionAddReq extends BaseRequest {\n\n @ApiModelProperty(\"系统(或服务)名称\")\n @NotBlank\n @Length(max = 127)\n private String sysName;\n\n @ApiModelProperty(\"权限标题\")\n @NotBlank\n @Length(max = 255)\n private String title;\n\n @ApiModelProperty(\"唯一权限标识字符串\")\n @Length(min = 6, max = 255)\n private String permissionStr;\n\n @ApiModelProperty(\"权限类型,1:web资源权限, 2:菜单权限,3:ui权限,4:自定义\")\n @NotNull\n @Range(min = 2, max = 4)\n private Integer resourcesType;\n\n @ApiModelProperty(\"权限说明\")\n @Length(max = 127)\n private String description;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeServices.java<|end_filename|>\npackage org.clever.security.rememberme;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.token.SecurityContextToken;\nimport org.clever.security.token.login.RememberMeToken;\nimport org.json.JSONObject;\nimport org.springframework.security.authentication.AbstractAuthenticationToken;\nimport org.springframework.security.authentication.RememberMeAuthenticationToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsChecker;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;\nimport org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;\n\nimport javax.servlet.http.HttpServletRequest;\n\n/**\n * \"记住我\"功能实现\n * 作者: lzw
\n * 创建时间:2018-09-20 20:23
\n */\n@Slf4j\npublic class RememberMeServices extends PersistentTokenBasedRememberMeServices {\n\n public static final String REMEMBER_ME_KEY = \"remember-me-key\";\n public static final String REMEMBER_ME_COOKIE_NAME = \"remember-me\";\n\n\n public RememberMeServices(\n String key,\n UserDetailsService userDetailsService,\n PersistentTokenRepository tokenRepository,\n UserDetailsChecker userDetailsChecker) {\n super(key, userDetailsService, tokenRepository);\n this.setUserDetailsChecker(userDetailsChecker);\n }\n\n /**\n * 判断是否需要\"记住我\"的功能\n */\n @Override\n protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {\n String rememberMe = request.getParameter(parameter);\n if (rememberMe == null) {\n Object json = request.getAttribute(Constant.Login_Data_Body_Request_Key);\n if (json != null) {\n JSONObject object = new JSONObject(json.toString());\n rememberMe = object.optString(parameter);\n }\n }\n if (rememberMe != null) {\n if (rememberMe.equalsIgnoreCase(\"true\")\n || rememberMe.equalsIgnoreCase(\"on\")\n || rememberMe.equalsIgnoreCase(\"yes\")\n || rememberMe.equals(\"1\")) {\n return true;\n }\n }\n if (log.isDebugEnabled()) {\n log.debug(\"Did not send remember-me cookie (principal did not set \" + \"parameter '\" + parameter + \"')\");\n }\n return false;\n }\n\n /**\n * 通过RememberMe登录创建LoginToken而非RememberMeAuthenticationToken,以免遇到403时跳转到登录页面
\n * 不合理应该修改UserLoginEntryPoint.java\n */\n @Override\n protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) {\n AbstractAuthenticationToken authentication;\n if (user instanceof LoginUserDetails) {\n LoginUserDetails loginUserDetails = (LoginUserDetails) user;\n RememberMeToken rememberMeToken = new RememberMeToken();\n rememberMeToken.setUsername(loginUserDetails.getUsername());\n authentication = new SecurityContextToken(rememberMeToken, loginUserDetails);\n } else {\n authentication = new RememberMeAuthenticationToken(\n this.getKey(),\n user,\n user.getAuthorities());\n }\n // 设置用户 \"details\" 属性(设置请求IP和SessionID) -- 需要提前创建Session\n request.getSession();\n authentication.setDetails(this.getAuthenticationDetailsSource().buildDetails(request));\n return authentication;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/ForcedOfflineRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-12 16:21
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ForcedOfflineRes extends BaseResponse {\n\n @ApiModelProperty(\"删除Session数\")\n private int count = 0;\n\n @ApiModelProperty(\"用户名\")\n private String sysName;\n\n @ApiModelProperty(\"系统名\")\n private String username;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/strategy/SessionExpiredStrategy.java<|end_filename|>\npackage org.clever.security.strategy;\n\nimport lombok.Data;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.model.response.ErrorResponse;\nimport org.clever.common.utils.mapper.JacksonMapper;\nimport org.springframework.security.web.DefaultRedirectStrategy;\nimport org.springframework.security.web.RedirectStrategy;\nimport org.springframework.security.web.session.SessionInformationExpiredEvent;\nimport org.springframework.security.web.session.SessionInformationExpiredStrategy;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\nimport java.util.Date;\n\n/**\n * Session 过期时的处理\n * 作者: lzw
\n * 创建时间:2018-09-20 15:00
\n */\n@Data\n@Slf4j\npublic class SessionExpiredStrategy implements SessionInformationExpiredStrategy {\n\n private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();\n\n /**\n * 需要跳转\n */\n private Boolean needRedirect = false;\n\n /**\n * 跳转Url\n */\n private String destinationUrl = \"/login.html\";\n\n @Override\n public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {\n HttpServletRequest request = event.getRequest();\n HttpServletResponse response = event.getResponse();\n if (needRedirect) {\n redirectStrategy.sendRedirect(request, response, destinationUrl);\n return;\n }\n if (!response.isCommitted()) {\n ErrorResponse errorResponse = new ErrorResponse();\n errorResponse.setPath(request.getPathInfo());\n errorResponse.setTimestamp(new Date());\n errorResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);\n errorResponse.setError(\"当前登录已过期(可能是因为同一用户尝试多次并发登录)\");\n errorResponse.setMessage(\"当前登录已过期(可能是因为同一用户尝试多次并发登录)\");\n response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);\n response.setCharacterEncoding(\"UTF-8\");\n response.setContentType(\"application/json;charset=utf-8\");\n response.getWriter().print(JacksonMapper.nonEmptyMapper().toJson(errorResponse));\n }\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/RememberMeTokenMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.entity.RememberMeToken;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.Date;\n\n/**\n * “记住我”功能的token(RememberMeToken)表数据库访问层\n *\n * @author lizw\n * @since 2018-09-21 20:10:31\n */\n@Repository\n@Mapper\npublic interface RememberMeTokenMapper extends BaseMapper {\n\n int updateBySeries(@Param(\"series\") String series, @Param(\"tokenValue\") String tokenValue, @Param(\"lastUsed\") Date lastUsed);\n\n RememberMeToken getBySeries(@Param(\"series\") String series);\n\n int deleteByUsername(@Param(\"username\") String username);\n\n int deleteBySysNameAndUsername(@Param(\"sysName\") String sysName, @Param(\"username\") String username);\n}\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/JwtTokenService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport io.jsonwebtoken.*;\nimport io.jsonwebtoken.impl.DefaultClaims;\nimport io.jsonwebtoken.security.Keys;\nimport io.jsonwebtoken.security.SignatureException;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.DateTimeUtils;\nimport org.clever.common.utils.IDCreateUtils;\nimport org.clever.common.utils.SnowFlake;\nimport org.clever.common.utils.codec.EncodeDecodeUtils;\nimport org.clever.common.utils.mapper.JacksonMapper;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.TokenConfig;\nimport org.clever.security.token.JwtAccessToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.stereotype.Component;\n\nimport java.security.Key;\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-16 16:45
\n */\n@Component\n@Slf4j\npublic class JwtTokenService {\n\n private static final String PermissionKey = \"permissions\";\n private static final String RoleKey = \"roles\";\n private static final String SecretKeySuffix = \"0123456789012345678901234567890123456789012345678901234567890123\";\n\n /**\n * 签名密钥\n */\n private final String secretKey;\n\n /**\n * Token有效时间(默认)\n */\n private final long tokenValidityInMilliseconds;\n\n /**\n * Token记住我有效时间(记住我)\n */\n private final long tokenValidityInMillisecondsForRememberMe;\n\n /**\n * 设置密钥过期时间 (格式 HH:mm:ss)\n */\n private final String hoursInDay;\n\n /**\n * JWT Token配置\n */\n private final TokenConfig tokenConfig;\n\n protected JwtTokenService(SecurityConfig securityConfig) {\n tokenConfig = securityConfig.getTokenConfig();\n if (tokenConfig == null) {\n throw new BusinessException(\"未配置TokenConfig\");\n }\n this.secretKey = tokenConfig.getSecretKey() + SecretKeySuffix;\n this.tokenValidityInMilliseconds = tokenConfig.getTokenValidity().toMillis();\n this.tokenValidityInMillisecondsForRememberMe = tokenConfig.getTokenValidityForRememberMe().toMillis();\n this.hoursInDay = tokenConfig.getHoursInDay();\n }\n\n /**\n * 创建Token,并将Token写入Redis\n *\n * @param authentication 授权信息\n * @param rememberMe 使用记住我\n */\n public JwtAccessToken createToken(Authentication authentication, boolean rememberMe) {\n // 用户权限信息\n Set authorities = authentication.getAuthorities().stream()\n .map(GrantedAuthority::getAuthority)\n .collect(Collectors.toSet());\n //获取当前时间戳\n long now = System.currentTimeMillis();\n //存放过期时间\n Date expiration;\n if (rememberMe) {\n expiration = new Date(now + this.tokenValidityInMillisecondsForRememberMe);\n } else {\n expiration = new Date(now + this.tokenValidityInMilliseconds);\n }\n // 优化过期时间\n if (StringUtils.isNotBlank(hoursInDay)) {\n String tmp = DateTimeUtils.formatToString(expiration, DateTimeUtils.yyyy_MM_dd);\n try {\n expiration = DateTimeUtils.parseDate(tmp.trim() + \" \" + hoursInDay.trim(), DateTimeUtils.yyyy_MM_dd_HH_mm_ss);\n } catch (Throwable e) {\n log.warn(\"### TokenConfig.hoursInDay配置错误\", e);\n }\n if (expiration.getTime() <= now) {\n expiration = DateTimeUtils.addDays(expiration, 1);\n }\n }\n //创建Token令牌 - iss(签发者), aud(接收方), sub(面向的用户),exp(过期时间戳), iat(签发时间), jti(JWT ID)\n DefaultClaims claims = new DefaultClaims();\n claims.setIssuer(tokenConfig.getIssuer());\n claims.setAudience(tokenConfig.getAudience());\n claims.setSubject(authentication.getName());\n claims.setExpiration(expiration);\n claims.setIssuedAt(new Date());\n claims.setId(String.valueOf(SnowFlake.SNOW_FLAKE.nextId()));\n // 设置角色和权限\n claims.put(PermissionKey, authorities);\n // TODO 设置角色\n claims.put(RoleKey, new HashSet(0));\n // 签名私钥\n Key key = Keys.hmacShaKeyFor((authentication.getName() + secretKey).getBytes());\n String token = Jwts.builder()\n .setClaims(claims)\n .signWith(key, SignatureAlgorithm.HS512)\n .compact();\n // 构建返回数据\n Jws claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(token);\n JwtAccessToken jwtAccessToken = new JwtAccessToken();\n jwtAccessToken.setToken(token);\n jwtAccessToken.setHeader(claimsJws.getHeader());\n jwtAccessToken.setClaims(claimsJws.getBody());\n jwtAccessToken.setRefreshToken(createRefreshToken(authentication.getName()));\n return jwtAccessToken;\n }\n\n /**\n * 校验Token,校验失败抛出异常\n */\n public Jws getClaimsJws(String token) {\n String[] strArray = token.split(\"\\\\.\");\n if (strArray.length != 3) {\n throw new MalformedJwtException(\"Token格式不正确\");\n }\n // 解析获得签名私钥\n String payload = strArray[1];\n payload = new String(EncodeDecodeUtils.decodeBase64(payload));\n DefaultClaims claims = JacksonMapper.nonEmptyMapper().fromJson(payload, DefaultClaims.class);\n Key key = Keys.hmacShaKeyFor((claims.getSubject() + secretKey).getBytes());\n try {\n //通过密钥验证Token\n return Jwts.parser().setSigningKey(key).parseClaimsJws(token);\n } catch (SignatureException e) {\n // 签名异常\n throw new BusinessException(\"Token签名异常\", e);\n } catch (MalformedJwtException e) {\n // JWT格式错误\n throw new BusinessException(\"Token格式错误\", e);\n } catch (ExpiredJwtException e) {\n // JWT过期\n throw new BusinessException(\"TokenJWT过期\", e);\n } catch (UnsupportedJwtException e) {\n // 不支持该JWT\n throw new BusinessException(\"不支持该Token\", e);\n } catch (IllegalArgumentException e) {\n // 参数错误异常\n throw new BusinessException(\"Token参数错误异常\", e);\n }\n }\n\n /**\n * 生成刷新令牌\n */\n private String createRefreshToken(String username) {\n return username + \":\" + IDCreateUtils.shortUuid();\n }\n\n// /**\n// * 通过刷新令牌得到用户名\n// */\n// public String getUsernameByRefreshToken(String refreshToken) {\n// return refreshToken.substring(0, refreshToken.lastIndexOf(':'));\n// }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/SessionWebSecurityConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.authentication.CollectLoginToken;\nimport org.clever.security.authentication.UserLoginEntryPoint;\nimport org.clever.security.authentication.filter.UserLoginFilter;\nimport org.clever.security.config.model.LoginConfig;\nimport org.clever.security.config.model.RememberMeConfig;\nimport org.clever.security.handler.UserAccessDeniedHandler;\nimport org.clever.security.handler.UserLogoutSuccessHandler;\nimport org.clever.security.rememberme.RememberMeServices;\nimport org.clever.security.repository.SecurityContextRepositoryProxy;\nimport org.clever.security.service.GlobalUserDetailsService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.access.AccessDecisionManager;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.AuthenticationProvider;\nimport org.springframework.security.config.BeanIds;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;\nimport org.springframework.security.web.context.SecurityContextRepository;\nimport org.springframework.security.web.session.SessionInformationExpiredStrategy;\nimport org.springframework.session.security.SpringSessionBackedSessionRegistry;\n\nimport java.util.List;\n\n/**\n * Session 登录配置\n * 作者: lzw
\n * 创建时间:2018-03-14 14:45
\n */\n@Configuration\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"session\")\n@Slf4j\npublic class SessionWebSecurityConfig extends BaseWebSecurityConfig {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private UserLoginFilter userLoginFilter;\n @Autowired\n private GlobalUserDetailsService globalUserDetailsService;\n @Autowired\n private List authenticationProviderList;\n @Autowired\n private UserLoginEntryPoint userLoginEntryPoint;\n @Autowired\n private UserLogoutSuccessHandler userLogoutSuccessHandler;\n @Autowired\n private UserAccessDeniedHandler userAccessDeniedHandler;\n @Autowired\n private AccessDecisionManager accessDecisionManager;\n @Autowired\n private BCryptPasswordEncoder bCryptPasswordEncoder;\n @Autowired\n private SecurityContextRepositoryProxy securityContextRepositoryProxy;\n @Autowired\n private SpringSessionBackedSessionRegistry sessionRegistry;\n @Autowired\n private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;\n @Autowired\n private org.springframework.security.web.authentication.RememberMeServices rememberMeServices;\n\n @Override\n PasswordEncoder getPasswordEncoder() {\n return bCryptPasswordEncoder;\n }\n\n @Override\n UserDetailsService getUserDetailsService() {\n return globalUserDetailsService;\n }\n\n @Override\n List getAuthenticationProviderList() {\n return authenticationProviderList;\n }\n\n @Override\n SecurityConfig getSecurityConfig() {\n return securityConfig;\n }\n\n /**\n * 在Spring容器中注册 AuthenticationManager\n */\n @Bean(name = BeanIds.AUTHENTICATION_MANAGER)\n @Override\n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean();\n }\n\n /**\n * 具体的权限控制规则配置\n */\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http.setSharedObject(SecurityContextRepository.class, securityContextRepositoryProxy);\n // 自定义登录 Filter --> UserLoginFilter\n http.addFilterAt(userLoginFilter, UsernamePasswordAuthenticationFilter.class);\n\n// http\n// .csrf().and()\n// .addFilter(new WebAsyncManagerIntegrationFilter())\n// .exceptionHandling().and()\n// .headers().and()\n// .sessionManagement().and()\n// .securityContext().and()\n// .requestCache().and()\n// .anonymous().and()\n// .servletApi().and()\n// .apply(new DefaultLoginPageConfigurer<>()).and()\n// .logout();\n// ClassLoader classLoader = this.getApplicationContext().getClassLoader();\n// List defaultHttpConfigurers = SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);\n// for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) {\n// http.apply(configurer);\n// }\n\n // 过滤器配置\n http\n .csrf().disable()\n .exceptionHandling().authenticationEntryPoint(userLoginEntryPoint).accessDeniedHandler(userAccessDeniedHandler)\n .and()\n .authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager)\n .and()\n .formLogin().disable()\n .logout().logoutUrl(securityConfig.getLogout().getLogoutUrl()).logoutSuccessHandler(userLogoutSuccessHandler).permitAll()\n ;\n // 设置\"记住我功能配置\"\n RememberMeConfig rememberMe = securityConfig.getRememberMe();\n if (rememberMe != null && rememberMe.getEnable()) {\n http.rememberMe()\n .rememberMeServices(rememberMeServices)\n .alwaysRemember(rememberMe.getAlwaysRemember())\n .tokenValiditySeconds((int) rememberMe.getValidity().getSeconds())\n .rememberMeParameter(CollectLoginToken.REMEMBER_ME_PARAM)\n .rememberMeCookieName(RememberMeServices.REMEMBER_ME_COOKIE_NAME)\n .key(RememberMeServices.REMEMBER_ME_KEY)\n ;\n }\n // 登录并发控制\n LoginConfig login = securityConfig.getLogin();\n if (login.getConcurrentLoginCount() != null) {\n int concurrentLoginCount = login.getConcurrentLoginCount() <= 0 ? -1 : login.getConcurrentLoginCount();\n boolean notAllowAfterLogin = false;\n if (login.getNotAllowAfterLogin() != null) {\n notAllowAfterLogin = login.getNotAllowAfterLogin();\n }\n http.sessionManagement()\n .maximumSessions(concurrentLoginCount)\n .maxSessionsPreventsLogin(notAllowAfterLogin)\n .sessionRegistry(sessionRegistry)\n .expiredSessionStrategy(sessionInformationExpiredStrategy)\n ;\n }\n log.info(\"### HttpSecurity 配置完成!\");\n }\n}\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserBindRoleRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\nimport org.clever.security.entity.Role;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 21:54
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserBindRoleRes extends BaseResponse {\n\n @ApiModelProperty(\"用户名\")\n private String username;\n\n @ApiModelProperty(\"角色集合\")\n private List roleList;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/UserAuthorityMixin.java<|end_filename|>\npackage org.clever.security.jackson2;\n\nimport com.fasterxml.jackson.annotation.JsonAutoDetect;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-22 22:02
\n */\n//@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY)\n@JsonAutoDetect\n@JsonIgnoreProperties(ignoreUnknown = true)\nclass UserAuthorityMixin {\n\n @JsonCreator\n public UserAuthorityMixin(@JsonProperty(\"authority\") String authority, @JsonProperty(\"title\") String title) {\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/annotation/UrlAuthorization.java<|end_filename|>\npackage org.clever.security.annotation;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * 定义Url授权信息\n * 作者: lzw
\n * 创建时间:2018-09-20 17:49
\n */\n@Target({ElementType.TYPE, ElementType.METHOD})\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface UrlAuthorization {\n\n /**\n * 权限标题\n */\n String title() default \"\";\n\n /**\n * 权限说明\n */\n String description() default \"\";\n\n /**\n * 唯一权限标识字符串\n */\n String permissionStr() default \"\";\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/RememberMeTokenService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.server.service.BaseService;\nimport org.clever.security.entity.RememberMeToken;\nimport org.clever.security.mapper.RememberMeTokenMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 16:35
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class RememberMeTokenService extends BaseService {\n\n @Autowired\n private RememberMeTokenMapper rememberMeTokenMapper;\n\n /**\n * 新增RememberMeToken\n */\n @Transactional\n public RememberMeToken addRememberMeToken(RememberMeToken req) {\n // 校验token序列号是否唯一\n RememberMeToken exists = rememberMeTokenMapper.getBySeries(req.getSeries());\n if (exists != null) {\n throw new BusinessException(\"token序列号已经存在\");\n }\n rememberMeTokenMapper.insert(req);\n return rememberMeTokenMapper.selectById(req.getId());\n }\n\n public RememberMeToken getRememberMeToken(String series) {\n return rememberMeTokenMapper.getBySeries(series);\n }\n\n @Transactional\n public Integer delRememberMeToken(String username) {\n return rememberMeTokenMapper.deleteByUsername(username);\n }\n\n /**\n * @param series token序列号\n * @param tokenValue token值\n * @param lastUsed 最后使用时间\n */\n @Transactional\n public RememberMeToken updateRememberMeToken(String series, String tokenValue, Date lastUsed) {\n rememberMeTokenMapper.updateBySeries(series, tokenValue, lastUsed);\n return rememberMeTokenMapper.getBySeries(series);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/QueryMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.dto.request.RememberMeTokenQueryReq;\nimport org.clever.security.dto.request.ServiceSysQueryReq;\nimport org.clever.security.dto.request.UserLoginLogQueryReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.entity.User;\nimport org.clever.security.entity.model.UserLoginLogModel;\nimport org.clever.security.entity.model.UserRememberMeToken;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-07 21:02
\n */\n@Repository\n@Mapper\npublic interface QueryMapper extends BaseMapper {\n\n List allSysName();\n\n List allRoleName();\n\n List findRoleNameByUser(@Param(\"username\") String username);\n\n List findPermissionStrByRole(@Param(\"roleName\") String roleName);\n\n List findRememberMeToken(@Param(\"query\") RememberMeTokenQueryReq query, IPage page);\n\n List findUserLoginLog(@Param(\"query\") UserLoginLogQueryReq query, IPage page);\n\n List findServiceSys(@Param(\"query\") ServiceSysQueryReq query, IPage page);\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authorization/RequestAccessDecisionVoter.java<|end_filename|>\npackage org.clever.security.authorization;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.client.WebPermissionClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.WebPermissionModelGetReq;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.model.UserAuthority;\nimport org.clever.security.token.SecurityContextToken;\nimport org.clever.security.token.ServerApiAccessContextToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.access.AccessDecisionVoter;\nimport org.springframework.security.access.ConfigAttribute;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.web.FilterInvocation;\nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.method.HandlerMethod;\nimport org.springframework.web.servlet.HandlerExecutionChain;\nimport org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;\n\nimport javax.annotation.PostConstruct;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Objects;\n\n/**\n * 基于HttpRequest授权校验\n *

\n * 作者: lzw
\n * 创建时间:2018-03-15 17:51
\n *\n * @see org.springframework.security.access.SecurityMetadataSource\n */\n@Component\n@Slf4j\npublic class RequestAccessDecisionVoter implements AccessDecisionVoter {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private WebPermissionClient webPermissionClient;\n @Autowired\n private RequestMappingHandlerMapping requestMappingHandlerMapping;\n // 不去需要授权就能访问的Url\n private List antPathRequestMatcherList = new ArrayList<>();\n\n @PostConstruct\n public void init() {\n if (securityConfig.getIgnoreAuthorizationUrls() != null) {\n for (String url : securityConfig.getIgnoreAuthorizationUrls()) {\n antPathRequestMatcherList.add(new AntPathRequestMatcher(url));\n }\n // 打印相应的日志\n if (log.isInfoEnabled()) {\n StringBuilder strTmp = new StringBuilder();\n strTmp.append(\"\\r\\n\");\n strTmp.append(\"#=======================================================================================================================#\\r\\n\");\n strTmp.append(\"不需要授权检查的资源:\\r\\n\");\n for (String url : securityConfig.getIgnoreAuthorizationUrls()) {\n strTmp.append(\"\\t\").append(url).append(\"\\r\\n\");\n }\n strTmp.append(\"#=======================================================================================================================#\");\n log.info(strTmp.toString());\n }\n }\n }\n\n @Override\n public boolean supports(ConfigAttribute attribute) {\n return true;\n }\n\n @Override\n public boolean supports(Class clazz) {\n return FilterInvocation.class.isAssignableFrom(clazz);\n }\n\n /**\n * 授权实现\n */\n @Override\n public int vote(Authentication authentication, FilterInvocation filterInvocation, Collection attributes) {\n if (authentication instanceof ServerApiAccessContextToken) {\n log.info(\"[ServerApiAccessContextToken]允许访问 -> {}\", authentication);\n return ACCESS_GRANTED;\n }\n if (!(authentication instanceof SecurityContextToken)) {\n log.info(\"### 放弃授权(authentication类型不匹配SecurityContextToken) -> [{}] [{}]\", authentication.getClass().getSimpleName(), filterInvocation.getRequestUrl());\n return ACCESS_ABSTAIN;\n }\n SecurityContextToken securityContextToken = (SecurityContextToken) authentication;\n LoginUserDetails loginUserDetails = securityContextToken.getUserDetails();\n if (loginUserDetails == null) {\n log.info(\"### 放弃授权(loginUserDetails为空) -> [{}]\", filterInvocation.getRequestUrl());\n return ACCESS_ABSTAIN;\n }\n log.info(\"### 开始授权 [username={}] -> [{}]\", loginUserDetails.getUsername(), filterInvocation.getRequestUrl());\n HandlerExecutionChain handlerExecutionChain;\n try {\n handlerExecutionChain = requestMappingHandlerMapping.getHandler(filterInvocation.getHttpRequest());\n } catch (Throwable e) {\n log.warn(\"### 授权时出现异常\", e);\n return ACCESS_DENIED;\n }\n if (handlerExecutionChain == null) {\n log.info(\"### 授权通过(未知的资源404) -> [{}]\", filterInvocation.getRequestUrl());\n return ACCESS_GRANTED;\n }\n // 匹配是否是不需要授权就能访问的Url\n for (AntPathRequestMatcher antPathRequestMatcher : antPathRequestMatcherList) {\n if (antPathRequestMatcher.matches(filterInvocation.getRequest())) {\n log.info(\"### 授权通过(不需要授权的URL) [{}] -> [{}]\", antPathRequestMatcher.getPattern(), filterInvocation.getRequestUrl());\n return ACCESS_GRANTED;\n }\n }\n HandlerMethod handlerMethod = (HandlerMethod) handlerExecutionChain.getHandler();\n String targetClass = handlerMethod.getBeanType().getName();\n String targetMethod = handlerMethod.getMethod().getName();\n // 获取放签名\n StringBuilder methodParams = new StringBuilder();\n Class[] paramTypes = handlerMethod.getMethod().getParameterTypes();\n for (Class clzz : paramTypes) {\n if (methodParams.length() > 0) {\n methodParams.append(\", \");\n }\n methodParams.append(clzz.getName());\n }\n WebPermissionModelGetReq req = new WebPermissionModelGetReq();\n req.setSysName(securityConfig.getSysName());\n req.setTargetClass(targetClass);\n req.setTargetMethod(targetMethod);\n req.setTargetMethodParams(methodParams.toString());\n WebPermissionModel webPermissionModel = webPermissionClient.getWebPermissionModel(req);\n if (webPermissionModel == null) {\n log.info(\"### 授权通过(当前资源未配置权限) [{}#{}] -> [{}]\", targetClass, targetMethod, filterInvocation.getRequestUrl());\n return ACCESS_GRANTED;\n }\n log.info(\"### 权限字符串 [{}] -> [{}]\", webPermissionModel.getPermissionStr(), filterInvocation.getRequestUrl());\n if (Objects.equals(webPermissionModel.getNeedAuthorization(), EnumConstant.Permission_NeedAuthorization_2)) {\n log.info(\"### 授权通过(当前资源不需要访问权限) [{}#{}] [{}] -> [{}]\", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl());\n return ACCESS_GRANTED;\n }\n // 对比权限字符串 permission.getPermission()\n if (checkPermission(webPermissionModel.getPermissionStr(), loginUserDetails.getAuthorities())) {\n log.info(\"### 授权通过(已授权) [{}#{}] [{}] -> [{}]\", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl());\n return ACCESS_GRANTED;\n }\n log.info(\"### 授权失败(未授权) [{}#{}] [{}] -> [{}]\", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl());\n return ACCESS_DENIED;\n }\n\n /**\n * 校验权限字符串\n */\n private boolean checkPermission(String permissionStr, Collection authorities) {\n if (authorities == null) {\n return false;\n }\n for (UserAuthority userAuthority : authorities) {\n if (Objects.equals(permissionStr, userAuthority.getAuthority())) {\n log.info(\"### 权限字符串匹配成功 [{}] [{}]\", userAuthority.getAuthority(), userAuthority.getTitle());\n return true;\n }\n }\n return false;\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ServiceSysController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.ServiceSysAddReq;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.service.ServiceSysService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-22 20:34
\n */\n@Api(\"服务系统\")\n@RestController\n@RequestMapping(\"/api\")\npublic class ServiceSysController {\n\n @Autowired\n private ServiceSysService serviceSysService;\n\n @ApiOperation(\"查询所有系统信息\")\n @GetMapping(\"/service_sys\")\n public List allSysName() {\n return serviceSysService.selectAll();\n }\n\n @ApiOperation(\"注册系统\")\n @PostMapping(\"/service_sys\")\n public ServiceSys registerSys(@RequestBody @Validated ServiceSysAddReq serviceSysAddReq) {\n ServiceSys serviceSys = BeanMapper.mapper(serviceSysAddReq, ServiceSys.class);\n return serviceSysService.registerSys(serviceSys);\n }\n\n @ApiOperation(\"删除系统\")\n @DeleteMapping(\"/service_sys/{sysName}\")\n public ServiceSys delServiceSys(@PathVariable(\"sysName\") String sysName) {\n return serviceSysService.delServiceSys(sysName);\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByPermissionService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.IDCreateUtils;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.PermissionQueryReq;\nimport org.clever.security.dto.request.PermissionUpdateReq;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.WebPermission;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.mapper.PermissionMapper;\nimport org.clever.security.mapper.RoleMapper;\nimport org.clever.security.mapper.WebPermissionMapper;\nimport org.clever.security.service.internal.ReLoadSessionService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Set;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 12:51
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ManageByPermissionService {\n\n @Autowired\n private PermissionMapper permissionMapper;\n @Autowired\n private WebPermissionMapper webPermissionMapper;\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private ReLoadSessionService reLoadSessionService;\n\n public IPage findByPage(PermissionQueryReq queryReq) {\n Page page = new Page<>(queryReq.getPageNo(), queryReq.getPageSize());\n page.setRecords(permissionMapper.findByPage(queryReq, page));\n return page;\n }\n\n @Transactional\n public WebPermissionModel addPermission(Permission permission) {\n if (StringUtils.isBlank(permission.getPermissionStr())) {\n permission.setPermissionStr(IDCreateUtils.shortUuid());\n }\n int count = permissionMapper.existsPermission(permission.getPermissionStr());\n if (count > 0) {\n throw new BusinessException(\"权限已存在\");\n }\n permissionMapper.insert(permission);\n return permissionMapper.getByPermissionStr(permission.getPermissionStr());\n }\n\n @Transactional\n public WebPermissionModel updatePermission(String permissionStr, PermissionUpdateReq permissionUpdateReq) {\n WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permissionStr);\n if (webPermissionModel == null) {\n throw new BusinessException(\"权限[\" + permissionStr + \"]不存在\");\n }\n if (StringUtils.isBlank(permissionUpdateReq.getPermissionStr())) {\n permissionUpdateReq.setPermissionStr(null);\n }\n if (StringUtils.isNotBlank(permissionUpdateReq.getPermissionStr())\n && permissionUpdateReq.getPermissionStr().startsWith(\"[auto]\")\n && !webPermissionModel.getPermissionStr().equals(permissionUpdateReq.getPermissionStr())) {\n throw new BusinessException(\"权限标识不能以“[auto]”开始\");\n }\n // 更新权限\n if (Objects.equals(webPermissionModel.getResourcesType(), EnumConstant.Permission_ResourcesType_1)\n && permissionUpdateReq.getNeedAuthorization() != null\n && !Objects.equals(webPermissionModel.getNeedAuthorization(), permissionUpdateReq.getNeedAuthorization())) {\n // 更新WEB权限\n WebPermission webPermission = new WebPermission();\n webPermission.setId(webPermissionModel.getWebPermissionId());\n webPermission.setPermissionStr(permissionUpdateReq.getPermissionStr());\n webPermission.setNeedAuthorization(permissionUpdateReq.getNeedAuthorization());\n webPermissionMapper.updateById(webPermission);\n }\n Permission permission = BeanMapper.mapper(permissionUpdateReq, Permission.class);\n permission.setId(webPermissionModel.getPermissionId());\n if (permission.getTitle() != null || permission.getPermissionStr() != null || permission.getResourcesType() != null || permission.getDescription() != null) {\n permissionMapper.updateById(permission);\n }\n if (permissionUpdateReq.getPermissionStr() != null && !Objects.equals(permissionStr, permissionUpdateReq.getPermissionStr())) {\n // 更新 role_permission 表 - 先查询受影响的角色\n List roleNameList = roleMapper.findRoleNameByPermissionStr(permissionStr);\n roleMapper.updateRolePermissionByPermissionStr(permissionStr, permissionUpdateReq.getPermissionStr());\n // 计算影响的用户 更新Session\n reLoadSessionService.onChangeRole(roleNameList);\n }\n String newPermissionStr = StringUtils.isBlank(permissionUpdateReq.getPermissionStr()) ? permissionStr : permissionUpdateReq.getPermissionStr();\n return permissionMapper.getByPermissionStr(newPermissionStr);\n }\n\n public WebPermissionModel getPermissionModel(String permissionStr) {\n return permissionMapper.getByPermissionStr(permissionStr);\n }\n\n @Transactional\n public WebPermissionModel delPermissionModel(String permissionStr) {\n WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permissionStr);\n if (webPermissionModel == null) {\n throw new BusinessException(\"权限[\" + permissionStr + \"]不存在\");\n }\n permissionMapper.deleteById(webPermissionModel.getPermissionId());\n webPermissionMapper.deleteById(webPermissionModel.getWebPermissionId());\n // 删除 role_permission 表 - 先查询受影响的角色\n List roleNameList = roleMapper.findRoleNameByPermissionStr(permissionStr);\n permissionMapper.delRolePermission(permissionStr);\n // 计算影响的用户 更新Session\n reLoadSessionService.onChangeRole(roleNameList);\n return webPermissionModel;\n }\n\n @Transactional\n public List delPermissionModels(Set permissionSet) {\n List list = new ArrayList<>();\n for (String permission : permissionSet) {\n WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permission);\n if (webPermissionModel == null) {\n throw new BusinessException(\"权限[\" + permission + \"]不存在\");\n }\n list.add(webPermissionModel);\n }\n // 删除 - 先查询受影响的角色\n List roleNameList = roleMapper.findRoleNameByPermissionStrList(permissionSet);\n for (WebPermissionModel webPermissionModel : list) {\n permissionMapper.deleteById(webPermissionModel.getPermissionId());\n webPermissionMapper.deleteById(webPermissionModel.getWebPermissionId());\n permissionMapper.delRolePermission(webPermissionModel.getPermissionStr());\n }\n // 计算影响的用户 更新Session\n reLoadSessionService.onChangeRole(roleNameList);\n return list;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/EnumConstant.java<|end_filename|>\npackage org.clever.security.entity;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 14:15
\n */\npublic class EnumConstant {\n\n /**\n * 帐号是否锁定,0:未锁定\n */\n public static final Integer User_Locked_0 = 0;\n\n /**\n * 帐号是否锁定,1:锁定\n */\n public static final Integer User_Locked_1 = 1;\n\n /**\n * 是否启用,0:禁用\n */\n public static final Integer User_Enabled_0 = 0;\n\n /**\n * 是否启用,1:启用\n */\n public static final Integer User_Enabled_1 = 1;\n\n /**\n * 需要授权才允许访问(1:需要)\n */\n public static final Integer Permission_NeedAuthorization_1 = 1;\n\n /**\n * 需要授权才允许访问(2:不需要)\n */\n public static final Integer Permission_NeedAuthorization_2 = 2;\n\n /**\n * 权限类型,1:web资源权限\n */\n public static final Integer Permission_ResourcesType_1 = 1;\n\n /**\n * 权限类型,2:菜单权限\n */\n public static final Integer Permission_ResourcesType_2 = 2;\n\n /**\n * 权限类型,3:ui权限\n */\n public static final Integer Permission_ResourcesType_3 = 3;\n\n /**\n * controller路由资源是否存在,0:不存在\n */\n public static final Integer WebPermission_targetExist_0 = 0;\n\n /**\n * controller路由资源是否存在,1:存在\n */\n public static final Integer WebPermission_targetExist_1 = 1;\n\n /**\n * 登录状态,0:未知\n */\n public static final Integer UserLoginLog_LoginState_0 = 0;\n\n /**\n * 登录状态,1:已登录\n */\n public static final Integer UserLoginLog_LoginState_1 = 1;\n\n /**\n * 登录状态,2:登录已过期\n */\n public static final Integer UserLoginLog_LoginState_2 = 2;\n\n /**\n * 登录类型,0:session-cookie\n */\n public static final Integer ServiceSys_LoginModel_0 = 0;\n\n /**\n * 登录类型,1:jwt-token\n */\n public static final Integer ServiceSys_LoginModel_1 = 1;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserQueryPageReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.QueryByPage;\n\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 21:22
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserQueryPageReq extends QueryByPage {\n\n @ApiModelProperty(\"登录名(一条记录的手机号不能当另一条记录的用户名用)\")\n private String username;\n\n @ApiModelProperty(\"用户类型,0:系统内建,1:外部系统用户\")\n private Integer userType;\n\n @ApiModelProperty(\"手机号\")\n private String telephone;\n\n @ApiModelProperty(\"邮箱\")\n private String email;\n\n @ApiModelProperty(\"帐号过期时间-开始\")\n private Date expiredTimeStart;\n\n @ApiModelProperty(\"帐号过期时间-结束\")\n private Date expiredTimeEnd;\n\n @ApiModelProperty(\"帐号是否锁定,0:未锁定;1:锁定\")\n private Integer locked;\n\n @ApiModelProperty(\"是否启用,0:禁用;1:启用\")\n private Integer enabled;\n\n @ApiModelProperty(\"登录名、手机号、邮箱(模糊匹配)\")\n private String search;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/UserRole.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 用户-角色(UserRole)实体类\n *\n * @author lizw\n * @since 2018-09-16 21:24:44\n */\n@Data\npublic class UserRole implements Serializable {\n private static final long serialVersionUID = -79782786523606049L;\n /** 登录名 */ \n private String username;\n \n /** 角色名称 */ \n private String roleName;\n \n /** 创建时间 */ \n private Date createAt;\n \n /** 更新时间 */ \n private Date updateAt;\n \n}\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/JwtAccessToken.java<|end_filename|>\npackage org.clever.security.token;\n\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.JwsHeader;\nimport lombok.Data;\n\nimport java.io.Serializable;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-18 22:27
\n */\n@Data\npublic class JwtAccessToken implements Serializable {\n\n /**\n * JWT Token 字符串\n */\n private String token;\n\n /**\n * JWT 刷新 Token 字符串\n */\n private String refreshToken;\n\n /**\n * JWT Token Header\n */\n private JwsHeader header;\n\n /**\n * JWT Token Body\n */\n private Claims claims;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/GenerateKeyService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport io.jsonwebtoken.Claims;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.TokenConfig;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-19 11:22
\n */\n@Component\n@Slf4j\npublic class GenerateKeyService {\n /**\n * SecurityContext Key\n */\n private static final String SecurityContextKey = \"security-context\";\n /**\n * JWT Token 令牌Key\n */\n private static final String JwtTokenKey = \"jwt-token\";\n /**\n * JWT Token 刷新令牌Key\n */\n private static final String JwtTokenRefreshKey = \"refresh-token\";\n /**\n * 验证码 Key\n */\n private static final String CaptchaInfoKey = \"captcha-info\";\n /**\n * 登录失败次数 Key\n */\n private static final String LoginFailCountKey = \"login-fail-count\";\n\n /**\n * Token Redis前缀\n */\n private final String redisNamespace;\n\n protected GenerateKeyService(SecurityConfig securityConfig) {\n TokenConfig tokenConfig = securityConfig.getTokenConfig();\n if (tokenConfig == null || StringUtils.isBlank(tokenConfig.getRedisNamespace())) {\n throw new BusinessException(\"TokenConfig 的 RedisNamespace 属性未配置\");\n }\n String tmp = tokenConfig.getRedisNamespace();\n if (tmp.endsWith(\":\")) {\n tmp = tmp.substring(0, tmp.length() - 1);\n }\n redisNamespace = tmp;\n }\n\n /**\n * 生成 Redis 存储 SecurityContextKey\n */\n public String getSecurityContextKey(String username) {\n // {redisNamespace}:{SecurityContextKey}:{username}\n return String.format(\"%s:%s:%s\", redisNamespace, SecurityContextKey, username);\n }\n\n /**\n * 生成 Redis 存储 JwtTokenKey\n */\n public String getJwtTokenKey(Claims claims) {\n return getJwtTokenKey(claims.getSubject(), claims.getId());\n }\n\n /**\n * 生成 Redis 存储 JwtTokenKey\n */\n public String getJwtTokenKey(String username, String tokenId) {\n // {redisNamespace}:{JwtTokenKey}:{username}:{JWT ID}\n return String.format(\"%s:%s:%s:%s\", redisNamespace, JwtTokenKey, username, tokenId);\n }\n\n /**\n * 生成 Redis 存储 JwtTokenKey Pattern\n */\n public String getJwtTokenPatternKey(String username) {\n // {redisNamespace}:{JwtTokenKey}:{username}:{*}\n return String.format(\"%s:%s:%s:%s\", redisNamespace, JwtTokenKey, username, \"*\");\n }\n\n /**\n * 生成 Redis 存储 JwtTokenRefreshKey\n */\n public String getJwtRefreshTokenKey(String refreshToken) {\n // {redisNamespace}:{JwtTokenRefreshKey}:{refreshToken}\n return String.format(\"%s:%s:%s\", redisNamespace, JwtTokenRefreshKey, refreshToken);\n }\n\n /**\n * 生成 Redis 存储 CaptchaInfoKey\n */\n public String getCaptchaInfoKey(String code, String imageDigest) {\n // {redisNamespace}:{CaptchaInfoKey}:{code}:{imageDigest}\n return String.format(\"%s:%s:%s:%s\", redisNamespace, CaptchaInfoKey, code, imageDigest);\n }\n\n /**\n * 生成 Redis 存储 LoginFailCountKey\n */\n public String getLoginFailCountKey(String username) {\n // {redisNamespace}:{LoginFailCountKey}:{username}\n return String.format(\"%s:%s:%s\", redisNamespace, LoginFailCountKey, username);\n }\n\n// /**\n// * 生成 Redis 存储 JwtTokenRefreshKey Pattern\n// */\n// public String getJwtRefreshTokenPatternKey(String username) {\n// // {redisNamespace}:{JwtTokenRefreshKey}:{username}:{*}\n// return String.format(\"%s:%s:%s:%s\", redisNamespace, JwtTokenRefreshKey, username, \"*\");\n// }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/WebPermissionClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.WebPermissionInitReq;\nimport org.clever.security.dto.request.WebPermissionModelGetReq;\nimport org.clever.security.dto.response.WebPermissionInitRes;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.cloud.openfeign.SpringQueryMap;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 19:14
\n */\n@FeignClient(\n contextId = \"org.clever.security.client.WebPermissionClient\",\n name = \"clever-security-server\",\n path = \"/api\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface WebPermissionClient {\n\n /**\n * 根据系统和Controller信息查询Web权限\n */\n @GetMapping(\"/web_permission\")\n WebPermissionModel getWebPermissionModel(@SpringQueryMap WebPermissionModelGetReq req);\n\n /**\n * 查询某个系统的所有Web权限\n */\n @GetMapping(\"/web_permission/{sysName}\")\n List findAllWebPermissionModel(@PathVariable(\"sysName\") String sysName);\n\n /**\n * 初始化某个系统的所有Web权限\n */\n @PostMapping(\"/web_permission/{sysName}\")\n WebPermissionInitRes initWebPermission(@PathVariable(\"sysName\") String sysName, @RequestBody WebPermissionInitReq req);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/UserLoginLogService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.entity.UserLoginLog;\nimport org.clever.security.mapper.UserLoginLogMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-23 16:03
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class UserLoginLogService {\n\n @Autowired\n private UserLoginLogMapper userLoginLogMapper;\n\n @Transactional\n public UserLoginLog addUserLoginLog(UserLoginLog userLoginLog) {\n userLoginLogMapper.insert(userLoginLog);\n return userLoginLogMapper.selectById(userLoginLog.getId());\n }\n\n public UserLoginLog getUserLoginLog(String sessionId) {\n return userLoginLogMapper.getBySessionId(sessionId);\n }\n\n @Transactional\n public UserLoginLog updateUserLoginLog(String sessionId, UserLoginLog update) {\n UserLoginLog old = userLoginLogMapper.getBySessionId(sessionId);\n if (old == null) {\n throw new BusinessException(\"登录记录不存在,SessionId=\" + sessionId);\n }\n update.setId(old.getId());\n userLoginLogMapper.updateById(update);\n return userLoginLogMapper.selectById(old.getId());\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/SecurityContextRepositoryProxy.java<|end_filename|>\npackage org.clever.security.repository;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.LoginModel;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.ServerApiAccessToken;\nimport org.clever.security.token.ServerApiAccessContextToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextImpl;\nimport org.springframework.security.web.context.HttpRequestResponseHolder;\nimport org.springframework.security.web.context.HttpSessionSecurityContextRepository;\nimport org.springframework.security.web.context.SecurityContextRepository;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-05-16 14:28
\n */\n@Component\n@Slf4j\npublic class SecurityContextRepositoryProxy implements SecurityContextRepository {\n\n private SecurityConfig securityConfig;\n @Autowired(required = false)\n private JwtRedisSecurityContextRepository jwtRedisSecurityContextRepository;\n @Autowired(required = false)\n private HttpSessionSecurityContextRepository httpSessionSecurityContextRepository;\n\n public SecurityContextRepositoryProxy(@Autowired SecurityConfig securityConfig) {\n this.securityConfig = securityConfig;\n if (LoginModel.session.equals(securityConfig.getLoginModel())) {\n httpSessionSecurityContextRepository = new HttpSessionSecurityContextRepository();\n }\n }\n\n @Override\n public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {\n if (userServerApiAccessToken(requestResponseHolder.getRequest())) {\n ServerApiAccessToken serverApiAccessToken = securityConfig.getServerApiAccessToken();\n if (validationServerApiAccessToken(requestResponseHolder.getRequest())) {\n ServerApiAccessContextToken serverApiAccessContextToken = new ServerApiAccessContextToken(serverApiAccessToken.getTokenName(), serverApiAccessToken.getTokenValue());\n // log.info(\"[ServerApiAccessContextToken]创建成功 -> {}\", serverApiAccessContextToken);\n return new SecurityContextImpl(serverApiAccessContextToken);\n }\n }\n return getSecurityContextRepository().loadContext(requestResponseHolder);\n }\n\n @Override\n public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {\n if (context.getAuthentication() instanceof ServerApiAccessContextToken) {\n // log.info(\"[ServerApiAccessContextToken]不需要持久化保存 -> {}\", context.getAuthentication());\n return;\n }\n getSecurityContextRepository().saveContext(context, request, response);\n }\n\n @Override\n public boolean containsContext(HttpServletRequest request) {\n if (userServerApiAccessToken(request)) {\n if (validationServerApiAccessToken(request)) {\n return true;\n }\n }\n return getSecurityContextRepository().containsContext(request);\n }\n\n private SecurityContextRepository getSecurityContextRepository() {\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n return jwtRedisSecurityContextRepository;\n } else if (LoginModel.session.equals(securityConfig.getLoginModel())) {\n return httpSessionSecurityContextRepository;\n }\n throw new InternalAuthenticationServiceException(\"未知的登入模式\");\n }\n\n /**\n * 验证请求使用的 ServerApiAccessToken\n */\n private boolean validationServerApiAccessToken(HttpServletRequest request) {\n ServerApiAccessToken serverApiAccessToken = securityConfig.getServerApiAccessToken();\n String token = request.getHeader(serverApiAccessToken.getTokenName());\n boolean result = Objects.equals(token, serverApiAccessToken.getTokenValue());\n if (!result) {\n log.warn(\"[ServerApiAccessContextToken]ServerApiAccessToken验证失败 -> {}\", token);\n }\n return result;\n }\n\n /**\n * 是否使用了 ServerApiAccessToken\n */\n private boolean userServerApiAccessToken(HttpServletRequest request) {\n return securityConfig != null\n && securityConfig.getServerApiAccessToken() != null\n && StringUtils.isNotBlank(securityConfig.getServerApiAccessToken().getTokenName())\n && StringUtils.isNotBlank(securityConfig.getServerApiAccessToken().getTokenValue())\n && StringUtils.isNotBlank(request.getHeader(securityConfig.getServerApiAccessToken().getTokenName()));\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/JwtTokenSecurityContextService.java<|end_filename|>\npackage org.clever.security.service.impl;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.entity.*;\nimport org.clever.security.mapper.ServiceSysMapper;\nimport org.clever.security.mapper.UserLoginLogMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.model.UserAuthority;\nimport org.clever.security.service.ISecurityContextService;\nimport org.clever.security.token.SecurityContextToken;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextImpl;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-22 19:51
\n */\n@SuppressWarnings(\"Duplicates\")\n@Transactional(readOnly = true)\n@Service(\"JwtTokenSecurityContextService\")\n@Slf4j\npublic class JwtTokenSecurityContextService implements ISecurityContextService {\n\n /**\n * SecurityContext Key\n */\n private static final String SecurityContextKey = \"security-context\";\n /**\n * JWT Token 令牌Key\n */\n private static final String JwtTokenKey = \"jwt-token\";\n /**\n * JWT Token 刷新令牌Key\n */\n private static final String JwtTokenRefreshKey = \"refresh-token\";\n\n @Autowired\n private ServiceSysMapper serviceSysMapper;\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private UserLoginLogMapper userLoginLogMapper;\n @Autowired\n private RedisTemplate redisTemplate;\n\n /**\n * 生成 Redis 存储 SecurityContextKey\n */\n private String getSecurityContextKey(String redisNamespace, String username) {\n // {redisNamespace}:{SecurityContextKey}:{username}\n return String.format(\"%s:%s:%s\", redisNamespace, SecurityContextKey, username);\n }\n\n /**\n * 生成 Redis 存储 JwtTokenKey Pattern\n */\n private String getJwtTokenPatternKey(String redisNamespace, String username) {\n // {redisNamespace}:{JwtTokenKey}:{username}:{*}\n return String.format(\"%s:%s:%s:%s\", redisNamespace, JwtTokenKey, username, \"*\");\n }\n\n /**\n * 生成 Redis 存储 JwtTokenRefreshKey\n */\n private String getJwtRefreshTokenKey(String redisNamespace, String refreshToken) {\n // {redisNamespace}:{JwtTokenRefreshKey}:{refreshToken}\n return String.format(\"%s:%s:%s\", redisNamespace, JwtTokenRefreshKey, refreshToken);\n }\n\n /**\n * 加载用户安全信息\n *\n * @param loginToken 当前的loginToken\n * @param sysName 系统名\n * @param userName 用户名\n * @return 不存在返回null\n */\n private SecurityContextToken loadUserLoginToken(BaseLoginToken loginToken, String sysName, String userName) {\n // 获取用所有权限\n User user = userMapper.getByUnique(userName);\n if (user == null) {\n return null;\n }\n List permissionList = userMapper.findByUsername(userName, sysName);\n LoginUserDetails userDetails = new LoginUserDetails(user);\n for (Permission permission : permissionList) {\n userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle()));\n }\n // TODO 加载角色\n // userDetails.getRoles().add();\n // 组装 UserLoginToken\n return new SecurityContextToken(loginToken, userDetails);\n }\n\n /**\n * 加载用户安全信息\n *\n * @param newUserLoginToken 新的Token\n * @param oldUserLoginToken 旧的Token\n */\n private SecurityContext loadSecurityContext(SecurityContextToken newUserLoginToken, SecurityContextToken oldUserLoginToken) {\n newUserLoginToken.setDetails(oldUserLoginToken.getDetails());\n newUserLoginToken.eraseCredentials();\n // 组装 SecurityContext\n return new SecurityContextImpl(newUserLoginToken);\n }\n\n @Override\n public Map getSecurityContext(String sysName, String userName) {\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n return null;\n }\n String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userName);\n Object securityObject = redisTemplate.opsForValue().get(securityContextKey);\n if (securityObject == null) {\n return null;\n }\n Map map = new HashMap<>();\n SecurityContext securityContext = null;\n if (securityObject instanceof SecurityContext) {\n securityContext = (SecurityContext) securityObject;\n }\n map.put(sysName, securityContext);\n return map;\n }\n\n @Override\n public SecurityContext getSecurityContext(String tokenId) {\n UserLoginLog userLoginLog = userLoginLogMapper.getBySessionId(tokenId);\n ServiceSys serviceSys = serviceSysMapper.getBySysName(userLoginLog.getSysName());\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n return null;\n }\n String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userLoginLog.getUsername());\n Object securityObject = redisTemplate.opsForValue().get(securityContextKey);\n if (securityObject == null) {\n return null;\n }\n if (securityObject instanceof SecurityContext) {\n return (SecurityContext) securityObject;\n }\n return null;\n }\n\n @Override\n public List reloadSecurityContext(String sysName, String userName) {\n List newSecurityContextList = new ArrayList<>();\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n return null;\n }\n String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userName);\n Object oldSecurityObject = redisTemplate.opsForValue().get(securityContextKey);\n if (!(oldSecurityObject instanceof SecurityContext)) {\n return null;\n }\n SecurityContext oldSecurityContext = (SecurityContext) oldSecurityObject;\n if (!(oldSecurityContext.getAuthentication() instanceof SecurityContextToken)) {\n return null;\n }\n SecurityContextToken oldUserLoginToken = (SecurityContextToken) oldSecurityContext.getAuthentication();\n SecurityContextToken newUserLoginToken = loadUserLoginToken(oldUserLoginToken.getLoginToken(), sysName, userName);\n if (newUserLoginToken == null) {\n return null;\n }\n SecurityContext newSecurityContext = loadSecurityContext(newUserLoginToken, oldUserLoginToken);\n newSecurityContextList.add(newSecurityContext);\n redisTemplate.opsForValue().set(securityContextKey, newSecurityContext);\n // 删除 JwtToken\n String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName);\n Set JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern);\n if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) {\n redisTemplate.delete(JwtTokenKeySet);\n }\n return newSecurityContextList;\n }\n\n @Override\n public Map> reloadSecurityContext(String userName) {\n Map> result = new HashMap<>();\n List sysList = userMapper.findSysByUsername(userName);\n if (sysList == null || sysList.size() <= 0) {\n return result;\n }\n for (ServiceSys serviceSys : sysList) {\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n continue;\n }\n List securityContextList = reloadSecurityContext(serviceSys.getSysName(), userName);\n result.put(serviceSys.getSysName(), securityContextList);\n }\n return result;\n }\n\n @Override\n public int forcedOffline(String sysName, String userName) {\n int count = 0;\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n return 0;\n }\n // 删除 JwtToken\n String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName);\n Set JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern);\n if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) {\n redisTemplate.delete(JwtTokenKeySet);\n count = JwtTokenKeySet.size();\n }\n // 删除 RefreshToken\n String jwtRefreshTokenKeyPattern = getJwtRefreshTokenKey(serviceSys.getRedisNameSpace(), userName + \":*\");\n Set jwtRefreshTokenKeySet = redisTemplate.keys(jwtRefreshTokenKeyPattern);\n if (jwtRefreshTokenKeySet != null && jwtRefreshTokenKeySet.size() > 0) {\n redisTemplate.delete(jwtRefreshTokenKeySet);\n count = jwtRefreshTokenKeySet.size();\n }\n return count;\n }\n\n @Override\n public void delSession(String userName) {\n List sysList = userMapper.findSysByUsername(userName);\n if (sysList == null || sysList.size() <= 0) {\n return;\n }\n for (ServiceSys serviceSys : sysList) {\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n continue;\n }\n delSession(serviceSys.getSysName(), userName);\n }\n }\n\n @Override\n public void delSession(String sysName, String userName) {\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) {\n return;\n }\n // 删除 JwtToken\n String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName);\n Set JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern);\n if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) {\n redisTemplate.delete(JwtTokenKeySet);\n }\n // 删除 RefreshToken\n String jwtRefreshTokenKeyPattern = getJwtRefreshTokenKey(serviceSys.getRedisNameSpace(), userName + \":*\");\n Set jwtRefreshTokenKeySet = redisTemplate.keys(jwtRefreshTokenKeyPattern);\n if (jwtRefreshTokenKeySet != null && jwtRefreshTokenKeySet.size() > 0) {\n redisTemplate.delete(jwtRefreshTokenKeySet);\n }\n }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/ManageByUserClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.UserAddReq;\nimport org.clever.security.dto.response.UserAddRes;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\n\n@FeignClient(\n contextId = \"org.clever.security.client.ManageByUserClient\",\n name = \"clever-security-server\",\n path = \"/api/manage\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface ManageByUserClient {\n\n /**\n * 新增用户\n */\n @PostMapping(\"/user\")\n UserAddRes addUser(@RequestBody UserAddReq userAddReq);\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/UserLoginLogController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.UserLoginLogAddReq;\nimport org.clever.security.dto.request.UserLoginLogUpdateReq;\nimport org.clever.security.entity.UserLoginLog;\nimport org.clever.security.service.UserLoginLogService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 19:21
\n */\n@Api(\"用户登录日志\")\n@RestController\n@RequestMapping(\"/api\")\npublic class UserLoginLogController extends BaseController {\n\n @Autowired\n private UserLoginLogService userLoginLogService;\n\n @ApiOperation(\"新增登录日志\")\n @PostMapping(\"/user_login_log\")\n public UserLoginLog addUserLoginLog(@RequestBody @Validated UserLoginLogAddReq req) {\n UserLoginLog userLoginLog = BeanMapper.mapper(req, UserLoginLog.class);\n return userLoginLogService.addUserLoginLog(userLoginLog);\n }\n\n @ApiOperation(\"根据SessionID查询用户登录日志\")\n @GetMapping(\"/user_login_log/{sessionId}\")\n public UserLoginLog getUserLoginLog(@PathVariable(\"sessionId\") String sessionId) {\n return userLoginLogService.getUserLoginLog(sessionId);\n }\n\n @ApiOperation(\"更新登录日志信息\")\n @PutMapping(\"/user_login_log/{sessionId}\")\n public UserLoginLog updateUserLoginLog(@PathVariable(\"sessionId\") String sessionId, @RequestBody @Validated UserLoginLogUpdateReq req) {\n UserLoginLog update = BeanMapper.mapper(req, UserLoginLog.class);\n return userLoginLogService.updateUserLoginLog(sessionId, update);\n }\n\n}\n\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/UserLoginLogClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.UserLoginLogAddReq;\nimport org.clever.security.dto.request.UserLoginLogUpdateReq;\nimport org.clever.security.entity.UserLoginLog;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 19:25
\n */\n@FeignClient(\n contextId = \"org.clever.security.client.UserLoginLogClient\",\n name = \"clever-security-server\",\n path = \"/api\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface UserLoginLogClient {\n\n /**\n * 新增登录日志\n */\n @PostMapping(\"/user_login_log\")\n UserLoginLog addUserLoginLog(@RequestBody @Validated UserLoginLogAddReq req);\n\n /**\n * 根据SessionID查询用户登录日志\n */\n @GetMapping(\"/user_login_log/{sessionId}\")\n UserLoginLog getUserLoginLog(@PathVariable(\"sessionId\") String sessionId);\n\n /**\n * 更新登录日志信息\n */\n @PutMapping(\"/user_login_log/{sessionId}\")\n UserLoginLog updateUserLoginLog(@PathVariable(\"sessionId\") String sessionId, @RequestBody UserLoginLogUpdateReq req);\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/init/InitSystemUrlPermission.java<|end_filename|>\npackage org.clever.security.init;\n\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.config.SecurityConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.context.event.ContextRefreshedEvent;\nimport org.springframework.stereotype.Component;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * 初始化系统的所有Url权限\n *

\n * 作者: lzw
\n * 创建时间:2018-03-17 11:24
\n */\n@Component\n@Slf4j\npublic class InitSystemUrlPermission implements ApplicationListener {\n\n /**\n * 是否初始化完成\n */\n private boolean initFinish = false;\n private AtomicInteger count = new AtomicInteger(0);\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private InitSystemUrlPermissionJob job;\n\n\n @Override\n public void onApplicationEvent(ContextRefreshedEvent event) {\n int countTmp = count.addAndGet(1);\n if (countTmp < securityConfig.getWaitSpringContextInitCount()) {\n log.info(\"### [系统权限初始化] 等待Spring容器初始化次数 {} \", countTmp);\n return;\n }\n log.info(\"### [系统权限初始化] 当前Spring容器初始化次数 {} \", countTmp);\n if (job == null) {\n log.info(\"### [系统权限初始化] 等待InitSystemUrlPermissionJob注入...\");\n return;\n }\n if (initFinish) {\n log.info(\"### [系统权限初始化] 已经初始化完成,跳过。\");\n return;\n }\n if (StringUtils.isBlank(securityConfig.getSysName())) {\n throw new RuntimeException(\"系统名称未配置\");\n }\n initFinish = job.execute();\n if (initFinish) {\n log.info(\"### [系统权限初始化] 初始化完成!Spring容器初始化次数 {}\", countTmp);\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/ServerApiAccessContextToken.java<|end_filename|>\npackage org.clever.security.token;\n\nimport org.springframework.security.authentication.AbstractAuthenticationToken;\n\nimport java.util.ArrayList;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-05-16 13:55
\n */\npublic class ServerApiAccessContextToken extends AbstractAuthenticationToken {\n\n /**\n * 请求头Token名称\n */\n private String tokenName;\n\n /**\n * 请求头Token值\n */\n private String tokenValue;\n\n /**\n * @param tokenName 请求头Token名称\n * @param tokenValue 请求头Token值\n */\n public ServerApiAccessContextToken(String tokenName, String tokenValue) {\n super(new ArrayList<>());\n this.tokenName = tokenName;\n this.tokenValue = tokenValue;\n super.setAuthenticated(true);\n }\n\n @Override\n public Object getCredentials() {\n return tokenValue;\n }\n\n @Override\n public Object getPrincipal() {\n return tokenName;\n }\n\n @Override\n public String toString() {\n return \"ServerApiAccessContextToken{\" +\n \"tokenName='\" + tokenName + '\\'' +\n \", tokenValue='\" + tokenValue + '\\'' +\n '}';\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/ServiceSys.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 服务系统(ServiceSys)实体类\n *\n * @author lizw\n * @since 2018-10-22 15:22:30\n */\n@Data\npublic class ServiceSys implements Serializable {\n private static final long serialVersionUID = 178234483743559404L;\n /**\n * 主键id\n */\n private Long id;\n\n /**\n * 系统(或服务)名称\n */\n private String sysName;\n\n /**\n * 全局的Session Redis前缀\n */\n private String redisNameSpace;\n\n /**\n * 登录类型,0:sesion-cookie,1:jwt-token\n */\n private Integer loginModel;\n\n /**\n * 说明\n */\n private String description;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n}\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/RememberMeTokenController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.RememberMeTokenAddReq;\nimport org.clever.security.dto.request.RememberMeTokenUpdateReq;\nimport org.clever.security.entity.RememberMeToken;\nimport org.clever.security.service.RememberMeTokenService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 16:36
\n */\n@Api(\"RememberMeToken\")\n@RestController\n@RequestMapping(\"/api\")\npublic class RememberMeTokenController extends BaseController {\n\n @Autowired\n private RememberMeTokenService rememberMeTokenService;\n\n @ApiOperation(\"新增RememberMeToken\")\n @PostMapping(\"/remember_me_token\")\n public RememberMeToken addRememberMeToken(@RequestBody @Validated RememberMeTokenAddReq req) {\n RememberMeToken rememberMeToken = BeanMapper.mapper(req, RememberMeToken.class);\n return rememberMeTokenService.addRememberMeToken(rememberMeToken);\n }\n\n @ApiOperation(\"读取RememberMeToken\")\n @GetMapping(\"/remember_me_token/series\")\n public RememberMeToken getRememberMeToken(@RequestParam(\"series\") String series) {\n return rememberMeTokenService.getRememberMeToken(series);\n }\n\n @ApiOperation(\"删除RememberMeToken\")\n @DeleteMapping(\"/remember_me_token/{username}\")\n public Map delRememberMeToken(@PathVariable(\"username\") String username) {\n Map map = new HashMap<>();\n Integer delCount = rememberMeTokenService.delRememberMeToken(username);\n map.put(\"delCount\", delCount);\n return map;\n }\n\n @ApiOperation(\"修改RememberMeToken\")\n @PutMapping(\"/remember_me_token/series\")\n public RememberMeToken updateRememberMeToken(@RequestParam(\"series\") String series, @RequestBody @Validated RememberMeTokenUpdateReq req) {\n return rememberMeTokenService.updateRememberMeToken(series, req.getToken(), req.getLastUsed());\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/ManageByUserServiceProxy.java<|end_filename|>\npackage org.clever.security.service.local;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.client.ManageByUserClient;\nimport org.clever.security.dto.request.UserAddReq;\nimport org.clever.security.dto.response.UserAddRes;\nimport org.clever.security.entity.User;\nimport org.clever.security.service.ManageByUserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-29 19:08
\n */\n@Component\n@Slf4j\npublic class ManageByUserServiceProxy implements ManageByUserClient {\n\n @Autowired\n private ManageByUserService manageByUserService;\n\n @Override\n public UserAddRes addUser(UserAddReq userAddReq) {\n User user = manageByUserService.addUser(userAddReq);\n return BeanMapper.mapper(user, UserAddRes.class);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/WebPermission.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * web权限表(permission子表)(WebPermission)实体类\n *\n * @author lizw\n * @since 2018-09-16 21:24:44\n */\n@Data\npublic class WebPermission implements Serializable {\n private static final long serialVersionUID = 197256500272108557L;\n /** 主键id */ \n private Long id;\n \n /** 权限标识字符串 */ \n private String permissionStr;\n \n /** controller类名称 */ \n private String targetClass;\n \n /** controller类的方法名称 */ \n private String targetMethod;\n \n /** controller类的方法参数签名 */ \n private String targetMethodParams;\n \n /** 资源url地址(只用作显示使用) */ \n private String resourcesUrl;\n \n /** 需要授权才允许访问,1:需要;2:不需要 */ \n private Integer needAuthorization;\n \n /** controller路由资源是否存在,0:不存在;1:存在 */ \n private Integer targetExist;\n \n /** 创建时间 */ \n private Date createAt;\n \n /** 更新时间 */ \n private Date updateAt;\n \n}\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserInfoRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.Role;\n\nimport java.util.Date;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 22:46
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserInfoRes extends BaseResponse {\n\n @ApiModelProperty(\"主键id\")\n private Long id;\n\n @ApiModelProperty(\"登录名(一条记录的手机号不能当另一条记录的用户名用)\")\n private String username;\n\n @ApiModelProperty(\"用户类型,0:系统内建,1:外部系统用户\")\n private Integer userType;\n\n @ApiModelProperty(\"手机号\")\n private String telephone;\n\n @ApiModelProperty(\"邮箱\")\n private String email;\n\n @ApiModelProperty(\"帐号过期时间\")\n private Date expiredTime;\n\n @ApiModelProperty(\"帐号是否锁定,0:未锁定;1:锁定\")\n private Integer locked;\n\n @ApiModelProperty(\"是否启用,0:禁用;1:启用\")\n private Integer enabled;\n\n @ApiModelProperty(\"说明\")\n private String description;\n\n @ApiModelProperty(\"创建时间\")\n private Date createAt;\n\n @ApiModelProperty(\"更新时间\")\n private Date updateAt;\n\n @ApiModelProperty(\"角色信息\")\n private List roleList;\n\n @ApiModelProperty(\"权限信息\")\n private List permissionList;\n\n @ApiModelProperty(\"授权系统信息\")\n private List sysNameList;\n\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/AesKeyConfig.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\n/**\n * AES对称加密key配置\n * 作者: lzw
\n * 创建时间:2019-04-25 19:03
\n */\n@Data\npublic class AesKeyConfig {\n /**\n * 密码AES加密 key(Hex编码) -- 请求数据,与前端一致\n */\n private String reqPasswordAesKey;\n\n /**\n * 密码AES加密 iv(Hex编码) -- 请求数据,与前端一致\n */\n private String reqPasswordAesIv;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/DelegateSecurityContextService.java<|end_filename|>\npackage org.clever.security.service.impl;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.service.ISecurityContextService;\nimport org.springframework.context.annotation.Primary;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-22 20:08
\n */\n@Primary\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class DelegateSecurityContextService implements ISecurityContextService {\n\n private final List sessionServiceList = new ArrayList<>();\n\n public DelegateSecurityContextService(SessionSecurityContextService cookieSessionService, JwtTokenSecurityContextService JwtTokenSessionService) {\n sessionServiceList.add(cookieSessionService);\n sessionServiceList.add(JwtTokenSessionService);\n }\n\n @Override\n public Map getSecurityContext(String sysName, String userName) {\n Map map = new HashMap<>();\n for (ISecurityContextService sessionService : sessionServiceList) {\n Map tmp = sessionService.getSecurityContext(sysName, userName);\n if (tmp != null) {\n map.putAll(tmp);\n }\n }\n return map;\n }\n\n @Override\n public SecurityContext getSecurityContext(String sessionId) {\n SecurityContext securityContext = null;\n for (ISecurityContextService sessionService : sessionServiceList) {\n SecurityContext tmp = sessionService.getSecurityContext(sessionId);\n if (tmp != null) {\n securityContext = tmp;\n break;\n }\n }\n return securityContext;\n }\n\n @Override\n public List reloadSecurityContext(String sysName, String userName) {\n List securityContextList = new ArrayList<>();\n for (ISecurityContextService sessionService : sessionServiceList) {\n List tmp = sessionService.reloadSecurityContext(sysName, userName);\n if (tmp != null) {\n securityContextList.addAll(tmp);\n }\n }\n return securityContextList;\n }\n\n @Override\n public Map> reloadSecurityContext(String userName) {\n Map> map = new HashMap<>();\n for (ISecurityContextService sessionService : sessionServiceList) {\n Map> tmp = sessionService.reloadSecurityContext(userName);\n if (tmp != null) {\n map.putAll(tmp);\n }\n }\n return map;\n }\n\n @Override\n public int forcedOffline(String sysName, String userName) {\n int count = 0;\n for (ISecurityContextService sessionService : sessionServiceList) {\n int tmp = sessionService.forcedOffline(sysName, userName);\n count += tmp;\n }\n return count;\n }\n\n @Override\n public void delSession(String userName) {\n for (ISecurityContextService sessionService : sessionServiceList) {\n sessionService.delSession(userName);\n }\n }\n\n @Override\n public void delSession(String sysName, String userName) {\n for (ISecurityContextService sessionService : sessionServiceList) {\n sessionService.delSession(sysName, userName);\n }\n }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/RememberMeTokenClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.RememberMeTokenAddReq;\nimport org.clever.security.dto.request.RememberMeTokenUpdateReq;\nimport org.clever.security.entity.RememberMeToken;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 18:45
\n */\n@FeignClient(\n contextId = \"org.clever.security.client.RememberMeTokenClient\",\n name = \"clever-security-server\",\n path = \"/api\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface RememberMeTokenClient {\n\n /**\n * 新增RememberMeToken\n */\n @PostMapping(\"/remember_me_token\")\n RememberMeToken addRememberMeToken(@RequestBody RememberMeTokenAddReq req);\n\n /**\n * 读取RememberMeToken\n */\n @GetMapping(\"/remember_me_token/series\")\n RememberMeToken getRememberMeToken(@RequestParam(\"series\") String series);\n\n /**\n * 删除RememberMeToken\n */\n @DeleteMapping(\"/remember_me_token/{username}\")\n Map delRememberMeToken(@PathVariable(\"username\") String username);\n\n /**\n * 修改RememberMeToken\n */\n @PutMapping(\"/remember_me_token/series\")\n RememberMeToken updateRememberMeToken(@RequestParam(\"series\") String series, @RequestBody RememberMeTokenUpdateReq req);\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/BaseLoginToken.java<|end_filename|>\npackage org.clever.security.token.login;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport lombok.Getter;\nimport lombok.Setter;\nimport org.springframework.security.core.AuthenticatedPrincipal;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.CredentialsContainer;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.userdetails.UserDetails;\n\nimport java.io.Serializable;\nimport java.security.Principal;\nimport java.util.Collection;\n\n/**\n * 用户登录请求参数基础Token\n *

\n * 作者: lzw
\n * 创建时间:2019-04-27 20:46
\n */\n@JsonIgnoreProperties(value = {\"isRememberMe\", \"credentials\", \"authorities\", \"name\"})\npublic abstract class BaseLoginToken implements Authentication, CredentialsContainer, Serializable {\n\n /**\n * 是否使用记住我功能\n */\n @Setter\n @Getter\n private boolean isRememberMe = false;\n\n /**\n * 当前登录类型(用户名密码、手机号验证码、其他三方登录方式)\n */\n @JsonProperty(access = JsonProperty.Access.READ_ONLY)\n @Setter\n @Getter\n private String loginType;\n\n /**\n * 登录请求其他信息(请求IP地址和SessionID,如: WebAuthenticationDetails)\n */\n @Setter\n private Object details;\n\n /**\n * 登录验证码\n */\n @Setter\n @Getter\n private String captcha;\n\n /**\n * 登录验证码签名\n */\n @Setter\n @Getter\n private String captchaDigest;\n\n public BaseLoginToken(String loginType) {\n this.loginType = loginType;\n }\n\n @Override\n public Collection getAuthorities() {\n return null;\n }\n\n /**\n * 没有认证成功只能返回false\n */\n @Override\n public boolean isAuthenticated() {\n return false;\n }\n\n /**\n * 设置当前Token是否认证成功(只能设置false)\n */\n @Override\n public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {\n if (isAuthenticated == this.isAuthenticated()) {\n return;\n }\n if (isAuthenticated) {\n throw new IllegalArgumentException(\"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead\");\n }\n }\n\n /**\n * 返回登录请求其他信息\n */\n @Override\n public Object getDetails() {\n return details;\n }\n\n /**\n * 返回认证用户的唯一ID\n */\n @Override\n public String getName() {\n if (this.getPrincipal() instanceof UserDetails) {\n return ((UserDetails) this.getPrincipal()).getUsername();\n }\n if (this.getPrincipal() instanceof AuthenticatedPrincipal) {\n return ((AuthenticatedPrincipal) this.getPrincipal()).getName();\n }\n if (this.getPrincipal() instanceof Principal) {\n return ((Principal) this.getPrincipal()).getName();\n }\n return (this.getPrincipal() == null) ? \"\" : this.getPrincipal().toString();\n }\n\n /**\n * 擦除密码\n */\n @Override\n public void eraseCredentials() {\n eraseSecret(getCredentials());\n eraseSecret(getPrincipal());\n eraseSecret(details);\n }\n\n private void eraseSecret(Object secret) {\n if (secret instanceof CredentialsContainer) {\n ((CredentialsContainer) secret).eraseCredentials();\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/ServiceSysAddReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.clever.common.validation.ValidIntegerStatus;\nimport org.hibernate.validator.constraints.Length;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-22 20:41
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ServiceSysAddReq extends BaseRequest {\n\n @ApiModelProperty(\"系统(或服务)名称\")\n @NotBlank\n @Length(max = 127)\n private String sysName;\n\n @ApiModelProperty(\"全局的Session Redis前缀\")\n @NotBlank\n @Length(max = 127)\n private String redisNameSpace;\n\n @ApiModelProperty(\"登录类型,0:sesion-cookie,1:jwt-token\")\n @NotNull\n @ValidIntegerStatus({0, 1})\n private Integer loginModel;\n\n @ApiModelProperty(\"说明\")\n @Length(max = 511)\n private String description;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/CurrentLoginUserController.java<|end_filename|>\npackage org.clever.security.embed.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.dto.response.UserRes;\nimport org.clever.security.utils.AuthenticationUtils;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-12 17:03
\n */\n@Api(\"当前登录用户信息\")\n@RestController\n@Slf4j\npublic class CurrentLoginUserController {\n\n @ApiOperation(\"获取当前登录用户信息\")\n @GetMapping(\"/login/user_info.json\")\n public UserRes currentLoginUser() {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n return AuthenticationUtils.getUserRes(authentication);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/RequestCryptoService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.common.utils.codec.CryptoUtils;\nimport org.clever.common.utils.codec.EncodeDecodeUtils;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.config.model.AesKeyConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.BadCredentialsException;\nimport org.springframework.stereotype.Component;\n\n/**\n * 请求参数加密/解密\n *

\n * 作者: lzw
\n * 创建时间:2018-11-01 10:42
\n */\n@Component\n@Slf4j\npublic class RequestCryptoService {\n\n @Autowired\n private SecurityConfig securityConfig;\n\n /**\n * 登录密码 AES 加密\n *\n * @return Base64编码密码\n */\n @SuppressWarnings(\"Duplicates\")\n public String reqAesEncrypt(String input) {\n try {\n AesKeyConfig aesKey = securityConfig.getLoginReqAesKey();\n if (aesKey == null) {\n throw new BusinessException(\"请先配置登录密码AesKey\");\n }\n byte[] passwordData = input.getBytes();\n byte[] key = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesKey());\n byte[] iv = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesIv());\n return EncodeDecodeUtils.encodeBase64(CryptoUtils.aesEncrypt(passwordData, key, iv));\n } catch (Exception e) {\n throw new BadCredentialsException(\"请求密码加密失败\");\n }\n }\n\n /**\n * 登录密码 AES 解密\n *\n * @param input Base64编码密码\n */\n @SuppressWarnings(\"Duplicates\")\n public String reqAesDecrypt(String input) {\n try {\n AesKeyConfig aesKey = securityConfig.getLoginReqAesKey();\n if (aesKey == null) {\n throw new BusinessException(\"请先配置登录密码AesKey\");\n }\n byte[] passwordData = EncodeDecodeUtils.decodeBase64(input);\n byte[] key = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesKey());\n byte[] iv = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesIv());\n return CryptoUtils.aesDecrypt(passwordData, key, iv);\n } catch (Exception e) {\n throw new BadCredentialsException(\"请求密码解密失败\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserRoleReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\n\nimport javax.validation.constraints.NotBlank;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-04 13:26
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserRoleReq extends BaseRequest {\n\n @ApiModelProperty(\"用户名\")\n @NotBlank\n private String username;\n\n @ApiModelProperty(\"角色名\")\n @NotBlank\n private String roleName;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageBySecurityService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.dto.request.*;\nimport org.clever.security.dto.response.RoleBindPermissionRes;\nimport org.clever.security.dto.response.UserBindRoleRes;\nimport org.clever.security.dto.response.UserBindSysRes;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.Role;\nimport org.clever.security.entity.User;\nimport org.clever.security.mapper.RoleMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.service.internal.ReLoadSessionService;\nimport org.clever.security.service.internal.RoleBindPermissionService;\nimport org.clever.security.service.internal.UserBindRoleService;\nimport org.clever.security.service.internal.UserBindSysNameService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 21:24
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class ManageBySecurityService {\n\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private RoleMapper roleMapper;\n @Autowired\n private UserBindSysNameService userBindSysNameService;\n @Autowired\n private UserBindRoleService userBindRoleService;\n @Autowired\n private RoleBindPermissionService resetRoleBindPermission;\n @Autowired\n private ManageByQueryService manageByQueryService;\n @Autowired\n private ISecurityContextService sessionService;\n @Autowired\n private ReLoadSessionService reLoadSessionService;\n\n @Transactional\n public List userBindSys(UserBindSysReq userBindSysReq) {\n // 校验用户全部存在\n for (String username : userBindSysReq.getUsernameList()) {\n int count = userMapper.existsByUserName(username);\n if (count <= 0) {\n throw new BusinessException(\"用户[\" + username + \"]不存在\");\n }\n }\n // 校验系统全部存在\n List allSysName = manageByQueryService.allSysName();\n for (String sysName : userBindSysReq.getSysNameList()) {\n if (!allSysName.contains(sysName)) {\n throw new BusinessException(\"系统[\" + sysName + \"]不存在\");\n }\n }\n List result = new ArrayList<>();\n // 设置用户绑定的系统\n for (String username : userBindSysReq.getUsernameList()) {\n userBindSysNameService.resetUserBindSys(username, userBindSysReq.getSysNameList());\n List sysNameList = userMapper.findSysNameByUsername(username);\n UserBindSysRes userBindSysRes = new UserBindSysRes();\n userBindSysRes.setUsername(username);\n userBindSysRes.setSysNameList(sysNameList);\n result.add(userBindSysRes);\n }\n return result;\n }\n\n @Transactional\n public List userBindRole(UserBindRoleReq userBindSysReq) {\n // 校验用户全部存在\n for (String username : userBindSysReq.getUsernameList()) {\n int count = userMapper.existsByUserName(username);\n if (count <= 0) {\n throw new BusinessException(\"用户[\" + username + \"]不存在\");\n }\n }\n List result = new ArrayList<>();\n // 设置用户绑定的系统\n for (String username : userBindSysReq.getUsernameList()) {\n userBindRoleService.resetUserBindRole(username, userBindSysReq.getRoleNameList());\n List roleList = userMapper.findRoleByUsername(username);\n UserBindRoleRes userBindRoleRes = new UserBindRoleRes();\n userBindRoleRes.setUsername(username);\n userBindRoleRes.setRoleList(roleList);\n result.add(userBindRoleRes);\n }\n return result;\n }\n\n @Transactional\n public List roleBindPermission(RoleBindPermissionReq roleBindPermissionReq) {\n // 校验角色全部存在\n for (String roleName : roleBindPermissionReq.getRoleNameList()) {\n int count = roleMapper.existsByRole(roleName);\n if (count <= 0) {\n throw new BusinessException(\"角色[\" + roleName + \"]不存在\");\n }\n }\n List result = new ArrayList<>();\n // 设置用户绑定的系统\n for (String roleName : roleBindPermissionReq.getRoleNameList()) {\n resetRoleBindPermission.resetRoleBindPermission(roleName, roleBindPermissionReq.getPermissionStrList());\n List permissionList = roleMapper.findPermissionByRoleName(roleName);\n RoleBindPermissionRes roleBindPermissionRes = new RoleBindPermissionRes();\n roleBindPermissionRes.setRoleName(roleName);\n roleBindPermissionRes.setPermissionList(permissionList);\n result.add(roleBindPermissionRes);\n }\n return result;\n }\n\n @SuppressWarnings(\"Duplicates\")\n @Transactional\n public UserBindSysRes userBindSys(UserSysReq userSysReq) {\n // 校验用户存在\n User user = userMapper.getByUsername(userSysReq.getUsername());\n if (user == null) {\n throw new BusinessException(\"用户[\" + userSysReq.getUsername() + \"]不存在\");\n }\n // 校验系统存在\n List allSysName = manageByQueryService.allSysName();\n if (!allSysName.contains(userSysReq.getSysName())) {\n throw new BusinessException(\"系统[\" + userSysReq.getSysName() + \"]不存在\");\n }\n userMapper.addUserSys(userSysReq.getUsername(), userSysReq.getSysName());\n UserBindSysRes userBindSysRes = new UserBindSysRes();\n userBindSysRes.setUsername(user.getUsername());\n userBindSysRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername()));\n return userBindSysRes;\n }\n\n @SuppressWarnings(\"Duplicates\")\n @Transactional\n public UserBindSysRes userUnBindSys(UserSysReq userSysReq) {\n // 校验用户存在\n User user = userMapper.getByUsername(userSysReq.getUsername());\n if (user == null) {\n throw new BusinessException(\"用户[\" + userSysReq.getUsername() + \"]不存在\");\n }\n // 校验系统存在\n List allSysName = manageByQueryService.allSysName();\n if (!allSysName.contains(userSysReq.getSysName())) {\n throw new BusinessException(\"系统[\" + userSysReq.getSysName() + \"]不存在\");\n }\n userMapper.delUserSys(userSysReq.getUsername(), userSysReq.getSysName());\n // 删除 Session\n sessionService.delSession(userSysReq.getSysName(), userSysReq.getUsername());\n // 构造返回数据\n UserBindSysRes userBindSysRes = new UserBindSysRes();\n userBindSysRes.setUsername(user.getUsername());\n userBindSysRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername()));\n return userBindSysRes;\n }\n\n @Transactional\n public UserBindRoleRes userBindRole(UserRoleReq userRoleReq) {\n int count = userMapper.existsUserRole(userRoleReq.getUsername(), userRoleReq.getRoleName());\n if (count >= 1) {\n throw new BusinessException(\"用户[\" + userRoleReq.getUsername() + \"]已经拥有角色[\" + userRoleReq.getRoleName() + \"]\");\n }\n userMapper.addRole(userRoleReq.getUsername(), userRoleReq.getRoleName());\n // 更新Session\n sessionService.reloadSecurityContext(userRoleReq.getUsername());\n // 构造返回数据\n UserBindRoleRes res = new UserBindRoleRes();\n res.setUsername(userRoleReq.getUsername());\n res.setRoleList(userMapper.findRoleByUsername(userRoleReq.getUsername()));\n return res;\n }\n\n @Transactional\n public UserBindRoleRes userUnBindRole(UserRoleReq userRoleReq) {\n int count = userMapper.existsUserRole(userRoleReq.getUsername(), userRoleReq.getRoleName());\n if (count <= 0) {\n throw new BusinessException(\"用户[\" + userRoleReq.getUsername() + \"]未拥有角色[\" + userRoleReq.getRoleName() + \"]\");\n }\n userMapper.delRole(userRoleReq.getUsername(), userRoleReq.getRoleName());\n // 更新Session\n sessionService.reloadSecurityContext(userRoleReq.getUsername());\n // 构造返回数据\n UserBindRoleRes res = new UserBindRoleRes();\n res.setUsername(userRoleReq.getUsername());\n res.setRoleList(userMapper.findRoleByUsername(userRoleReq.getUsername()));\n return res;\n }\n\n @Transactional\n public RoleBindPermissionRes roleBindPermission(RolePermissionReq rolePermissionReq) {\n int count = roleMapper.existsRolePermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr());\n if (count >= 1) {\n throw new BusinessException(\"角色[\" + rolePermissionReq.getRoleName() + \"]已经拥有权限[\" + rolePermissionReq.getPermissionStr() + \"]\");\n }\n roleMapper.addPermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr());\n // 计算受影响的用户 更新Session\n reLoadSessionService.onChangeRole(rolePermissionReq.getRoleName());\n // 构造返回数据\n RoleBindPermissionRes res = new RoleBindPermissionRes();\n res.setRoleName(rolePermissionReq.getRoleName());\n res.setPermissionList(roleMapper.findPermissionByRoleName(rolePermissionReq.getRoleName()));\n return res;\n }\n\n @Transactional\n public RoleBindPermissionRes roleUnBindPermission(RolePermissionReq rolePermissionReq) {\n int count = roleMapper.existsRolePermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr());\n if (count <= 0) {\n throw new BusinessException(\"角色[\" + rolePermissionReq.getRoleName() + \"]未拥有权限[\" + rolePermissionReq.getPermissionStr() + \"]\");\n }\n roleMapper.delPermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr());\n // 计算受影响的用户 更新Session\n reLoadSessionService.onChangeRole(rolePermissionReq.getRoleName());\n // 构造返回数据\n RoleBindPermissionRes res = new RoleBindPermissionRes();\n res.setRoleName(rolePermissionReq.getRoleName());\n res.setPermissionList(roleMapper.findPermissionByRoleName(rolePermissionReq.getRoleName()));\n return res;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/ConcurrentLoginException.java<|end_filename|>\npackage org.clever.security.exception;\n\nimport org.springframework.security.core.AuthenticationException;\n\n/**\n * 并发登录异常\n *

\n * 作者: lzw
\n * 创建时间:2018-11-19 20:41
\n */\npublic class ConcurrentLoginException extends AuthenticationException {\n public ConcurrentLoginException(String msg) {\n super(msg);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/User.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 用户表(User)实体类\n *\n * @author lizw\n * @since 2018-09-16 21:24:44\n */\n@Data\npublic class User implements Serializable {\n private static final long serialVersionUID = -73828129880873228L;\n /**\n * 主键id\n */\n private Long id;\n\n /**\n * 登录名(一条记录的手机号不能当另一条记录的用户名用)\n */\n private String username;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 用户类型,0:系统内建,1:外部系统用户\n */\n private Integer userType;\n\n /**\n * 手机号\n */\n private String telephone;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * 帐号过期时间\n */\n private Date expiredTime;\n\n /**\n * 帐号是否锁定,0:未锁定;1:锁定\n */\n private Integer locked;\n\n /**\n * 是否启用,0:禁用;1:启用\n */\n private Integer enabled;\n\n /**\n * 说明\n */\n private String description;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n\n}\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/SessionSecurityContextService.java<|end_filename|>\npackage org.clever.security.service.impl;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.security.entity.*;\nimport org.clever.security.mapper.RememberMeTokenMapper;\nimport org.clever.security.mapper.ServiceSysMapper;\nimport org.clever.security.mapper.UserLoginLogMapper;\nimport org.clever.security.mapper.UserMapper;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.model.UserAuthority;\nimport org.clever.security.service.ISecurityContextService;\nimport org.clever.security.token.SecurityContextToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextImpl;\nimport org.springframework.session.FindByIndexNameSessionRepository;\nimport org.springframework.session.data.redis.RedisOperationsSessionRepository;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-22 19:33
\n */\n@SuppressWarnings(\"Duplicates\")\n@Transactional(readOnly = true)\n@Service(\"sessionSecurityContextService\")\n@Slf4j\npublic class SessionSecurityContextService implements ISecurityContextService {\n\n private static final String SPRING_SECURITY_CONTEXT = \"sessionAttr:SPRING_SECURITY_CONTEXT\";\n\n @Autowired\n private ServiceSysMapper serviceSysMapper;\n @Autowired\n private UserMapper userMapper;\n @Autowired\n private UserLoginLogMapper userLoginLogMapper;\n @Autowired\n private RememberMeTokenMapper rememberMeTokenMapper;\n @Autowired\n private RedisOperationsSessionRepository sessionRepository;\n\n /**\n * 参考 RedisOperationsSessionRepository#getPrincipalKey\n */\n private String getPrincipalKey(String redisNameSpace, String userName) {\n // {redisNameSpace}:{index}:{PRINCIPAL_NAME_INDEX_NAME}:{userName}\n // spring:session:clever-security:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:lizw\n return redisNameSpace + \":index:\" + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + \":\" + userName;\n }\n\n /**\n * 获取SessionKey\n */\n private String getSessionKey(String redisNameSpace, String sessionId) {\n // {redisNameSpace}:{sessions}:{sessionId}\n // spring:session:clever-security:sessions:962e63c3-4e2e-4089-94f1-02a9137661b4\n return redisNameSpace + \":sessions:\" + sessionId;\n }\n\n private LoginUserDetails loadUserLoginToken(String sysName, String userName) {\n // 获取用所有权限\n User user = userMapper.getByUnique(userName);\n if (user == null) {\n return null;\n }\n List permissionList = userMapper.findByUsername(userName, sysName);\n LoginUserDetails userDetails = new LoginUserDetails(user);\n for (Permission permission : permissionList) {\n userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle()));\n }\n // TODO 加载角色\n // userDetails.getRoles().add();\n return userDetails;\n }\n\n// /**\n// * 加载用户安全信息\n// *\n// * @param sysName 系统名\n// * @param userName 用户名\n// * @return 不存在返回null\n// */\n// private SecurityContextToken loadUserLoginToken(BaseLoginToken loginToken, String sysName, String userName) {\n// // 获取用所有权限\n// User user = userMapper.getByUnique(userName);\n// if (user == null) {\n// return null;\n// }\n// List permissionList = userMapper.findByUsername(userName, sysName);\n// LoginUserDetails userDetails = new LoginUserDetails(user);\n// for (Permission permission : permissionList) {\n// userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle()));\n// }\n// // TODO 加载角色\n// // userDetails.getRoles().add();\n// // 组装 UserLoginToken\n// return new SecurityContextToken(loginToken, userDetails);\n// }\n\n /**\n * 加载用户安全信息\n *\n * @param newUserLoginToken 新的Token\n * @param oldUserLoginToken 旧的Token\n */\n private SecurityContext loadSecurityContext(SecurityContextToken newUserLoginToken, SecurityContextToken oldUserLoginToken) {\n newUserLoginToken.setDetails(oldUserLoginToken.getDetails());\n newUserLoginToken.eraseCredentials();\n // 组装 SecurityContext\n return new SecurityContextImpl(newUserLoginToken);\n }\n\n @Override\n public Map getSecurityContext(String sysName, String userName) {\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n return null;\n }\n String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName);\n Set sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members();\n if (sessionIds == null) {\n return null;\n }\n Map map = new HashMap<>();\n for (Object sessionId : sessionIds) {\n if (sessionId == null || StringUtils.isBlank(sessionId.toString())) {\n continue;\n }\n String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId.toString());\n Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT);\n SecurityContext securityContext = null;\n if (securityObject instanceof SecurityContext) {\n securityContext = (SecurityContext) securityObject;\n }\n map.put(sessionId.toString(), securityContext);\n }\n return map;\n }\n\n @Override\n public SecurityContext getSecurityContext(String sessionId) {\n if (sessionId == null || StringUtils.isBlank(sessionId)) {\n return null;\n }\n UserLoginLog userLoginLog = userLoginLogMapper.getBySessionId(sessionId);\n if (userLoginLog == null || StringUtils.isBlank(userLoginLog.getSysName())) {\n return null;\n }\n ServiceSys serviceSys = serviceSysMapper.getBySysName(userLoginLog.getSysName());\n if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace())) {\n return null;\n }\n String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId);\n Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT);\n if (securityObject instanceof SecurityContext) {\n return (SecurityContext) securityObject;\n }\n return null;\n }\n\n @Override\n public List reloadSecurityContext(String sysName, String userName) {\n List newSecurityContextList = new ArrayList<>();\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n return null;\n }\n String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName);\n Set sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members();\n if (sessionIds == null) {\n return null;\n }\n LoginUserDetails loginUserDetails = null;\n for (Object sessionId : sessionIds) {\n if (sessionId == null || StringUtils.isBlank(sessionId.toString())) {\n continue;\n }\n String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId.toString());\n Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT);\n if (!(securityObject instanceof SecurityContext)) {\n log.error(\"重新加载SecurityContext失败, SecurityContext类型错误,{}\", securityObject == null ? \"null\" : securityObject.getClass());\n continue;\n }\n SecurityContext oldSecurityContext = (SecurityContext) securityObject;\n if (!(oldSecurityContext.getAuthentication() instanceof SecurityContextToken)) {\n log.error(\"重新加载SecurityContext失败, Authentication类型错误,{}\", oldSecurityContext.getAuthentication().getClass());\n continue;\n }\n SecurityContextToken oldUserLoginToken = (SecurityContextToken) oldSecurityContext.getAuthentication();\n if (loginUserDetails == null) {\n loginUserDetails = loadUserLoginToken(sysName, userName);\n if (loginUserDetails == null) {\n return null;\n }\n }\n SecurityContextToken newUserLoginToken = new SecurityContextToken(oldUserLoginToken.getLoginToken(), loginUserDetails);\n SecurityContext newSecurityContext = loadSecurityContext(newUserLoginToken, oldUserLoginToken);\n sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).put(SPRING_SECURITY_CONTEXT, newSecurityContext);\n newSecurityContextList.add(newSecurityContext);\n }\n return newSecurityContextList;\n }\n\n @Override\n public Map> reloadSecurityContext(String userName) {\n Map> result = new HashMap<>();\n List sysList = userMapper.findSysByUsername(userName);\n if (sysList == null || sysList.size() <= 0) {\n return result;\n }\n for (ServiceSys serviceSys : sysList) {\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n return null;\n }\n List securityContextList = reloadSecurityContext(serviceSys.getSysName(), userName);\n result.put(serviceSys.getSysName(), securityContextList);\n }\n return result;\n }\n\n @Transactional\n @Override\n public int forcedOffline(String sysName, String userName) {\n int count = 0;\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n return 0;\n }\n String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName);\n Set sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members();\n if (sessionIds == null) {\n return 0;\n }\n // 删除 RememberMe Token\n rememberMeTokenMapper.deleteBySysNameAndUsername(sysName, userName);\n // 删除Session\n for (Object sessionId : sessionIds) {\n if (sessionId == null || StringUtils.isBlank(sessionId.toString())) {\n continue;\n }\n count++;\n sessionRepository.deleteById(sessionId.toString());\n }\n return count;\n }\n\n @Override\n public void delSession(String userName) {\n List sysList = userMapper.findSysByUsername(userName);\n if (sysList == null || sysList.size() <= 0) {\n return;\n }\n for (ServiceSys serviceSys : sysList) {\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n continue;\n }\n delSession(serviceSys.getSysName(), userName);\n }\n }\n\n @Override\n public void delSession(String sysName, String userName) {\n ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName);\n if (serviceSys == null\n || StringUtils.isBlank(serviceSys.getRedisNameSpace())\n || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) {\n return;\n }\n String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName);\n Set sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members();\n if (sessionIds == null) {\n return;\n }\n for (Object sessionId : sessionIds) {\n if (sessionId == null || StringUtils.isBlank(sessionId.toString())) {\n continue;\n }\n sessionRepository.deleteById(sessionId.toString());\n }\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/init/InitSystemUrlPermissionJob.java<|end_filename|>\npackage org.clever.security.init;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.utils.GlobalJob;\nimport org.clever.common.utils.IDCreateUtils;\nimport org.clever.common.utils.reflection.ReflectionsUtils;\nimport org.clever.security.LoginModel;\nimport org.clever.security.annotation.UrlAuthorization;\nimport org.clever.security.client.ServiceSysClient;\nimport org.clever.security.client.WebPermissionClient;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.ServiceSysAddReq;\nimport org.clever.security.dto.request.WebPermissionInitReq;\nimport org.clever.security.dto.response.WebPermissionInitRes;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.ServiceSys;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.method.HandlerMethod;\nimport org.springframework.web.servlet.mvc.method.RequestMappingInfo;\nimport org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;\n\nimport java.lang.reflect.Method;\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-11 14:42
\n */\n@Component\n@Slf4j\npublic class InitSystemUrlPermissionJob extends GlobalJob {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private RequestMappingHandlerMapping handlerMapping;\n @Autowired(required = false)\n private RedisHttpSessionConfiguration redisHttpSessionConfiguration;\n @Autowired\n private ServiceSysClient serviceSysClient;\n @Autowired\n private WebPermissionClient webPermissionClient;\n\n @Override\n protected void exceptionHandle(Throwable e) {\n log.info(\"### [系统权限初始化] 初始化系统的所有Url权限异常\", e);\n // throw ExceptionUtils.unchecked(e);\n }\n\n @Override\n protected void internalExecute() {\n log.info(\"### [系统权限初始化] 开始初始化...\");\n // 注册系统信息\n ServiceSysAddReq serviceSysAddReq = new ServiceSysAddReq();\n serviceSysAddReq.setSysName(securityConfig.getSysName());\n if (LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n // JwtToken\n serviceSysAddReq.setRedisNameSpace(securityConfig.getTokenConfig().getRedisNamespace());\n serviceSysAddReq.setLoginModel(EnumConstant.ServiceSys_LoginModel_1);\n } else if (LoginModel.session.equals(securityConfig.getLoginModel())) {\n // Session\n serviceSysAddReq.setRedisNameSpace(ReflectionsUtils.getFieldValue(redisHttpSessionConfiguration, \"redisNamespace\").toString());\n serviceSysAddReq.setLoginModel(EnumConstant.ServiceSys_LoginModel_0);\n } else {\n throw new IllegalArgumentException(\"配置项[loginModel - 登入模式]必须指定\");\n }\n ServiceSys serviceSys = serviceSysClient.registerSys(serviceSysAddReq);\n log.info(\"### 注册系统成功: {}\", serviceSys);\n // 获取系统中所有的资源,并排序 - allPermission\n List allPermission = new ArrayList<>();\n Map handlerMap = handlerMapping.getHandlerMethods();\n for (Map.Entry entry : handlerMap.entrySet()) {\n RequestMappingInfo requestMappingInfo = entry.getKey();\n HandlerMethod handlerMethod = entry.getValue();\n // 获取URL路由信息\n allPermission.add(newPermissions(requestMappingInfo, handlerMethod));\n }\n Collections.sort(allPermission);\n // 初始化某个系统的所有Web权限\n WebPermissionInitReq req = new WebPermissionInitReq();\n req.setAllPermission(allPermission);\n WebPermissionInitRes res = webPermissionClient.initWebPermission(securityConfig.getSysName(), req);\n // 打印相应的日志\n if (log.isInfoEnabled()) {\n StringBuilder strTmp = new StringBuilder();\n strTmp.append(\"\\r\\n\");\n strTmp.append(\"#=======================================================================================================================#\\r\\n\");\n strTmp\n .append(\"# 系统注册信息:\").append(serviceSys.toString()).append(\"\\n\")\n .append(\"# 新增的权限配置如下(\")\n .append(res.getAddPermission().size())\n .append(\"条):\")\n .append(\"\\t\\t---> \")\n .append(securityConfig.getDefaultNeedAuthorization() ? \"需要授权\" : \"不需要授权\")\n .append(\"\\r\\n\");\n for (WebPermissionModel permission : res.getAddPermission()) {\n strTmp.append(\"#\\t \").append(getPermissionStr(permission)).append(\"\\r\\n\");\n }\n strTmp.append(\"# 数据库里无效的权限配置(\").append(res.getNotExistPermission().size()).append(\"条):\\r\\n\");\n for (WebPermissionModel permission : res.getNotExistPermission()) {\n strTmp.append(\"#\\t \").append(getPermissionStr(permission)).append(\"\\r\\n\");\n }\n strTmp.append(\"#=======================================================================================================================#\");\n log.info(strTmp.toString());\n }\n }\n\n /**\n * 打印权限配置信息字符串\n */\n private String getPermissionStr(WebPermissionModel permission) {\n return String.format(\"| %1$s | [%2$s] [%3$s#%4$s] -> [%5$s]\",\n permission.getSysName(),\n permission.getTitle(),\n permission.getTargetClass(),\n permission.getTargetMethod(),\n permission.getResourcesUrl());\n }\n\n /**\n * 创建一个 Permission\n */\n @SuppressWarnings(\"deprecation\")\n private WebPermissionModel newPermissions(RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) {\n // 提取MVC路由信息\n Class beanType = handlerMethod.getBeanType();\n Method method = handlerMethod.getMethod();\n // 获取标题\n String titlePrefix = beanType.getSimpleName();\n String titleSuffix = method.getName();\n UrlAuthorization urlAuthorizationForClass = beanType.getAnnotation(UrlAuthorization.class);\n Api api = beanType.getAnnotation(Api.class);\n if (urlAuthorizationForClass != null && StringUtils.isNotBlank(urlAuthorizationForClass.title())) {\n titlePrefix = urlAuthorizationForClass.title();\n } else if (api != null && (StringUtils.isNotBlank(api.value()) || StringUtils.isNotBlank(api.description()))) {\n titlePrefix = StringUtils.isNotBlank(api.value()) ? api.value() : api.description();\n }\n UrlAuthorization urlAuthorizationForMethod = handlerMethod.getMethodAnnotation(UrlAuthorization.class);\n ApiOperation apiOperation = handlerMethod.getMethodAnnotation(ApiOperation.class);\n if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.title())) {\n titleSuffix = urlAuthorizationForMethod.title();\n } else if (apiOperation != null && StringUtils.isNotBlank(apiOperation.value())) {\n titleSuffix = apiOperation.value();\n }\n String title = String.format(\"[%1$s]-%2$s\", titlePrefix, titleSuffix);\n // 获取资源说明\n String description = \"系统自动生成的权限配置\";\n if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.description())) {\n description = urlAuthorizationForMethod.description();\n } else if (apiOperation != null && StringUtils.isNotBlank(apiOperation.notes())) {\n description = apiOperation.notes();\n }\n // 获取资源字符串\n String permissionStr = \"[auto]:\" + IDCreateUtils.shortUuid();\n String permissionStrPrefix = \"\";\n if (urlAuthorizationForClass != null && StringUtils.isNotBlank(urlAuthorizationForClass.permissionStr())) {\n permissionStrPrefix = urlAuthorizationForClass.permissionStr();\n }\n if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.permissionStr())) {\n if (StringUtils.isBlank(permissionStrPrefix)) {\n permissionStr = urlAuthorizationForMethod.permissionStr();\n } else {\n permissionStr = String.format(\"[%1$s]%2$s\", permissionStrPrefix, urlAuthorizationForMethod.permissionStr());\n }\n }\n // 获取方法参数签名\n StringBuilder methodParams = new StringBuilder();\n Class[] paramTypes = method.getParameterTypes();\n for (Class clzz : paramTypes) {\n if (methodParams.length() > 0) {\n methodParams.append(\", \");\n }\n methodParams.append(clzz.getName());\n }\n // 请求Url\n StringBuilder resourcesUrl = new StringBuilder();\n Set urlArray = requestMappingInfo.getPatternsCondition().getPatterns();\n for (String url : urlArray) {\n if (resourcesUrl.length() > 0) {\n resourcesUrl.append(\" | \");\n }\n resourcesUrl.append(url);\n }\n // 构建权限信息\n WebPermissionModel permission = new WebPermissionModel();\n permission.setSysName(securityConfig.getSysName());\n permission.setPermissionStr(permissionStr);\n if (securityConfig.getDefaultNeedAuthorization() != null && securityConfig.getDefaultNeedAuthorization()) {\n permission.setNeedAuthorization(EnumConstant.Permission_NeedAuthorization_1);\n } else {\n permission.setNeedAuthorization(EnumConstant.Permission_NeedAuthorization_2);\n }\n permission.setResourcesType(EnumConstant.Permission_ResourcesType_1);\n permission.setTitle(title);\n permission.setTargetClass(beanType.getName());\n permission.setTargetMethod(method.getName());\n permission.setTargetMethodParams(methodParams.toString());\n permission.setResourcesUrl(resourcesUrl.toString());\n permission.setTargetExist(EnumConstant.WebPermission_targetExist_1);\n permission.setDescription(description);\n permission.setCreateAt(new Date());\n return permission;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/SecurityConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.Data;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.config.model.*;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.context.properties.NestedConfigurationProperty;\nimport org.springframework.stereotype.Component;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-15 14:31
\n */\n@ConfigurationProperties(prefix = Constant.ConfigPrefix)\n@Component\n@Data\npublic class SecurityConfig {\n\n /**\n * 登入模式\n */\n private LoginModel loginModel = LoginModel.jwt;\n\n /**\n * 启用Spring Security调试功能\n */\n private Boolean enableDebug = false;\n /**\n * 系统名称\n */\n private String sysName;\n /**\n * 等待spring容器初始化次数(用于系统启动之后初始化系统权限)\n */\n private Integer waitSpringContextInitCount = 0;\n /**\n * 是否需要控制Web资源权限,默认true(true 需要;false 不要)\n */\n private Boolean defaultNeedAuthorization = true;\n /**\n * 不需要认证的URL\n */\n private List ignoreUrls = new ArrayList<>();\n /**\n * 不需要授权的URL\n */\n private List ignoreAuthorizationUrls = new ArrayList<>();\n /**\n * 隐藏登录用户找不到的异常\n */\n private Boolean hideUserNotFoundExceptions = true;\n /**\n * 未登录时是否需要跳转\n */\n private Boolean notLoginNeedForward = false;\n /**\n * 无权访问时是否需要跳转\n */\n private Boolean forbiddenNeedForward = false;\n /**\n * 无权访问时跳转页面(请求转发)\n */\n private String forbiddenForwardPage = \"/403.html\";\n\n /**\n * Session 过期需要跳转的地址,值为空就不跳转\n */\n private String sessionExpiredRedirectUrl = \"/index.html\";\n\n // ----------------------------------------------------------------------------------------\n\n /**\n * 用户登录相关配置\n */\n @NestedConfigurationProperty\n private final LoginConfig login = new LoginConfig();\n /**\n * 用户登出相关配置\n */\n @NestedConfigurationProperty\n private final LogoutConfig logout = new LogoutConfig();\n /**\n * 用户登录请求参数加密配置 Aes Key\n */\n @NestedConfigurationProperty\n private final AesKeyConfig loginReqAesKey = new AesKeyConfig();\n /**\n * \"记住我\"相关配置\n */\n @NestedConfigurationProperty\n private final RememberMeConfig rememberMe = new RememberMeConfig();\n /**\n * token配置(只有JWT Token有效)\n */\n @NestedConfigurationProperty\n private final TokenConfig tokenConfig = new TokenConfig();\n\n /**\n * 服务间免登陆Token访问配置\n */\n @NestedConfigurationProperty\n private ServerApiAccessToken serverApiAccessToken = new ServerApiAccessToken();\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/UserRememberMeToken.java<|end_filename|>\npackage org.clever.security.entity.model;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-21 21:59
\n */\n@Data\npublic class UserRememberMeToken implements Serializable {\n\n /**\n * 主键id\n */\n private Long id;\n\n /**\n * 系统(或服务)名称\n */\n private String sysName;\n\n /**\n * token序列号\n */\n private String series;\n\n /**\n * 用户登录名\n */\n private String username;\n\n /**\n * token数据\n */\n private String token;\n\n /**\n * 最后使用时间\n */\n private Date lastUsed;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n\n // ----------------------------------------------------------------------------- User\n\n /**\n * 主键id\n */\n private Long userId;\n\n /**\n * 用户类型,0:系统内建,1:外部系统用户\n */\n private Integer userType;\n\n /**\n * 手机号\n */\n private String telephone;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * 帐号过期时间\n */\n private Date expiredTime;\n\n /**\n * 帐号是否锁定,0:未锁定;1:锁定\n */\n private Integer locked;\n\n /**\n * 是否启用,0:禁用;1:启用\n */\n private Integer enabled;\n\n /**\n * 说明\n */\n private String description;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/RememberMeToken.java<|end_filename|>\npackage org.clever.security.entity;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * “记住我”功能的token(RememberMeToken)实体类\n *\n * @author lizw\n * @since 2018-09-21 20:10:31\n */\n@Data\npublic class RememberMeToken implements Serializable {\n private static final long serialVersionUID = -57228137236940071L;\n /** 主键id */ \n private Long id;\n\n /** 系统(或服务)名称 */\n private String sysName;\n\n /** token序列号 */ \n private String series;\n \n /** 用户登录名 */ \n private String username;\n \n /** token数据 */ \n private String token;\n \n /** 最后使用时间 */ \n private Date lastUsed;\n \n /** 创建时间 */ \n private Date createAt;\n \n /** 更新时间 */ \n private Date updateAt;\n \n}\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/WebPermissionMapper.java<|end_filename|>\npackage org.clever.security.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport org.apache.ibatis.annotations.Mapper;\nimport org.apache.ibatis.annotations.Param;\nimport org.clever.security.entity.WebPermission;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 9:13
\n */\n@Repository\n@Mapper\npublic interface WebPermissionMapper extends BaseMapper {\n\n WebPermissionModel getBySysNameAndTarget(\n @Param(\"sysName\") String sysName,\n @Param(\"targetClass\") String targetClass,\n @Param(\"targetMethod\") String targetMethod,\n @Param(\"targetMethodParams\") String targetMethodParams\n );\n\n List findBySysName(@Param(\"sysName\") String sysName);\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/LoginRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 13:57
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LoginRes extends BaseResponse {\n /**\n * 是否登录成功\n */\n private Boolean success;\n\n /**\n * 错误消息\n */\n private String message;\n\n /**\n * 时间戳\n */\n private Long timestamp = System.currentTimeMillis();\n\n /**\n * 登录是否需要验证码\n */\n private Boolean needCaptcha = false;\n\n /**\n * 当前登录用户信息\n */\n private UserRes user;\n\n public LoginRes(Boolean success, String message) {\n this.success = success;\n this.message = message;\n }\n\n public LoginRes(Boolean success, String message, UserRes user) {\n this.success = success;\n this.message = message;\n this.user = user;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/token/SecurityContextToken.java<|end_filename|>\npackage org.clever.security.token;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport lombok.ToString;\nimport org.clever.security.model.LoginUserDetails;\nimport org.clever.security.token.login.BaseLoginToken;\nimport org.springframework.security.authentication.AbstractAuthenticationToken;\n\n/**\n * 登录成功的Token\n *

\n * 作者: lzw
\n * 创建时间:2019-04-27 20:50
\n */\n//@JsonIgnoreProperties(value = {\"details\"})\n@ToString(exclude = {\"userDetails\"})\npublic class SecurityContextToken extends AbstractAuthenticationToken {\n\n /**\n * 用户登录请求参数Token\n */\n private BaseLoginToken loginToken;\n /**\n * 数据库中用户信息\n */\n private LoginUserDetails userDetails;\n\n /**\n * 用于创建登录成功的用户信息\n */\n public SecurityContextToken(BaseLoginToken loginToken, LoginUserDetails userDetails) {\n super(userDetails.getAuthorities());\n this.loginToken = loginToken;\n this.userDetails = userDetails;\n super.setAuthenticated(true);\n }\n\n /**\n * 获取登录凭证(password 密码)\n */\n @Override\n public Object getCredentials() {\n return loginToken;\n }\n\n /**\n * 获取登录的用户信息\n */\n @Override\n public Object getPrincipal() {\n return userDetails;\n }\n\n @Override\n public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {\n if (isAuthenticated == this.isAuthenticated()) {\n return;\n }\n if (isAuthenticated) {\n throw new IllegalArgumentException(\"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead\");\n }\n super.setAuthenticated(false);\n }\n\n @Override\n public void eraseCredentials() {\n super.eraseCredentials();\n loginToken.eraseCredentials();\n userDetails.eraseCredentials();\n }\n\n @JsonIgnore\n public BaseLoginToken getLoginToken() {\n return loginToken;\n }\n\n @JsonIgnore\n public LoginUserDetails getUserDetails() {\n return userDetails;\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/ServerApiAccessToken.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\n/**\n * 服务间免登陆Token访问配置\n * 作者: lzw
\n * 创建时间:2019-05-16 11:07
\n */\n@Data\npublic class ServerApiAccessToken {\n\n /**\n * 请求头Token名称\n */\n private String tokenName = \"ServerApiToken\";\n\n /**\n * 请求头Token值\n */\n private String tokenValue;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/WebPermissionInitReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\nimport org.clever.security.entity.model.WebPermissionModel;\n\nimport javax.validation.constraints.NotNull;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 20:36
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class WebPermissionInitReq extends BaseRequest {\n\n @NotNull\n @ApiModelProperty(\"当前系统所有权限\")\n private List allPermission;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/WebPermissionService.java<|end_filename|>\npackage org.clever.security.service;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.server.service.BaseService;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.WebPermissionInitReq;\nimport org.clever.security.dto.request.WebPermissionModelGetReq;\nimport org.clever.security.dto.response.WebPermissionInitRes;\nimport org.clever.security.entity.EnumConstant;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.WebPermission;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.mapper.PermissionMapper;\nimport org.clever.security.mapper.WebPermissionMapper;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport java.util.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-20 15:53
\n */\n@Transactional(readOnly = true)\n@Service\n@Slf4j\npublic class WebPermissionService extends BaseService {\n @Autowired\n private PermissionMapper permissionMapper;\n @Autowired\n private WebPermissionMapper webPermissionMapper;\n\n /**\n * 保存Web权限\n */\n @Transactional\n public void saveWebPermission(WebPermissionModel webPermissionModel) {\n Permission permission = BeanMapper.mapper(webPermissionModel, Permission.class);\n WebPermission webPermission = BeanMapper.mapper(webPermissionModel, WebPermission.class);\n permissionMapper.insert(permission);\n webPermissionMapper.insert(webPermission);\n }\n\n public WebPermissionModel getWebPermissionModel(WebPermissionModelGetReq req) {\n return webPermissionMapper.getBySysNameAndTarget(\n req.getSysName(),\n req.getTargetClass(),\n req.getTargetMethod(),\n req.getTargetMethodParams()\n );\n }\n\n public List findAllWebPermissionModel(String sysName) {\n return webPermissionMapper.findBySysName(sysName);\n }\n\n /**\n * 初始化某个系统的所有Web权限\n */\n @Transactional\n public WebPermissionInitRes initWebPermission(String sysName, WebPermissionInitReq req) {\n List allPermission = req.getAllPermission();\n // 校验数据正确\n for (WebPermissionModel webPermissionModel : allPermission) {\n webPermissionModel.check();\n }\n // 排序\n Collections.sort(allPermission);\n // 加载当前模块所有的权限信息 - moduleAllPermission\n List moduleAllPermission = webPermissionMapper.findBySysName(sysName);\n // 保存系统中有而数据库里没有的资源 - addPermission\n List addPermission = this.addPermission(allPermission, moduleAllPermission);\n // 统计数据库中有而系统中没有的资源数据 - notExistPermission\n moduleAllPermission = webPermissionMapper.findBySysName(sysName);\n List notExistPermission = this.getNotExistPermission(allPermission, moduleAllPermission);\n // 构造返回信息\n WebPermissionInitRes res = new WebPermissionInitRes();\n res.setAddPermission(addPermission);\n res.setNotExistPermission(notExistPermission);\n return res;\n }\n\n /**\n * 保存所有新增的权限 (module targetClass targetMethod resourcesUrl)\n *\n * @param allPermission 当前模块所有权限\n * @param moduleAllPermission 数据库中当前模块所有的权限信息\n * @return 新增的权限\n */\n @Transactional\n protected List addPermission(List allPermission, List moduleAllPermission) {\n List addPermission = new ArrayList<>();\n Set setPermission = new HashSet<>();\n // module targetClass targetMethod targetMethodParams\n String format = \"%1$-128s|%2$-255s|%3$-255s|%4$-255s\";\n for (WebPermissionModel permission : moduleAllPermission) {\n setPermission.add(String.format(format,\n permission.getSysName(),\n permission.getTargetClass(),\n permission.getTargetMethod(),\n permission.getTargetMethodParams()));\n }\n for (WebPermissionModel permission : allPermission) {\n String key = String.format(format,\n permission.getSysName(),\n permission.getTargetClass(),\n permission.getTargetMethod(),\n permission.getTargetMethodParams());\n if (!setPermission.contains(key)) {\n // 新增不存在的权限配置\n this.saveWebPermission(permission);\n addPermission.add(permission);\n }\n }\n return addPermission;\n }\n\n /**\n * 统计数据库中有而系统中没有的资源数据\n *\n * @param allPermission 当前模块所有权限\n * @param moduleAllPermission 数据库中当前模块所有的权限信息\n * @return 数据库中有而系统中没有的资源数据\n */\n @Transactional\n protected List getNotExistPermission(List allPermission, List moduleAllPermission) {\n List notExistPermission = new ArrayList<>();\n Map mapPermission = new HashMap<>();\n // module targetClass targetMethod targetMethodParams\n String format = \"%1$-128s|%2$-255s|%3$-255s|%4$-255s\";\n for (WebPermissionModel permission : allPermission) {\n mapPermission.put(String.format(format,\n permission.getSysName(),\n permission.getTargetClass(),\n permission.getTargetMethod(),\n permission.getTargetMethodParams()), permission);\n }\n for (WebPermissionModel dbPermission : moduleAllPermission) {\n String key = String.format(format,\n dbPermission.getSysName(),\n dbPermission.getTargetClass(),\n dbPermission.getTargetMethod(),\n dbPermission.getTargetMethodParams());\n WebPermissionModel permission = mapPermission.get(key);\n if (permission == null) {\n // 数据库里有 系统中没有 - 更新 targetExist\n if (!Objects.equals(dbPermission.getTargetExist(), EnumConstant.WebPermission_targetExist_0)) {\n WebPermission update = new WebPermission();\n update.setId(dbPermission.getWebPermissionId());\n update.setTargetExist(EnumConstant.WebPermission_targetExist_0);\n update.setUpdateAt(new Date());\n webPermissionMapper.updateById(update);\n }\n notExistPermission.add(dbPermission);\n } else {\n // 数据库里有 系统中也有 - 更新 resourcesUrl\n boolean permissionStrChange = !Objects.equals(permission.getPermissionStr(), dbPermission.getPermissionStr())\n && !(dbPermission.getPermissionStr().startsWith(\"[auto]:\") && permission.getPermissionStr().startsWith(\"[auto]:\"));\n if (!Objects.equals(permission.getResourcesUrl(), dbPermission.getResourcesUrl())\n || permissionStrChange) {\n WebPermission update = new WebPermission();\n update.setId(dbPermission.getPermissionId());\n update.setResourcesUrl(permission.getResourcesUrl());\n update.setPermissionStr(permission.getPermissionStr());\n webPermissionMapper.updateById(update);\n }\n if (!Objects.equals(permission.getTitle(), dbPermission.getTitle())\n || !Objects.equals(permission.getDescription(), dbPermission.getDescription())\n || permissionStrChange) {\n Permission update = new Permission();\n update.setId(dbPermission.getPermissionId());\n update.setTitle(permission.getTitle());\n update.setDescription(permission.getDescription());\n update.setPermissionStr(permission.getPermissionStr());\n permissionMapper.updateById(update);\n }\n }\n }\n return notExistPermission;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/ServiceSysQueryReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.QueryByPage;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-11-25 20:09
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ServiceSysQueryReq extends QueryByPage {\n\n @ApiModelProperty(\"系统(或服务)名称\")\n private String sysName;\n\n @ApiModelProperty(\"登录类型,0:sesion-cookie,1:jwt-token\")\n private Integer loginModel;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/LoginTypeConstant.java<|end_filename|>\npackage org.clever.security;\n\n/**\n * 登录类型字符串常量\n *

\n * 作者: lzw
\n * 创建时间:2019-04-27 21:50
\n */\npublic class LoginTypeConstant {\n\n /**\n * 使用\"记住我\"功能自动登录登录\n */\n public static final String RememberMe = \"RememberMe\";\n\n /**\n * 使用用户名密码登录\n */\n public static final String UsernamePassword = \"\";\n\n /**\n * 使用手机号验证码登录\n */\n public static final String TelephoneCode = \"TelephoneCode\";\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/LoginModel.java<|end_filename|>\npackage org.clever.security;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-25 19:51
\n */\npublic enum LoginModel {\n /**\n * session-cookie\n */\n session,\n\n /**\n * jwt-token\n */\n jwt,\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/ManageCryptoService.java<|end_filename|>\npackage org.clever.security.service.internal;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.codec.CryptoUtils;\nimport org.clever.common.utils.codec.EncodeDecodeUtils;\nimport org.clever.security.config.GlobalConfig;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.BadCredentialsException;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.stereotype.Component;\n\n/**\n * 管理系统敏感数据加密-解密\n * 作者: lzw
\n * 创建时间:2018-11-12 9:29
\n */\n@Component\n@Slf4j\npublic class ManageCryptoService {\n\n @Autowired\n private GlobalConfig globalConfig;\n @Autowired\n private BCryptPasswordEncoder bCryptPasswordEncoder;\n\n /**\n * 请求数据 AES 加密\n *\n * @return Base64编码密码\n */\n public String reqAesEncrypt(String input) {\n try {\n byte[] passwordData = input.getBytes();\n byte[] key = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesKey());\n byte[] iv = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesIv());\n return EncodeDecodeUtils.encodeBase64(CryptoUtils.aesEncrypt(passwordData, key, iv));\n } catch (Exception e) {\n throw new BadCredentialsException(\"请求密码加密失败\");\n }\n }\n\n /**\n * 请求数据 AES 解密\n *\n * @param input Base64编码密码\n */\n public String reqAesDecrypt(String input) {\n try {\n byte[] passwordData = EncodeDecodeUtils.decodeBase64(input);\n byte[] key = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesKey());\n byte[] iv = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesIv());\n return CryptoUtils.aesDecrypt(passwordData, key, iv);\n } catch (Exception e) {\n throw new BadCredentialsException(\"请求密码解密失败\");\n }\n }\n\n /**\n * 存储数据 加密\n */\n public String dbEncode(String input) {\n try {\n return bCryptPasswordEncoder.encode(input);\n } catch (Exception e) {\n throw new BadCredentialsException(\"存储密码加密失败\");\n }\n }\n\n /**\n * 数据库加密数据匹配\n */\n public boolean dbMatches(String str1, String str2) {\n try {\n return bCryptPasswordEncoder.matches(str1, str2);\n } catch (Exception e) {\n throw new BadCredentialsException(\"存储密码解密失败\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/model/CaptchaInfo.java<|end_filename|>\npackage org.clever.security.model;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\n\n/**\n * 验证码信息\n * 作者: lzw
\n * 创建时间:2018-09-19 21:34
\n */\n@Data\npublic class CaptchaInfo implements Serializable {\n\n /**\n * 验证码\n */\n private String code;\n\n /**\n * 创建时间戳(毫秒)\n */\n private Long createTime;\n\n /**\n * 有效时间(毫秒)\n */\n private Long effectiveTime;\n\n /**\n * 验证码文件图片签名\n */\n private String imageDigest;\n\n /**\n * 默认构造\n */\n public CaptchaInfo() {\n createTime = System.currentTimeMillis();\n }\n\n /**\n * Session 登录模式使用\n *\n * @param code 验证码\n * @param effectiveTime 有效时间(毫秒)\n */\n public CaptchaInfo(String code, Long effectiveTime) {\n this.code = code;\n this.createTime = System.currentTimeMillis();\n this.effectiveTime = effectiveTime;\n }\n\n /**\n * JWT Token 登录模式使用\n *\n * @param code 验证码\n * @param effectiveTime 有效时间(毫秒)\n * @param imageDigest 验证码文件图片签名\n */\n public CaptchaInfo(String code, Long effectiveTime, String imageDigest) {\n this.code = code;\n this.createTime = System.currentTimeMillis();\n this.effectiveTime = effectiveTime;\n this.imageDigest = imageDigest;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/RoleInfoRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\nimport org.clever.security.entity.Permission;\n\nimport java.util.Date;\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-03 9:35
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class RoleInfoRes extends BaseResponse {\n\n @ApiModelProperty(\"主键id\")\n private Long id;\n\n @ApiModelProperty(\"角色名称\")\n private String name;\n\n @ApiModelProperty(\"角色说明\")\n private String description;\n\n @ApiModelProperty(\"创建时间\")\n private Date createAt;\n\n @ApiModelProperty(\"更新时间\")\n private Date updateAt;\n\n @ApiModelProperty(\"拥有权限\")\n private List permissionList;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/AccessDeniedRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-18 15:19
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class AccessDeniedRes extends BaseResponse {\n\n /**\n * 错误消息\n */\n private String message = \"没有访问权限\";\n\n /**\n * 时间戳\n */\n private Long timestamp = System.currentTimeMillis();\n\n public AccessDeniedRes() {\n }\n\n public AccessDeniedRes(String message) {\n this.message = message;\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/WebPermissionInitRes.java<|end_filename|>\npackage org.clever.security.dto.response;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.response.BaseResponse;\nimport org.clever.security.entity.model.WebPermissionModel;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 20:45
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class WebPermissionInitRes extends BaseResponse {\n\n @ApiModelProperty(\"新增的权限\")\n private List addPermission;\n\n @ApiModelProperty(\"数据库里存在,系统中不存在的权限\")\n private List notExistPermission;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/WebPermissionController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.security.dto.request.WebPermissionInitReq;\nimport org.clever.security.dto.request.WebPermissionModelGetReq;\nimport org.clever.security.dto.response.WebPermissionInitRes;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.service.WebPermissionService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 18:59
\n */\n@Api(\"Web权限\")\n@RestController\n@RequestMapping(\"/api\")\npublic class WebPermissionController extends BaseController {\n\n @Autowired\n private WebPermissionService webPermissionService;\n\n @ApiOperation(\"根据系统和Controller信息查询Web权限\")\n @GetMapping(\"/web_permission\")\n public WebPermissionModel getWebPermissionModel(@Validated WebPermissionModelGetReq req) {\n return webPermissionService.getWebPermissionModel(req);\n }\n\n @ApiOperation(\"查询某个系统的所有Web权限\")\n @GetMapping(\"/web_permission/{sysName}\")\n public List findAllWebPermissionModel(@PathVariable(\"sysName\") String sysName) {\n return webPermissionService.findAllWebPermissionModel(sysName);\n }\n\n @ApiOperation(\"初始化某个系统的所有Web权限\")\n @PostMapping(\"/web_permission/{sysName}\")\n public WebPermissionInitRes initWebPermission(@PathVariable(\"sysName\") String sysName, @RequestBody @Validated WebPermissionInitReq req) {\n return webPermissionService.initWebPermission(sysName, req);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/UserLoginLogModel.java<|end_filename|>\npackage org.clever.security.entity.model;\n\nimport lombok.Data;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-21 22:11
\n */\n@Data\npublic class UserLoginLogModel implements Serializable {\n /**\n * 主键id\n */\n private Long id;\n\n /**\n * 系统(或服务)名称\n */\n private String sysName;\n\n /**\n * 用户登录名\n */\n private String username;\n\n /**\n * 登录时间\n */\n private Date loginTime;\n\n /**\n * 登录IP\n */\n private String loginIp;\n\n /**\n * 登录的用户信息\n */\n private String authenticationInfo;\n\n /**\n * 登录类型,0:sesion-cookie,1:jwt-token\n */\n private Integer loginModel;\n\n /**\n * 登录SessionID\n */\n private String sessionId;\n\n /**\n * 登录状态,0:未知;1:已登录;2:登录已过期\n */\n private Integer loginState;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n\n // ----------------------------------------------------------------------------- User\n\n /**\n * 主键id\n */\n private Long userId;\n\n /**\n * 用户类型,0:系统内建,1:外部系统用户\n */\n private Integer userType;\n\n /**\n * 手机号\n */\n private String telephone;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * 帐号过期时间\n */\n private Date expiredTime;\n\n /**\n * 帐号是否锁定,0:未锁定;1:锁定\n */\n private Integer locked;\n\n /**\n * 是否启用,0:禁用;1:启用\n */\n private Integer enabled;\n\n /**\n * 说明\n */\n private String description;\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserAuthenticationReq.java<|end_filename|>\npackage org.clever.security.dto.request;\n\nimport io.swagger.annotations.ApiModelProperty;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport org.clever.common.model.request.BaseRequest;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.Pattern;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-24 10:28
\n */\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class UserAuthenticationReq extends BaseRequest {\n\n public static final String LoginType_Username = \"username\";\n public static final String LoginType_Telephone = \"telephone\";\n\n @ApiModelProperty(\"用户登录名(登录名、手机、邮箱)\")\n @NotBlank\n private String loginName;\n\n @ApiModelProperty(\"登录方式(username、telephone)\")\n @Pattern(regexp = \"username|telephone\")\n private String loginType = \"username\";\n\n @ApiModelProperty(\"验证密码(使用AES对称加密)\")\n @NotBlank\n private String password;\n\n @ApiModelProperty(\"系统名称(选填)\")\n private String sysName;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/UserLoginEntryPoint.java<|end_filename|>\npackage org.clever.security.authentication;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.model.response.ErrorResponse;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.utils.HttpRequestUtils;\nimport org.clever.security.utils.HttpResponseUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.web.AuthenticationEntryPoint;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n/**\n * 未登录访问时的处理\n *

\n * 作者: lzw
\n * 创建时间:2018-03-16 11:20
\n */\n@Component\n@Slf4j\npublic class UserLoginEntryPoint implements AuthenticationEntryPoint {\n\n @Autowired\n private SecurityConfig securityConfig;\n\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {\n log.info(\"### 未登录访问拦截,访问地址[{}] {}\", request.getMethod(), request.getRequestURL().toString());\n if (!securityConfig.getNotLoginNeedForward() || HttpRequestUtils.isJsonResponse(request)) {\n // 返回401错误\n ErrorResponse errorResponse = new ErrorResponse(\"您还未登录,请先登录\", authException, HttpServletResponse.SC_UNAUTHORIZED, request.getRequestURI());\n HttpResponseUtils.sendJsonBy401(response, errorResponse);\n return;\n }\n // 跳转到登录页面\n String redirectUrl = securityConfig.getLogin().getLoginPage();\n if (StringUtils.isBlank(redirectUrl)) {\n redirectUrl = \"/index.html\";\n }\n HttpResponseUtils.sendRedirect(response, redirectUrl);\n }\n}\n\n\n<|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/WebPermissionModel.java<|end_filename|>\npackage org.clever.security.entity.model;\n\nimport lombok.Data;\nimport org.apache.commons.lang3.StringUtils;\nimport org.clever.common.exception.BusinessException;\nimport org.clever.security.entity.EnumConstant;\n\nimport java.io.Serializable;\nimport java.util.Date;\nimport java.util.Objects;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-17 16:56
\n */\n@Data\npublic class WebPermissionModel implements Serializable, Comparable {\n private Long permissionId;\n\n /**\n * 系统(或服务)名称\n */\n private String sysName;\n\n /**\n * 资源标题\n */\n private String title;\n\n /**\n * 资源访问所需要的权限标识字符串\n */\n private String permissionStr;\n\n /**\n * 资源类型(1:请求URL地址, 2:其他资源)\n */\n private Integer resourcesType;\n\n /**\n * 资源说明\n */\n private String description;\n\n /**\n * 创建时间\n */\n private Date createAt;\n\n /**\n * 更新时间\n */\n private Date updateAt;\n\n // ----------------------------------------------------------------\n\n private Long webPermissionId;\n\n /**\n * 需要授权才允许访问(1:需要;2:不需要)\n */\n private Integer needAuthorization;\n\n /**\n * Spring Controller类名称\n */\n private String targetClass;\n\n /**\n * Spring Controller类的方法名称\n */\n private String targetMethod;\n\n /**\n * Spring Controller类的方法参数签名\n */\n private String targetMethodParams;\n\n /**\n * 资源URL地址\n */\n private String resourcesUrl;\n\n /**\n * Spring Controller路由资源是否存在,0:不存在;1:存在\n */\n private Integer targetExist;\n\n /**\n * 定义排序规则\n */\n @SuppressWarnings(\"NullableProblems\")\n @Override\n public int compareTo(WebPermissionModel permission) {\n // module resourcesType targetClass targetMethod targetMethodParams title\n String format = \"%1$-128s|%2$-20s|%3$-255s|%4$-255s|%5$-255s|%6$-255s\";\n String strA = String.format(format,\n this.getSysName(),\n this.getResourcesType(),\n this.getTargetClass(),\n this.getTargetMethod(),\n this.getTargetMethodParams(),\n this.getTitle());\n String strB = String.format(format,\n permission.getSysName(),\n permission.getResourcesType(),\n permission.getTargetClass(),\n permission.getTargetMethod(),\n permission.getTargetMethodParams(),\n permission.getTitle());\n return strA.compareTo(strB);\n }\n\n /**\n * 校验数据是否正确\n */\n public void check() {\n if (StringUtils.isBlank(sysName)) {\n throw new BusinessException(\"系统(或服务)名称不能为空\");\n }\n if (StringUtils.isBlank(title)) {\n throw new BusinessException(\"资源标题不能为空\");\n }\n if (StringUtils.isBlank(permissionStr)) {\n throw new BusinessException(\"权限标识不能为空\");\n }\n if (resourcesType == null) {\n throw new BusinessException(\"系统(或服务)名称不能为空\");\n }\n if (needAuthorization == null) {\n throw new BusinessException(\"需要授权才允许访问不能为空\");\n }\n if (Objects.equals(resourcesType, EnumConstant.Permission_ResourcesType_1)) {\n if (StringUtils.isBlank(targetClass)) {\n throw new BusinessException(\"目标类名不能为空\");\n }\n if (StringUtils.isBlank(targetMethod)) {\n throw new BusinessException(\"目标方法名不能为空\");\n }\n if (StringUtils.isBlank(resourcesUrl)) {\n throw new BusinessException(\"目标Url不能为空\");\n }\n }\n if (targetExist == null) {\n throw new BusinessException(\"资源是否存在不能为空\");\n }\n }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/client/UserClient.java<|end_filename|>\npackage org.clever.security.client;\n\nimport org.clever.security.config.CleverSecurityFeignConfiguration;\nimport org.clever.security.dto.request.UserAuthenticationReq;\nimport org.clever.security.dto.response.UserAuthenticationRes;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.User;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\n\nimport java.util.List;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-09-24 20:17
\n */\n@FeignClient(\n contextId = \"org.clever.security.client.UserClient\",\n name = \"clever-security-server\",\n path = \"/api\",\n configuration = CleverSecurityFeignConfiguration.class\n)\npublic interface UserClient {\n\n /**\n * 获取用户\n */\n @GetMapping(\"/user/{unique}\")\n User getUser(@PathVariable(\"unique\") String unique);\n\n /**\n * 获取某个用户在某个系统下的所有权限\n */\n @GetMapping(\"/user/{username}/{sysName}/permission\")\n List findAllPermission(@PathVariable(\"username\") String username, @PathVariable(\"sysName\") String sysName);\n\n /**\n * 用户是否有权登录某个系统\n */\n @GetMapping(\"/user/{username}/{sysName}\")\n Boolean canLogin(@PathVariable(\"username\") String username, @PathVariable(\"sysName\") String sysName);\n\n /**\n * 用户登录认证\n */\n @PostMapping(\"/user/authentication\")\n UserAuthenticationRes authentication(@RequestBody UserAuthenticationReq req);\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/RefreshTokenController.java<|end_filename|>\npackage org.clever.security.embed.controller;\n\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.common.utils.CookieUtils;\nimport org.clever.security.Constant;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.dto.request.RefreshTokenReq;\nimport org.clever.security.dto.response.JwtLoginRes;\nimport org.clever.security.repository.RedisJwtRepository;\nimport org.clever.security.token.JwtAccessToken;\nimport org.clever.security.token.JwtRefreshToken;\nimport org.clever.security.utils.AuthenticationUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * 作者: lzw
\n * 创建时间:2019-04-29 10:29
\n */\n@Api(\"JwtToken刷新登录令牌\")\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"jwt\")\n@RestController\n@Slf4j\npublic class RefreshTokenController {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n\n @ApiOperation(\"使用刷新令牌延长登录JwtToken过期时间\")\n @PutMapping(\"/login/refresh_token.json\")\n public JwtLoginRes refreshToken(HttpServletResponse response, @RequestBody @Validated RefreshTokenReq refreshTokenReq) {\n JwtRefreshToken jwtRefreshToken = redisJwtRepository.getRefreshToken(refreshTokenReq.getRefreshToken());\n SecurityContext securityContext = redisJwtRepository.getSecurityContext(jwtRefreshToken.getUsername());\n // 生成新的 JwtAccessToken 和 JwtRefreshToken\n JwtAccessToken newJwtAccessToken = redisJwtRepository.saveJwtToken(AuthenticationUtils.getSecurityContextToken(securityContext.getAuthentication()));\n // 删除之前的令牌\n JwtAccessToken oldJwtAccessToken = null;\n try {\n oldJwtAccessToken = redisJwtRepository.getJwtToken(jwtRefreshToken.getUsername(), jwtRefreshToken.getTokenId());\n } catch (Throwable ignored) {\n }\n if (oldJwtAccessToken != null) {\n redisJwtRepository.deleteJwtToken(oldJwtAccessToken);\n }\n if (securityConfig.getTokenConfig().isUseCookie()) {\n CookieUtils.setRooPathCookie(response, securityConfig.getTokenConfig().getJwtTokenKey(), newJwtAccessToken.getToken());\n }\n return new JwtLoginRes(\n true,\n \"刷新登录令牌成功\",\n AuthenticationUtils.getUserRes(securityContext.getAuthentication()),\n newJwtAccessToken.getToken(),\n newJwtAccessToken.getRefreshToken()\n );\n }\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByUserController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.UserAddReq;\nimport org.clever.security.dto.request.UserQueryPageReq;\nimport org.clever.security.dto.request.UserUpdateReq;\nimport org.clever.security.dto.response.UserAddRes;\nimport org.clever.security.dto.response.UserInfoRes;\nimport org.clever.security.entity.User;\nimport org.clever.security.service.ManageByUserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 20:45
\n */\n@Api(\"用户管理\")\n@RestController\n@RequestMapping(\"/api/manage\")\npublic class ManageByUserController extends BaseController {\n\n @Autowired\n private ManageByUserService manageByUserService;\n\n @ApiOperation(\"查询用户列表\")\n @GetMapping(\"/user\")\n public IPage findByPage(UserQueryPageReq userQueryPageReq) {\n return manageByUserService.findByPage(userQueryPageReq);\n }\n\n @ApiOperation(\"获取用户详情(全部角色、权限、系统)\")\n @GetMapping(\"/user/{username}\")\n public UserInfoRes getUserInfo(@PathVariable(\"username\") String username) {\n return manageByUserService.getUserInfo(username);\n }\n\n @ApiOperation(\"新增用户\")\n @PostMapping(\"/user\")\n public UserAddRes addUser(@RequestBody @Validated UserAddReq userAddReq) {\n User user = manageByUserService.addUser(userAddReq);\n return BeanMapper.mapper(user, UserAddRes.class);\n }\n\n @ApiOperation(\"更新用户\")\n @PutMapping(\"/user/{username}\")\n public UserAddRes updateUser(@PathVariable(\"username\") String username, @RequestBody @Validated UserUpdateReq req) {\n return BeanMapper.mapper(manageByUserService.updateUser(username, req), UserAddRes.class);\n }\n\n @ApiOperation(\"删除用户\")\n @DeleteMapping(\"/user/{username}\")\n public UserAddRes deleteUser(@PathVariable(\"username\") String username) {\n return BeanMapper.mapper(manageByUserService.deleteUser(username), UserAddRes.class);\n }\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/LoginConfig.java<|end_filename|>\npackage org.clever.security.config.model;\n\nimport lombok.Data;\n\nimport java.time.Duration;\n\n/**\n * 用户登录配置\n * 作者: lzw
\n * 创建时间:2019-04-25 19:01
\n */\n@Data\npublic class LoginConfig {\n\n /**\n * 登录页面\n */\n private String loginPage = \"/index.html\";\n\n /**\n * 登录请求URL\n */\n private String loginUrl = \"/login\";\n\n /**\n * 登录只支持POST请求\n */\n private Boolean postOnly = true;\n\n /**\n * Json 数据提交方式\n */\n private Boolean jsonDataSubmit = true;\n\n /**\n * 登录成功 - 是否需要跳转(重定向)\n */\n private Boolean loginSuccessNeedRedirect = false;\n\n /**\n * 登录成功默认跳转的页面\n */\n private String loginSuccessRedirectPage = \"/home.html\";\n\n /**\n * 登录失败 - 是否需要跳转(重定向)\n */\n private Boolean loginFailureNeedRedirect = false;\n\n /**\n * 登录失败 - 是否需要跳转(请求转发) 优先级低于loginFailureNeedRedirect\n */\n private Boolean loginFailureNeedForward = false;\n\n /**\n * 登录失败默认跳转的页面\n */\n private String loginFailureRedirectPage = \"/index.html\";\n\n /**\n * 登录是否需要验证码\n */\n private Boolean needCaptcha = true;\n\n /**\n * 登录失败多少次才需要验证码(小于等于0,总是需要验证码)\n */\n private Integer needCaptchaByLoginFailCount = 3;\n\n /**\n * 验证码有效时间\n */\n private Duration captchaEffectiveTime = Duration.ofSeconds(120);\n\n /**\n * 同一个用户并发登录次数限制(-1表示不限制)\n */\n private Integer concurrentLoginCount = 1;\n\n /**\n * 同一个用户并发登录次数达到最大值之后,是否不允许之后的登录(false 之后登录的把之前登录的挤下来)\n */\n private Boolean notAllowAfterLogin = false;\n}\n\n\n<|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLogoutHandler.java<|end_filename|>\npackage org.clever.security.handler;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.clever.security.Constant;\nimport org.clever.security.LoginModel;\nimport org.clever.security.config.SecurityConfig;\nimport org.clever.security.repository.RedisJwtRepository;\nimport org.clever.security.token.JwtAccessToken;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.web.authentication.logout.LogoutHandler;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.Set;\n\n/**\n * 用户登出处理\n * 作者: lzw
\n * 创建时间:2018-11-19 15:13
\n */\n@ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = \"login-model\", havingValue = \"jwt\")\n@Component\n@Slf4j\npublic class UserLogoutHandler implements LogoutHandler {\n\n @Autowired\n private SecurityConfig securityConfig;\n @Autowired\n private RedisJwtRepository redisJwtRepository;\n\n @Override\n public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {\n if (!LoginModel.jwt.equals(securityConfig.getLoginModel())) {\n return;\n }\n JwtAccessToken jwtAccessToken = null;\n try {\n jwtAccessToken = redisJwtRepository.getJwtToken(request);\n } catch (Throwable ignored) {\n }\n if (jwtAccessToken != null) {\n redisJwtRepository.deleteJwtToken(jwtAccessToken);\n log.info(\"### 删除 JWT Token成功\");\n Set ketSet = redisJwtRepository.getJwtTokenPatternKey(jwtAccessToken.getClaims().getSubject());\n if (ketSet != null && ketSet.size() <= 0) {\n redisJwtRepository.deleteSecurityContext(jwtAccessToken.getClaims().getSubject());\n log.info(\"### 删除 SecurityContext 成功\");\n }\n }\n }\n}\n\n\n<|start_filename|>clever-security-client/src/main/java/org/clever/security/config/CleverSecurityAccessTokenConfig.java<|end_filename|>\npackage org.clever.security.config;\n\nimport lombok.Data;\nimport org.clever.security.Constant;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\nimport java.util.Map;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-03-15 14:31
\n */\n@SuppressWarnings(\"ConfigurationProperties\")\n@ConfigurationProperties(prefix = Constant.ConfigPrefix)\n@Component\n@Data\npublic class CleverSecurityAccessTokenConfig {\n\n /**\n * 访问 clever-security-server 服务API的授权Token请求头\n */\n private Map accessTokenHeads;\n}\n\n\n<|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByPermissionController.java<|end_filename|>\npackage org.clever.security.controller;\n\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.clever.common.server.controller.BaseController;\nimport org.clever.common.utils.mapper.BeanMapper;\nimport org.clever.security.dto.request.PermissionAddReq;\nimport org.clever.security.dto.request.PermissionQueryReq;\nimport org.clever.security.dto.request.PermissionUpdateReq;\nimport org.clever.security.entity.Permission;\nimport org.clever.security.entity.model.WebPermissionModel;\nimport org.clever.security.service.ManageByPermissionService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * 作者: lzw
\n * 创建时间:2018-10-02 20:48
\n */\n@Api(\"权限管理\")\n@RestController\n@RequestMapping(\"/api/manage\")\npublic class ManageByPermissionController extends BaseController {\n\n @Autowired\n private ManageByPermissionService manageByPermissionService;\n\n @ApiOperation(\"查询权限列表\")\n @GetMapping(\"/permission\")\n public IPage findByPage(PermissionQueryReq queryReq) {\n return manageByPermissionService.findByPage(queryReq);\n }\n\n @ApiOperation(\"新增权限\")\n @PostMapping(\"/permission\")\n public WebPermissionModel addPermission(@RequestBody @Validated PermissionAddReq permissionAddReq) {\n Permission permission = BeanMapper.mapper(permissionAddReq, Permission.class);\n return manageByPermissionService.addPermission(permission);\n }\n\n @ApiOperation(\"更新权限\")\n @PutMapping(\"/permission/{permissionStr}\")\n public WebPermissionModel updatePermission(\n @PathVariable(\"permissionStr\") String permissionStr,\n @RequestBody @Validated PermissionUpdateReq permissionUpdateReq) {\n return manageByPermissionService.updatePermission(permissionStr, permissionUpdateReq);\n }\n\n @ApiOperation(\"获取权限信息\")\n @GetMapping(\"/permission/{permissionStr}\")\n public WebPermissionModel getPermissionModel(@PathVariable(\"permissionStr\") String permissionStr) {\n return manageByPermissionService.getPermissionModel(permissionStr);\n }\n\n @ApiOperation(\"删除权限信息\")\n @DeleteMapping(\"/permission/{permissionStr}\")\n public WebPermissionModel delPermissionModel(@PathVariable(\"permissionStr\") String permissionStr) {\n return manageByPermissionService.delPermissionModel(permissionStr);\n }\n\n @ApiOperation(\"删除权限信息(批量)\")\n @DeleteMapping(\"/permission/batch\")\n public List delPermissionModels(@RequestParam(\"permissionSet\") Set permissionSet) {\n if (permissionSet == null) {\n return null;\n }\n return manageByPermissionService.delPermissionModels(permissionSet);\n }\n}\n"},"max_stars_repo_name":{"kind":"string","value":"Lzw2016/clever-security"}}},{"rowIdx":236,"cells":{"content":{"kind":"string","value":"<|start_filename|>doc/functionIndex/@mlep/encodeData.html<|end_filename|>\n\n\n\n Description of encodeData\n \n \n \n \">\n \n \n\n\n\n

Home &gt; @mlep &gt; encodeData.m
\n\n\n\n

encodeData\n

\n\n

PURPOSE \"^\"

\n
ENCODEDATA - Encode data to packet.
\n\n

SYNOPSIS \"^\"

\n
function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)
\n\n

DESCRIPTION \"^\"

\n
ENCODEDATA - Encode data to packet.\nEncode data to a packet (a string) that can be sent to the external\nprogram.  The packet format follows the BCVTB co-simulation\ncommunication protocol.\n\n   Syntax: packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)\n\n   Inputs:\n        vernumber - Version of the protocol to be used. Currently, version 1\n                    and 2 are supported.\n             flag - An integer specifying the (status) flag. Refer to the BCVTB\n                    protocol for allowed flag values.\n        timevalue - A real value which is the current simulation time in\n                    seconds.\n       realvalues - A vector of real value data to be sent. Can be empty.\n        intvalues - A vector of integer value data to be sent. Can be empty.\n       boolvalues - A vector of boolean value data to be sent. Can be\n                    empty.\n\n Outputs:\n           packet - String that contains the encoded data.\n\n Protocol Version 1 &amp; 2:\n Packet has the form:\n       &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \\n&quot;\n where\n   v    - version number (1,2)\n   f    - flag (0: communicate, 1: finish, -10: initialization error,\n                -20: time integration error, -1: unknown error)\n   dr   - number of real values\n   di   - number of integer values\n   db   - number of boolean values\n   t    - current simulation time in seconds (format %20.15e)\n   r1 r2 ... are real values (format %20.15e)\n   i1 i2 ... are integer values (format %d)\n   b1 b2 ... are boolean values (format %d)\n   \\n   - carriage return\n\n Note that if f is non-zero, other values after it will not be processed.\n\n   See also: MLEP.DECODEPACKET, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,\n             WRITE\n\n (C) 2010,  ()
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)\n0002 %ENCODEDATA - Encode data to packet.\n0003 %Encode data to a packet (a string) that can be sent to the external\n0004 %program.  The packet format follows the BCVTB co-simulation\n0005 %communication protocol.\n0006 %\n0007 %   Syntax: packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)\n0008 %\n0009 %   Inputs:\n0010 %        vernumber - Version of the protocol to be used. Currently, version 1\n0011 %                    and 2 are supported.\n0012 %             flag - An integer specifying the (status) flag. Refer to the BCVTB\n0013 %                    protocol for allowed flag values.\n0014 %        timevalue - A real value which is the current simulation time in\n0015 %                    seconds.\n0016 %       realvalues - A vector of real value data to be sent. Can be empty.\n0017 %        intvalues - A vector of integer value data to be sent. Can be empty.\n0018 %       boolvalues - A vector of boolean value data to be sent. Can be\n0019 %                    empty.\n0020 %\n0021 % Outputs:\n0022 %           packet - String that contains the encoded data.\n0023 %\n0024 % Protocol Version 1 &amp; 2:\n0025 % Packet has the form:\n0026 %       &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \\n&quot;\n0027 % where\n0028 %   v    - version number (1,2)\n0029 %   f    - flag (0: communicate, 1: finish, -10: initialization error,\n0030 %                -20: time integration error, -1: unknown error)\n0031 %   dr   - number of real values\n0032 %   di   - number of integer values\n0033 %   db   - number of boolean values\n0034 %   t    - current simulation time in seconds (format %20.15e)\n0035 %   r1 r2 ... are real values (format %20.15e)\n0036 %   i1 i2 ... are integer values (format %d)\n0037 %   b1 b2 ... are boolean values (format %d)\n0038 %   \\n   - carriage return\n0039 %\n0040 % Note that if f is non-zero, other values after it will not be processed.\n0041 %\n0042 %   See also: MLEP.DECODEPACKET, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,\n0043 %             WRITE\n0044 %\n0045 % (C) 2010,  ()\n0046 \n0047 ni = nargin;\n0048 if ni &lt; 2\n0049     error('Not enough arguments: at least vernumber and flag must be specified.');\n0050 end\n0051 \n0052 if vernumber &lt;= 2\n0053     if flag == 0\n0054         if ni &lt; 3\n0055             error('Not enough arguments: time must be specified.');\n0056         end\n0057         \n0058         if ni &lt; 4, realvalues = []; end\n0059         \n0060         if ni &lt; 5, intvalues = []; end\n0061 \n0062         if ni &lt; 6\n0063             boolvalues = [];\n0064         else\n0065             boolvalues = logical(boolvalues(:)');   % Convert to boolean values\n0066         end\n0067 \n0068         % NOTE: although we can use num2str to print vectors to string, its\n0069         % performance is worse than that of sprintf, which would cause this\n0070         % function approx. 3 times slower.\n0071         packet = [sprintf('%d 0 %d %d %d %20.15e ', vernumber,...\n0072                             length(realvalues), ...\n0073                             length(intvalues), ...\n0074                             length(boolvalues), timevalue),...\n0075                   sprintf('%20.15e ', realvalues),...\n0076                   sprintf('%d ', intvalues),...\n0077                   sprintf('%d ', boolvalues)];\n0078     else\n0079         % Error\n0080         packet = sprintf('%d %d', vernumber, flag);\n0081     end\n0082 else\n0083     packet = '';\n0084 end\n0085 \n0086 end\n0087 \n0088 % Protocol Version 1 &amp; 2:\n0089 % Packet has the form:\n0090 %       v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...\n0091 % where\n0092 %   v    - version number (1,2)\n0093 %   f    - flag (0: communicate, 1: finish, -10: initialization error,\n0094 %                -20: time integration error, -1: unknown error)\n0095 %   dr   - number of real values\n0096 %   di   - number of integer values\n0097 %   db   - number of boolean values\n0098 %   t    - current simulation time in seconds (format %20.15e)\n0099 %   r1 r2 ... are real values (format %20.15e)\n0100 %   i1 i2 ... are integer values (format %d)\n0101 %   b1 b2 ... are boolean values (format %d)\n0102 %\n0103 % Note that if f is non-zero, other values after it will not be processed.
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/encodeStatus.html<|end_filename|>\n\n\n\n Description of encodeStatus\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; encodeStatus.m
\n\n\n\n

encodeStatus\n

\n\n

PURPOSE \"^\"

\n
ENCODESTATUS - Encode status flag to a packet.
\n\n

SYNOPSIS \"^\"

\n
function packet = encodeStatus(vernumber, flag)
\n\n

DESCRIPTION \"^\"

\n
ENCODESTATUS - Encode status flag to a packet.\nEncode a status flag to a packet (a string) that can be sent to the\nexternal program.  This function is a special version of\nmlepEncodeData in which only a flag (non-zero) is transferred. \n\n   Syntax: packet = mlepEncodeStatus(vernumber, flag)\n\n   Inputs:\n  vernumber - Version of the protocol to be used. Currently, version 1\n              and 2 are supported.\n       flag - An integer specifying the (status) flag. Refer to the BCVTB\n              protocol for allowed flag values.\n\n   Output:\n     packet - A string that contains the encoded data.\n\n   See also: MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODEREALDATA,\n             WRITE\n\n (C) 2010,  ()
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function packet = encodeStatus(vernumber, flag)\n0002 %ENCODESTATUS - Encode status flag to a packet.\n0003 %Encode a status flag to a packet (a string) that can be sent to the\n0004 %external program.  This function is a special version of\n0005 %mlepEncodeData in which only a flag (non-zero) is transferred.\n0006 %\n0007 %   Syntax: packet = mlepEncodeStatus(vernumber, flag)\n0008 %\n0009 %   Inputs:\n0010 %  vernumber - Version of the protocol to be used. Currently, version 1\n0011 %              and 2 are supported.\n0012 %       flag - An integer specifying the (status) flag. Refer to the BCVTB\n0013 %              protocol for allowed flag values.\n0014 %\n0015 %   Output:\n0016 %     packet - A string that contains the encoded data.\n0017 %\n0018 %   See also: MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODEREALDATA,\n0019 %             WRITE\n0020 %\n0021 % (C) 2010,  ()\n0022 \n0023 ni = nargin;\n0024 if ni &lt; 2\n0025     error('Not enough arguments: all input arguments are required.');\n0026 end\n0027 \n0028 if vernumber &lt;= 2\n0029     packet = sprintf('%d %d', vernumber, flag);\n0030 else\n0031     packet = '';\n0032 end\n0033 \n0034 end\n0035 \n0036 % Protocol Version 1 &amp; 2:\n0037 % Packet has the form:\n0038 %       v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...\n0039 % where\n0040 %   v    - version number (1,2)\n0041 %   f    - flag (0: communicate, 1: finish, -10: initialization error,\n0042 %                -20: time integration error, -1: unknown error)\n0043 %   dr   - number of real values\n0044 %   di   - number of integer values\n0045 %   db   - number of boolean values\n0046 %   t    - current simulation time in seconds (format %20.15e)\n0047 %   r1 r2 ... are real values (format %20.15e)\n0048 %   i1 i2 ... are integer values (format %d)\n0049 %   b1 b2 ... are boolean values (format %d)\n0050 %\n0051 % Note that if f is non-zero, other values after it will not be processed.
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/library/slblocks.html<|end_filename|>\n\n\n\n Description of slblocks\n \n \n \n \">\n \n \n\n\n\n
Home &gt; library &gt; slblocks.m
\n\n\n\n

slblocks\n

\n\n

PURPOSE \"^\"

\n
SLBLOCKS - Simulink Library browser definition file
\n\n

SYNOPSIS \"^\"

\n
function blkStruct = slblocks
\n\n

DESCRIPTION \"^\"

\n
 SLBLOCKS - Simulink Library browser definition file
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function blkStruct = slblocks\n0002 % SLBLOCKS - Simulink Library browser definition file\n0003 \n0004 % Name of the subsystem which will show up in the Simulink Blocksets\n0005 % and Toolboxes subsystem.\n0006 blkStruct.Name = sprintf('mlep\\nLibrary');\n0007 \n0008 % The function that will be called when the user double-clicks on\n0009 % this icon.\n0010 blkStruct.OpenFcn = 'open(''mlepLibrary.slx'');';\n0011 \n0012 % The argument to be set as the Mask Display for the subsystem.\n0013 blkStruct.MaskDisplay = 'disp(''mlep Library Blocks'');';\n0014 \n0015 % Library information for Simulink library browser\n0016 blkStruct.Browser = struct();\n0017 blkStruct.Browser.Library = 'mlepLibrary';\n0018 blkStruct.Browser.Name    = 'mlep Blocks';
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/readIDF.html<|end_filename|>\n\n\n\n Description of readIDF\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; readIDF.m
\n\n\n\n

readIDF\n

\n\n

PURPOSE \"^\"

\n
READIDF - Read and parse EnergyPlus IDF file.
\n\n

SYNOPSIS \"^\"

\n
function data = readIDF(filename, classnames)
\n\n

DESCRIPTION \"^\"

\n
 READIDF - Read and parse EnergyPlus IDF file.\n\n   data = readIDF(filename) reads all data entries from an IDF\n   file with name filename. The output data is a structure array,\n   where each item is one data entry. Each item k has two fields:\n     data(k).class is a string of the class name\n     data(k).fields is a cell array of strings, each cell is a\n                    data field after the class name.\n   The order of the entries is the same as in the IDF file.\n\n   data = readIDF(filename, classnames) reads all data entries\n   of the classes given in classnames, from a given IDF\n   file. Input argument classnames is either a string or a cell\n   array of strings specifying the class(es) that will be\n   read. Data entries not of those classes will be skipped. The output\n   'data' is a structure array (a bit DIFFERENT from above): each item k\n   of the array contains ALL data entries for CLASS k in 'classnames' (not\n   entry k in the IDF file), with 2 fields:\n     data(k).class is a string, the name of the class k in 'classnames',\n                   converted to lower-case (e.g. 'TimeStep' becomes\n                   'timestep').\n     data(k).fields is a cell array of cell arrays of strings, each cell\n                   contains the fields' strings for one entry of class k.\n                   If there is no entry of class k then this field is an\n                   empty cell.\n\n Class names are case insensitive.\n\n Examples:\n   data = readIDF('SmOffPSZ.idf', 'Timestep')\n       to read only the time step, e.g. data could be\n           data = \n               class: 'timestep'\n               fields: {{1x1 cell}}\n           with data(1).fields{1} = {'4'}\n\n   data = readIDF('SmOffPSZ.idf',...\n                   {'Timestep', 'ExternalInterface:Schedule'})\n       to read time step and all external schedule variables.\n           data = \n           1x2 struct array with fields:\n               class\n               fields\n\n           data(2) =\n               class: 'externalinterface:schedule'\n               fields: {{1x3 cell}  {1x3 cell}}\n\n\n (C) 2018 by  ()\n (C) 2012 by  ()
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function data = readIDF(filename, classnames)\n0002 % READIDF - Read and parse EnergyPlus IDF file.\n0003 %\n0004 %   data = readIDF(filename) reads all data entries from an IDF\n0005 %   file with name filename. The output data is a structure array,\n0006 %   where each item is one data entry. Each item k has two fields:\n0007 %     data(k).class is a string of the class name\n0008 %     data(k).fields is a cell array of strings, each cell is a\n0009 %                    data field after the class name.\n0010 %   The order of the entries is the same as in the IDF file.\n0011 %\n0012 %   data = readIDF(filename, classnames) reads all data entries\n0013 %   of the classes given in classnames, from a given IDF\n0014 %   file. Input argument classnames is either a string or a cell\n0015 %   array of strings specifying the class(es) that will be\n0016 %   read. Data entries not of those classes will be skipped. The output\n0017 %   'data' is a structure array (a bit DIFFERENT from above): each item k\n0018 %   of the array contains ALL data entries for CLASS k in 'classnames' (not\n0019 %   entry k in the IDF file), with 2 fields:\n0020 %     data(k).class is a string, the name of the class k in 'classnames',\n0021 %                   converted to lower-case (e.g. 'TimeStep' becomes\n0022 %                   'timestep').\n0023 %     data(k).fields is a cell array of cell arrays of strings, each cell\n0024 %                   contains the fields' strings for one entry of class k.\n0025 %                   If there is no entry of class k then this field is an\n0026 %                   empty cell.\n0027 %\n0028 % Class names are case insensitive.\n0029 %\n0030 % Examples:\n0031 %   data = readIDF('SmOffPSZ.idf', 'Timestep')\n0032 %       to read only the time step, e.g. data could be\n0033 %           data =\n0034 %               class: 'timestep'\n0035 %               fields: {{1x1 cell}}\n0036 %           with data(1).fields{1} = {'4'}\n0037 %\n0038 %   data = readIDF('SmOffPSZ.idf',...\n0039 %                   {'Timestep', 'ExternalInterface:Schedule'})\n0040 %       to read time step and all external schedule variables.\n0041 %           data =\n0042 %           1x2 struct array with fields:\n0043 %               class\n0044 %               fields\n0045 %\n0046 %           data(2) =\n0047 %               class: 'externalinterface:schedule'\n0048 %               fields: {{1x3 cell}  {1x3 cell}}\n0049 %\n0050 %\n0051 % (C) 2018 by  ()\n0052 % (C) 2012 by  ()\n0053 \n0054 % --- Input check ---------------------------------------------------------\n0055 narginchk(1, 2);\n0056 assert(ischar(filename), 'File name must be a string.');\n0057 if ~exist('classnames', 'var')\n0058     classnames = {};\n0059 else\n0060     % Lower case strings in classnames\n0061     if ischar(classnames)\n0062         classnames = {lower(classnames)};\n0063     elseif iscell(classnames)\n0064         assert(all(cellfun(@ischar, classnames)),...\n0065                'classnames must be a cell array of strings.');\n0066         classnames = cellfun(@lower, classnames,...\n0067                              'UniformOutput', false);\n0068     else\n0069         error('classnames must be either a string or a cell array.');\n0070     end\n0071 end\n0072 \n0073 noClassnames = isempty(classnames);\n0074 nClassnames = length(classnames);\n0075 \n0076 % --- Open File - preallocate ---------------------------------------------\n0077 \n0078 % Open the file in text mode\n0079 [fid, msg] = fopen(filename, 'rt');\n0080 if fid &lt; 0\n0081     error('Cannot open IDF file: %s', msg);\n0082 end\n0083 \n0084 % Read the file to system cache (performance)\n0085 filetext = fileread(filename);\n0086 lineIdx = strfind(filetext,newline);\n0087 nLines = numel(lineIdx);\n0088 \n0089 % Close the file\n0090 \n0091 % Read line by line and parse\n0092 syntaxerr = false;  % If there is a syntax error in the IDF file\n0093 syntaxmsg = '';\n0094 \n0095 % Pre-allocate the data struct for faster performance and less\n0096 % fragmented memory\n0097 if noClassnames\n0098     nBlocks = 0;  % Number of blocks read from file\n0099     data = repmat(struct('class', '', 'fields', {{}}), 1, 128);\n0100 else\n0101     data = struct('class', classnames, ...\n0102         'fields', repmat({{}}, 1, nClassnames));\n0103 end\n0104 \n0105 inBlock = false;  % A block is a block of code ended with ;\n0106 saveBlock = false;  % Is the current block being saved?\n0107 \n0108 % --- Parse ---------------------------------------------------------------\n0109 %   A field is a group of 0 or more characters not including comma,\n0110 %   semi-colon and exclamation; a line consists of a number of fields,\n0111 %   separated by either a comma or a semi-colon.\n0112 \n0113 startLineIdx = 1;\n0114 for iLine = 1:nLines\n0115     \n0116     % Get line\n0117     endLineIdx = lineIdx(iLine);\n0118     line = filetext(startLineIdx:endLineIdx);\n0119     startLineIdx = endLineIdx + 1;    \n0120     \n0121     % Remove all surrounding spaces\n0122     line = strtrim(line);\n0123     \n0124     % If l is empty or a comment line, ignore it\n0125     if isempty(line) || line(1) == '!'\n0126         continue;\n0127     end\n0128     \n0129     % Remove the comment part if any\n0130     dataEndIdx = strfind(line, '!');\n0131     if ~isempty(dataEndIdx)\n0132         % Remove from the first occurence of '!' to the end\n0133         line = strtrim(line(1:dataEndIdx(1)-1));\n0134     end\n0135     \n0136 \n0137     \n0138     % If we are not in a block and if class names are given, we search\n0139     % for any class name in the current line and only parse the line if we\n0140     % find an interested class name.  Because we are not in a block, the\n0141     % class name must be at the beginning of the line.\n0142     if ~inBlock &amp;&amp; ~noClassnames\n0143         lowerL = lower(line);\n0144         foundClassname = false;\n0145         \n0146         for k = 1:nClassnames\n0147             if ~isempty(strncmp(classnames{k}, lowerL,strlength(classnames{k})))\n0148                 foundClassname = true;\n0149                 break;\n0150             end\n0151         end\n0152         \n0153         if ~foundClassname\n0154             % Could not find a class name in l, then skip this line\n0155             continue;\n0156         end\n0157     end\n0158     \n0159     % Get all fields in the line\n0160     dataEndIdx = strfind(line, ',');\n0161     semIdx = strfind(line, ';');        \n0162     \n0163     if (isempty(dataEndIdx) &amp;&amp; isempty(semIdx)) || ...\n0164             (~isempty(semIdx) &amp;&amp; ~isempty(dataEndIdx) &amp;&amp; (semIdx &lt; dataEndIdx(end)))\n0165             % Syntax error\n0166             syntaxerr = true;\n0167             syntaxmsg = line;\n0168             break;\n0169     end\n0170     \n0171     % Append semicolon position if any\n0172     if ~isempty(semIdx) \n0173         dataEndIdx = [dataEndIdx semIdx]; %#ok&lt;AGROW&gt; % When there is only &quot;;&quot; in the line\n0174     end\n0175 \n0176     % Parse fields\n0177     nFields = numel(dataEndIdx);\n0178     dataEndIdx = [0 dataEndIdx]; %#ok&lt;AGROW&gt;\n0179     for k = 1:nFields  \n0180         field = strtrim(line(dataEndIdx(k)+1:dataEndIdx(k+1)-1));\n0181         if ~inBlock\n0182             % Start a new block\n0183             inBlock = true;\n0184             \n0185             % Only save the block if its class name is desired\n0186             if noClassnames\n0187                 saveBlock = true;\n0188                 nBlocks = nBlocks + 1;\n0189                 data(nBlocks).class = field;\n0190                 data(nBlocks).fields = {};\n0191             else\n0192                 [saveBlock, classIdx] = ...\n0193                     ismember(lower(field), classnames);\n0194                 \n0195                 if saveBlock\n0196                     data(classIdx).fields{end+1} = {};\n0197                 end\n0198             end\n0199         elseif saveBlock\n0200             % Continue the previous block\n0201             if noClassnames\n0202                 data(nBlocks).fields{end+1} = field;\n0203             else\n0204                 data(classIdx).fields{end}{end+1} = field;\n0205             end\n0206         end\n0207     end\n0208     \n0209     % Close block?\n0210     if ~isempty(semIdx)\n0211         inBlock = false;\n0212     end      \n0213 end\n0214 \n0215 if syntaxerr\n0216     error('Syntax error: %s', syntaxmsg);\n0217 end\n0218 \n0219 % Free unused spaces (if any)\n0220 if noClassnames\n0221     data((1+nBlocks):end) = [];\n0222 end\n0223 end
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_variables_cfg_example.html<|end_filename|>\n\n\n\n Description of mlepMatlab_variables_cfg_example\n \n \n \n \">\n \n \n\n\n\n
Home &gt; examples &gt; legacy_example &gt; mlepMatlab_variables_cfg_example.m
\n\n\n\n

mlepMatlab_variables_cfg_example\n

\n\n

PURPOSE \"^\"

\n
% Co-simulation example - specify I/O in variables.cfg
\n\n

SYNOPSIS \"^\"

\n
This is a script file.
\n\n

DESCRIPTION \"^\"

\n
% Co-simulation example - specify I/O in variables.cfg\n Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in \n a small office building simulation scenario.\n\n Note that a start of the simulation period as well as a timestep and\n an input/output configuration is defined by the the EnergyPlus simulation\n configuration file (.IDF). Climatic conditions are obtained from a\n EnergyPlus Weather data file (.EPW). \n\n See also: mlepMatlab_so_example.m, mlepSimulink_example.slx
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 %% Co-simulation example - specify I/O in variables.cfg\n0002 % Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in\n0003 % a small office building simulation scenario.\n0004 %\n0005 % Note that a start of the simulation period as well as a timestep and\n0006 % an input/output configuration is defined by the the EnergyPlus simulation\n0007 % configuration file (.IDF). Climatic conditions are obtained from a\n0008 % EnergyPlus Weather data file (.EPW).\n0009 %\n0010 % See also: mlepMatlab_so_example.m, mlepSimulink_example.slx\n0011 \n0012 %% Create mlep instance and configure it\n0013 \n0014 % Instantiate co-simulation tool\n0015 ep = mlep;\n0016 \n0017 % Building simulation configuration file\n0018 ep.idfFile = 'SmOffPSZ';\n0019 \n0020 % Weather file\n0021 ep.epwFile = 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3';\n0022 \n0023 % Initialize the co-simulation.\n0024 % Note: Two configurations of inputs/outputs are present in this example.\n0025 % It was therefore necessary to call initialization routine separately. In\n0026 % the case of one fixed setting you can use just the 'start' method (e.g.\n0027 % 'ep.start').\n0028 ep.initialize; \n0029 \n0030 %% Input/output configuration\n0031 % If there is no &quot;variables.cfg&quot; config file present in the directory\n0032 % where the IDF file resides, then the IDF file is parsed for configured\n0033 % inputs/outputs (and &quot;variables.cfg&quot; file is created under output directory\n0034 % - named 'eplusout' by default). If a user-defined &quot;variables.cfg&quot; is\n0035 % present then it should contain a subset of the IDF I/O and it defines\n0036 % the co-simulation inputs/outputs.\n0037 \n0038 % Display inputs/outputs defined in the IDF file. (no &quot;variables.cfg&quot; file\n0039 % present).\n0040 disp('Input/output configuration without the &quot;variables.cfg&quot; file present.');\n0041 inputTable = ep.inputTable    %#ok&lt;*NASGU,*NOPTS&gt;\n0042 outputTable = ep.outputTable\n0043 \n0044 % Now with the &quot;variables.cfg&quot; file (example file contains a subset of the\n0045 % IDF i/o set).\n0046 cd(fileparts(mfilename('fullpath')));\n0047 copyfile('variables_example.cfg','variables.cfg');\n0048 \n0049 % Re-initialize\n0050 ep.initialize;\n0051 \n0052 disp('Input/output configuration with the &quot;variables.cfg&quot; file present.');\n0053 inputTable = ep.inputTable\n0054 outputTable = ep.outputTable\n0055 \n0056 % The IDF i/o configuration can still be viewed\n0057 disp('Alternative way to obtain IDF input/output configuration.');\n0058 inputTableIDF = ep.idfData.inputTable\n0059 outputTableIDF = ep.idfData.outputTable\n0060 \n0061 %% Simulate\n0062 \n0063 % Specify simulation duration\n0064 endTime = 4*24*60*60; %[s]\n0065 \n0066 % Prepare data logging\n0067 nRows = ceil(endTime / ep.timestep); %Query timestep after mlep initialization\n0068 logTable = table('Size',[0, 1 + ep.nOut],...\n0069     'VariableTypes',repmat({'double'},1,1 + ep.nOut),...\n0070     'VariableNames',[{'Time'}; ep.outputSigName]);\n0071 iLog = 1;\n0072 \n0073 % Start the co-simulation process and communication.\n0074 ep.start\n0075 \n0076 % The simulation loop\n0077 t = 0;\n0078 while t &lt; endTime\n0079     % Prepare inputs (possibly from last outputs)\n0080     u = [20 25];\n0081     \n0082     % Get outputs from EnergyPlus\n0083     [y, t] = ep.read;\n0084     \n0085     % Send inputs to EnergyPlus\n0086     ep.write(u,t); \n0087     \n0088     % Log\n0089     logTable(iLog, :) = num2cell([t y(:)']);\n0090     iLog = iLog + 1;        \n0091 end\n0092 % Stop co-simulation process\n0093 ep.stop;\n0094 \n0095 %% Plot results\n0096 \n0097 plot(seconds(table2array(logTable(:,1))),...\n0098     table2array(logTable(:,2:end)));\n0099 xtickformat('hh:mm:ss');\n0100 legend(logTable.Properties.VariableNames(2:end),'Interpreter','none');\n0101 \n0102 title(ep.idfFile);\n0103 xlabel('Time [hh:mm:ss]');\n0104 ylabel('Temperature [C]');\n0105 \n0106 %% Clean up\n0107 delete variables.cfg
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/decodePacket.html<|end_filename|>\n\n\n\n Description of decodePacket\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; decodePacket.m
\n\n\n\n

decodePacket\n

\n\n

PURPOSE \"^\"

\n
DECODEPACKET - Decode packet to data.
\n\n

SYNOPSIS \"^\"

\n
function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)
\n\n

DESCRIPTION \"^\"

\n
DECODEPACKET - Decode packet to data.\nDecode a packet (a string) to data.  The packet format follows the\nBCVTB co-simulation communication protocol .\n\n   Syntax: [flag, timevalue, realvalues, intvalues, boolvalues] = mlepDecodePacket(packet)\n\n   Inputs:\n       packet: the packet to be decoded (a string).\n\n   Outputs:\n             flag - An integer specifying the (status) flag. Refer to the BCVTB\n                    protocol for allowed flag values.\n        timevalue - A real value which is the current simulation time in\n                    seconds.\n       realvalues - A vector of received real value data.\n        intvalues - a vector of received integer value data.\n       boolvalues - a vector of received boolean value data.\n\n       Each of the received data vector can be empty if there is no data\n       of that type sent.\n\n Protocol Version 1 &amp; 2:\n Packet has the form:\n       &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \\n&quot;\n where\n   v    - version number (1,2)\n   f    - flag (0: communicate, 1: finish, -10: initialization error,\n                -20: time integration error, -1: unknown error)\n   dr   - number of real values\n   di   - number of integer values\n   db   - number of boolean values\n   t    - current simulation time in seconds (format %20.15e)\n   r1 r2 ... are real values (format %20.15e)\n   i1 i2 ... are integer values (format %d)\n   b1 b2 ... are boolean values (format %d)\n   \\n   - carriage return\n\n Note that if f is non-zero, other values after it will not be processed.\n\n   See also: MLEP.ENCODEDATA, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,\n             READ\n\n (C) 2010,  ()
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)\n0002 %DECODEPACKET - Decode packet to data.\n0003 %Decode a packet (a string) to data.  The packet format follows the\n0004 %BCVTB co-simulation communication protocol .\n0005 %\n0006 %   Syntax: [flag, timevalue, realvalues, intvalues, boolvalues] = mlepDecodePacket(packet)\n0007 %\n0008 %   Inputs:\n0009 %       packet: the packet to be decoded (a string).\n0010 %\n0011 %   Outputs:\n0012 %             flag - An integer specifying the (status) flag. Refer to the BCVTB\n0013 %                    protocol for allowed flag values.\n0014 %        timevalue - A real value which is the current simulation time in\n0015 %                    seconds.\n0016 %       realvalues - A vector of received real value data.\n0017 %        intvalues - a vector of received integer value data.\n0018 %       boolvalues - a vector of received boolean value data.\n0019 %\n0020 %       Each of the received data vector can be empty if there is no data\n0021 %       of that type sent.\n0022 %\n0023 % Protocol Version 1 &amp; 2:\n0024 % Packet has the form:\n0025 %       &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \\n&quot;\n0026 % where\n0027 %   v    - version number (1,2)\n0028 %   f    - flag (0: communicate, 1: finish, -10: initialization error,\n0029 %                -20: time integration error, -1: unknown error)\n0030 %   dr   - number of real values\n0031 %   di   - number of integer values\n0032 %   db   - number of boolean values\n0033 %   t    - current simulation time in seconds (format %20.15e)\n0034 %   r1 r2 ... are real values (format %20.15e)\n0035 %   i1 i2 ... are integer values (format %d)\n0036 %   b1 b2 ... are boolean values (format %d)\n0037 %   \\n   - carriage return\n0038 %\n0039 % Note that if f is non-zero, other values after it will not be processed.\n0040 %\n0041 %   See also: MLEP.ENCODEDATA, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,\n0042 %             READ\n0043 %\n0044 % (C) 2010,  ()\n0045 \n0046 % Remove non-printable characters from packet, then\n0047 % convert packet string to a vector of numbers\n0048 [data, status] = str2num(packet(isstrprop(packet, 'print')));  % This function is very fast\n0049 if ~status\n0050     error('Error while parsing the packet string: %s', packet);\n0051 end\n0052 \n0053 % Check data\n0054 datalen = length(data);\n0055 if datalen &lt; 2\n0056     error('Invalid packet format: length is only %d.', datalen);\n0057 end\n0058 \n0059 % data(1) is version number\n0060 if data(1) &lt;= 2\n0061     % Get the flag number\n0062     flag = data(2);\n0063     \n0064     realvalues = [];\n0065     intvalues = [];\n0066     boolvalues = [];\n0067     \n0068     if flag == 0  % Read on\n0069         if datalen &lt; 5\n0070             error('Invalid packet: lacks lengths of data.');\n0071         end\n0072         \n0073         data(3:5) = fix(data(3:5));\n0074         pos1 = data(3) + data(4);\n0075         pos2 = pos1 + data(5);\n0076         if 6 + pos2 &gt; datalen\n0077             error('Invalid packet: not enough data.');\n0078         end\n0079         \n0080         % Now read data to vectors\n0081         timevalue = data(6);\n0082         realvalues = data(7:6+data(3));\n0083         intvalues = data(7+data(3):6+pos1);\n0084         boolvalues = logical(data(7+pos1:6+pos2));\n0085     else\n0086         % Non-zero flag --&gt; don't need to read on\n0087         timevalue = [];\n0088     end\n0089     \n0090 else\n0091     error('Unsupported packet format version: %g.', data(1));\n0092 end\n0093 \n0094 end\n0095
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/library/vector2Bus_clbk.html<|end_filename|>\n\n\n\n Description of vector2Bus_clbk\n \n \n \n \">\n \n \n\n\n\n
Home &gt; library &gt; vector2Bus_clbk.m
\n\n\n\n

vector2Bus_clbk\n

\n\n

PURPOSE \"^\"

\n
VECTOR2BUS_CLBK - Callback functions.
\n\n

SYNOPSIS \"^\"

\n
function vector2Bus_clbk(block, type)
\n\n

DESCRIPTION \"^\"

\n
VECTOR2BUS_CLBK - Callback functions.\n Valid type options are 'popup', 'initMask', 'InitFcn', 'CopyFcn'.
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n

SUBFUNCTIONS \"^\"

\n\n\n

SOURCE CODE \"^\"

\n
0001 function vector2Bus_clbk(block, type)\n0002 %VECTOR2BUS_CLBK - Callback functions.\n0003 % Valid type options are 'popup', 'initMask', 'InitFcn', 'CopyFcn'.\n0004 \n0005 % Copyright (c) 2018,  ()\n0006 % All rights reserved.\n0007 \n0008 % String to be displayed when no Bus object is selected\n0009 default_str = 'Select a Bus object...';\n0010 \n0011 % String to be displayed when no Bus object is found\n0012 empty_str = 'No Bus objects found.';\n0013 \n0014 switch type\n0015     case 'popup'\n0016         vector2Bus_popup(block);\n0017     case 'maskInit'\n0018         vector2Bus_maskInit(block);\n0019     case 'InitFcn'\n0020         vector2Bus_InitFcn(block);\n0021     case 'CopyFcn'\n0022         vector2Bus_CopyFcn(block);\n0023     otherwise\n0024         error('Unknown callback: ''%s.''', type);\n0025 end\n0026 \n0027     function vector2Bus_popup(block)\n0028         % Using variable names terminated with &quot;_BOBC&quot; to lessen the chances of\n0029         % collisions with existing workspace variables.\n0030         \n0031         % Get the current block handle and mask handle.\n0032         maskObj     = Simulink.Mask.get(block);\n0033         popupParam  = maskObj.getParameter('busType');\n0034         \n0035         % --- Find Bus objects ---\n0036         % Get base workspace variables\n0037         bwVars = evalin('base','whos');\n0038         allBusNames = {};\n0039         if ~isempty(bwVars)\n0040             flag = strcmp({bwVars.class},'Simulink.Bus');\n0041             allBusNames = {bwVars(flag).name};                    \n0042         end\n0043         \n0044         % Get Data dictionary variables\n0045         ddName = get_param(bdroot(block),'DataDictionary');\n0046         if ~isempty(ddName)\n0047             dd = Simulink.data.dictionary.open(ddName);  \n0048             ddSec = getSection(dd,'Design Data');\n0049             ddVars = find(ddSec,'-value','-class','Simulink.Bus'); %#ok&lt;GTARG&gt;\n0050             allBusNames = [allBusNames {ddVars.Name}];\n0051         end\n0052         \n0053         % --- Create popup ---\n0054         % Create popup entries\n0055         busOpts = strcat({'Bus: '}, allBusNames);\n0056        \n0057         if ~isempty(busOpts)\n0058             % Add default option\n0059             extOpts = [{default_str}, busOpts];\n0060             \n0061             % Current number of options\n0062             old_opts = popupParam.TypeOptions;\n0063             \n0064             % Fill out the BusType options\n0065             if ~strcmp([old_opts{:}],[extOpts{:}])\n0066                 popupParam.TypeOptions = extOpts;\n0067             end\n0068         else\n0069             popupParam.TypeOptions = {empty_str};\n0070         end    \n0071         \n0072         % Internal Bus Creator handle\n0073         bch = get_param([block '/BusCreator'],'handle');\n0074         \n0075         % --- Mask popup functionality ---\n0076         % all options that can happen, hopefully\n0077         currentOutDataTypeStr = get_param(bch, 'OutDataTypeStr');        \n0078         selectedDataType = get_param(block,'busType');\n0079         lastManuallySelectedParam = popupParam.Value;\n0080           \n0081         if strcmp(currentOutDataTypeStr,'Inherit: auto')            \n0082             if ~ismember(selectedDataType,{default_str, empty_str})                \n0083                 % = Previously unused block and valid selection\n0084                 % Set Output Data Type to the selected value\n0085                 set_param(bch, 'OutDataTypeStr',selectedDataType);\n0086                 set_param(block,'busType',selectedDataType);\n0087                 popupParam.Value = selectedDataType;\n0088             end\n0089         else            \n0090             if strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; ...\n0091                     strcmp(currentOutDataTypeStr, selectedDataType)\n0092                 % = no change\n0093                 % Do nothing, nothing changed\n0094             elseif ismember(selectedDataType,{default_str}) || ...\n0095                     (~strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; ...\n0096                     strcmp(lastManuallySelectedParam,currentOutDataTypeStr))\n0097                 % = default or empty selected, or option has disappeared\n0098                 % Keep the Output data type and try to select the popup\n0099                 % option pertaining to the Output data type\n0100                 if ismember(currentOutDataTypeStr, busOpts)            \n0101                     set_param(block,'busType',currentOutDataTypeStr);\n0102                     popupParam.Value = currentOutDataTypeStr;\n0103                 else\n0104                     set_param(block,'busType',default_str);\n0105                     popupParam.Value = default_str;\n0106                 end\n0107             elseif strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; ...\n0108                     ismember(currentOutDataTypeStr, busOpts)\n0109                 % = bus objects changed, but the output type is still\n0110                 % available\n0111                 % Keep the Output data type and try to select the popup\n0112                 % option pertaining to the Output data type\n0113                 set_param(block,'busType',currentOutDataTypeStr);\n0114                 popupParam.Value = currentOutDataTypeStr;\n0115             elseif ~strcmp(lastManuallySelectedParam,selectedDataType)\n0116                 % = new bus option selected\n0117                 % Set Output Data Type to the selected value\n0118                 set_param(bch, 'OutDataTypeStr',selectedDataType);\n0119                 set_param(block,'busType',selectedDataType);\n0120                 popupParam.Value = selectedDataType;\n0121             else \n0122                 % = bus object changed and the current selection is missing\n0123                 % Actually, it is not possible in connection to mlep.\n0124                set_param(bch, 'OutDataTypeStr','Inherit: auto');\n0125             end            \n0126         end\n0127         \n0128         % Set the options to the BusCreator block\n0129         set_param(bch,'InheritFromInputs', 'off');\n0130     end\n0131 \n0132     function vector2Bus_maskInit(block)\n0133         % Create demux and bus creator inside. Serves also is an indicator\n0134         % for bus selection validity\n0135         \n0136         %% Validate busType\n0137         \n0138         % Get current option\n0139         selectedBusTypeStr = get_param(block, 'busType');\n0140         \n0141         if ismember(selectedBusTypeStr,{default_str, empty_str}) || ...\n0142             isempty(regexp(selectedBusTypeStr,'Bus: ','ONCE'))                       \n0143             return\n0144         end\n0145         \n0146         % Get Bus Type\n0147         busType = getBusTypeFromBusTypeStr(selectedBusTypeStr);\n0148         \n0149         % Get Bus object\n0150         model = bdroot(block);\n0151         busObj = getBusObject(model, busType);\n0152         \n0153         % Check the busObj\n0154         if isempty(busObj)          \n0155             warning('Simulink.Bus object ''%s'' not found in a data dictionary nor the base workspace.',...\n0156                 busType);\n0157             return\n0158         end\n0159         \n0160         % Get the desired number of elements\n0161         nSignals = busObj.getNumLeafBusElements;\n0162         \n0163         % Set internal Demux, Bus Creator and connect\n0164         createConnection(block, nSignals);\n0165         \n0166     end\n0167 \n0168     function vector2Bus_InitFcn(block)\n0169         % Check if Output Data Bus object is available, set &quot;Inherit:auto&quot;\n0170         % if not to allow for its creation elsewhere\n0171         \n0172         % Validate\n0173         vector2Bus_popup(block);\n0174         \n0175         % Internal Bus Creator handle\n0176         bch = get_param([block '/BusCreator'],'handle');\n0177         \n0178         % Get current Output data\n0179         currentOutDataTypeStr = get_param(bch, 'OutDataTypeStr');\n0180         \n0181         if ~strcmp(currentOutDataTypeStr, 'Inherit: auto')\n0182             % Get Bus Type\n0183             busType = getBusTypeFromBusTypeStr(currentOutDataTypeStr);\n0184 \n0185             % Get Bus object\n0186             model = bdroot(block);           \n0187             \n0188             % Validate bus object\n0189             if isempty(getBusObject(model, busType))\n0190                 %Give error\n0191                 hilite_system(block);\n0192                 error('''%s'': Selected Bus object ''%s'' doesn''t exists in the base workspace nor in any linked data dictionary.', block, busType);\n0193             end\n0194         end\n0195     end\n0196 \n0197     function vector2Bus_CopyFcn(block)\n0198        % Disable library link\n0199        set_param(block,'LinkStatus','none');\n0200        set_param(block,'CopyFcn','');\n0201     end\n0202 \n0203     function busObj = getBusObject(model, busType)\n0204         % Load the selected Bus object\n0205         busObj = [];        \n0206         mws = get_param(model,'ModelWorkspace');\n0207         if Simulink.data.existsInGlobal(model,busType)\n0208             % From Data Dictionary first\n0209             busObj = Simulink.data.evalinGlobal(model,busType);            \n0210 %         elseif hasVariable(mws,busType)\n0211 %             % From Model workspace next (maybe it will be allowed in the\n0212 %             % future)\n0213 %             busObj = getVariable(mws, busType);\n0214         elseif evalin('base',['exist(''' busType ''',''var'')'])\n0215             % From Base workspace last\n0216             busObj = evalin('base',busType);            \n0217         end\n0218     end\n0219 end\n0220 \n0221 function busType = getBusTypeFromBusTypeStr(busTypeStr)\n0222 % ... and parse off &quot;Bus: &quot; so the string of the desired bus contained in\n0223 % 'OutDataTypeStr' matches the raw workspace bus names.\n0224 busType = regexp(busTypeStr,'^Bus: (.*)','tokens');\n0225 assert(~isempty(busType));\n0226 busType = busType{1}{1};\n0227 end\n0228 \n0229 function createConnection(block, nSignals)\n0230 %% Create demux, bus creator and connect them\n0231 \n0232 % Get the current vector size\n0233 nDemuxSignals = str2double(get_param([block '/Demux'],'Outputs'));\n0234 nBCSignals = str2double(get_param([block '/BusCreator'],'Inputs'));\n0235 \n0236 if nDemuxSignals ~= nBCSignals\n0237     % Recreate the block completely\n0238     \n0239     % Find lines\n0240     lines = find_system(gcb, ...\n0241         'LookUnderMasks','all',...\n0242         'FindAll','on',...\n0243         'type','line');\n0244     \n0245     % Delete lines\n0246     delete_line(lines);    \n0247     \n0248     % Add lines from/to ports\n0249     add_line(block,'In1/1','Demux/1'); \n0250     add_line(block,'BusCreator/1','Out1/1'); \n0251     \n0252     % Set number of demux signals to trigger recreation\n0253     nDemuxSignals = 0;\n0254 end\n0255 \n0256 % Create connections\n0257 if nSignals &gt; nDemuxSignals\n0258     % Add just the right number of lines\n0259     set_param([block '/Demux'],'Outputs',num2str(nSignals))\n0260     set_param([block '/BusCreator'],'Inputs',num2str(nSignals))\n0261     for iSig = (nDemuxSignals+1):nSignals\n0262         add_line(block,['Demux/' num2str(iSig)],['BusCreator/' num2str(iSig)])\n0263     end\n0264 elseif nSignals &lt; nDemuxSignals\n0265     % Remove just the right number of lines\n0266     for iSig = (nSignals+1):nDemuxSignals\n0267         delete_line(block,['Demux/' num2str(iSig)],['BusCreator/' num2str(iSig)])\n0268     end\n0269     set_param([block '/Demux'],'Outputs',num2str(nSignals))\n0270     set_param([block '/BusCreator'],'Inputs',num2str(nSignals))\n0271 end\n0272 end
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/library/mlepEnergyPlusSimulation_clbk.html<|end_filename|>\n\n\n\n Description of mlepEnergyPlusSimulation_clbk\n \n \n \n \">\n \n \n\n\n\n
Home &gt; library &gt; mlepEnergyPlusSimulation_clbk.m
\n\n\n\n

mlepEnergyPlusSimulation_clbk\n

\n\n

PURPOSE \"^\"

\n
MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.
\n\n

SYNOPSIS \"^\"

\n
function mlepEnergyPlusSimulation_clbk(block, type, varargin)
\n\n

DESCRIPTION \"^\"

\n
MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n

SUBFUNCTIONS \"^\"

\n\n\n

SOURCE CODE \"^\"

\n
0001 function mlepEnergyPlusSimulation_clbk(block, type, varargin)\n0002 %MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.\n0003 \n0004 % Copyright (c) 2018,  ()\n0005 % All rights reserved.\n0006 %\n0007 \n0008 switch type\n0009     case 'OpenFcn'\n0010         mlepEnergyPlusSimulation_OpenFcn(block);            \n0011     case {'InitFcn','generateBus'}\n0012         mlepEnergyPlusSimulation_InitFcn(block);\n0013     case 'browseButton'\n0014         mlepEnergyPlusSimulation_browseButton(block, varargin{:});    \n0015     otherwise\n0016         error('Unknown callback: ''%s.''', type);\n0017 end\n0018 end\n0019 \n0020 function mlepEnergyPlusSimulation_OpenFcn(block)\n0021 \n0022 % Mask of a System Object cannot be programatically opened (r18a). So\n0023 % promoted parameters are used instead (at least semi-automatic way).\n0024 \n0025 % Open mask\n0026 open_system(block,'mask');\n0027 end\n0028 \n0029 function mlepEnergyPlusSimulation_InitFcn(block)\n0030 % Create new mlep instance (the actual existing instance is not reachable\n0031 % at the moment) and run validate properties routine of the system object!\n0032 \n0033 if strcmp(get_param(bdroot, 'BlockDiagramType'),'library') %strcmp(get_param(bdroot, 'SimulationStatus'),'initializing')\n0034     return\n0035 end\n0036 \n0037 % Get bus names\n0038 inputBusName = get_param(block,'inputBusName');\n0039 outputBusName = get_param(block,'outputBusName');\n0040 \n0041 % Create mlep instance\n0042 ep = mlep;\n0043 \n0044 % Set its properties\n0045 ep.idfFile = get_param(block,'idfFile');\n0046 ep.epwFile = get_param(block,'epwFile');\n0047 ep.useDataDictionary = strcmp(...\n0048                         get_param(block,'useDataDictionary'),...\n0049                         'on');\n0050 ep.inputBusName = inputBusName;\n0051 ep.outputBusName = outputBusName;\n0052 \n0053 % Load bus objects\n0054 loadBusObjects(ep);      \n0055 \n0056 % The bus objects are available now. Set them into all necessary blocks.\n0057 % Set Vector2Bus\n0058 set_param([block '/Vector to Bus'], 'busType', ['Bus: ' outputBusName]);\n0059 vector2Bus_clbk([block '/Vector to Bus'],'popup');\n0060 \n0061 % Set output\n0062 set_param([block '/Out'], 'OutDataTypeStr', ['Bus: ' outputBusName]);\n0063 \n0064 % Set input\n0065 set_param([block '/In'], 'OutDataTypeStr', ['Bus: ' inputBusName]);\n0066 end\n0067 \n0068 function selectedFile = mlepEnergyPlusSimulation_browseButton(block, varargin)\n0069 %mlepEnergyPlusSimulation_browseButton Browse button callback.\n0070 % Syntax: mlepEnergyPlusSimulation_browseButton(block, filetype) The\n0071 % filetype is either 'IDF' or 'EPW' and the the block parameters are set or\n0072 %\n0073 \n0074 assert(nargin == 2);\n0075 validateattributes(varargin{1},{'char'},{'scalartext'});\n0076 filetype = validatestring(varargin{1},{'IDF','EPW'});\n0077 \n0078 fileNameToSet = [lower(filetype), 'File']; % 'idfFile_SO' or 'epwFile_SO'\n0079 \n0080 % Ask for file\n0081 selectedFile = mlep.browseForFile(filetype);\n0082 if selectedFile ~= 0 % not a Cancel button\n0083     if isfield(get_param(block, 'ObjectParameters'),fileNameToSet) % parameter exists\n0084         % Set mask parameters\n0085         set_param(block, fileNameToSet, selectedFile);\n0086     else\n0087         warning('Parameter ''%s'' does not exist in block ''%s''. Not setting the selected path anywhere.', fileNameToSet, block);\n0088     end\n0089 end\n0090 end\n0091 \n0092 \n0093
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_so_example.html<|end_filename|>\n\n\n\n Description of mlepMatlab_so_example\n \n \n \n \">\n \n \n\n\n\n
Home &gt; examples &gt; legacy_example &gt; mlepMatlab_so_example.m
\n\n\n\n

mlepMatlab_so_example\n

\n\n

PURPOSE \"^\"

\n
% Co-simulation example using System Object
\n\n

SYNOPSIS \"^\"

\n
This is a script file.
\n\n

DESCRIPTION \"^\"

\n
% Co-simulation example using System Object\n Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool on \n a small office building simulation scenario.\n\n Note that a start of the simulation period as well as a timestep and\n an input/output configuration is defined by the the EnergyPlus simulation\n configuration file (.IDF). Climatic conditions are obtained from a\n EnergyPlus Weather data file (.EPW). \n\n For a detailed description of mlep usage please refere to the\n 'mlepMatlab_example.m' example.\n\n See also: mlepSimulink_example.slx
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 %% Co-simulation example using System Object\n0002 % Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool on\n0003 % a small office building simulation scenario.\n0004 %\n0005 % Note that a start of the simulation period as well as a timestep and\n0006 % an input/output configuration is defined by the the EnergyPlus simulation\n0007 % configuration file (.IDF). Climatic conditions are obtained from a\n0008 % EnergyPlus Weather data file (.EPW).\n0009 %\n0010 % For a detailed description of mlep usage please refere to the\n0011 % 'mlepMatlab_example.m' example.\n0012 %\n0013 % See also: mlepSimulink_example.slx\n0014 clear all\n0015 \n0016 %% Instantiate mlep and configure simulation\n0017 ep = mlep;\n0018 ep.idfFile = 'SmOffPSZ';\n0019 ep.epwFile = 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3';\n0020 \n0021 % Use user-defined I/O configuration\n0022 cd(fileparts(mfilename('fullpath')));\n0023 copyfile('variables_example.cfg','variables.cfg');\n0024 \n0025 ep.setup('init'); \n0026 pause(1); % pause to have the initial EnergyPlus output in this section\n0027 \n0028 %% Simulate\n0029 \n0030 endTime = 4*24*60*60;\n0031 nRows = ceil(endTime / ep.timestep);\n0032 logTable = table('Size',[0, 1 + ep.nOut],...\n0033     'VariableTypes',repmat({'double'},1,1 + ep.nOut),...\n0034     'VariableNames',[{'Time'}; ep.outputSigName]);\n0035 iLog = 1;\n0036 t = 0;\n0037 \n0038 while t &lt; endTime\n0039     \n0040     u = [20 25];\n0041     \n0042     % Send inputs to/ get outputs from EnergyPlus\n0043     y = ep.step(u); \n0044     \n0045     % Obtain elapsed simulation time [s]\n0046     t = ep.time;\n0047 \n0048     % Log data\n0049     logTable(iLog, :) = num2cell([t y']);\n0050     iLog = iLog + 1;    \n0051 end\n0052 ep.release;\n0053 \n0054 %% Plot results\n0055 plot(seconds(table2array(logTable(:,1))),...\n0056     table2array(logTable(:,2:end)));\n0057 xtickformat('hh:mm:ss');\n0058 legend(logTable.Properties.VariableNames(2:end),'Interpreter','none');\n0059 \n0060 title(ep.idfFile);\n0061 xlabel('Time [hh:mm:ss]');\n0062 ylabel('Temperature [C]');\n0063 \n0064 %% Clean up\n0065 delete variables.cfg
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/writeSocketConfig.html<|end_filename|>\n\n\n\n Description of writeSocketConfig\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; writeSocketConfig.m
\n\n\n\n

writeSocketConfig\n

\n\n

PURPOSE \"^\"

\n
WRITESOCKETCONFIG - Create socket configuration file.
\n\n

SYNOPSIS \"^\"

\n
function writeSocketConfig(fullFilePath, hostname, port)
\n\n

DESCRIPTION \"^\"

\n
 WRITESOCKETCONFIG - Create socket configuration file. \nCreate a BCVTB communication configuration file. \n\n  Syntax: writeSocketConfig(fullFilePath, serverSocket, hostname)\n\n  Inputs:\n   fullFilePath - A path to write the configuration to. \n       hostname - Hostname.\n           port - Port on the host.\n\n   See also: MLEP.MAKESOCKET\n\n (C) 2015,  ()\n     2018,  ()\n All rights reserved. Usage must follow the license given in the class\n definition.
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function writeSocketConfig(fullFilePath, hostname, port)\n0002 % WRITESOCKETCONFIG - Create socket configuration file.\n0003 %Create a BCVTB communication configuration file.\n0004 %\n0005 %  Syntax: writeSocketConfig(fullFilePath, serverSocket, hostname)\n0006 %\n0007 %  Inputs:\n0008 %   fullFilePath - A path to write the configuration to.\n0009 %       hostname - Hostname.\n0010 %           port - Port on the host.\n0011 %\n0012 %   See also: MLEP.MAKESOCKET\n0013 %\n0014 % (C) 2015,  ()\n0015 %     2018,  ()\n0016 % All rights reserved. Usage must follow the license given in the class\n0017 % definition.\n0018 \n0019 fid = fopen(fullFilePath, 'w');\n0020 if fid == -1\n0021     % error\n0022     error('Error while creating socket config file: %s', ferror(fid));\n0023 end\n0024 \n0025 % Write socket config to file\n0026 socket_config = [...\n0027     '&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;\\n' ...\n0028     '&lt;BCVTB-client&gt;\\n' ...\n0029     '&lt;ipc&gt;\\n' ...\n0030     '&lt;socket port=&quot;%d&quot; hostname=&quot;%s&quot;/&gt;\\n' ...\n0031     '&lt;/ipc&gt;\\n' ...\n0032     '&lt;/BCVTB-client&gt;'];\n0033 fprintf(fid, socket_config, port, hostname);\n0034 \n0035 [femsg, ferr] = ferror(fid);\n0036 if ferr ~= 0  % Error while writing config file\n0037     fclose(fid);\n0038     error('Error while writing socket config file: %s', femsg);\n0039 end\n0040 \n0041 fclose(fid);\n0042 end
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/library/busObjectBusCreator_clbk.html<|end_filename|>\n\n\n\n Description of busObjectBusCreator_clbk\n \n \n \n \">\n \n \n\n\n\n
Home &gt; library &gt; busObjectBusCreator_clbk.m
\n\n\n\n

busObjectBusCreator_clbk\n

\n\n

PURPOSE \"^\"

\n
BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.
\n\n

SYNOPSIS \"^\"

\n
function busObjectBusCreator_clbk(block, type)
\n\n

DESCRIPTION \"^\"

\n
BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n

SUBFUNCTIONS \"^\"

\n\n\n

SOURCE CODE \"^\"

\n
0001 function busObjectBusCreator_clbk(block, type)\n0002 %BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.\n0003 \n0004 % Copyright (c) 2018,  ()\n0005 % All rights reserved.\n0006 %\n0007 % Code influenced by Landon Wagner, 2015 code of 'Bus Object Bus Creator'.\n0008 \n0009 % String to be displayed when no Bus object is selected\n0010 default_str = 'Select a Bus object...';\n0011 \n0012 % String to be displayed when no Bus object is found\n0013 empty_str = 'No Bus objects found.';\n0014 \n0015 switch type\n0016     case 'popup'\n0017         busObjectBusCreator_popup(block);\n0018     case 'button'\n0019         busObjectBusCreator_button(block);\n0020     case 'CopyFcn'\n0021         busObjectBusCreator_CopyFcn(block);\n0022     otherwise\n0023         error('Unknown callback: ''%s.''', type);\n0024 end\n0025 \n0026 \n0027     function busObjectBusCreator_popup(block)\n0028         % Get the current block handle and mask handle.\n0029         bch = get_param(block,'handle');\n0030         maskObj = Simulink.Mask.get(block);\n0031         popupParam = maskObj.getParameter('busType');        \n0032         \n0033         % --- Find Bus objects ---\n0034         % Get base workspace variables\n0035         bwVars = evalin('base','whos');\n0036         allBusNames = {};\n0037         if ~isempty(bwVars)\n0038             flag = strcmp({bwVars.class},'Simulink.Bus');\n0039             allBusNames = {bwVars(flag).name};                    \n0040         end\n0041         \n0042         % Get Data dictionary - Design Data Bus objects\n0043         ddName = get_param(bdroot(block),'DataDictionary');\n0044         if ~isempty(ddName)\n0045             dd = Simulink.data.dictionary.open(ddName);  \n0046             ddSec = getSection(dd,'Design Data');\n0047             ddVars = find(ddSec,'-value','-class','Simulink.Bus'); %#ok&lt;GTARG&gt;\n0048             allBusNames = [allBusNames {ddVars.Name}];\n0049         end\n0050         \n0051         % --- Create popup ---\n0052         % Create popup entries\n0053         busOpts = strcat({'Bus: '}, allBusNames);\n0054         \n0055         if ~isempty(busOpts)            \n0056             % Add default option\n0057             extOpts = [{default_str}, busOpts];\n0058             \n0059             % Current number of options\n0060             old_opts = popupParam.TypeOptions;\n0061             \n0062             % Fill out the BusType options\n0063             if ~strcmp([old_opts{:}],[extOpts{:}])\n0064                 popupParam.TypeOptions = extOpts;\n0065             end\n0066         end\n0067         \n0068         % If the currently selected bus data type ('OutDataTypeStr') is not\n0069         % 'Inherit: auto' then get the current 'OutDataTypeStr' and 'maskVal.'\n0070         currentOutDataTypeStr = get_param(bch, 'OutDataTypeStr');\n0071         if ~strcmp(currentOutDataTypeStr, 'Inherit: auto')\n0072             \n0073             if ismember(currentOutDataTypeStr, busOpts)\n0074                 % Upon re-opening the mask if the default 'TypeOptions' list member\n0075                 % (The first one.) contained in 'maskVal' does not match the\n0076                 % currently selected bus data type ('OutDataTypeStr') then set the\n0077                 % 'TypeOptions' list member to the selected bus data type. (Cuts down\n0078                 % on confusion to have the displayed list member match the selected\n0079                 % bus data type rather than the first entry.)\n0080                 popupParam.Value = currentOutDataTypeStr;\n0081             else\n0082                 if isempty(busOpts)\n0083                     popupParam.TypeOptions = {empty_str};\n0084                     popupParam.Value = empty_str;\n0085                 else\n0086                     popupParam.Value = default_str;                    \n0087                 end                \n0088                 warning('The Output Data Type ''%s'' is no longer available in a data dictionary nor base workspace. Setting the Output Data Type to ''Inherit: auto''.',...\n0089                     currentOutDataTypeStr);                \n0090                 set_param(bch, 'OutDataTypeStr','Inherit: auto');\n0091             end\n0092         end \n0093     end\n0094 \n0095     function busObjectBusCreator_button(block)\n0096         % Using variable names terminated with &quot;_BOBC&quot; to lessen the chances of\n0097         % collisions with existing workspace variables.\n0098         \n0099         % Get the current block, current block handle and mask handle.\n0100         bch = get_param(block,'handle');\n0101         \n0102         % Get the desired bus type...\n0103         selectedBusTypeStr = get_param(bch, 'busType');\n0104         \n0105         if ismember(selectedBusTypeStr,{default_str, empty_str}) \n0106             helpdlg(selectedBusTypeStr);\n0107             return \n0108         elseif isempty(regexp(selectedBusTypeStr,'Bus: ','ONCE'))\n0109             warndlg('Invalid data entry &quot;%s&quot;',selectedBusTypeStr);\n0110             return\n0111         else\n0112             set_param(bch, 'OutDataTypeStr','Inherit: auto');            \n0113         end\n0114         \n0115         % ... and set the 'OutDataTypeStr' to it.\n0116         set_param(bch, 'OutDataTypeStr', selectedBusTypeStr);\n0117         \n0118                 \n0119         % Get the block path for 'add_line' function.\n0120         blockPath = get_param(bch, 'Parent');\n0121         \n0122         % Get the newly selected bus type ('OutDataTypeStr')...\n0123         busType = get_param(block, 'OutDataTypeStr');\n0124         \n0125         % ... and parse off &quot;Bus: &quot; so the string of the desired bus contained in\n0126         % 'OutDataTypeStr' matches the raw workspace bus names.\n0127         busType = busType(6:end);\n0128         \n0129         % Load the selected Bus object\n0130         if Simulink.data.existsInGlobal(bdroot(block),busType)\n0131             % From Data Dictionary first\n0132             busObj = Simulink.data.evalinGlobal(bdroot(block),busType);\n0133         elseif evalin('base',['exist(''' busType ''',''var'')'])\n0134             busObj = evalin('base',busType);\n0135         else\n0136             error('Simulink.Bus object ''%s'' not found in a data dictionary nor the base workspace.',...\n0137                 busType);\n0138         end\n0139                 \n0140         % From the parameters grab the number of lines to add.\n0141         nElems = busObj.getNumLeafBusElements;        \n0142         assert(nElems &gt; 0, 'The Simulink.Bus object ''%s'' contains zero elements.', busType);\n0143         \n0144         % First delete any existing lines on the port.\n0145         % Get the line handles.\n0146         lineHandle = get_param(bch, 'LineHandles');\n0147         \n0148         % If any lines exist (Non- -1 line handles.), delete them and start over.\n0149         if max(lineHandle.Inport &gt; 0)\n0150             \n0151             for i = 1:length(lineHandle.Inport)\n0152                 if lineHandle.Inport(i) &gt; 0\n0153                     delete_line(lineHandle.Inport(i))\n0154                 end\n0155             end\n0156         end\n0157         \n0158         % Set the number of inputs of the masked bus creator to the number of lines\n0159         % to add.\n0160         set_param(bch, 'Inputs', num2str(nElems));\n0161         \n0162         % Set heigh\n0163         sz = get_param(bch, 'Position');\n0164         y0 = sz(2) + (sz(4)-sz(2))/2; % vertical center\n0165         h  = max(95, nElems*10); % height\n0166         sz = [sz(1), ...\n0167             y0 - h/2, ...\n0168             sz(3), ...\n0169             y0 + h/2];\n0170         set_param(bch, 'Position', sz);\n0171                 \n0172         % Get Input port handles so we can grab the positions of them.\n0173         portHandle = get_param(bch, 'PortHandles');\n0174         \n0175         % Get longest signal name to adjust the line lenght right\n0176         signalNames = {busObj.Elements.Name};\n0177         lineLength = ceil(50/10*max(strlength(signalNames)))+10;\n0178         for i = 1:nElems            \n0179             % Get the position of input port number 'i'.\n0180             portPos = get_param(portHandle.Inport(i), 'Position');            \n0181             % Add a line long as the longest name\n0182             %(This must be done because it's the lines that get named,\n0183             % not the port positions.)\n0184             portLine = add_line(blockPath, ...\n0185                 [portPos - [lineLength 0]; portPos]);\n0186             \n0187             % Rename the new line to the bus 'i-st/nd/rd/th' element name.\n0188             set_param(portLine, 'Name', busObj.Elements(i).Name)\n0189         end\n0190         \n0191     end\n0192 \n0193     function busObjectBusCreator_CopyFcn(block)\n0194         % Disable library link\n0195         set_param(block,'LinkStatus','none');\n0196     end\n0197 end
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/encodeRealData.html<|end_filename|>\n\n\n\n Description of encodeRealData\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; encodeRealData.m
\n\n\n\n

encodeRealData\n

\n\n

PURPOSE \"^\"

\n
ENCODEREALDATA Encode real value data to packet.
\n\n

SYNOPSIS \"^\"

\n
function packet = encodeRealData(vernumber, flag, timevalue, realvalues)
\n\n

DESCRIPTION \"^\"

\n
ENCODEREALDATA Encode real value data to packet.\nEncode real value data to a packet (a string) that can be sent to the\nexternal program.  This function is a special version of\nmlep.encodeData in which integer and boolean data does not exist.\n\n   Syntax: packet = encodeRealData(vernumber, flag, timevalue, realvalues)\n\n   Inputs:\n       vernumber - Version of the protocol to be used. Currently, version 1\n                   and 2 are supported.\n            flag - An integer specifying the (status) flag. Refer to the BCVTB\n                   protocol for allowed flag values.\n       timevalue - A real value which is the current simulation time in\n                   seconds.\n      realvalues - A vector of real value data to be sent. Can be empty.\n\n  Outputs:\n          packet - A string that contains the encoded data.\n\n   See also:\n       MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODESTATUS\n\n (C) 2010 by  ()
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function packet = encodeRealData(vernumber, flag, timevalue, realvalues)\n0002 %ENCODEREALDATA Encode real value data to packet.\n0003 %Encode real value data to a packet (a string) that can be sent to the\n0004 %external program.  This function is a special version of\n0005 %mlep.encodeData in which integer and boolean data does not exist.\n0006 %\n0007 %   Syntax: packet = encodeRealData(vernumber, flag, timevalue, realvalues)\n0008 %\n0009 %   Inputs:\n0010 %       vernumber - Version of the protocol to be used. Currently, version 1\n0011 %                   and 2 are supported.\n0012 %            flag - An integer specifying the (status) flag. Refer to the BCVTB\n0013 %                   protocol for allowed flag values.\n0014 %       timevalue - A real value which is the current simulation time in\n0015 %                   seconds.\n0016 %      realvalues - A vector of real value data to be sent. Can be empty.\n0017 %\n0018 %  Outputs:\n0019 %          packet - A string that contains the encoded data.\n0020 %\n0021 %   See also:\n0022 %       MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODESTATUS\n0023 %\n0024 % (C) 2010 by  ()\n0025 \n0026 ni = nargin;\n0027 if ni &lt; 4\n0028     error('Not enough arguments: all input arguments are required.');\n0029 end\n0030 \n0031 if vernumber &lt;= 2\n0032     if flag == 0\n0033         packet = [sprintf('%d 0 %d 0 0 %20.15e ', ...\n0034                         vernumber,...\n0035                         length(realvalues),...\n0036                         timevalue), ...\n0037                   sprintf('%20.15e ', realvalues)];\n0038     else\n0039         % Error\n0040         packet = sprintf('%d %d', vernumber, flag);\n0041     end\n0042 else\n0043     packet = '';\n0044 end\n0045 \n0046 end\n0047 \n0048 % Protocol Version 1 &amp; 2:\n0049 % Packet has the form:\n0050 %       v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...\n0051 % where\n0052 %   v    - version number (1,2)\n0053 %   f    - flag (0: communicate, 1: finish, -10: initialization error,\n0054 %                -20: time integration error, -1: unknown error)\n0055 %   dr   - number of real values\n0056 %   di   - number of integer values\n0057 %   db   - number of boolean values\n0058 %   t    - current simulation time in seconds (format %20.15e)\n0059 %   r1 r2 ... are real values (format %20.15e)\n0060 %   i1 i2 ... are integer values (format %d)\n0061 %   b1 b2 ... are boolean values (format %d)\n0062 %\n0063 % Note that if f is non-zero, other values after it will not be processed.
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/@mlep/writeVariableConfig.html<|end_filename|>\n\n\n\n Description of writeVariableConfig\n \n \n \n \">\n \n \n\n\n\n
Home &gt; @mlep &gt; writeVariableConfig.m
\n\n\n\n

writeVariableConfig\n

\n\n

PURPOSE \"^\"

\n
WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol.
\n\n

SYNOPSIS \"^\"

\n
function writeVariableConfig(fullFilePath, inputTable, outputTable)
\n\n

DESCRIPTION \"^\"

\n
 WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol.\nCreate a XML file (&quot;variables.cfg&quot;) with input/output configuration to be\nused by the BCVTB protocol on both sides of the communication socket. \n\n  Syntax: writeVariableConfig(fullFilePath, inputTable, outputTable)\n\n  Inputs:\n   fullFilePath - A path to write the configuration to. \n     inputTable - Table containing specification of the inputs to\n                  EnergyPlus.\n    outputTable - Table containing specification of the outputs from\n                  EnergyPlus.\n\n   See also: MLEP.PARSEVARIABLESCONFIGFILE, MLEP.MAKEVARIABLESCONFIGFILE\n\n (C) 2015,  ()\n     2018,  ()\n All rights reserved. Usage must follow the license given in the class\n definition.
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 function writeVariableConfig(fullFilePath, inputTable, outputTable)\n0002 % WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol.\n0003 %Create a XML file (&quot;variables.cfg&quot;) with input/output configuration to be\n0004 %used by the BCVTB protocol on both sides of the communication socket.\n0005 %\n0006 %  Syntax: writeVariableConfig(fullFilePath, inputTable, outputTable)\n0007 %\n0008 %  Inputs:\n0009 %   fullFilePath - A path to write the configuration to.\n0010 %     inputTable - Table containing specification of the inputs to\n0011 %                  EnergyPlus.\n0012 %    outputTable - Table containing specification of the outputs from\n0013 %                  EnergyPlus.\n0014 %\n0015 %   See also: MLEP.PARSEVARIABLESCONFIGFILE, MLEP.MAKEVARIABLESCONFIGFILE\n0016 %\n0017 % (C) 2015,  ()\n0018 %     2018,  ()\n0019 % All rights reserved. Usage must follow the license given in the class\n0020 % definition.\n0021 \n0022 % XML header\n0023 docType = com.mathworks.xml.XMLUtils.createDocumentType('SYSTEM', [],'variables.dtd');\n0024 docNode = com.mathworks.xml.XMLUtils.createDocument([], 'BCVTB-variables', docType);\n0025 setEncoding(docNode, 'ISO-8859-1');\n0026 setVersion(docNode, '1.0')\n0027 \n0028 % Disclaimer\n0029 disclaimer = docNode.createComment([newline, ...\n0030     '|===========================================================|' newline,...\n0031     '|           THIS FILE IS AUTOMATICALLY GENERATED            |' newline,...\n0032     '| DO NOT EDIT THIS FILE AS ANY CHANGES WILL BE OVERWRITTEN! |' newline,...\n0033     '|===========================================================|' newline,...\n0034     ]);\n0035 \n0036 % INPUT to E+\n0037 docRootNode = docNode.getDocumentElement;\n0038 insertBefore(docNode, disclaimer, docRootNode);\n0039 %docRootNode.setAttribute('SYSTEM','variables.dtd');\n0040 appendChild(docRootNode, docNode.createComment('INPUT to E+'));\n0041 \n0042 table = inputTable;\n0043 names = table.Name;\n0044 types = table.Type;\n0045 for i=1:height(inputTable)\n0046     \n0047     %Example: &lt;variable source=&quot;Ptolemy&quot;&gt;\n0048     thisElement = createElement(docNode, 'variable');\n0049     setAttribute(thisElement, 'source','Ptolemy');\n0050     \n0051     %Example: &lt;EnergyPlus schedule=&quot;TSetHea&quot;/&gt;\n0052     newElement = createElement(docNode, 'EnergyPlus');\n0053     setAttribute(newElement, names(i),... % schedule, actuator, variable\n0054                              types(i));   % particular name\n0055     \n0056     appendChild(thisElement, newElement);\n0057     appendChild(docRootNode, thisElement);\n0058 end\n0059 \n0060 % OUTPUT from E+\n0061 docRootNode.appendChild(docNode.createComment('OUTPUT from E+'));\n0062 table = outputTable;\n0063 names = table.Name;\n0064 types = table.Type;\n0065 for i=1:height(outputTable)\n0066     \n0067     %Example: &lt;variable source=&quot;EnergyPlus&quot;&gt;\n0068     thisElement = createElement(docNode, 'variable');\n0069     setAttribute(thisElement, 'source','EnergyPlus');\n0070     \n0071     %Example: &lt;EnergyPlus name=&quot;ZSF1&quot; type=&quot;Zone Air Temperature&quot;/&gt;\n0072     newElement = createElement(docNode, 'EnergyPlus');\n0073     setAttribute(newElement, 'name',names(i)); % key value ('zone name')\n0074     setAttribute(newElement, 'type',types(i)); % variable name ('signal')\n0075     \n0076     appendChild(thisElement, newElement);\n0077     appendChild(docRootNode, thisElement);\n0078 end\n0079 \n0080 xmlwrite_r18a(fullFilePath,docNode);\n0081 end
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/library/functionIndex.html<|end_filename|>\n\n\n\n Index for Directory library\n \n \n \n \">\n \n \n\n\n\n\n
\"<\"&nbsp;Master indexIndex for library&nbsp;\"\" border=\"0\" src=\"../right.png\">
\n\n

Index for library

\n\n

Matlab files in this directory:

\n\n
\"\"&nbsp;busObjectBusCreator_clbkBUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.
\"\"&nbsp;mlepEnergyPlusSimulation_clbkMLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.
\"\"&nbsp;mlepSOMLEPSO EnergyPlus co-simulation system object.
\"\"&nbsp;slblocksSLBLOCKS - Simulink Library browser definition file
\"\"&nbsp;vector2Bus_clbkVECTOR2BUS_CLBK - Callback functions.
\n\n\n\n\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n\n\n<|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_example.html<|end_filename|>\n\n\n\n Description of mlepMatlab_example\n \n \n \n \">\n \n \n\n\n\n
Home &gt; examples &gt; legacy_example &gt; mlepMatlab_example.m
\n\n\n\n

mlepMatlab_example\n

\n\n

PURPOSE \"^\"

\n
% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example
\n\n

SYNOPSIS \"^\"

\n
This is a script file.
\n\n

DESCRIPTION \"^\"

\n
% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example\n Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in \n a small office building simulation scenario.\n\n Note that a start of the simulation period as well as a timestep and\n an input/output configuration is defined by the the EnergyPlus simulation\n configuration file (.IDF). Climatic conditions are obtained from a\n EnergyPlus Weather data file (.EPW). \n\n See also: mlepMatlab_so_example.m, mlepSimulink_example.slx
\n\n\n

CROSS-REFERENCE INFORMATION \"^\"

\nThis function calls:\n
    \n
\nThis function is called by:\n
    \n
\n\n\n\n\n

SOURCE CODE \"^\"

\n
0001 %% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example\n0002 % Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in\n0003 % a small office building simulation scenario.\n0004 %\n0005 % Note that a start of the simulation period as well as a timestep and\n0006 % an input/output configuration is defined by the the EnergyPlus simulation\n0007 % configuration file (.IDF). Climatic conditions are obtained from a\n0008 % EnergyPlus Weather data file (.EPW).\n0009 %\n0010 % See also: mlepMatlab_so_example.m, mlepSimulink_example.slx\n0011 \n0012 %% Create mlep instance and configure it\n0013 \n0014 % Instantiate co-simulation tool\n0015 ep = mlep;\n0016 \n0017 % Building simulation configuration file\n0018 ep.idfFile = 'SmOffPSZ';\n0019 \n0020 % Weather file\n0021 ep.epwFile = 'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3';\n0022 \n0023 \n0024 %% Input/output configuration\n0025 \n0026 % Initialize the co-simulation. This will load the IDF file.\n0027 ep.initialize; \n0028 \n0029 % Display inputs/outputs defined in the IDF file.\n0030 disp('Input/output configuration.');\n0031 inputTable = ep.inputTable    %#ok&lt;*NASGU,*NOPTS&gt;\n0032 outputTable = ep.outputTable\n0033 \n0034 %% Simulate\n0035 \n0036 % Specify simulation duration\n0037 endTime = 4*24*60*60; %[s]\n0038 \n0039 % Prepare data logging\n0040 nRows = ceil(endTime / ep.timestep); %Query timestep after mlep initialization\n0041 logTable = table('Size',[0, 1 + ep.nOut],...\n0042     'VariableTypes',repmat({'double'},1,1 + ep.nOut),...\n0043     'VariableNames',[{'Time'}; ep.outputSigName]);\n0044 iLog = 1;\n0045 \n0046 % Start the co-simulation process and communication.\n0047 ep.start\n0048 \n0049 % The simulation loop\n0050 t = 0;\n0051 while t &lt; endTime\n0052     % Prepare inputs (possibly from last outputs)\n0053     u = [20 25];\n0054     \n0055     % Get outputs from EnergyPlus\n0056     [y, t] = ep.read;\n0057     \n0058     % Send inputs to EnergyPlus\n0059     ep.write(u,t); \n0060     \n0061     % Log\n0062     logTable(iLog, :) = num2cell([t y(:)']);\n0063     iLog = iLog + 1;        \n0064 end\n0065 % Stop co-simulation process\n0066 ep.stop;\n0067 \n0068 %% Plot results\n0069 \n0070 plot(seconds(table2array(logTable(:,1))),...\n0071     table2array(logTable(:,2:end)));\n0072 xtickformat('hh:mm:ss');\n0073 legend(logTable.Properties.VariableNames(2:end),'Interpreter','none');\n0074 \n0075 title(ep.idfFile);\n0076 xlabel('Time [hh:mm:ss]');\n0077 ylabel('Temperature [C]');
\n
EnergyPlus Co-simulation Toolbox &copy; 2018
\n\n"},"max_stars_repo_name":{"kind":"string","value":"UCEEB/EnergyPlus-co-simulation-toolbox"}}},{"rowIdx":237,"cells":{"content":{"kind":"string","value":"<|start_filename|>src/k81x-fkeys.cpp<|end_filename|>\n// Copyright 2017 <>\n#include \"./k81x.h\"\n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\nvoid usage() {\n cout << \"Usage: sudo k81x-fkeys [-d device_path] [-u udev_path] [-v] on|off\" << endl;\n cout << \"Controls the functions of Logitech K810/K811 Keyboard F-keys\" << endl\n << endl;\n\n cout << \"As seen above, this tool needs root privileges to operate. Options:\"\n << endl;\n cout << \"\\t-d device_path\\tOptional Device file path of the Logitech keyboard,\"\n << endl\n << \"\\t\\t\\tusually /dev/hidraw0. Autodetecion is peformed if\" << endl\n << \"\\t\\t\\tthis and -u parameters are omitted.\" << endl;\n cout << \"\\t-u udev_path\\tUdev path of the Logitech keyboard, usually\"\n << endl\n << \"\\t\\t\\tstarting with /sys/devices. Autodetecion is peformed\" << endl\n << \"\\t\\t\\tif this and -d parameters are omitted.\" << endl;\n cout << \"\\t-v\\t\\tVerbose mode.\" << endl;\n cout << \"\\ton|off\\t\\t\\\"on\\\" causes the F-keys to act like standard\" << endl\n << \"\\t\\t\\tF1-F12 keys, \\\"off\\\" enables the enhanced functions.\" << endl;\n}\n\nint main(int argc, char **argv) {\n bool verbose = false, switch_on, silent = false;\n int error_return = 1;\n const char *device_path = NULL, *device_udevpath = NULL;\n\n // Fetch the command line arguments.\n int opt;\n while ((opt = getopt(argc, argv, \"d:u:vs\")) != -1) {\n switch (opt) {\n case 'd':\n device_path = optarg;\n break;\n case 'u':\n device_udevpath = optarg;\n break;\n case 'v':\n verbose = true;\n break;\n case 's':\n silent = true;\n error_return = 0;\n break;\n }\n }\n if (optind >= argc) {\n // No on/off argument.\n usage();\n return error_return;\n }\n if (!strcmp(\"on\", argv[optind])) {\n switch_on = true;\n } else if (!strcmp(\"off\", argv[optind])) {\n switch_on = false;\n } else {\n cerr << \"Invalid switch value, should be either \\\"on\\\" or \\\"off\\\".\" << endl;\n usage();\n return error_return;\n }\n\n // Check the privileges.\n if (geteuid() != 0 && !silent) {\n cerr << \"Warning: Program not running as root. It will most likely fail.\"\n << endl;\n }\n\n // Initialize the device.\n K81x *k81x = NULL;\n if (device_path == NULL && device_udevpath == NULL) {\n k81x = K81x::FromAutoFind(verbose);\n if (NULL == k81x && !silent) {\n cerr << \"Error while looking for a Logitech K810/K811 keyboard.\" << endl;\n }\n } else {\n if (NULL != device_path) {\n k81x = K81x::FromDevicePath(device_path, verbose);\n if (NULL == k81x && !silent) {\n cerr\n << \"Device \" << device_path\n << \" cannot be recognized as a supported Logitech K810/K811 keyboard.\"\n << endl;\n }\n }\n if (NULL == k81x && NULL != device_udevpath) {\n k81x = K81x::FromDeviceSysPath(device_udevpath, verbose);\n if (NULL == k81x && !silent) {\n cerr\n << \"Udev device \" << device_udevpath\n << \" cannot be recognized as a supported Logitech K810/K811 keyboard.\"\n << endl;\n }\n }\n }\n\n int result = 0;\n if (k81x != NULL) {\n // Switch the Kn keys mode.\n if (!k81x->SetFnKeysMode(switch_on) && !silent) {\n cerr << \"Error while setting the F-keys mode.\" << endl;\n result = error_return;\n }\n\n delete k81x;\n } else {\n result = error_return;\n }\n if (result && !verbose && !silent) {\n cerr << \"Try running with -v parameter to get more details.\" << endl;\n }\n return result;\n}\n\n\n<|start_filename|>Makefile<|end_filename|>\nCC=gcc\nCXX=g++\nRM=rm -f\nCPPFLAGS=-g -pthread\nLDFLAGS=-g -Wl,-z,now,-z,relro\nLDLIBS=-ludev\nTARGET=k81x-fkeys\n\nSRCS=src/k81x.cpp src/k81x-fkeys.cpp\nOBJS=$(subst .cpp,.o,$(SRCS))\n\nall: $(TARGET)\n\n$(TARGET): $(OBJS)\n\t$(CXX) $(LDFLAGS) -o $(TARGET) $(OBJS) $(LDLIBS) \n\ndepend: .depend\n\n.depend: $(SRCS)\n\t$(RM) ./.depend\n\t$(CXX) $(CPPFLAGS) -MM $^>>./.depend;\n\nclean:\n\t$(RM) $(OBJS)\n\ndistclean: clean\n\t$(RM) *~ .depend\n\t$(RM) $(TARGET)\n\ninstall: $(TARGET)\n\tinstall -D -m 0755 $(TARGET) $(DESTDIR)/opt/k81x/$(TARGET)\n\tinstall -D -m 0755 contrib/k81x.sh $(DESTDIR)/opt/k81x/k81x.sh\n\tinstall -D -m 0644 contrib/00-k81x.rules $(DESTDIR)/etc/udev/rules.d/00-k81x.rules\n\ninclude .depend\n\n\n<|start_filename|>src/k81x.cpp<|end_filename|>\n// Copyright 2017 <>\n#include \"./k81x.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\n#define LOGITECH_VENDOR (__u32)0x046d\n#define PRODUCT_K810 (__s16)0xb319\n#define PRODUCT_K811 (__s16)0xb317\n\nconst unsigned char fn_keys_on[] = {};\nconst unsigned char fn_keys_off[] = {};\n\nK81x::K81x(string device_path, int device_file, bool verbose) {\n device_path_ = device_path;\n device_file_ = device_file;\n verbose_ = verbose;\n}\n\nK81x::~K81x() {\n if (device_file_ >= 0) {\n close(device_file_);\n }\n}\n\nK81x* K81x::FromDevicePath(const string device_path, bool verbose) {\n int device_file_ = open(device_path.c_str(), O_RDWR | O_NONBLOCK);\n if (device_file_ < 0) {\n if (verbose) cerr << \"Unable to open device \" << device_path << endl;\n return NULL;\n }\n struct hidraw_devinfo info;\n memset(&info, 0x0, sizeof(info));\n K81x* result = NULL;\n if (ioctl(device_file_, HIDIOCGRAWINFO, &info) >= 0) {\n if (verbose)\n cout << \"Checking whether \" << device_path\n << \" is a Logitech K810/K811 keyboard.\" << endl;\n if (info.bustype != BUS_BLUETOOTH || info.vendor != LOGITECH_VENDOR ||\n (info.product != PRODUCT_K810 && info.product != PRODUCT_K811)) {\n if (verbose)\n cerr << \"Cannot identify \" << device_path\n << \" as a supported Logitech Keyboard\" << endl;\n\n } else {\n result = new K81x(device_path, device_file_, verbose);\n }\n } else {\n if (verbose)\n cerr << \"Cannot fetch parameter of a device: \" << device_path << endl;\n }\n if (result == NULL) {\n close(device_file_);\n }\n return result;\n}\n\nK81x* K81x::FromDeviceSysPath(const string device_syspath, bool verbose) {\n struct udev* udev;\n udev = udev_new();\n if (!udev) {\n if (verbose) cerr << \"Cannot create udev.\" << endl;\n return NULL;\n }\n udev_device* raw_dev = udev_device_new_from_syspath(udev, device_syspath.c_str());\n udev_unref(udev);\n if (!raw_dev) {\n if (verbose) cerr << \"Unknown udev device \" << device_syspath << endl;\n return NULL;\n }\n string device_path = udev_device_get_devnode(raw_dev);\n if (verbose) cout << \"Device path: \" << device_path << endl;\n\n return K81x::FromDevicePath(device_path, verbose);\n}\n\nK81x* K81x::FromAutoFind(bool verbose) {\n struct udev* udev;\n udev = udev_new();\n if (!udev) {\n if (verbose) cerr << \"Cannot create udev.\" << endl;\n return NULL;\n }\n if (verbose) cout << \"Looking for hidraw devices\" << endl;\n udev_enumerate* enumerate = udev_enumerate_new(udev);\n udev_enumerate_add_match_subsystem(enumerate, \"hidraw\");\n udev_enumerate_scan_devices(enumerate);\n udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);\n udev_list_entry* dev_list_entry;\n K81x* result = NULL;\n\n udev_list_entry_foreach(dev_list_entry, devices) {\n const char* sysfs_path = udev_list_entry_get_name(dev_list_entry);\n if (verbose) cout << \"Found hidraw device: \" << sysfs_path << endl;\n udev_device* raw_dev = udev_device_new_from_syspath(udev, sysfs_path);\n string device_path = udev_device_get_devnode(raw_dev);\n if (verbose) cout << \"Device path: \" << device_path << endl;\n result = K81x::FromDevicePath(device_path, verbose);\n if (NULL != result) break;\n }\n udev_enumerate_unref(enumerate);\n udev_unref(udev);\n if (NULL == result) {\n if (verbose) cerr << \"Couldn't find a Logitech K810/K811 keyboard.\" << endl;\n }\n\n return result;\n}\n\nbool K81x::SetFnKeysMode(bool enabled) {\n if (enabled) {\n return WriteSequence(fn_keys_on, sizeof(fn_keys_on));\n }\n return WriteSequence(fn_keys_off, sizeof(fn_keys_off));\n}\n\nbool K81x::WriteSequence(const unsigned char* sequence, unsigned int size) {\n if (write(device_file_, sequence, size) < 0) {\n if (verbose_)\n cerr << \"Error while writing to the device: \" << string(strerror(errno))\n << endl;\n return false;\n } else {\n if (verbose_) cout << \"Successfully set the mode of keyboard F-keys!\" << endl;\n }\n return true;\n}\n\n\n<|start_filename|>src/k81x.h<|end_filename|>\n// Copyright 2017 <>\n#ifndef K81X_H_\n#define K81X_H_\n\n#include \n\nclass K81x {\n public:\n static K81x* FromDevicePath(const std::string device_path, bool verbose);\n static K81x* FromDeviceSysPath(const std::string device_syspath, bool verbose);\n static K81x* FromAutoFind(bool verbose);\n ~K81x();\n\n bool SetFnKeysMode(bool enabled);\n\n private:\n K81x(std::string device_path, int device_file, bool verbose);\n\n bool WriteSequence(const unsigned char* sequence, unsigned int size);\n\n int device_file_;\n std::string device_path_;\n bool verbose_;\n};\n\n#endif // K81X_H_\n"},"max_stars_repo_name":{"kind":"string","value":"themech/k810_k811_fkeys"}}},{"rowIdx":238,"cells":{"content":{"kind":"string","value":"<|start_filename|>components/widgets/krnpanel/assets/js/core/jquery.shapeshift.coffee<|end_filename|>\n# Project: jQuery.Shapeshift\n# Description: Align elements to grid with drag and drop.\n# Author: \n# Maintained By: We the Media, inc.\n# License: MIT\n\n(($, window, document) ->\n pluginName = \"shapeshift\"\n defaults =\n # The Basics\n selector: \"*\"\n\n # Features\n enableDrag: true\n enableCrossDrop: true\n enableResize: true\n enableTrash: false\n\n # Grid Properties\n align: \"center\"\n colWidth: null\n columns: null\n minColumns: 1\n autoHeight: true\n maxHeight: null\n minHeight: 100\n gutterX: 10\n gutterY: 10\n paddingX: 10\n paddingY: 10\n\n # Animation\n animated: true\n animateOnInit: false\n animationSpeed: 225\n animationThreshold: 100\n\n # Drag/Drop Options\n dragClone: false\n deleteClone: true\n dragRate: 100\n dragWhitelist: \"*\"\n crossDropWhitelist: \"*\"\n cutoffStart: null\n cutoffEnd: null\n handle: false\n\n # Customize CSS\n cloneClass: \"ss-cloned-child\"\n activeClass: \"ss-active-child\"\n draggedClass: \"ss-dragged-child\"\n placeholderClass: \"ss-placeholder-child\"\n originalContainerClass: \"ss-original-container\"\n currentContainerClass: \"ss-current-container\"\n previousContainerClass: \"ss-previous-container\"\n\n class Plugin\n constructor: (@element, options) ->\n @options = $.extend {}, defaults, options\n @globals = {}\n @$container = $(element)\n\n if @errorCheck()\n @init()\n\n\n # ----------------------------\n # errorCheck:\n # Determine if there are any conflicting options\n # ----------------------------\n errorCheck: ->\n options = @options\n errors = false\n error_msg = \"Shapeshift ERROR:\"\n\n # If there are no available children, a colWidth must be set\n if options.colWidth is null\n $children = @$container.children(options.selector)\n\n if $children.length is 0\n errors = true\n console.error \"#{error_msg} option colWidth must be specified if Shapeshift is initialized with no active children.\"\n\n return !errors\n\n # ----------------------------\n # Init:\n # Only enable features on initialization,\n # then call a full render of the elements\n # ----------------------------\n init: ->\n @createEvents()\n @setGlobals()\n @setIdentifier()\n @setActiveChildren()\n @enableFeatures()\n @gridInit()\n @render()\n @afterInit()\n\n # ----------------------------\n # createEvents:\n # Triggerable events on the container\n # which run certain functions\n # ----------------------------\n createEvents: ->\n options = @options\n $container = @$container\n\n $container.off(\"ss-arrange\").on \"ss-arrange\", (e, trigger_drop_finished = false) => @render(false, trigger_drop_finished)\n $container.off(\"ss-rearrange\").on \"ss-rearrange\", => @render(true)\n $container.off(\"ss-setTargetPosition\").on \"ss-setTargetPosition\", => @setTargetPosition()\n $container.off(\"ss-destroy\").on \"ss-destroy\", => @destroy()\n $container.off(\"ss-shuffle\").on \"ss-shuffle\", => @shuffle()\n\n # ----------------------------\n # setGlobals:\n # Globals that only need to be set on initialization\n # ----------------------------\n setGlobals: ->\n # Prevent initial animation if applicable\n @globals.animated = @options.animateOnInit\n @globals.dragging = false\n\n # ----------------------------\n # afterInit:\n # Take care of some dirty business\n # ----------------------------\n afterInit: ->\n # Return animation to normal\n @globals.animated = @options.animated\n \n # ----------------------------\n # setIdentifier\n # Create a random identifier to tie to this container so that\n # it is easy to unbind the specific resize event from the browser\n # ----------------------------\n setIdentifier: ->\n @identifier = \"shapeshifted_container_\" + Math.random().toString(36).substring(7)\n @$container.addClass(@identifier)\n\n # ----------------------------\n # enableFeatures:\n # Enables options features\n # ----------------------------\n enableFeatures: ->\n @enableResize() if @options.enableResize\n @enableDragNDrop() if @options.enableDrag or @options.enableCrossDrop\n\n # ----------------------------\n # setActiveChildren:\n # Make sure that only the children set by the\n # selector option can be affected by Shapeshifting\n # ----------------------------\n setActiveChildren: ->\n options = @options\n\n # Add active child class to each available child element\n $children = @$container.children(options.selector)\n active_child_class = options.activeClass\n total = $children.length\n\n for i in [0...total]\n $($children[i]).addClass(active_child_class)\n\n @setParsedChildren()\n\n # Detect if there are any colspans wider than\n # the column options that were set\n columns = options.columns\n for i in [0...@parsedChildren.length]\n colspan = @parsedChildren[i].colspan\n\n min_columns = options.minColumns\n if colspan > columns and colspan > min_columns\n options.minColumns = colspan\n console.error \"Shapeshift ERROR: There are child elements that have a larger colspan than the minimum columns set through options.\\noptions.minColumns has been set to #{colspan}\"\n\n # ----------------------------\n # setParsedChildren:\n # Calculates and returns commonly used \n # attributes for all the active children\n # ----------------------------\n setParsedChildren: ->\n $children = @$container.find(\".\" + @options.activeClass).filter(\":visible\")\n total = $children.length\n\n parsedChildren = []\n for i in [0...total]\n $child = $($children[i])\n child =\n i: i\n el: $child\n colspan: parseInt($child.attr(\"data-ss-colspan\")) || 1\n height: $child.outerHeight()\n parsedChildren.push child\n @parsedChildren = parsedChildren\n\n # ----------------------------\n # setGrid:\n # Calculates the dimensions of each column\n # and determines to total number of columns\n # ----------------------------\n gridInit: ->\n gutter_x = @options.gutterX\n\n unless @options.colWidth >= 1\n # Determine single item / col width\n first_child = @parsedChildren[0]\n fc_width = first_child.el.outerWidth()\n fc_colspan = first_child.colspan\n single_width = (fc_width - ((fc_colspan - 1) * gutter_x)) / fc_colspan\n @globals.col_width = single_width + gutter_x\n else\n @globals.col_width = @options.colWidth + gutter_x\n\n # ----------------------------\n # render:\n # Determine the active children and\n # arrange them to the calculated grid\n # ----------------------------\n render: (reparse = false, trigger_drop_finished) ->\n @setActiveChildren() if reparse\n @setGridColumns()\n @arrange(false, trigger_drop_finished)\n\n # ----------------------------\n # setGrid:\n # Calculates the dimensions of each column\n # and determines to total number of columns\n # ----------------------------\n setGridColumns: ->\n # Common\n globals = @globals\n options = @options\n col_width = globals.col_width\n gutter_x = options.gutterX\n padding_x = options.paddingX\n inner_width = @$container.innerWidth() - (padding_x * 2)\n\n # Determine how many columns there currently can be\n minColumns = options.minColumns\n columns = options.columns || Math.floor (inner_width + gutter_x) / col_width\n if minColumns and minColumns > columns\n columns = minColumns\n globals.columns = columns\n\n # Columns cannot exceed children span\n children_count = @parsedChildren.length\n if columns > children_count\n actual_columns = 0\n for i in [0...@parsedChildren.length]\n colspan = @parsedChildren[i].colspan\n\n if colspan + actual_columns <= columns\n actual_columns += colspan\n\n columns = actual_columns\n\n # Calculate the child offset from the left\n globals.child_offset = padding_x\n switch options.align\n when \"center\"\n grid_width = (columns * col_width) - gutter_x\n globals.child_offset += (inner_width - grid_width) / 2\n\n when \"right\"\n grid_width = (columns * col_width) - gutter_x\n globals.child_offset += (inner_width - grid_width)\n\n # ----------------------------\n # arrange:\n # Animates the elements into their calcluated positions\n # ----------------------------\n arrange: (reparse, trigger_drop_finished) ->\n @setParsedChildren() if reparse\n\n globals = @globals\n options = @options\n\n # Common\n $container = @$container\n child_positions = @getPositions()\n\n parsed_children = @parsedChildren\n total_children = parsed_children.length\n \n animated = globals.animated and total_children <= options.animationThreshold\n animation_speed = options.animationSpeed\n dragged_class = options.draggedClass\n\n # Arrange each child element\n for i in [0...total_children]\n $child = parsed_children[i].el\n attributes = child_positions[i]\n is_dragged_child = $child.hasClass(dragged_class)\n\n if is_dragged_child\n placeholder_class = options.placeholderClass\n $child = $child.siblings(\".\" + placeholder_class)\n\n if animated and !is_dragged_child\n $child.stop(true, false).animate attributes, animation_speed, ->\n else\n $child.css attributes\n\n\n if trigger_drop_finished\n if animated\n setTimeout (->\n $container.trigger(\"ss-drop-complete\")\n ), animation_speed\n else\n $container.trigger(\"ss-drop-complete\")\n $container.trigger(\"ss-arranged\")\n\n # Set the container height\n if options.autoHeight\n container_height = globals.container_height\n max_height = options.maxHeight\n min_height = options.minHeight\n\n if min_height and container_height < min_height\n container_height = min_height\n else if max_height and container_height > max_height\n container_height = max_height\n\n $container.height container_height\n\n # ----------------------------\n # getPositions:\n # Go over each child and determine which column they\n # fit into and return an array of their x/y dimensions\n # ----------------------------\n getPositions: (include_dragged = true) ->\n globals = @globals\n options = @options\n gutter_y = options.gutterY\n padding_y = options.paddingY\n dragged_class = options.draggedClass\n\n parsed_children = @parsedChildren\n total_children = parsed_children.length\n\n # Store the height for each column\n col_heights = []\n for i in [0...globals.columns]\n col_heights.push padding_y\n\n # ----------------------------\n # savePosition\n # Takes a child which has been correctly placed in a\n # column and saves it to that final x/y position.\n # ----------------------------\n savePosition = (child) =>\n col = child.col\n colspan = child.colspan\n offset_x = (child.col * globals.col_width) + globals.child_offset\n offset_y = col_heights[col]\n\n positions[child.i] = left: offset_x, top: offset_y\n col_heights[col] += child.height + gutter_y\n\n if colspan >= 1\n for j in [1...colspan]\n col_heights[col + j] = col_heights[col]\n\n # ----------------------------\n # determineMultiposition\n # Children with multiple column spans will need special\n # rules to determine if they are currently able to be\n # placed in the grid.\n # ----------------------------\n determineMultiposition = (child) =>\n # Only use the columns that this child can fit into\n possible_cols = col_heights.length - child.colspan + 1\n possible_col_heights = col_heights.slice(0).splice(0, possible_cols)\n\n chosen_col = undefined\n for offset in [0...possible_cols]\n col = @lowestCol(possible_col_heights, offset)\n colspan = child.colspan\n height = col_heights[col]\n\n kosher = true\n\n # Determine if it is able to be placed at this col\n for span in [1...colspan]\n next_height = col_heights[col + span]\n\n # The next height must not be higher\n if height < next_height\n kosher = false\n break\n\n if kosher\n chosen_col = col\n break\n\n return chosen_col\n\n # ----------------------------\n # recalculateSavedChildren\n # Sometimes child elements cannot save the first time around,\n # iterate over those children and determine if its ok to place now.\n # ----------------------------\n saved_children = []\n recalculateSavedChildren = =>\n to_pop = []\n for saved_i in [0...saved_children.length]\n saved_child = saved_children[saved_i]\n saved_child.col = determineMultiposition(saved_child)\n\n if saved_child.col >= 0\n savePosition(saved_child)\n to_pop.push(saved_i)\n\n # Popeye. Lol.\n for pop_i in [to_pop.length - 1..0] by -1\n index = to_pop[pop_i]\n saved_children.splice(index,1)\n\n # ----------------------------\n # determinePositions\n # Iterate over all the parsed children and determine\n # the calculations needed to get its x/y value.\n # ----------------------------\n positions = []\n do determinePositions = =>\n for i in [0...total_children]\n child = parsed_children[i]\n\n unless !include_dragged and child.el.hasClass(dragged_class)\n if child.colspan > 1\n child.col = determineMultiposition(child)\n else\n child.col = @lowestCol(col_heights)\n\n if child.col is undefined\n saved_children.push child\n else\n savePosition(child)\n\n recalculateSavedChildren()\n\n # Store the container height since we already have the data\n if options.autoHeight\n grid_height = col_heights[@highestCol(col_heights)] - gutter_y\n globals.container_height = grid_height + padding_y\n\n return positions\n\n # ----------------------------\n # enableDrag:\n # Optional feature.\n # Initialize dragging.\n # ----------------------------\n enableDragNDrop: ->\n options = @options\n\n $container = @$container\n active_class = options.activeClass\n dragged_class = options.draggedClass\n placeholder_class = options.placeholderClass\n original_container_class = options.originalContainerClass\n current_container_class = options.currentContainerClass\n previous_container_class = options.previousContainerClass\n delete_clone = options.deleteClone\n drag_rate = options.dragRate\n drag_clone = options.dragClone\n clone_class = options.cloneClass\n\n $selected = $placeholder = $clone = selected_offset_y = selected_offset_x = null\n drag_timeout = false\n\n if options.enableDrag\n $container.children(\".\" + active_class).filter(options.dragWhitelist).draggable\n addClasses: false\n containment: 'document'\n handle: options.handle\n zIndex: 9999\n\n start: (e, ui) =>\n @globals.dragging = true\n\n # Set $selected globals\n $selected = $(e.target)\n\n if drag_clone\n $clone = $selected.clone(false, false).insertBefore($selected).addClass(clone_class)\n\n $selected.addClass(dragged_class)\n\n # Create Placeholder\n selected_tag = $selected.prop(\"tagName\")\n $placeholder = $(\"<#{selected_tag} class='#{placeholder_class}' style='height: #{$selected.height()}px; width: #{$selected.width()}px'>\")\n \n # Set current container\n $selected.parent().addClass(original_container_class).addClass(current_container_class)\n\n # For manually centering the element with respect to mouse position\n selected_offset_y = $selected.outerHeight() / 2\n selected_offset_x = $selected.outerWidth() / 2\n\n drag: (e, ui) =>\n if !drag_timeout and !(drag_clone and delete_clone and $(\".\" + current_container_class)[0] is $(\".\" + original_container_class)[0])\n # Append placeholder to container\n $placeholder.remove().appendTo(\".\" + current_container_class)\n\n # Set drag target and rearrange everything\n $(\".\" + current_container_class).trigger(\"ss-setTargetPosition\")\n\n # Disallow dragging from occurring too much\n drag_timeout = true\n window.setTimeout ( ->\n drag_timeout = false\n ), drag_rate\n\n # Manually center the element with respect to mouse position\n ui.position.left = e.pageX - $selected.parent().offset().left - selected_offset_x;\n ui.position.top = e.pageY - $selected.parent().offset().top - selected_offset_y;\n\n stop: =>\n @globals.dragging = false\n\n $original_container = $(\".\" + original_container_class)\n $current_container = $(\".\" + current_container_class)\n $previous_container = $(\".\" + previous_container_class)\n\n # Clear globals\n $selected.removeClass(dragged_class)\n $(\".\" + placeholder_class).remove()\n\n if drag_clone\n if delete_clone and $(\".\" + current_container_class)[0] is $(\".\" + original_container_class)[0]\n $clone.remove()\n $(\".\" + current_container_class).trigger(\"ss-rearrange\")\n else\n $clone.removeClass(clone_class)\n\n # Trigger Events\n if $original_container[0] is $current_container[0]\n $current_container.trigger(\"ss-rearranged\", $selected)\n else\n $original_container.trigger(\"ss-removed\", $selected)\n $current_container.trigger(\"ss-added\", $selected)\n\n # Arrange dragged item into place and clear container classes\n $original_container.trigger(\"ss-arrange\").removeClass(original_container_class)\n $current_container.trigger(\"ss-arrange\", true).removeClass(current_container_class)\n $previous_container.trigger(\"ss-arrange\").removeClass(previous_container_class)\n\n $selected = $placeholder = null\n\n\n if options.enableCrossDrop\n $container.droppable\n accept: options.crossDropWhitelist\n tolerance: 'intersect'\n over: (e) =>\n $(\".\" + previous_container_class).removeClass(previous_container_class)\n $(\".\" + current_container_class).removeClass(current_container_class).addClass(previous_container_class)\n $(e.target).addClass(current_container_class)\n\n drop: (e, selected) =>\n if @options.enableTrash\n $original_container = $(\".\" + original_container_class)\n $current_container = $(\".\" + current_container_class)\n $previous_container = $(\".\" + previous_container_class)\n $selected = $(selected.helper)\n\n $current_container.trigger(\"ss-trashed\", $selected)\n $selected.remove()\n\n $original_container.trigger(\"ss-rearrange\").removeClass(original_container_class)\n $current_container.trigger(\"ss-rearrange\").removeClass(current_container_class)\n $previous_container.trigger(\"ss-arrange\").removeClass(previous_container_class)\n\n # ----------------------------\n # getTargetPosition:\n # Determine the target position for the selected\n # element and arrange it into place\n # ----------------------------\n setTargetPosition: ->\n options = @options\n\n unless options.enableTrash\n dragged_class = options.draggedClass\n\n $selected = $(\".\" + dragged_class)\n $start_container = $selected.parent()\n parsed_children = @parsedChildren\n child_positions = @getPositions(false)\n total_positions = child_positions.length\n\n selected_x = $selected.offset().left - $start_container.offset().left + (@globals.col_width / 2)\n selected_y = $selected.offset().top - $start_container.offset().top + ($selected.height() / 2)\n\n shortest_distance = 9999999\n target_position = 0\n\n if total_positions > 1\n cutoff_start = options.cutoffStart + 1 || 0\n cutoff_end = options.cutoffEnd || total_positions\n\n for position_i in [cutoff_start...cutoff_end]\n attributes = child_positions[position_i]\n\n if attributes\n y_dist = selected_x - attributes.left\n x_dist = selected_y - attributes.top\n\n if y_dist > 0 and x_dist > 0\n distance = Math.sqrt((x_dist * x_dist) + (y_dist * y_dist))\n\n if distance < shortest_distance\n shortest_distance = distance\n target_position = position_i\n\n if position_i is total_positions - 1\n if y_dist > parsed_children[position_i].height / 2\n target_position++\n\n\n\n if target_position is parsed_children.length\n $target = parsed_children[target_position - 1].el\n $selected.insertAfter($target)\n else\n $target = parsed_children[target_position].el\n $selected.insertBefore($target)\n else\n if total_positions is 1\n attributes = child_positions[0]\n\n if attributes.left < selected_x\n @$container.append $selected\n else\n @$container.prepend $selected\n else\n @$container.append $selected\n \n @arrange(true)\n\n if $start_container[0] isnt $selected.parent()[0]\n previous_container_class = options.previousContainerClass\n $(\".\" + previous_container_class).trigger \"ss-rearrange\"\n else\n placeholder_class = @options.placeholderClass\n $(\".\" + placeholder_class).remove()\n\n # ----------------------------\n # resize:\n # Optional feature.\n # Runs a full render of the elements when\n # the browser window is resized.\n # ----------------------------\n enableResize: ->\n animation_speed = @options.animationSpeed\n\n resizing = false\n binding = \"resize.\" + @identifier\n $(window).on binding, =>\n unless resizing\n resizing = true\n\n # Some funkyness to prevent too many renderings\n setTimeout (=> @render()), animation_speed / 3\n setTimeout (=> @render()), animation_speed / 3\n\n setTimeout =>\n resizing = false\n @render()\n , animation_speed / 3\n\n # ----------------------------\n # shuffle:\n # Randomly sort the child elements\n # ----------------------------\n shuffle: ->\n calculateShuffled = (container, activeClass) ->\n shuffle = (arr) ->\n j = undefined\n x = undefined\n i = arr.length\n\n while i\n j = parseInt(Math.random() * i)\n x = arr[--i]\n arr[i] = arr[j]\n arr[j] = x\n arr\n return container.each(->\n items = container.find(\".\" + activeClass).filter(\":visible\")\n (if (items.length) then container.html(shuffle(items)) else this)\n )\n\n unless @globals.dragging\n calculateShuffled @$container, @options.activeClass\n @enableFeatures()\n @$container.trigger \"ss-rearrange\"\n\n # ----------------------------\n # lowestCol:\n # Helper\n # Returns the index position of the\n # array column with the lowest number\n # ----------------------------\n lowestCol: (array, offset = 0) ->\n length = array.length\n augmented_array = []\n \n for i in [0...length]\n augmented_array.push [array[i], i]\n\n augmented_array.sort (a, b) ->\n ret = a[0] - b[0]\n ret = a[1] - b[1] if ret is 0\n ret\n augmented_array[offset][1]\n\n # ----------------------------\n # highestCol:\n # Helper\n # Returns the index position of the\n # array column with the highest number\n # ----------------------------\n highestCol: (array) ->\n $.inArray Math.max.apply(window,array), array\n\n # ----------------------------\n # destroy:\n # ----------------------------\n destroy: ->\n $container = @$container\n $container.off(\"ss-arrange\")\n $container.off(\"ss-rearrange\")\n $container.off(\"ss-setTargetPosition\")\n $container.off(\"ss-destroy\")\n\n active_class = @options.activeClass\n $active_children = $container.find(\".\" + active_class)\n \n if @options.enableDrag\n $active_children.draggable('destroy')\n if @options.enableCrossDrop\n $container.droppable('destroy')\n\n $active_children.removeClass(active_class)\n $container.removeClass(@identifier)\n\n\n $.fn[pluginName] = (options) ->\n @each ->\n # Destroy any old resize events\n old_class = $(@).attr(\"class\")?.match(/shapeshifted_container_\\w+/)?[0]\n if old_class\n bound_indentifier = \"resize.\" + old_class\n $(window).off(bound_indentifier)\n $(@).removeClass(old_class)\n\n # Create the new plugin instance\n $.data(@, \"plugin_#{pluginName}\", new Plugin(@, options))\n\n)(jQuery, window, document)\n"},"max_stars_repo_name":{"kind":"string","value":"Sylveriam/proyecto-Todo-Tu-Club"}}},{"rowIdx":239,"cells":{"content":{"kind":"string","value":"<|start_filename|>src/game/client/tf/c_sdkversionchecker.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"c_sdkversionchecker.h\"\n#include \"script_parser.h\"\n#include \"tier3/tier3.h\"\n#include \"cdll_util.h\"\n\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nstatic C_SDKVersionChecker g_SDKVersionChecker;\nC_SDKVersionChecker *GetSDKVersionChecker()\n{\n\treturn &g_SDKVersionChecker;\n}\n\nclass C_SDKVersionParser : public C_ScriptParser\n{\npublic:\n\tDECLARE_CLASS_GAMEROOT(C_SDKVersionParser, C_ScriptParser);\n\n\tC_SDKVersionParser()\n\t{\n\t\tQ_strncpy(sKey, \"Unknown\", sizeof(sKey));\n\t}\n\n\tvoid Parse(KeyValues *pKeyValuesData, bool bWildcard, const char *szFileWithoutEXT)\n\t{\n\t\tfor (KeyValues *pData = pKeyValuesData->GetFirstSubKey(); pData != NULL; pData = pData->GetNextKey())\n\t\t{\n\t\t\tif (!Q_stricmp(pData->GetName(), \"UserConfig\"))\n\t\t\t{\n\t\t\t\tQ_strncpy(sKey, pData->GetString(\"BetaKey\", \"\"), sizeof(sKey));\n\t\t\t\tif (!Q_stricmp(sKey, \"\"))\n\t\t\t\t{\n\t\t\t\t\tQ_strncpy(sKey, \"Default\", sizeof(sKey));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid SetSDKVersionChecker(C_SDKVersionChecker *pChecker)\n\t{\n\t\tpSDKVersionChecker = pChecker;\n\t}\n\n\tconst char* GetKey()\n\t{\n\t\tchar *szResult = (char*)malloc(sizeof(sKey));\n\t\tQ_strncpy(szResult, sKey, sizeof(sKey));\n\t\treturn szResult;\n\t}\n\nprivate:\n\tchar sKey[64];\n\tC_SDKVersionChecker *pSDKVersionChecker;\n};\nC_SDKVersionParser g_SDKVersionParser;\n\nvoid PrintBranchName(const CCommand &args)\n{\n\tMsg(\"SDK branch: %s\\n\", g_SDKVersionParser.GetKey());\n}\nConCommand tf2c_getsdkbranch(\"tf2c_getsdkbranch\", PrintBranchName);\n\n//-----------------------------------------------------------------------------\n// Purpose: constructor\n//-----------------------------------------------------------------------------\nC_SDKVersionChecker::C_SDKVersionChecker() : CAutoGameSystemPerFrame(\"C_SDKVersionChecker\")\n{\n\tif (!filesystem)\n\t\treturn;\n\n\tm_bInited = false;\n\tInit();\n}\n\nC_SDKVersionChecker::~C_SDKVersionChecker()\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Initializer\n//-----------------------------------------------------------------------------\nbool C_SDKVersionChecker::Init()\n{\n\tif (!m_bInited)\n\t{\n\t\tg_SDKVersionParser.SetSDKVersionChecker(this);\n\t\tg_SDKVersionParser.InitParser(\"../../appmanifest_243750.acf\", true, false, true);\n\t\tm_bInited = true;\n\t}\n\n\treturn true;\n}\n\nconst char* C_SDKVersionChecker::GetKey()\n{\n\treturn g_SDKVersionParser.GetKey();\n}\n\n<|start_filename|>src/game/shared/econ/econ_item_schema.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"econ_item_schema.h\"\n#include \"econ_item_system.h\"\n#include \"tier3/tier3.h\"\n#include \"vgui/ILocalize.h\"\n\n//-----------------------------------------------------------------------------\n// CEconItemAttribute\n//-----------------------------------------------------------------------------\n\nBEGIN_NETWORK_TABLE_NOBASE( CEconItemAttribute, DT_EconItemAttribute )\n#ifdef CLIENT_DLL\n\tRecvPropInt( RECVINFO( m_iAttributeDefinitionIndex ) ),\n\tRecvPropFloat( RECVINFO( value ) ),\n\tRecvPropString( RECVINFO( value_string ) ),\n\tRecvPropString( RECVINFO( attribute_class ) ),\n#else\n\tSendPropInt( SENDINFO( m_iAttributeDefinitionIndex ) ),\n\tSendPropFloat( SENDINFO( value ) ),\n\tSendPropString( SENDINFO( value_string ) ),\n\tSendPropString( SENDINFO( attribute_class ) ),\n#endif\nEND_NETWORK_TABLE()\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CEconItemAttribute::Init( int iIndex, float flValue, const char *pszAttributeClass /*= NULL*/ )\n{\n\tm_iAttributeDefinitionIndex = iIndex;\n\tvalue = flValue;\n\tvalue_string.GetForModify()[0] = '\\0';\n\n\tif ( pszAttributeClass )\n\t{\n\t\tV_strncpy( attribute_class.GetForModify(), pszAttributeClass, sizeof( attribute_class ) );\n\t}\n\telse\n\t{\n\t\tEconAttributeDefinition *pAttribDef = GetStaticData();\n\t\tif ( pAttribDef )\n\t\t{\n\t\t\tV_strncpy( attribute_class.GetForModify(), pAttribDef->attribute_class, sizeof( attribute_class ) );\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CEconItemAttribute::Init( int iIndex, const char *pszValue, const char *pszAttributeClass /*= NULL*/ )\n{\n\tm_iAttributeDefinitionIndex = iIndex;\n\tvalue = 0.0f;\n\tV_strncpy( value_string.GetForModify(), pszValue, sizeof( value_string ) );\n\n\tif ( pszAttributeClass )\n\t{\n\t\tV_strncpy( attribute_class.GetForModify(), pszAttributeClass, sizeof( attribute_class ) );\n\t}\n\telse\n\t{\n\t\tEconAttributeDefinition *pAttribDef = GetStaticData();\n\t\tif ( pAttribDef )\n\t\t{\n\t\t\tV_strncpy( attribute_class.GetForModify(), pAttribDef->attribute_class, sizeof( attribute_class ) );\n\t\t}\n\t}\n}\n\nEconAttributeDefinition *CEconItemAttribute::GetStaticData( void )\n{\n\treturn GetItemSchema()->GetAttributeDefinition( m_iAttributeDefinitionIndex );\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: for the UtlMap\n//-----------------------------------------------------------------------------\nstatic bool actLessFunc( const int &lhs, const int &rhs )\n{\n\treturn lhs < rhs;\n}\n\n//-----------------------------------------------------------------------------\n// EconItemVisuals\n//-----------------------------------------------------------------------------\n\nEconItemVisuals::EconItemVisuals()\n{\n\tanimation_replacement.SetLessFunc( actLessFunc );\n\tmemset( aWeaponSounds, 0, sizeof( aWeaponSounds ) );\n}\n\n\n\n//-----------------------------------------------------------------------------\n// CEconItemDefinition\n//-----------------------------------------------------------------------------\n\nEconItemVisuals *CEconItemDefinition::GetVisuals( int iTeamNum /*= TEAM_UNASSIGNED*/ )\n{\n\tif ( iTeamNum > LAST_SHARED_TEAM && iTeamNum < TF_TEAM_COUNT )\n\t{\n\t\treturn &visual[iTeamNum];\n\t}\n\n\treturn &visual[TEAM_UNASSIGNED];\n}\n\nint CEconItemDefinition::GetLoadoutSlot( int iClass /*= TF_CLASS_UNDEFINED*/ )\n{\n\tif ( iClass && item_slot_per_class[iClass] != -1 )\n\t{\n\t\treturn item_slot_per_class[iClass];\n\t}\n\n\treturn item_slot;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Generate item name to show in UI with prefixes, qualities, etc...\n//-----------------------------------------------------------------------------\nconst wchar_t *CEconItemDefinition::GenerateLocalizedFullItemName( void )\n{\n\tstatic wchar_t wszFullName[256];\n\twszFullName[0] = '\\0';\n\n\twchar_t wszQuality[128];\n\twszQuality[0] = '\\0';\n\n\tif ( item_quality == QUALITY_UNIQUE )\n\t{\n\t\t// Attach \"the\" if necessary to unique items.\n\t\tif ( propername )\n\t\t{\n\t\t\tconst wchar_t *pszPrepend = g_pVGuiLocalize->Find( \"#TF_Unique_Prepend_Proper_Quality\" );\n\n\t\t\tif ( pszPrepend )\n\t\t\t{\n\t\t\t\tV_wcsncpy( wszQuality, pszPrepend, sizeof( wszQuality ) );\n\t\t\t}\n\t\t}\n\t}\n\telse if ( item_quality != QUALITY_NORMAL )\n\t{\n\t\t// Live TF2 allows multiple qualities per item but eh, we don't need that for now.\n\t\tconst wchar_t *pszQuality = g_pVGuiLocalize->Find( g_szQualityLocalizationStrings[item_quality] );\n\n\t\tif ( pszQuality )\n\t\t{\n\t\t\tV_wcsncpy( wszQuality, pszQuality, sizeof( wszQuality ) );\n\t\t}\n\t}\n\n\t// Attach the original item name after we're done with all the prefixes.\n\twchar_t wszItemName[256];\n\n\tconst wchar_t *pszLocalizedName = g_pVGuiLocalize->Find( item_name );\n\tif ( pszLocalizedName && pszLocalizedName[0] )\n\t{\n\t\tV_wcsncpy( wszItemName, pszLocalizedName, sizeof( wszItemName ) );\n\t}\n\telse\n\t{\n\t\tg_pVGuiLocalize->ConvertANSIToUnicode( item_name, wszItemName, sizeof( wszItemName ) );\n\t}\n\n\tg_pVGuiLocalize->ConstructString( wszFullName, sizeof( wszFullName ), L\"%s1 %s2\", 2,\n\t\twszQuality, wszItemName );\n\n\treturn wszFullName;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Generate item name without qualities, prefixes, etc. for disguise HUD...\n//-----------------------------------------------------------------------------\nconst wchar_t *CEconItemDefinition::GenerateLocalizedItemNameNoQuality( void )\n{\n\tstatic wchar_t wszFullName[256];\n\twszFullName[0] = '\\0';\n\n\twchar_t wszQuality[128];\n\twszQuality[0] = '\\0';\n\n\t// Attach \"the\" if necessary to unique items.\n\tif ( propername )\n\t{\n\t\tconst wchar_t *pszPrepend = g_pVGuiLocalize->Find( \"#TF_Unique_Prepend_Proper_Quality\" );\n\n\t\tif ( pszPrepend )\n\t\t{\n\t\t\tV_wcsncpy( wszQuality, pszPrepend, sizeof( wszQuality ) );\n\t\t}\n\t}\n\n\t// Attach the original item name after we're done with all the prefixes.\n\twchar_t wszItemName[256];\n\n\tconst wchar_t *pszLocalizedName = g_pVGuiLocalize->Find( item_name );\n\tif ( pszLocalizedName && pszLocalizedName[0] )\n\t{\n\t\tV_wcsncpy( wszItemName, pszLocalizedName, sizeof( wszItemName ) );\n\t}\n\telse\n\t{\n\t\tg_pVGuiLocalize->ConvertANSIToUnicode( item_name, wszItemName, sizeof( wszItemName ) );\n\t}\n\n\tg_pVGuiLocalize->ConstructString( wszFullName, sizeof( wszFullName ), L\"%s1 %s2\", 2,\n\t\twszQuality, wszItemName );\n\n\treturn wszFullName;\n}\n\n\nCEconItemAttribute *CEconItemDefinition::IterateAttributes( string_t strClass )\n{\n\t// Returning the first attribute found.\n\tfor ( int i = 0; i < attributes.Count(); i++ )\n\t{\n\t\tCEconItemAttribute *pAttribute = &attributes[i];\n\n\t\tif ( pAttribute->m_strAttributeClass == strClass )\n\t\t{\n\t\t\treturn pAttribute;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n\n<|start_filename|>src/game/shared/tf/tf_projectile_stunball.h<|end_filename|>\n//=============================================================================//\n//\n// Purpose: StunBallate Projectile\n//\n//=============================================================================//\n\n#ifndef TF_PROJECTILE_STUNBALL_H\n#define TF_PROJECTILE_STUNBALL_H\n\n#ifdef _WIN32\n#pragma once\n#endif\n\n#include \"tf_weaponbase_grenadeproj.h\"\n#ifdef GAME_DLL\n#include \"iscorer.h\"\n#endif\n\n#ifdef CLIENT_DLL\n#define CTFStunBall C_TFStunBall\n#endif\n\n#ifdef GAME_DLL\nclass CTFStunBall : public CTFWeaponBaseGrenadeProj, public IScorer\n#else\nclass C_TFStunBall : public C_TFWeaponBaseGrenadeProj\n#endif\n{\npublic:\n\tDECLARE_CLASS( CTFStunBall, CTFWeaponBaseGrenadeProj );\n\tDECLARE_NETWORKCLASS();\n#ifdef GAME_DLL\n\tDECLARE_DATADESC();\n#endif\n\n\tCTFStunBall();\n\t~CTFStunBall();\n\n\tvirtual int\t\t\tGetWeaponID( void ) const \t{ return TF_WEAPON_BAT_WOOD; }\n\n#ifdef GAME_DLL\n\tstatic CTFStunBall \t*Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo );\n\n\t// IScorer interface\n\tvirtual CBasePlayer *GetScorer( void ) \t\t\t{ return NULL; }\n\tvirtual CBasePlayer *GetAssistant( void );\n\n\tvirtual void\tPrecache( void );\n\tvirtual void\tSpawn( void );\n\n\tvirtual int\t\tGetDamageType();\n\n\tvirtual void\tDetonate( void );\n\tvirtual void\tVPhysicsCollision( int index, gamevcollisionevent_t *pEvent );\n\n\tvoid\t\t\tStunBallTouch( CBaseEntity *pOther );\n\tconst char\t\t*GetTrailParticleName( void );\n\tvoid\t\t\tCreateTrail( void );\n\n\tvoid\t\t\tSetScorer( CBaseEntity *pScorer );\n\n\tvoid\t\t\tSetCritical( bool bCritical )\t{ m_bCritical = bCritical; }\n\n\tvirtual bool\tIsDeflectable() \t\t\t\t{ return true; }\n\tvirtual void\tDeflected( CBaseEntity *pDeflectedBy, Vector &vecDir );\n\n\tvirtual void\tExplode( trace_t *pTrace, int bitsDamageType );\n\n\tbool\t\t\tCanStun( CTFPlayer *pOther );\n\n#else\n\tvirtual void\tOnDataChanged( DataUpdateType_t updateType );\n\tvirtual void\tCreateTrails( void );\n\tvirtual int\t\tDrawModel( int flags );\n#endif\n\nprivate:\n#ifdef GAME_DLL\n\tCNetworkVar( bool, m_bCritical );\n\n\tCHandle\tm_hEnemy;\n\tEHANDLE\t\t\t\t\tm_Scorer;\n\tEHANDLE\t\t\t\t\tm_hSpriteTrail;\n#else\n\tbool\t\t\t\t\tm_bCritical;\n#endif\n\n\tfloat\t\t\t\t\tm_flCreationTime;\n};\n\n#endif // TF_PROJECTILE_STUNBALL_H\n\n<|start_filename|>src/game/client/tf/c_tf_viewmodeladdon.cpp<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. =================//\n//\n// Purpose: \n//\n//=============================================================================//\n\n#include \"cbase.h\"\n#include \"c_tf_viewmodeladdon.h\"\n#include \"c_tf_player.h\"\n#include \"tf_viewmodel.h\"\n#include \"model_types.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\nextern ConVar r_drawothermodels;\n\nvoid C_ViewmodelAttachmentModel::SetViewmodel( C_TFViewModel *vm )\n{\n\tm_viewmodel.Set(vm);\n}\n\nint C_ViewmodelAttachmentModel::InternalDrawModel( int flags )\n{\n\tCMatRenderContextPtr pRenderContext(materials);\n\n\tif (m_viewmodel->ShouldFlipViewModel())\n\t\tpRenderContext->CullMode(MATERIAL_CULLMODE_CW);\n\n\tint ret = BaseClass::InternalDrawModel(flags);\n\n\tpRenderContext->CullMode(MATERIAL_CULLMODE_CCW);\n\n\treturn ret;\n}\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\nbool C_ViewmodelAttachmentModel::OnPostInternalDrawModel( ClientModelRenderInfo_t *pInfo )\n{\n\tif ( BaseClass::OnPostInternalDrawModel( pInfo ) )\n\t{\n\t\tC_EconEntity *pEntity = GetOwningWeapon();\n\t\tif ( pEntity )\n\t\t{\n\t\t\tDrawEconEntityAttachedModels( this, pEntity, pInfo, 2 );\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: We're overriding this because DrawModel keeps calling the FollowEntity DrawModel function\n//\t\t\twhich in this case is CTFViewModel::DrawModel.\n//\t\t\tThis is basically just a straight copy of C_BaseAnimating::DrawModel, without the FollowEntity part\n//-----------------------------------------------------------------------------\nint C_ViewmodelAttachmentModel::DrawOverriddenViewmodel( int flags )\n{\n\tif ( !m_bReadyToDraw )\n\t\treturn 0;\n\n\tint drawn = 0;\n\n\tValidateModelIndex();\n\n\tif (r_drawothermodels.GetInt())\n\t{\n\t\tMDLCACHE_CRITICAL_SECTION();\n\n\t\tint extraFlags = 0;\n\t\tif (r_drawothermodels.GetInt() == 2)\n\t\t{\n\t\t\textraFlags |= STUDIO_WIREFRAME;\n\t\t}\n\n\t\tif (flags & STUDIO_SHADOWDEPTHTEXTURE)\n\t\t{\n\t\t\textraFlags |= STUDIO_SHADOWDEPTHTEXTURE;\n\t\t}\n\n\t\tif (flags & STUDIO_SSAODEPTHTEXTURE)\n\t\t{\n\t\t\textraFlags |= STUDIO_SSAODEPTHTEXTURE;\n\t\t}\n\n\t\t// Necessary for lighting blending\n\t\tCreateModelInstance();\n\n\t\tdrawn = InternalDrawModel(flags | extraFlags);\n\t}\n\n\t// If we're visualizing our bboxes, draw them\n\tDrawBBoxVisualizations();\n\n\treturn drawn;\n}\n\nint C_ViewmodelAttachmentModel::DrawModel( int flags )\n{\n\tif ( !IsVisible() )\n\t\treturn 0;\n\n\tif (m_viewmodel.Get() == NULL)\n\t\treturn 0;\n\n\tC_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();\n\tC_TFPlayer *pPlayer = ToTFPlayer( m_viewmodel.Get()->GetOwner() );\n\n\tif ( pLocalPlayer && pLocalPlayer->IsObserver() \n\t\t&& pLocalPlayer->GetObserverTarget() != m_viewmodel.Get()->GetOwner() )\n\t\treturn false;\n\n\tif ( pLocalPlayer && !pLocalPlayer->IsObserver() && ( pLocalPlayer != pPlayer ) )\n\t\treturn false;\n\n\treturn BaseClass::DrawModel( flags );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_ViewmodelAttachmentModel::StandardBlendingRules( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask )\n{\n\tBaseClass::StandardBlendingRules( hdr, pos, q, currentTime, boneMask );\n\tCTFWeaponBase *pWeapon = ( CTFWeaponBase * )m_viewmodel->GetOwningWeapon();\n\tif ( !pWeapon )\n\t\treturn;\n\tif ( m_viewmodel->GetViewModelType() == VMTYPE_TF2 )\n\t{\n\t\tpWeapon->SetMuzzleAttachment( LookupAttachment( \"muzzle\" ) );\n\t}\n\tpWeapon->ViewModelAttachmentBlending( hdr, pos, q, currentTime, boneMask );\n}\n\n<|start_filename|>src/game/shared/tf/tf_weapon_sniperrifle.cpp<|end_filename|>\n//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//\n//\n// Purpose: TF Sniper Rifle\n//\n//=============================================================================//\n#include \"cbase.h\" \n#include \"tf_fx_shared.h\"\n#include \"tf_weapon_sniperrifle.h\"\n#include \"in_buttons.h\"\n\n// Client specific.\n#ifdef CLIENT_DLL\n#include \"view.h\"\n#include \"beamdraw.h\"\n#include \"vgui/ISurface.h\"\n#include \n#include \"vgui_controls/Controls.h\"\n#include \"hud_crosshair.h\"\n#include \"functionproxy.h\"\n#include \"materialsystem/imaterialvar.h\"\n#include \"toolframework_client.h\"\n#include \"input.h\"\n\n// For TFGameRules() and Player resources\n#include \"tf_gamerules.h\"\n#include \"c_tf_playerresource.h\"\n\n// forward declarations\nvoid ToolFramework_RecordMaterialParams( IMaterial *pMaterial );\n#endif\n\n#define TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC\t50.0\n#define TF_WEAPON_SNIPERRIFLE_UNCHARGE_PER_SEC\t75.0\n#define\tTF_WEAPON_SNIPERRIFLE_DAMAGE_MIN\t\t50\n#define TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX\t\t150\n#define TF_WEAPON_SNIPERRIFLE_RELOAD_TIME\t\t1.5f\n#define TF_WEAPON_SNIPERRIFLE_ZOOM_TIME\t\t\t0.3f\n\n#define TF_WEAPON_SNIPERRIFLE_NO_CRIT_AFTER_ZOOM_TIME\t0.2f\n\n#define SNIPER_DOT_SPRITE_RED\t\t\"effects/sniperdot_red.vmt\"\n#define SNIPER_DOT_SPRITE_BLUE\t\t\"effects/sniperdot_blue.vmt\"\n#define SNIPER_DOT_SPRITE_GREEN\t\t\"effects/sniperdot_green.vmt\"\n#define SNIPER_DOT_SPRITE_YELLOW\t\"effects/sniperdot_yellow.vmt\"\n#define SNIPER_DOT_SPRITE_CLEAR\t\t\"effects/sniperdot_clear.vmt\"\n\n//=============================================================================\n//\n// Weapon Sniper Rifles tables.\n//\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFSniperRifle, DT_TFSniperRifle )\n\nBEGIN_NETWORK_TABLE_NOBASE( CTFSniperRifle, DT_SniperRifleLocalData )\n#if !defined( CLIENT_DLL )\n\tSendPropFloat( SENDINFO(m_flChargedDamage), 0, SPROP_NOSCALE | SPROP_CHANGES_OFTEN ),\n#else\n\tRecvPropFloat( RECVINFO(m_flChargedDamage) ),\n#endif\nEND_NETWORK_TABLE()\n\nBEGIN_NETWORK_TABLE( CTFSniperRifle, DT_TFSniperRifle )\n#if !defined( CLIENT_DLL )\n\tSendPropDataTable( \"SniperRifleLocalData\", 0, &REFERENCE_SEND_TABLE( DT_SniperRifleLocalData ), SendProxy_SendLocalWeaponDataTable ),\n#else\n\tRecvPropDataTable( \"SniperRifleLocalData\", 0, 0, &REFERENCE_RECV_TABLE( DT_SniperRifleLocalData ) ),\n#endif\nEND_NETWORK_TABLE()\n\nBEGIN_PREDICTION_DATA( CTFSniperRifle )\n#ifdef CLIENT_DLL\n\tDEFINE_PRED_FIELD( m_flUnzoomTime, FIELD_FLOAT, 0 ),\n\tDEFINE_PRED_FIELD( m_flRezoomTime, FIELD_FLOAT, 0 ),\n\tDEFINE_PRED_FIELD( m_bRezoomAfterShot, FIELD_BOOLEAN, 0 ),\n\tDEFINE_PRED_FIELD( m_flChargedDamage, FIELD_FLOAT, 0 ),\n#endif\nEND_PREDICTION_DATA()\n\nLINK_ENTITY_TO_CLASS( tf_weapon_sniperrifle, CTFSniperRifle );\nPRECACHE_WEAPON_REGISTER( tf_weapon_sniperrifle );\n\n//=============================================================================\n//\n// Weapon Sniper Rifles funcions.\n//\n\n//-----------------------------------------------------------------------------\n// Purpose: Constructor.\n//-----------------------------------------------------------------------------\nCTFSniperRifle::CTFSniperRifle()\n{\n// Server specific.\n#ifdef GAME_DLL\n\tm_hSniperDot = NULL;\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Destructor.\n//-----------------------------------------------------------------------------\nCTFSniperRifle::~CTFSniperRifle()\n{\n// Server specific.\n#ifdef GAME_DLL\n\tDestroySniperDot();\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::Spawn()\n{\n\tm_iAltFireHint = HINT_ALTFIRE_SNIPERRIFLE;\n\tBaseClass::Spawn();\n\n\tResetTimers();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::Precache()\n{\n\tBaseClass::Precache();\n\tPrecacheModel( SNIPER_DOT_SPRITE_RED );\n\tPrecacheModel( SNIPER_DOT_SPRITE_BLUE );\n\tPrecacheModel(SNIPER_DOT_SPRITE_GREEN);\n\tPrecacheModel(SNIPER_DOT_SPRITE_YELLOW);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::ResetTimers( void )\n{\n\tm_flUnzoomTime = -1;\n\tm_flRezoomTime = -1;\n\tm_bRezoomAfterShot = false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nbool CTFSniperRifle::Reload( void )\n{\n\t// We currently don't reload.\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CTFSniperRifle::CanHolster( void ) const\n{\n \tCTFPlayer *pPlayer = GetTFPlayerOwner();\n \tif ( pPlayer )\n\t{\n\t\t// don't allow us to holster this weapon if we're in the process of zooming and \n\t\t// we've just fired the weapon (next primary attack is only 1.5 seconds after firing)\n\t\tif ( ( pPlayer->GetFOV() < pPlayer->GetDefaultFOV() ) && ( m_flNextPrimaryAttack > gpGlobals->curtime ) )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn BaseClass::CanHolster();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nbool CTFSniperRifle::Holster( CBaseCombatWeapon *pSwitchingTo )\n{\n// Server specific.\n#ifdef GAME_DLL\n\t// Destroy the sniper dot.\n\tDestroySniperDot();\n#endif\n\n\tCTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() );\n\tif ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_ZOOMED ) )\n\t{\n\t\tZoomOut();\n\t}\n\n\tm_flChargedDamage = 0.0f;\n\tResetTimers();\n\n\treturn BaseClass::Holster( pSwitchingTo );\n}\n\nvoid CTFSniperRifle::WeaponReset( void )\n{\n\tBaseClass::WeaponReset();\n\n\tZoomOut();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::HandleZooms( void )\n{\n\t// Get the owning player.\n\tCTFPlayer *pPlayer = ToTFPlayer( GetOwner() );\n\tif ( !pPlayer )\n\t\treturn;\n\n\t// Handle the zoom when taunting.\n\tif ( pPlayer->m_Shared.InCond( TF_COND_TAUNTING ) || pPlayer->m_Shared.InCond( TF_COND_STUNNED ) )\n\t{\n\t\tif ( pPlayer->m_Shared.InCond( TF_COND_AIMING ) )\n\t\t{\n\t\t\tToggleZoom();\n\t\t}\n\n\t\t//Don't rezoom in the middle of a taunt.\n\t\tResetTimers();\n\t}\n\n\tif ( m_flUnzoomTime > 0 && gpGlobals->curtime > m_flUnzoomTime )\n\t{\n\t\tif ( m_bRezoomAfterShot )\n\t\t{\n\t\t\tZoomOutIn();\n\t\t\tm_bRezoomAfterShot = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tZoomOut();\n\t\t}\n\n\t\tm_flUnzoomTime = -1;\n\t}\n\n\tif ( m_flRezoomTime > 0 )\n\t{\n\t\tif ( gpGlobals->curtime > m_flRezoomTime )\n\t\t{\n ZoomIn();\n\t\t\tm_flRezoomTime = -1;\n\t\t}\n\t}\n\n\tif ( ( pPlayer->m_nButtons & IN_ATTACK2 ) && ( m_flNextSecondaryAttack <= gpGlobals->curtime ) )\n\t{\n\t\t// If we're in the process of rezooming, just cancel it\n\t\tif ( m_flRezoomTime > 0 || m_flUnzoomTime > 0 )\n\t\t{\n\t\t\t// Prevent them from rezooming in less time than they would have\n\t\t\tm_flNextSecondaryAttack = m_flRezoomTime + TF_WEAPON_SNIPERRIFLE_ZOOM_TIME;\n\t\t\tm_flRezoomTime = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tZoom();\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::ItemPostFrame( void )\n{\n\t// If we're lowered, we're not allowed to fire\n\tif ( m_bLowered )\n\t\treturn;\n\n\t// Get the owning player.\n\tCTFPlayer *pPlayer = ToTFPlayer( GetOwner() );\n\tif ( !pPlayer )\n\t\treturn;\n\n\tif ( !CanAttack() )\n\t{\n\t\tif ( IsZoomed() )\n\t\t{\n\t\t\tToggleZoom();\n\t\t}\n\t\treturn;\n\t}\n\n\tHandleZooms();\n\n#ifdef GAME_DLL\n\t// Update the sniper dot position if we have one\n\tif ( m_hSniperDot )\n\t{\n\t\tUpdateSniperDot();\n\t}\n#endif\n\n\t// Start charging when we're zoomed in, and allowed to fire\n\tif ( pPlayer->m_Shared.IsJumping() )\n\t{\n\t\t// Unzoom if we're jumping\n\t\tif ( IsZoomed() )\n\t\t{\n\t\t\tToggleZoom();\n\t\t}\n\n\t\tm_flChargedDamage = 0.0f;\n\t\tm_bRezoomAfterShot = false;\n\t}\n\telse if ( m_flNextSecondaryAttack <= gpGlobals->curtime )\n\t{\n\t\t// Don't start charging in the time just after a shot before we unzoom to play rack anim.\n\t\tif ( pPlayer->m_Shared.InCond( TF_COND_AIMING ) && !m_bRezoomAfterShot )\n\t\t{\n\t\t\tm_flChargedDamage = min( m_flChargedDamage + gpGlobals->frametime * TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC, TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_flChargedDamage = max( 0, m_flChargedDamage - gpGlobals->frametime * TF_WEAPON_SNIPERRIFLE_UNCHARGE_PER_SEC );\n\t\t}\n\t}\n\n\t// Fire.\n\tif ( pPlayer->m_nButtons & IN_ATTACK )\n\t{\n\t\tFire( pPlayer );\n\t}\n\n\t// Idle.\n\tif ( !( ( pPlayer->m_nButtons & IN_ATTACK) || ( pPlayer->m_nButtons & IN_ATTACK2 ) ) )\n\t{\n\t\t// No fire buttons down or reloading\n\t\tif ( !ReloadOrSwitchWeapons() && ( m_bInReload == false ) )\n\t\t{\n\t\t\tWeaponIdle();\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CTFSniperRifle::Lower( void )\n{\n\tif ( BaseClass::Lower() )\n\t{\n\t\tif ( IsZoomed() )\n\t\t{\n\t\t\tToggleZoom();\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Secondary attack.\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::Zoom( void )\n{\n\t// Don't allow the player to zoom in while jumping\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\tif ( pPlayer && pPlayer->m_Shared.IsJumping() )\n\t{\n\t\tif ( pPlayer->GetFOV() >= 75 )\n\t\t\treturn;\n\t}\n\n\tToggleZoom();\n\n\t// at least 0.1 seconds from now, but don't stomp a previous value\n\tm_flNextPrimaryAttack = max( m_flNextPrimaryAttack, gpGlobals->curtime + 0.1 );\n\tm_flNextSecondaryAttack = gpGlobals->curtime + TF_WEAPON_SNIPERRIFLE_ZOOM_TIME;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::ZoomOutIn( void )\n{\n\tZoomOut();\n\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\tif ( pPlayer && pPlayer->ShouldAutoRezoom() )\n\t{\n\t\tm_flRezoomTime = gpGlobals->curtime + 0.9;\n\t}\n\telse\n\t{\n\t\tm_flNextSecondaryAttack = gpGlobals->curtime + 1.0f;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::ZoomIn( void )\n{\n\t// Start aiming.\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\n\tif ( !pPlayer )\n\t\treturn;\n\n\tif ( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) <= 0 )\n\t\treturn;\n\n\tBaseClass::ZoomIn();\n\n\tpPlayer->m_Shared.AddCond( TF_COND_AIMING );\n\tpPlayer->TeamFortress_SetSpeed();\n\n#ifdef GAME_DLL\n\t// Create the sniper dot.\n\tCreateSniperDot();\n\tpPlayer->ClearExpression();\n#endif\n}\n\nbool CTFSniperRifle::IsZoomed( void )\n{\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\n\tif ( pPlayer )\n\t{\n\t\treturn pPlayer->m_Shared.InCond( TF_COND_ZOOMED );\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::ZoomOut( void )\n{\n\tBaseClass::ZoomOut();\n\n\t// Stop aiming\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\n\tif ( !pPlayer )\n\t\treturn;\n\n\tpPlayer->m_Shared.RemoveCond( TF_COND_AIMING );\n\tpPlayer->TeamFortress_SetSpeed();\n\n#ifdef GAME_DLL\n\t// Destroy the sniper dot.\n\tDestroySniperDot();\n\tpPlayer->ClearExpression();\n#endif\n\n\t// if we are thinking about zooming, cancel it\n\tm_flUnzoomTime = -1;\n\tm_flRezoomTime = -1;\n\tm_bRezoomAfterShot = false;\n\tm_flChargedDamage = 0.0f;\t\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::Fire( CTFPlayer *pPlayer )\n{\n\t// Check the ammo. We don't use clip ammo, check the primary ammo type.\n\tif ( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) <= 0 )\n\t{\n\t\tHandleFireOnEmpty();\n\t\treturn;\n\t}\n\n\tif ( m_flNextPrimaryAttack > gpGlobals->curtime )\n\t\treturn;\n\n\t// Fire the sniper shot.\n\tPrimaryAttack();\n\n\tif ( IsZoomed() )\n\t{\n\t\t// If we have more bullets, zoom out, play the bolt animation and zoom back in\n\t\tif( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) > 0 )\n\t\t{\n\t\t\tSetRezoom( true, 0.5f );\t// zoom out in 0.5 seconds, then rezoom\n\t\t}\n\t\telse\t\n\t\t{\n\t\t\t//just zoom out\n\t\t\tSetRezoom( false, 0.5f );\t// just zoom out in 0.5 seconds\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Prevent primary fire preventing zooms\n\t\tm_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration();\n\t}\n\n\tm_flChargedDamage = 0.0f;\n\n#ifdef GAME_DLL\n\tif ( m_hSniperDot )\n\t{\n\t\tm_hSniperDot->ResetChargeTime();\n\t}\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::SetRezoom( bool bRezoom, float flDelay )\n{\n\tm_flUnzoomTime = gpGlobals->curtime + flDelay;\n\n\tm_bRezoomAfterShot = bRezoom;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Output : float\n//-----------------------------------------------------------------------------\nfloat CTFSniperRifle::GetProjectileDamage( void )\n{\n\t// Uncharged? Min damage.\n\treturn max( m_flChargedDamage, TF_WEAPON_SNIPERRIFLE_DAMAGE_MIN );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint\tCTFSniperRifle::GetDamageType( void ) const\n{\n\t// Only do hit location damage if we're zoomed\n\tCTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() );\n\tif ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_ZOOMED ) )\n\t\treturn BaseClass::GetDamageType();\n\n\treturn ( BaseClass::GetDamageType() & ~DMG_USE_HITLOCATIONS );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::CreateSniperDot( void )\n{\n// Server specific.\n#ifdef GAME_DLL\n\n\t// Check to see if we have already been created?\n\tif ( m_hSniperDot )\n\t\treturn;\n\n\t// Get the owning player (make sure we have one).\n\tCBaseCombatCharacter *pPlayer = GetOwner();\n\tif ( !pPlayer )\n\t\treturn;\n\n\t// Create the sniper dot, but do not make it visible yet.\n\tm_hSniperDot = CSniperDot::Create( GetAbsOrigin(), pPlayer, true );\n\tm_hSniperDot->ChangeTeam( pPlayer->GetTeamNumber() );\n\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::DestroySniperDot( void )\n{\n// Server specific.\n#ifdef GAME_DLL\n\n\t// Destroy the sniper dot.\n\tif ( m_hSniperDot )\n\t{\n\t\tUTIL_Remove( m_hSniperDot );\n\t\tm_hSniperDot = NULL;\n\t}\n\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFSniperRifle::UpdateSniperDot( void )\n{\n// Server specific.\n#ifdef GAME_DLL\n\n\tCBasePlayer *pPlayer = ToBasePlayer( GetOwner() );\n\tif ( !pPlayer )\n\t\treturn;\n\n\t// Get the start and endpoints.\n\tVector vecMuzzlePos = pPlayer->Weapon_ShootPosition();\n\tVector forward;\n\tpPlayer->EyeVectors( &forward );\n\tVector vecEndPos = vecMuzzlePos + ( forward * MAX_TRACE_LENGTH );\n\n\ttrace_t\ttrace;\n\tUTIL_TraceLine( vecMuzzlePos, vecEndPos, ( MASK_SHOT & ~CONTENTS_WINDOW ), GetOwner(), COLLISION_GROUP_NONE, &trace );\n\n\t// Update the sniper dot.\n\tif ( m_hSniperDot )\n\t{\n\t\tCBaseEntity *pEntity = NULL;\n\t\tif ( trace.DidHitNonWorldEntity() )\n\t\t{\n\t\t\tpEntity = trace.m_pEnt;\n\t\t\tif ( !pEntity || !pEntity->m_takedamage )\n\t\t\t{\n\t\t\t\tpEntity = NULL;\n\t\t\t}\n\t\t}\n\n\t\tm_hSniperDot->Update( pEntity, trace.endpos, trace.plane.normal );\n\t}\n\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nbool CTFSniperRifle::CanFireCriticalShot( bool bIsHeadshot )\n{\n\t// can only fire a crit shot if this is a headshot\n\tif ( !bIsHeadshot )\n\t\treturn false;\n\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\tif ( pPlayer )\n\t{\n\t\t// no crits if they're not zoomed\n\t\tif ( pPlayer->GetFOV() >= pPlayer->GetDefaultFOV() )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\t// no crits for 0.2 seconds after starting to zoom\n\t\tif ( ( gpGlobals->curtime - pPlayer->GetFOVTime() ) < TF_WEAPON_SNIPERRIFLE_NO_CRIT_AFTER_ZOOM_TIME )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n//=============================================================================\n//\n// Client specific functions.\n//\n#ifdef CLIENT_DLL\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nfloat CTFSniperRifle::GetHUDDamagePerc( void )\n{\n\treturn (m_flChargedDamage / TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX);\n}\n\n//-----------------------------------------------------------------------------\n// Returns the sniper chargeup from 0 to 1\n//-----------------------------------------------------------------------------\nclass CProxySniperRifleCharge : public CResultProxy\n{\npublic:\n\tvoid OnBind( void *pC_BaseEntity );\n};\n\nvoid CProxySniperRifleCharge::OnBind( void *pC_BaseEntity )\n{\n\tAssert( m_pResult );\n\n\tC_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();\n\n\tif ( GetSpectatorTarget() != 0 && GetSpectatorMode() == OBS_MODE_IN_EYE )\n\t{\n\t\tpPlayer = (C_TFPlayer *)UTIL_PlayerByIndex( GetSpectatorTarget() );\n\t}\n\n\tif ( pPlayer )\n\t{\n\t\tCTFSniperRifle *pWeapon = assert_cast(pPlayer->GetActiveTFWeapon());\n\t\tif ( pWeapon )\n\t\t{\n\t\t\tfloat flChargeValue = ( ( 1.0 - pWeapon->GetHUDDamagePerc() ) * 0.8 ) + 0.6;\n\n\t\t\tVMatrix mat, temp;\n\n\t\t\tVector2D center( 0.5, 0.5 );\n\t\t\tMatrixBuildTranslation( mat, -center.x, -center.y, 0.0f );\n\n\t\t\t// scale\n\t\t\t{\n\t\t\t\tVector2D scale( 1.0f, 0.25f );\n\t\t\t\tMatrixBuildScale( temp, scale.x, scale.y, 1.0f );\n\t\t\t\tMatrixMultiply( temp, mat, mat );\n\t\t\t}\n\n\t\t\tMatrixBuildTranslation( temp, center.x, center.y, 0.0f );\n\t\t\tMatrixMultiply( temp, mat, mat );\n\n\t\t\t// translation\n\t\t\t{\n\t\t\t\tVector2D translation( 0.0f, flChargeValue );\n\t\t\t\tMatrixBuildTranslation( temp, translation.x, translation.y, 0.0f );\n\t\t\t\tMatrixMultiply( temp, mat, mat );\n\t\t\t}\n\n\t\t\tm_pResult->SetMatrixValue( mat );\n\t\t}\n\t}\n\n\tif ( ToolsEnabled() )\n\t{\n\t\tToolFramework_RecordMaterialParams( GetMaterial() );\n\t}\n}\n\nEXPOSE_INTERFACE( CProxySniperRifleCharge, IMaterialProxy, \"SniperRifleCharge\" IMATERIAL_PROXY_INTERFACE_VERSION );\n#endif\n\n//=============================================================================\n//\n// Laser Dot functions.\n//\n\nIMPLEMENT_NETWORKCLASS_ALIASED( SniperDot, DT_SniperDot )\n\nBEGIN_NETWORK_TABLE( CSniperDot, DT_SniperDot )\n#ifdef CLIENT_DLL\n\tRecvPropFloat( RECVINFO( m_flChargeStartTime ) ),\n#else\n\tSendPropTime( SENDINFO( m_flChargeStartTime ) ),\n#endif\nEND_NETWORK_TABLE()\n\nLINK_ENTITY_TO_CLASS( env_sniperdot, CSniperDot );\n\nBEGIN_DATADESC( CSniperDot )\nDEFINE_FIELD( m_vecSurfaceNormal,\tFIELD_VECTOR ),\nDEFINE_FIELD( m_hTargetEnt,\t\t\tFIELD_EHANDLE ),\nEND_DATADESC()\n\n//-----------------------------------------------------------------------------\n// Purpose: Constructor.\n//-----------------------------------------------------------------------------\nCSniperDot::CSniperDot( void )\n{\n\tm_vecSurfaceNormal.Init();\n\tm_hTargetEnt = NULL;\n\n#ifdef CLIENT_DLL\n\tm_hSpriteMaterial = NULL;\n#endif\n\n\tResetChargeTime();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Destructor.\n//-----------------------------------------------------------------------------\nCSniperDot::~CSniperDot( void )\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : &origin - \n// Output : CSniperDot\n//-----------------------------------------------------------------------------\nCSniperDot *CSniperDot::Create( const Vector &origin, CBaseEntity *pOwner, bool bVisibleDot )\n{\n// Client specific.\n#ifdef CLIENT_DLL\n\n\treturn NULL;\n\n// Server specific.\n#else\n\n\t// Create the sniper dot entity.\n\tCSniperDot *pDot = static_cast( CBaseEntity::Create( \"env_sniperdot\", origin, QAngle( 0.0f, 0.0f, 0.0f ) ) );\n\tif ( !pDot )\n\t\treturn NULL;\n\n\t//Create the graphic\n\tpDot->SetMoveType( MOVETYPE_NONE );\n\tpDot->AddSolidFlags( FSOLID_NOT_SOLID );\n\tpDot->AddEffects( EF_NOSHADOW );\n\tUTIL_SetSize( pDot, -Vector( 4.0f, 4.0f, 4.0f ), Vector( 4.0f, 4.0f, 4.0f ) );\n\n\t// Set owner.\n\tpDot->SetOwnerEntity( pOwner );\n\n\t// Force updates even though we don't have a model.\n\tpDot->AddEFlags( EFL_FORCE_CHECK_TRANSMIT );\n\n\treturn pDot;\n\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CSniperDot::Update( CBaseEntity *pTarget, const Vector &vecOrigin, const Vector &vecNormal )\n{\n\tSetAbsOrigin( vecOrigin );\n\tm_vecSurfaceNormal = vecNormal;\n\tm_hTargetEnt = pTarget;\n}\n\n//=============================================================================\n//\n// Client specific functions.\n//\n#ifdef CLIENT_DLL\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// TFTODO: Make the sniper dot get brighter the more damage it will do.\n//-----------------------------------------------------------------------------\nint CSniperDot::DrawModel( int flags )\n{\n\t// Get the owning player.\n\tC_TFPlayer *pPlayer = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pPlayer )\n\t\treturn -1;\n\n\t// Get the sprite rendering position.\n\tVector vecEndPos;\n\n\tfloat flSize = 6.0;\n\n\tif ( !pPlayer->IsDormant() )\n\t{\n\t\tVector vecAttachment, vecDir;\n\t\tQAngle angles;\n\n\t\tfloat flDist = MAX_TRACE_LENGTH;\n\n\t\t// Always draw the dot in front of our faces when in first-person.\n\t\tif ( pPlayer->IsLocalPlayer() )\n\t\t{\n\t\t\t// Take our view position and orientation\n\t\t\tvecAttachment = CurrentViewOrigin();\n\t\t\tvecDir = CurrentViewForward();\n\n\t\t\t// Clamp the forward distance for the sniper's firstperson\n\t\t\tflDist = 384;\n\n\t\t\tflSize = 2.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Take the owning player eye position and direction.\n\t\t\tvecAttachment = pPlayer->EyePosition();\n\t\t\tQAngle angles = pPlayer->EyeAngles();\n\t\t\tAngleVectors( angles, &vecDir );\n\t\t}\n\n\t\ttrace_t tr;\n\t\tUTIL_TraceLine( vecAttachment, vecAttachment + ( vecDir * flDist ), MASK_SHOT, pPlayer, COLLISION_GROUP_NONE, &tr );\n\n\t\t// Backup off the hit plane, towards the source\n\t\tvecEndPos = tr.endpos + vecDir * -4;\n\t}\n\telse\n\t{\n\t\t// Just use our position if we can't predict it otherwise.\n\t\tvecEndPos = GetAbsOrigin();\n\t}\n\n\t// Draw our laser dot in space.\n\tCMatRenderContextPtr pRenderContext( materials );\n\tpRenderContext->Bind( m_hSpriteMaterial, this );\n\n\tfloat flLifeTime = gpGlobals->curtime - m_flChargeStartTime;\n\tfloat flStrength = RemapValClamped( flLifeTime, 0.0, TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX / TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC, 0.1, 1.0 );\n\t\n\tcolor32 innercolor = { 255, 255, 255, 255 };\n\tcolor32 outercolor = { 255, 255, 255, 128 };\n\n\tDrawSprite( vecEndPos, flSize, flSize, outercolor );\n\tDrawSprite( vecEndPos, flSize * flStrength, flSize * flStrength, innercolor );\n\n\t// Successful.\n\treturn 1;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CSniperDot::ShouldDraw( void )\t\t\t\n{\n\tif ( IsEffectActive( EF_NODRAW ) )\n\t\treturn false;\n#if 0\n\t// Don't draw the sniper dot when in thirdperson.\n\tif ( ::input->CAM_IsThirdPerson() )\n\t\treturn false;\n#endif\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CSniperDot::OnDataChanged( DataUpdateType_t updateType )\n{\n\tif ( updateType == DATA_UPDATE_CREATED )\n\t{\n\t\tswitch (GetTeamNumber())\n\t\t{\n\t\tcase TF_TEAM_RED:\n\t\t\tm_hSpriteMaterial.Init(SNIPER_DOT_SPRITE_RED, TEXTURE_GROUP_CLIENT_EFFECTS);\n\t\t\tbreak;\n\t\tcase TF_TEAM_BLUE:\n\t\t\tm_hSpriteMaterial.Init(SNIPER_DOT_SPRITE_BLUE, TEXTURE_GROUP_CLIENT_EFFECTS);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n#endif\n\n\n<|start_filename|>src/game/shared/tf/tf_inventory.cpp<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: Simple Inventory\n// by MrModez\n// $NoKeywords: $\n//=============================================================================//\n\n\n#include \"cbase.h\"\n#include \"tf_shareddefs.h\"\n#include \"tf_inventory.h\"\n#include \"econ_item_system.h\"\n\nstatic CTFInventory g_TFInventory;\n\nCTFInventory *GetTFInventory()\n{\n\treturn &g_TFInventory;\n}\n\nCTFInventory::CTFInventory() : CAutoGameSystemPerFrame( \"CTFInventory\" )\n{\n#ifdef CLIENT_DLL\n\tm_pInventory = NULL;\n#endif\n\n\t// Generate dummy base items.\n\tfor ( int iClass = 0; iClass < TF_CLASS_COUNT_ALL; iClass++ )\n\t{\n\t\tfor ( int iSlot = 0; iSlot < TF_LOADOUT_SLOT_COUNT; iSlot++ )\n\t\t{\n\t\t\tm_Items[iClass][iSlot].AddToTail( NULL );\n\t\t}\n\t}\n};\n\nCTFInventory::~CTFInventory()\n{\n#if defined( CLIENT_DLL )\n\tm_pInventory->deleteThis();\n#endif\n}\n\nbool CTFInventory::Init( void )\n{\n\tGetItemSchema()->Init();\n\n\t// Generate item list.\n\tFOR_EACH_MAP( GetItemSchema()->m_Items, i )\n\t{\n\t\tint iItemID = GetItemSchema()->m_Items.Key( i );\n\t\tCEconItemDefinition *pItemDef = GetItemSchema()->m_Items.Element( i );\n\n\t\tif ( pItemDef->item_slot == -1 )\n\t\t\tcontinue;\n\n\t\t// Add it to each class that uses it.\n\t\tfor ( int iClass = 0; iClass < TF_CLASS_COUNT_ALL; iClass++ )\n\t\t{\n\t\t\tif ( pItemDef->used_by_classes & ( 1 << iClass ) )\n\t\t\t{\n\t\t\t\t// Show it if it's either base item or has show_in_armory flag.\n\t\t\t\tint iSlot = pItemDef->GetLoadoutSlot( iClass );\n\n\t\t\t\tif ( pItemDef->baseitem )\n\t\t\t\t{\n\t\t\t\t\tCEconItemView *pBaseItem = m_Items[iClass][iSlot][0];\n\t\t\t\t\tif ( pBaseItem != NULL )\n\t\t\t\t\t{\n\t\t\t\t\t\tWarning( \"Duplicate base item %d for class %s in slot %s!\\n\", iItemID, g_aPlayerClassNames_NonLocalized[iClass], g_LoadoutSlots[iSlot] );\n\t\t\t\t\t\tdelete pBaseItem;\n\t\t\t\t\t}\n\n\t\t\t\t\tCEconItemView *pNewItem = new CEconItemView( iItemID );\n\n#if defined ( GAME_DLL )\n\t\t\t\t\tpNewItem->SetItemClassNumber( iClass );\n#endif\n\t\t\t\t\tm_Items[iClass][iSlot][0] = pNewItem;\n\t\t\t\t}\n\t\t\t\telse if ( pItemDef->show_in_armory )\n\t\t\t\t{\n\t\t\t\t\tCEconItemView *pNewItem = new CEconItemView( iItemID );\n\n#if defined ( GAME_DLL )\n\t\t\t\t\tpNewItem->SetItemClassNumber( iClass );\n#endif\n\t\t\t\t\tm_Items[iClass][iSlot].AddToTail( pNewItem );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n#if defined( CLIENT_DLL )\n\tLoadInventory();\n#endif\n\n\treturn true;\n}\n\nvoid CTFInventory::LevelInitPreEntity( void )\n{\n\tGetItemSchema()->Precache();\n}\n\nint CTFInventory::GetNumPresets(int iClass, int iSlot)\n{\n\treturn m_Items[iClass][iSlot].Count();\n};\n\nint CTFInventory::GetWeapon(int iClass, int iSlot)\n{\n\treturn Weapons[iClass][iSlot];\n};\n\nCEconItemView *CTFInventory::GetItem( int iClass, int iSlot, int iNum )\n{\n\tif ( CheckValidWeapon( iClass, iSlot, iNum ) == false )\n\t\treturn NULL;\n\n\treturn m_Items[iClass][iSlot][iNum];\n};\n\nbool CTFInventory::CheckValidSlot(int iClass, int iSlot, bool bHudCheck /*= false*/)\n{\n\tif (iClass < TF_CLASS_UNDEFINED || iClass > TF_CLASS_COUNT)\n\t\treturn false;\n\n\tint iCount = (bHudCheck ? INVENTORY_ROWNUM : TF_LOADOUT_SLOT_COUNT);\n\n\t// Array bounds check.\n\tif ( iSlot >= iCount || iSlot < 0 )\n\t\treturn false;\n\n\t// Slot must contain a base item.\n\tif ( m_Items[iClass][iSlot][0] == NULL )\n\t\treturn false;\n\n\treturn true;\n};\n\nbool CTFInventory::CheckValidWeapon(int iClass, int iSlot, int iWeapon, bool bHudCheck /*= false*/)\n{\n\tif (iClass < TF_CLASS_UNDEFINED || iClass > TF_CLASS_COUNT)\n\t\treturn false;\n\n\tint iCount = ( bHudCheck ? INVENTORY_COLNUM : m_Items[iClass][iSlot].Count() );\n\n\t// Array bounds check.\n\tif ( iWeapon >= iCount || iWeapon < 0 )\n\t\treturn false;\n\n\t// Don't allow switching if this class has no weapon at this position.\n\tif ( m_Items[iClass][iSlot][iWeapon] == NULL )\n\t\treturn false;\n\n\treturn true;\n};\n\n#if defined( CLIENT_DLL )\nvoid CTFInventory::LoadInventory()\n{\n\tbool bExist = filesystem->FileExists(\"scripts/tf_inventory.txt\", \"MOD\");\n\tif (bExist)\n\t{\n\t\tif (!m_pInventory)\n\t\t{\n\t\t\tm_pInventory = new KeyValues(\"Inventory\");\n\t\t}\n\t\tm_pInventory->LoadFromFile(filesystem, \"scripts/tf_inventory.txt\");\n\t}\n\telse\n\t{\n\t\tResetInventory();\n\t}\n};\n\nvoid CTFInventory::SaveInventory()\n{\n\tm_pInventory->SaveToFile(filesystem, \"scripts/tf_inventory.txt\");\n};\n\nvoid CTFInventory::ResetInventory()\n{\n\tif (m_pInventory)\n\t{\n\t\tm_pInventory->deleteThis();\n\t}\n\n\tm_pInventory = new KeyValues(\"Inventory\");\n\n\tfor (int i = TF_CLASS_UNDEFINED; i < TF_CLASS_COUNT_ALL; i++)\n\t{\n\t\tKeyValues *pClassInv = new KeyValues(g_aPlayerClassNames_NonLocalized[i]);\n\t\tfor (int j = 0; j < TF_LOADOUT_SLOT_COUNT; j++)\n\t\t{\n\t\t\tpClassInv->SetInt( g_LoadoutSlots[j], 0 );\n\t\t}\n\t\tm_pInventory->AddSubKey(pClassInv);\n\t}\n\n\tSaveInventory();\n}\n\nint CTFInventory::GetWeaponPreset(int iClass, int iSlot)\n{\n\tKeyValues *pClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]);\n\tif (!pClass)\t//cannot find class node\n\t{\t\n\t\tResetInventory();\n\t\treturn 0;\n\t}\n\tint iPreset = pClass->GetInt(g_LoadoutSlots[iSlot], -1);\n\tif (iPreset == -1)\t//cannot find slot node\n\t{\n\t\tResetInventory();\n\t\treturn 0;\n\t}\n\n\tif ( CheckValidWeapon( iClass, iSlot, iPreset ) == false )\n\t\treturn 0;\n\n\treturn iPreset;\n};\n\nvoid CTFInventory::SetWeaponPreset(int iClass, int iSlot, int iPreset)\n{\n\tKeyValues* pClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]);\n\tif (!pClass)\t//cannot find class node\n\t{\n\t\tResetInventory();\n\t\tpClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]);\n\t}\n\tpClass->SetInt(GetSlotName(iSlot), iPreset);\n\tSaveInventory();\n}\n\nconst char* CTFInventory::GetSlotName(int iSlot)\n{\n\treturn g_LoadoutSlots[iSlot];\n};\n\n#endif\n\n// Legacy array, used when we're forced to use old method of giving out weapons.\nconst int CTFInventory::Weapons[TF_CLASS_COUNT_ALL][TF_PLAYER_WEAPON_COUNT] =\n{\n\t{\n\n\t},\n\t{\n\t\tTF_WEAPON_SCATTERGUN,\n\t\tTF_WEAPON_PISTOL_SCOUT,\n\t\tTF_WEAPON_BAT\n\t},\n\t{\n\t\tTF_WEAPON_SNIPERRIFLE,\n\t\tTF_WEAPON_SMG,\n\t\tTF_WEAPON_CLUB\n\t},\n\t{\n\t\tTF_WEAPON_ROCKETLAUNCHER,\n\t\tTF_WEAPON_SHOTGUN_SOLDIER,\n\t\tTF_WEAPON_SHOVEL\n\t},\n\t{\n\t\tTF_WEAPON_GRENADELAUNCHER,\n\t\tTF_WEAPON_PIPEBOMBLAUNCHER,\n\t\tTF_WEAPON_BOTTLE\n\t},\n\t{\n\t\tTF_WEAPON_SYRINGEGUN_MEDIC,\n\t\tTF_WEAPON_MEDIGUN,\n\t\tTF_WEAPON_BONESAW\n\t},\n\t{\n\t\tTF_WEAPON_MINIGUN,\n\t\tTF_WEAPON_SHOTGUN_HWG,\n\t\tTF_WEAPON_FISTS\n\t},\n\t{\n\t\tTF_WEAPON_FLAMETHROWER,\n\t\tTF_WEAPON_SHOTGUN_PYRO,\n\t\tTF_WEAPON_FIREAXE\n\t},\n\t{\n\t\tTF_WEAPON_REVOLVER,\n\t\tTF_WEAPON_NONE,\n\t\tTF_WEAPON_KNIFE,\n\t\tTF_WEAPON_PDA_SPY,\n\t\tTF_WEAPON_INVIS\n\t},\n\t{\n\t\tTF_WEAPON_SHOTGUN_PRIMARY,\n\t\tTF_WEAPON_PISTOL,\n\t\tTF_WEAPON_WRENCH,\n\t\tTF_WEAPON_PDA_ENGINEER_BUILD,\n\t\tTF_WEAPON_PDA_ENGINEER_DESTROY\n\t},\n};\n\n\n<|start_filename|>src/game/shared/tf/tf_weapon_buff_item.cpp<|end_filename|>\n//=========== Copyright © 2018, LFE-Team, Not All rights reserved. ============\n//\n// Purpose: \n//\n//=============================================================================\n#include \"cbase.h\"\n#include \"tf_weapon_buff_item.h\"\n#include \"tf_fx_shared.h\"\n#include \"in_buttons.h\"\n#include \"datacache/imdlcache.h\"\n#include \"effect_dispatch_data.h\"\n#include \"engine/IEngineSound.h\"\n#include \"tf_gamerules.h\"\n\n// Client specific.\n#ifdef CLIENT_DLL\n#include \"c_tf_player.h\"\n#include \"particles_new.h\"\n#include \"tf_wearable.h\"\n#include \"tf_projectile_arrow.h\"\n// Server specific.\n#else\n#include \"tf_player.h\"\n#include \"ai_basenpc.h\"\n#include \"soundent.h\"\n#include \"te_effect_dispatch.h\"\n#include \"tf_fx.h\"\n#include \"tf_gamestats.h\"\n#endif\n\nconst char *g_BannerModels[] =\n{\n\t\"models/weapons/c_models/c_buffbanner/c_buffbanner.mdl\", \n\t\"models/workshop/weapons/c_models/c_battalion_buffbanner/c_battalion_buffbanner.mdl\",\n\t\"models/workshop_partner/weapons/c_models/c_shogun_warbanner/c_shogun_warbanner.mdl\",\n\t\"models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_parachute.mdl\",\n};\n\n//=============================================================================\n//\n// Weapon BUFF item tables.\n//\n\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFBuffItem, DT_WeaponBuffItem )\n\nBEGIN_NETWORK_TABLE( CTFBuffItem, DT_WeaponBuffItem )\n#ifdef CLIENT_DLL\n\tRecvPropBool( RECVINFO( m_bBuffUsed ) ),\n#else\n\tSendPropBool( SENDINFO( m_bBuffUsed ) ),\n#endif\nEND_NETWORK_TABLE()\n\nBEGIN_PREDICTION_DATA( CTFBuffItem )\n#ifdef CLIENT_DLL\n#endif\nEND_PREDICTION_DATA()\n\nLINK_ENTITY_TO_CLASS( tf_weapon_buff_item, CTFBuffItem );\nPRECACHE_WEAPON_REGISTER( tf_weapon_buff_item );\n\n// Server specific.\n#ifndef CLIENT_DLL\nBEGIN_DATADESC( CTFBuffItem )\nEND_DATADESC()\n#endif\n\nCTFBuffItem::CTFBuffItem()\n{\n\tm_flEffectBarRegenTime = 0.0f;\n\tUseClientSideAnimation();\n\n#ifdef CLIENT_DLL\n\tListenForGameEvent( \"deploy_buff_banner\" );\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFBuffItem::Precache( void )\n{\n\tPrecacheTeamParticles( \"soldierbuff_%s_buffed\" );\n\tPrecacheParticleSystem( \"soldierbuff_mvm\" );\n\n\tfor ( int i = 0; i < ARRAYSIZE( g_BannerModels ); i++ )\n\t{\n\t\tPrecacheModel( g_BannerModels[i] );\n\t}\n\tPrecacheModel( \"models/weapons/c_models/c_buffpack/c_buffpack.mdl\" );\n\tPrecacheModel( \"models/workshop/weapons/c_models/c_battalion_buffpack/c_battalion_buffpack.mdl\" );\n\tPrecacheModel( \"models/workshop_partner/weapons/c_models/c_shogun_warpack/c_shogun_warpack.mdl\" );\n\tPrecacheModel( \"models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_pack_open.mdl\" );\n\tPrecacheModel( \"models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_pack.mdl\" );\n\n\tPrecacheScriptSound( \"Weapon_BuffBanner.HornRed\" );\n\tPrecacheScriptSound( \"Weapon_BuffBanner.HornBlue\" );\n\tPrecacheScriptSound( \"Weapon_BattalionsBackup.HornRed\" );\n\tPrecacheScriptSound( \"Weapon_BattalionsBackup.HornBlue\" );\n\tPrecacheScriptSound( \"Samurai.Conch\" );\n\tPrecacheScriptSound( \"Weapon_BuffBanner.Flag\" );\n\n\tBaseClass::Precache();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Only holster when the buff isn't used\n//-----------------------------------------------------------------------------\nbool CTFBuffItem::Holster( CBaseCombatWeapon *pSwitchingTo )\n{\n\tif ( !m_bBuffUsed )\n\t{\n\t\treturn BaseClass::Holster( pSwitchingTo );\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Reset the charge meter \n//-----------------------------------------------------------------------------\nvoid CTFBuffItem::WeaponReset( void )\n{\n\tm_bBuffUsed = false;\n\n\tBaseClass::WeaponReset();\n}\n\n// ---------------------------------------------------------------------------- -\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFBuffItem::PrimaryAttack( void )\n{\n\t// Rage not ready\n\t//if ( !IsFull() )\n\t\t//return;\n\n\tif ( !CanAttack() )\n\t\treturn;\n\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( !pOwner )\n\t\treturn;\n\n\tif ( !m_bBuffUsed && pOwner->m_Shared.GetRageProgress() >= 100.0f )\n\t{\n\t\tif ( GetTeamNumber() == TF_TEAM_RED )\n\t\t{\n\t\t\tSendWeaponAnim( ACT_VM_PRIMARYATTACK );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSendWeaponAnim( ACT_VM_SECONDARYATTACK );\n\t\t}\n\n\t\tpOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_SECONDARY );\n\n#ifdef GAME_DLL\n\t\tSetContextThink( &CTFBuffItem::BlowHorn, gpGlobals->curtime + 0.22f, \"BlowHorn\" );\n#endif\n\t}\n}\n\n// ---------------------------------------------------------------------------- -\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFBuffItem::BlowHorn( void )\n{\n\tif ( !CanAttack() )\n\t\treturn;\n\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( !pOwner || !pOwner->IsAlive() )\n\t\treturn;\n\n\tint iBuffType = GetBuffType();\n\tconst char *iszSound = \"\\0\";\n\tswitch( iBuffType )\n\t{\n\t\tcase TF_BUFF_OFFENSE:\n\t\t\tif ( pOwner->GetTeamNumber() == TF_TEAM_RED )\n\t\t\t\tiszSound = \"Weapon_BuffBanner.HornRed\";\n\t\t\telse\n\t\t\t\tiszSound = \"Weapon_BuffBanner.HornBlue\";\n\t\t\tbreak;\n\t\tcase TF_BUFF_DEFENSE:\n\t\t\tif ( pOwner->GetTeamNumber() == TF_TEAM_RED )\n\t\t\t\tiszSound = \"Weapon_BattalionsBackup.HornRed\";\n\t\t\telse\n\t\t\t\tiszSound = \"Weapon_BattalionsBackup.HornBlue\";\n\t\t\tbreak;\n\t\tcase TF_BUFF_REGENONDAMAGE:\n\t\t\tiszSound = \"Samurai.Conch\";\n\t\t\tbreak;\n\t};\n\tpOwner->EmitSound( iszSound );\n}\n\n// ---------------------------------------------------------------------------- -\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFBuffItem::RaiseFlag( void )\n{\n\tif ( !CanAttack() )\n\t\treturn;\n\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( !pOwner || !pOwner->IsAlive() )\n\t\treturn;\n\n\tint iBuffType = GetBuffType();\n\n#ifdef GAME_DLL\n\tm_bBuffUsed = false;\n\tIGameEvent *event = gameeventmanager->CreateEvent( \"deploy_buff_banner\" );\n\tif ( event )\n\t{\n\t\tevent->SetInt( \"buff_type\", iBuffType );\n\t\tevent->SetInt( \"buff_owner\", pOwner->entindex() );\n \t\tgameeventmanager->FireEvent( event );\n\t}\n\n\tpOwner->EmitSound( \"Weapon_BuffBanner.Flag\" );\n\tpOwner->SpeakConceptIfAllowed( MP_CONCEPT_PLAYER_BATTLECRY );\n#endif\n\n\tpOwner->m_Shared.ActivateRageBuff( this, iBuffType );\n\tpOwner->SwitchToNextBestWeapon( this );\n}\n\n// -----------------------------------------------------------------------------\n// Purpose:\n// -----------------------------------------------------------------------------\nint CTFBuffItem::GetBuffType( void )\n{\n\tint iBuffType = 0;\n\tCALL_ATTRIB_HOOK_INT( iBuffType, set_buff_type );\n\treturn iBuffType;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nfloat CTFBuffItem::GetEffectBarProgress( void )\n{\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( pOwner)\n\t{\n\t\treturn pOwner->m_Shared.GetRageProgress() / 100.0f;\n\t}\n\n\treturn 0.0f;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nbool CTFBuffItem::EffectMeterShouldFlash( void )\n{\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\n\t// Rage meter should flash while draining\n\tif ( pOwner && pOwner->m_Shared.IsRageActive() && pOwner->m_Shared.GetRageProgress() < 100.0f )\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Make sure the weapon uses the correct animations \n//-----------------------------------------------------------------------------\nbool CTFBuffItem::SendWeaponAnim( int iActivity )\n{\t\n\tint iNewActivity = iActivity;\n\n\tswitch ( iActivity )\n\t{\n\tcase ACT_VM_DRAW:\n\t\tiNewActivity =ACT_ITEM1_VM_DRAW;\n\t\tbreak;\n\tcase ACT_VM_HOLSTER:\n\t\tiNewActivity = ACT_ITEM1_VM_HOLSTER;\n\t\tbreak;\n\tcase ACT_VM_IDLE:\n\t\tiNewActivity = ACT_ITEM1_VM_IDLE;\n\n\t\t// Do the flag raise animation \n\t\tif ( m_bBuffUsed )\n\t\t{\n\t\t\tRaiseFlag();\n\t\t\tiNewActivity = ACT_RESET;\n\t\t}\n\t\telse\n\n\t\tbreak;\n\tcase ACT_VM_PULLBACK:\n\t\tiNewActivity = ACT_ITEM1_VM_PULLBACK;\n\t\tbreak;\n\tcase ACT_VM_PRIMARYATTACK:\n\t\tiNewActivity = ACT_ITEM1_VM_PRIMARYATTACK;\n\t\tm_bBuffUsed = true;\n\t\tbreak;\n\tcase ACT_VM_SECONDARYATTACK:\n\t\tiNewActivity = ACT_ITEM1_VM_SECONDARYATTACK;\n\t\tm_bBuffUsed = true;\n\t\tbreak;\n\tcase ACT_VM_IDLE_TO_LOWERED:\n\t\tiNewActivity = ACT_ITEM1_VM_IDLE_TO_LOWERED;\n\t\tbreak;\n\tcase ACT_VM_IDLE_LOWERED:\n\t\tiNewActivity = ACT_ITEM1_VM_IDLE_LOWERED;\n\t\tbreak;\n\tcase ACT_VM_LOWERED_TO_IDLE:\n\t\tiNewActivity = ACT_ITEM1_VM_LOWERED_TO_IDLE;\n\t\tbreak;\n\t};\n\t\n\treturn BaseClass::SendWeaponAnim( iNewActivity );\n}\n\n#ifdef CLIENT_DLL\n//-----------------------------------------------------------------------------\n// Purpose: Create the banner addon for the backpack\n//-----------------------------------------------------------------------------\nvoid C_TFBuffItem::CreateBanner( int iBuffType )\n{\n\tC_TFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( !pOwner || !pOwner->IsAlive() )\n\t\treturn;\n\n\tC_EconWearable *pWearable = pOwner->GetWearableForLoadoutSlot( TF_LOADOUT_SLOT_SECONDARY );\n\n\t// if we don't have a backpack for some reason don't make a banner\n\tif ( !pWearable )\n\t\treturn;\n\n\t// yes I really am using the arrow class as a base\n\t// create the flag\n\tC_TFProjectile_Arrow *pBanner = new C_TFProjectile_Arrow();\n\tif ( pBanner )\n\t{\n\t\tpBanner->InitializeAsClientEntity( g_BannerModels[iBuffType - 1], RENDER_GROUP_OPAQUE_ENTITY );\n\n\t\t// Attach the flag to the backpack\n\t\tint bone = pWearable->LookupBone( \"bip_spine_3\" );\n\t\tif ( bone != -1 )\n\t\t{\n\t\t\tpBanner->SetDieTime( gpGlobals->curtime + 10.0f );\n\t\t\tpBanner->AttachEntityToBone( pWearable, bone );\n\t\t}\n\t}\n}\n\n/*//-----------------------------------------------------------------------------\n// Purpose: Destroy the banner addon for the backpack\n//-----------------------------------------------------------------------------\nvoid C_TFBuffItem::DestroyBanner( void )\n{\n\tC_TFPlayer *pOwner = GetTFPlayerOwner();\n\n\tif ( !pOwner )\n\t\treturn;\n\n\tC_EconWearable *pWearable = pOwner->GetWearableForLoadoutSlot( TF_LOADOUT_SLOT_SECONDARY );\n\n\tif ( !pWearable )\n\t\treturn;\n\n\tpWearable->DestroyBoneAttachments();\n}*/\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFBuffItem::FireGameEvent(IGameEvent *event)\n{\n\tif ( V_strcmp( event->GetName(), \"deploy_buff_banner\" ) == 0 )\n\t{\n\t\tint entindex = event->GetInt( \"buff_owner\" );\n\n\t\t// Make sure the person who deployed owns this weapon\n\t\tif ( UTIL_PlayerByIndex( entindex ) == GetPlayerOwner() )\n\t\t{\n\t\t\t// Create the banner addon\n\t\t\tCreateBanner( event->GetInt( \"buff_type\" ) );\n\t\t}\n\t}\n}\n#endif\n\n<|start_filename|>src/game/shared/tf/tf_projectile_jar.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"tf_projectile_jar.h\"\n#include \"tf_gamerules.h\"\n#include \"effect_dispatch_data.h\"\n#include \"tf_weapon_jar.h\"\n\n#ifdef GAME_DLL\n#include \"tf_fx.h\"\n#else\n#include \"particles_new.h\"\n#endif\n\n\n#define TF_WEAPON_JAR_MODEL\t\t\"models/weapons/c_models/urinejar.mdl\"\n#define TF_WEAPON_JAR_LIFETIME 2.0f\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_Jar, DT_TFProjectile_Jar )\n\nBEGIN_NETWORK_TABLE( CTFProjectile_Jar, DT_TFProjectile_Jar )\n#ifdef CLIENT_DLL\n\tRecvPropBool( RECVINFO( m_bCritical ) ),\n#else\n\tSendPropBool( SENDINFO( m_bCritical ) ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef GAME_DLL\nBEGIN_DATADESC( CTFProjectile_Jar )\nEND_DATADESC()\n#endif\n\nConVar tf_jar_show_radius( \"tf_jar_show_radius\", \"0\", FCVAR_REPLICATED | FCVAR_CHEAT /*| FCVAR_DEVELOPMENTONLY*/, \"Render jar radius.\" );\n\nLINK_ENTITY_TO_CLASS( tf_projectile_jar, CTFProjectile_Jar );\nPRECACHE_REGISTER( tf_projectile_jar );\n\nCTFProjectile_Jar::CTFProjectile_Jar()\n{\n}\n\nCTFProjectile_Jar::~CTFProjectile_Jar()\n{\n#ifdef CLIENT_DLL\n\tParticleProp()->StopEmission();\n#endif\n}\n\n#ifdef GAME_DLL\nCTFProjectile_Jar *CTFProjectile_Jar::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo )\n{\n\tCTFProjectile_Jar *pJar = static_cast( CBaseEntity::CreateNoSpawn( \"tf_projectile_jar\", vecOrigin, vecAngles, pOwner ) );\n\n\tif ( pJar )\n\t{\n\t\t// Set scorer.\n\t\tpJar->SetScorer( pScorer );\n\n\t\t// Set firing weapon.\n\t\tpJar->SetLauncher( pWeapon );\n\n\t\tDispatchSpawn( pJar );\n\n\t\tpJar->InitGrenade( vecVelocity, angVelocity, pOwner, weaponInfo );\n\n\t\tpJar->ApplyLocalAngularVelocityImpulse( angVelocity );\n\t}\n\n\treturn pJar;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::Precache( void )\n{\n\tPrecacheModel( TF_WEAPON_JAR_MODEL );\n\n\tPrecacheTeamParticles( \"peejar_trail_%s\", false, g_aTeamNamesShort );\n\tPrecacheParticleSystem( \"peejar_impact\" );\n\n\tPrecacheScriptSound( \"Jar.Explode\" );\n\n\tBaseClass::Precache();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::Spawn( void )\n{\n\tSetModel( TF_WEAPON_JAR_MODEL );\n\tSetDetonateTimerLength( TF_WEAPON_JAR_LIFETIME );\n\n\tBaseClass::Spawn();\n\tSetTouch( &CTFProjectile_Jar::JarTouch );\n\n\t// Pumpkin Bombs\n\tAddFlag( FL_GRENADE );\n\n\t// Don't collide with anything for a short time so that we never get stuck behind surfaces\n\tSetCollisionGroup( TFCOLLISION_GROUP_NONE );\n\n\tAddSolidFlags( FSOLID_TRIGGER );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::Explode( trace_t *pTrace, int bitsDamageType )\n{\n\t// Invisible.\n\tSetModelName( NULL_STRING );\n\tAddSolidFlags( FSOLID_NOT_SOLID );\n\tm_takedamage = DAMAGE_NO;\n\n\t// Pull out of the wall a bit\n\tif ( pTrace->fraction != 1.0 )\n\t{\n\t\tSetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) );\n\t}\n\n\tCTFWeaponBase *pWeapon = dynamic_cast( m_hLauncher.Get() );\n\n\t// Pull out a bit.\n\tif ( pTrace->fraction != 1.0 )\n\t{\n\t\tSetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) );\n\t}\n\n\t// Play explosion sound and effect.\n\tVector vecOrigin = GetAbsOrigin();\n\t//EmitSound( \"Jar.Explode\" );\n\tCPVSFilter filter( vecOrigin );\n\tTE_TFExplosion( filter, 0.0f, vecOrigin, pTrace->plane.normal, GetWeaponID(), -1 );\n\n\t// Damage.\n\tCBaseEntity *pAttacker = NULL;\n\tpAttacker = pWeapon->GetOwnerEntity();\n\n\tfloat flRadius = GetDamageRadius();\n\n\tCTFRadiusDamageInfo radiusInfo;\n\tradiusInfo.info.Set( this, pAttacker, m_hLauncher, vec3_origin, vecOrigin, GetDamage(), GetDamageType() );\n\tradiusInfo.m_vecSrc = vecOrigin;\n\tradiusInfo.m_flRadius = flRadius;\n\tradiusInfo.m_flSelfDamageRadius = 121.0f; // Original rocket radius?\n\n\t// If we extinguish a friendly player reduce our recharge time by four seconds\n\tif ( TFGameRules()->RadiusJarEffect( radiusInfo, TF_COND_URINE ) && m_iDeflected == 0 && pWeapon ) \n\t{\n\t\tpWeapon->ReduceEffectBarRegenTime( 4.0f );\n\t}\n\n\t// Debug!\n\tif ( tf_jar_show_radius.GetBool() )\n\t{\n\t\tDrawRadius( flRadius );\n\t}\n\n\tSetThink( &CBaseGrenade::SUB_Remove );\n\tSetTouch( NULL );\n\t\n\tUTIL_Remove( this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::JarTouch( CBaseEntity *pOther )\n{\n\tif ( pOther == GetThrower() )\n\t{\n\t\t// Make us solid if we're not already\n\t\tif ( GetCollisionGroup() == TFCOLLISION_GROUP_NONE )\n\t\t{\n\t\t\tSetCollisionGroup( COLLISION_GROUP_PROJECTILE );\n\t\t}\n\t\treturn;\n\t}\n\n\t// Verify a correct \"other.\"\n\tif ( !pOther->IsSolid() || pOther->IsSolidFlagSet( FSOLID_VOLUME_CONTENTS ) )\n\t\treturn;\n\n\t// Handle hitting skybox (disappear).\n\ttrace_t pTrace;\n\tVector velDir = GetAbsVelocity();\n\tVectorNormalize( velDir );\n\tVector vecSpot = GetAbsOrigin() - velDir * 32;\n\tUTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_NONE, &pTrace );\n\n\tif ( pTrace.fraction < 1.0 && pTrace.surface.flags & SURF_SKY )\n\t{\n\t\tUTIL_Remove( this );\n\t\treturn;\n\t}\n\n\t// Blow up if we hit a player\n\tif ( pOther->IsPlayer() )\n\t{\n\t\tExplode( &pTrace, GetDamageType() );\n\t}\n\t// We should bounce off of certain surfaces (resupply cabinets, spawn doors, etc.)\n\telse\n\t{\n\t\treturn;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::Detonate()\n{\n\ttrace_t\t\ttr;\n\tVector\t\tvecSpot;// trace starts here!\n\n\tSetThink( NULL );\n\n\tvecSpot = GetAbsOrigin() + Vector ( 0 , 0 , 8 );\n\tUTIL_TraceLine ( vecSpot, vecSpot + Vector ( 0, 0, -32 ), MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, & tr);\n\n\tExplode( &tr, GetDamageType() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )\n{\n\tBaseClass::VPhysicsCollision( index, pEvent );\n\n\tint otherIndex = !index;\n\tCBaseEntity *pHitEntity = pEvent->pEntities[otherIndex];\n\n\tif ( !pHitEntity )\n\t{\n\t\treturn;\n\t}\n\n\t// TODO: This needs to be redone properly\n\t/*if ( pHitEntity->GetMoveType() == MOVETYPE_NONE )\n\t{\n\t\t// Blow up\n\t\tSetThink( &CTFProjectile_Jar::Detonate );\n\t\tSetNextThink( gpGlobals->curtime );\n\t}*/\n\n\t\t// Blow up\n\t\tSetThink( &CTFProjectile_Jar::Detonate );\n\t\tSetNextThink( gpGlobals->curtime );\n\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::SetScorer( CBaseEntity *pScorer )\n{\n\tm_Scorer = pScorer;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nCBasePlayer *CTFProjectile_Jar::GetAssistant( void )\n{\n\treturn dynamic_cast( m_Scorer.Get() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Jar::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir )\n{\n\t/*// Get jar's speed.\n\tfloat flVel = GetAbsVelocity().Length();\n\n\tQAngle angForward;\n\tVectorAngles( vecDir, angForward );\n\tAngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) );\n\n\t// Now change jar's direction.\n\tSetAbsAngles( angForward );\n\tSetAbsVelocity( vecDir * flVel );\n\n\t// Bounce it up a bit\n\tApplyLocalAngularVelocityImpulse( angVelocity );\n\n\tIncremenentDeflected();\n\tSetOwnerEntity( pDeflectedBy );\n\tChangeTeam( pDeflectedBy->GetTeamNumber() );\n\tSetScorer( pDeflectedBy );*/\n\n\tIPhysicsObject *pPhysicsObject = VPhysicsGetObject();\n\tif ( pPhysicsObject )\n\t{\n\t\tVector vecOldVelocity, vecVelocity;\n\n\t\tpPhysicsObject->GetVelocity( &vecOldVelocity, NULL );\n\n\t\tfloat flVel = vecOldVelocity.Length();\n\n\t\tvecVelocity = vecDir;\n\t\tvecVelocity *= flVel;\n\t\tAngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) );\n\n\t\t// Now change grenade's direction.\n\t\tpPhysicsObject->SetVelocityInstantaneous( &vecVelocity, &angVelocity );\n\t}\n\n\tCBaseCombatCharacter *pBCC = pDeflectedBy->MyCombatCharacterPointer();\n\n\tIncremenentDeflected();\n\tm_hDeflectOwner = pDeflectedBy;\n\tSetThrower( pBCC );\n\tChangeTeam( pDeflectedBy->GetTeamNumber() );\n}\n#else\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Jar::OnDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnDataChanged( updateType );\n\n\tif ( updateType == DATA_UPDATE_CREATED )\n\t{\n\t\tm_flCreationTime = gpGlobals->curtime;\n\t\tCreateTrails();\n\t}\n\n\tif ( m_iOldTeamNum && m_iOldTeamNum != m_iTeamNum )\n\t{\n\t\tParticleProp()->StopEmission();\n\t\tCreateTrails();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Jar::CreateTrails( void )\n{\n\tif ( IsDormant() )\n\t\treturn;\n\n\tconst char *pszEffectName = ConstructTeamParticle( \"peejar_trail_%s\", GetTeamNumber(), false, g_aTeamNamesShort );\n\n\tParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Don't draw if we haven't yet gone past our original spawn point\n//-----------------------------------------------------------------------------\nint CTFProjectile_Jar::DrawModel( int flags )\n{\n\tif ( gpGlobals->curtime - m_flCreationTime < 0.1f )\n\t\treturn 0;\n\n\treturn BaseClass::DrawModel( flags );\n}\n#endif\n\n<|start_filename|>src/game/shared/econ/econ_entity.cpp<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: \n//\n//===========================================================================//\n\n#include \"cbase.h\"\n#include \"econ_entity.h\"\n#include \"eventlist.h\"\n\n#ifdef GAME_DLL\n#include \"tf_player.h\"\n#else\n#include \"c_tf_player.h\"\n#include \"model_types.h\"\n#endif\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n#ifdef CLIENT_DLL\nEXTERN_RECV_TABLE( DT_ScriptCreatedItem )\n#else\nEXTERN_SEND_TABLE( DT_ScriptCreatedItem )\n#endif\n\nIMPLEMENT_NETWORKCLASS_ALIASED( EconEntity, DT_EconEntity )\n\nBEGIN_NETWORK_TABLE( CEconEntity, DT_EconEntity )\n#ifdef CLIENT_DLL\n\tRecvPropDataTable( RECVINFO_DT( m_Item ), 0, &REFERENCE_RECV_TABLE( DT_ScriptCreatedItem ) ),\n\tRecvPropDataTable( RECVINFO_DT( m_AttributeManager ), 0, &REFERENCE_RECV_TABLE( DT_AttributeContainer ) ),\n#else\n\tSendPropDataTable( SENDINFO_DT( m_Item ), &REFERENCE_SEND_TABLE( DT_ScriptCreatedItem ) ),\n\tSendPropDataTable( SENDINFO_DT( m_AttributeManager ), &REFERENCE_SEND_TABLE( DT_AttributeContainer ) ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef CLIENT_DLL\nBEGIN_PREDICTION_DATA( C_EconEntity )\n\tDEFINE_PRED_TYPEDESCRIPTION( m_AttributeManager, CAttributeContainer ),\nEND_PREDICTION_DATA()\n#endif\n\nCEconEntity::CEconEntity()\n{\n\tm_pAttributes = this;\n}\n\n#ifdef CLIENT_DLL\n\nvoid CEconEntity::OnPreDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnPreDataChanged( updateType );\n\n\tm_AttributeManager.OnPreDataChanged( updateType );\n}\n\nvoid CEconEntity::OnDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnDataChanged( updateType );\n\n\tm_AttributeManager.OnDataChanged( updateType );\n}\n\nvoid CEconEntity::FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options )\n{\n\tif ( event == AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN )\n\t{\n\t\tC_ViewmodelAttachmentModel *pAttach = GetViewmodelAddon();\n\t\tif ( pAttach)\n\t\t{\n\t\t\tpAttach->FireEvent( origin, angles, AE_CL_BODYGROUP_SET_VALUE, options );\n\t\t}\n\t}\n\telse\n\t\tBaseClass::FireEvent( origin, angles, event, options );\n}\n\nbool CEconEntity::OnFireEvent( C_BaseViewModel *pViewModel, const Vector& origin, const QAngle& angles, int event, const char *options )\n{\n\tif ( event == AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN )\n\t{\n\t\tC_ViewmodelAttachmentModel *pAttach = GetViewmodelAddon();\n\t\tif ( pAttach)\n\t\t{\n\t\t\tpAttach->FireEvent( origin, angles, AE_CL_BODYGROUP_SET_VALUE, options );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool CEconEntity::OnInternalDrawModel( ClientModelRenderInfo_t *pInfo )\n{\n\tif ( BaseClass::OnInternalDrawModel( pInfo ) )\n\t{\n\t\tDrawEconEntityAttachedModels( this, this, pInfo, 1 );\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\nvoid CEconEntity::ViewModelAttachmentBlending( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask )\n{\n\t// NUB\n}\n\n#endif\n\nvoid CEconEntity::SetItem( CEconItemView &newItem )\n{\n\tm_Item = newItem;\n}\n\nCEconItemView *CEconEntity::GetItem( void )\n{\n\treturn &m_Item;\n}\n\nbool CEconEntity::HasItemDefinition( void ) const\n{\n\treturn ( m_Item.GetItemDefIndex() >= 0 );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Shortcut to get item ID.\n//-----------------------------------------------------------------------------\nint CEconEntity::GetItemID( void )\n{\n\treturn m_Item.GetItemDefIndex();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Derived classes need to override this.\n//-----------------------------------------------------------------------------\nvoid CEconEntity::GiveTo( CBaseEntity *pEntity )\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Add or remove this from owner's attribute providers list.\n//-----------------------------------------------------------------------------\nvoid CEconEntity::ReapplyProvision( void )\n{\n\tCBaseEntity *pOwner = GetOwnerEntity();\n\tCBaseEntity *pOldOwner = m_hOldOwner.Get();\n\n\tif ( pOwner != pOldOwner )\n\t{\n\t\tif ( pOldOwner )\n\t\t{\n\t\t\tm_AttributeManager.StopProvidingTo( pOldOwner );\n\t\t}\n\n\t\tif ( pOwner )\n\t\t{\n\t\t\tm_AttributeManager.ProviteTo( pOwner );\n\t\t\tm_hOldOwner = pOwner;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_hOldOwner = NULL;\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Update visible bodygroups\n//-----------------------------------------------------------------------------\nvoid CEconEntity::UpdatePlayerBodygroups( void )\n{\n\tCTFPlayer *pPlayer = dynamic_cast < CTFPlayer * >( GetOwnerEntity() );\n\n\tif ( !pPlayer )\n\t{\n\t\treturn;\n\t}\n\n\t// bodygroup enabling/disabling\n\tCEconItemDefinition *pStatic = m_Item.GetStaticData();\n\tif ( pStatic )\n\t{\n\t\tEconItemVisuals *pVisuals =\tpStatic->GetVisuals();\n\t\tif ( pVisuals )\n\t\t{\n\t\t\tfor ( int i = 0; i < pPlayer->GetNumBodyGroups(); i++ )\n\t\t\t{\n\t\t\t\tunsigned int index = pVisuals->player_bodygroups.Find( pPlayer->GetBodygroupName( i ) );\n\t\t\t\tif ( pVisuals->player_bodygroups.IsValidIndex( index ) )\n\t\t\t\t{\n\t\t\t\t\tbool bTrue = pVisuals->player_bodygroups.Element( index );\n\t\t\t\t\tif ( bTrue )\n\t\t\t\t\t{\n\t\t\t\t\t\tpPlayer->SetBodygroup( i , 1 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpPlayer->SetBodygroup( i , 0 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CEconEntity::UpdateOnRemove( void )\n{\n\tSetOwnerEntity( NULL );\n\tReapplyProvision();\n\tBaseClass::UpdateOnRemove();\n}\n\nCEconEntity::~CEconEntity()\n{\n\n}\n\n#ifdef CLIENT_DLL\nvoid DrawEconEntityAttachedModels( C_BaseAnimating *pAnimating, C_EconEntity *pEconEntity, ClientModelRenderInfo_t const *pInfo, int iModelType )\n{\n\t/*if ( pAnimating && pEconEntity && pInfo )\n\t{\n\t\tif ( pEconEntity->HasItemDefinition() )\n\t\t{\n\t\t\tCEconItemDefinition *pItemDef = pEconEntity->GetItem()->GetStaticData();\n\t\t\tif ( pItemDef )\n\t\t\t{\n\t\t\t\tEconItemVisuals *pVisuals = pItemDef->GetVisuals( pEconEntity->GetTeamNumber() );\n\t\t\t\tif ( pVisuals )\n\t\t\t\t{\n\t\t\t\t\tconst char *pszModelName = NULL;\n\t\t\t\t\tfor ( int i = 0; i < pVisuals->attached_models.Count(); i++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch ( iModelType )\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tif ( pVisuals->attached_models[i].world_model == 1 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpszModelName = pVisuals->attached_models[i].model;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tif ( pVisuals->attached_models[i].view_model == 1 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpszModelName = pVisuals->attached_models[i].model;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( pszModelName != NULL )\n\t\t\t\t\t{\n\t\t\t\t\t\tClientModelRenderInfo_t *pNewInfo = new ClientModelRenderInfo_t( *pInfo );\n\t\t\t\t\t\tmodel_t *model = (model_t *)engine->LoadModel( pszModelName );\n\t\t\t\t\t\tpNewInfo->pModel = model;\n\n\t\t\t\t\t\tpNewInfo->pModelToWorld = &pNewInfo->modelToWorld;\n\t\t\t\t\t\t// Turns the origin + angles into a matrix\n\t\t\t\t\t\tAngleMatrix( pNewInfo->angles, pNewInfo->origin, pNewInfo->modelToWorld );\n\n\t\t\t\t\t\tDrawModelState_t state;\n\t\t\t\t\t\tmatrix3x4_t *pBoneToWorld = NULL;\n\t\t\t\t\t\tbool bMarkAsDrawn = modelrender->DrawModelSetup( *pNewInfo, &state, NULL, &pBoneToWorld );\n\t\t\t\t\t\tpAnimating->DoInternalDrawModel( pNewInfo, ( bMarkAsDrawn && ( pNewInfo->flags & STUDIO_RENDER ) ) ? &state : NULL, pBoneToWorld );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}*/\n}\n#endif\n\n<|start_filename|>src/game/client/tf/vgui/panels/tf_statsummarydialog.cpp<|end_filename|>\n#include \"cbase.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ienginevgui.h\"\n#include \n\n#include \"tf_statsummarydialog.h\"\n#include \"tf_mainmenu.h\"\n#include \n#include \"fmtstr.h\"\n\nusing namespace vgui;\n\n//-----------------------------------------------------------------------------\n// Purpose: Constructor\n//-----------------------------------------------------------------------------\nCTFStatsSummaryDialog::CTFStatsSummaryDialog(vgui::Panel* parent, const char *panelName) : CTFDialogPanelBase(parent, panelName)\n{\n\tInit();\n}\n\nbool CTFStatsSummaryDialog::Init()\n{\n\tBaseClass::Init();\n\n\tm_bControlsLoaded = false;\n\tm_xStartLHBar = 0;\n\tm_xStartRHBar = 0;\n\tm_iBarHeight = 1;\n\tm_iBarMaxWidth = 1;\n\n\tm_pPlayerData = new vgui::EditablePanel(this, \"statdata\");\n\tm_pBarChartComboBoxA = new vgui::ComboBox(m_pPlayerData, \"BarChartComboA\", 10, false);\n\tm_pBarChartComboBoxB = new vgui::ComboBox(m_pPlayerData, \"BarChartComboB\", 10, false);\n\tm_pClassComboBox = new vgui::ComboBox(m_pPlayerData, \"ClassCombo\", 10, false);\n\n\tm_pBarChartComboBoxA->AddActionSignalTarget(this);\n\tm_pBarChartComboBoxB->AddActionSignalTarget(this);\n\tm_pClassComboBox->AddActionSignalTarget(this);\n\n\tReset();\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Applies scheme settings\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::ApplySchemeSettings(vgui::IScheme *pScheme)\n{\n\tBaseClass::ApplySchemeSettings(pScheme);\n\n\tLoadControlSettings(\"Resource/UI/main_menu/StatsSummaryDialog.res\");\n\tm_bControlsLoaded = true;\n\n\t// get the dimensions and position of a left-hand bar and a right-hand bar so we can do bar sizing later\n\tPanel *pLHBar = m_pPlayerData->FindChildByName(\"ClassBar1A\");\n\tPanel *pRHBar = m_pPlayerData->FindChildByName(\"ClassBar1B\");\n\tif (pLHBar && pRHBar)\n\t{\n\t\tint y;\n\t\tpLHBar->GetBounds(m_xStartLHBar, y, m_iBarMaxWidth, m_iBarHeight);\n\t\tpRHBar->GetBounds(m_xStartRHBar, y, m_iBarMaxWidth, m_iBarHeight);\n\t}\n\n\t// fill the combo box selections appropriately\n\tInitBarChartComboBox(m_pBarChartComboBoxA);\n\tInitBarChartComboBox(m_pBarChartComboBoxB);\n\n\t// fill the class names in the class combo box\n\tHFont hFont = scheme()->GetIScheme(GetScheme())->GetFont(\"ScoreboardSmall\", true);\n\tm_pClassComboBox->SetFont(hFont);\n\tm_pClassComboBox->RemoveAll();\n\tKeyValues *pKeyValues = new KeyValues(\"data\");\n\tpKeyValues->SetInt(\"class\", TF_CLASS_UNDEFINED);\n\tm_pClassComboBox->AddItem(\"#StatSummary_Label_AsAnyClass\", pKeyValues);\n\tfor (int iClass = TF_FIRST_NORMAL_CLASS; iClass <= TF_CLASS_COUNT; iClass++)\n\t{\n\t\tpKeyValues = new KeyValues(\"data\");\n\t\tpKeyValues->SetInt(\"class\", iClass);\n\t\tm_pClassComboBox->AddItem(g_aPlayerClassNames[iClass], pKeyValues);\n\t}\n\tm_pClassComboBox->ActivateItemByRow(0);\n\n\tSetDefaultSelections();\n\tUpdateDialog();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::PerformLayout()\n{\n\tBaseClass::PerformLayout();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Shows this dialog as a modal dialog\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::Show()\n{\n\tBaseClass::Show();\n\n\tGetStatPanel()->UpdateMainMenuDialog();\n\tUpdateDialog();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Command handler\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::OnCommand(const char *command)\n{\n\tif (0 == Q_stricmp(command, \"vguicancel\"))\n\t{\n\t\tUpdateDialog();\n\t\tHide();\n\t\tSetDefaultSelections();\n\t}\n\n\tBaseClass::OnCommand(command);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Resets the dialog\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::Reset()\n{\n\tm_aClassStats.RemoveAll();\n\n\tSetDefaultSelections();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Sets all user-controllable dialog settings to default values\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::SetDefaultSelections()\n{\n\tm_iSelectedClass = TF_CLASS_UNDEFINED;\n\tm_statBarGraph[0] = TFSTAT_POINTSSCORED;\n\tm_displayBarGraph[0] = SHOW_MAX;\n\tm_statBarGraph[1] = TFSTAT_PLAYTIME;\n\tm_displayBarGraph[1] = SHOW_TOTAL;\n\n\tm_pBarChartComboBoxA->ActivateItemByRow(0);\n\tm_pBarChartComboBoxB->ActivateItemByRow(10);\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::OnKeyCodePressed(KeyCode code)\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Sets stats to use\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::SetStats(CUtlVector &vecClassStats)\n{\n\tm_aClassStats = vecClassStats;\n\tif (m_bControlsLoaded)\n\t{\n\t\tUpdateDialog();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Updates the dialog\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::UpdateDialog()\n{\n\tRandomSeed(Plat_MSTime());\n\n\tm_iTotalSpawns = 0;\n\n\t// if we don't have stats for any class, add empty stat entries for them \n\tfor (int iClass = TF_FIRST_NORMAL_CLASS; iClass <= TF_CLASS_COUNT; iClass++)\n\t{\n\t\tint j;\n\t\tfor (j = 0; j < m_aClassStats.Count(); j++)\n\t\t{\n\t\t\tif (m_aClassStats[j].iPlayerClass == iClass)\n\t\t\t{\n\t\t\t\tm_iTotalSpawns += m_aClassStats[j].iNumberOfRounds;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (j == m_aClassStats.Count())\n\t\t{\n\t\t\tClassStats_t stats;\n\t\t\tstats.iPlayerClass = iClass;\n\t\t\tm_aClassStats.AddToTail(stats);\n\t\t}\n\t}\n\n\n\t// fill out bar charts\n\tUpdateBarCharts();\n\t// fill out class details\n\tUpdateClassDetails();\n\t// show or hide controls depending on if we're interactive or not\n\tUpdateControls();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Shows or hides controls\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::UpdateControls()\n{\n\tm_pPlayerData->SetVisible(true);\n\tm_pPlayerData->SetVisible(true);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Updates bar charts\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::UpdateBarCharts()\n{\n\t// sort the class stats by the selected stat for right-hand bar chart\n\tm_aClassStats.Sort(&CTFStatsSummaryDialog::CompareClassStats);\n\n\t// loop for left & right hand charts\n\tfor (int iChart = 0; iChart < 2; iChart++)\n\t{\n\t\tfloat flMax = 0;\n\t\tfor (int i = 0; i < m_aClassStats.Count(); i++)\n\t\t{\n\t\t\t// get max value of stat being charted so we know how to scale the graph\n\t\t\tfloat flVal = GetDisplayValue(m_aClassStats[i], m_statBarGraph[iChart], m_displayBarGraph[iChart]);\n\t\t\tflMax = max(flVal, flMax);\n\t\t}\n\n\t\t// draw the bar chart value for each player class\n\t\tfor (int i = 0; i < m_aClassStats.Count(); i++)\n\t\t{\n\t\t\tif (0 == iChart)\n\t\t\t{\n\t\t\t\t// if this is the first chart, set the class label for each class\n\t\t\t\tint iClass = m_aClassStats[i].iPlayerClass;\n\t\t\t\tm_pPlayerData->SetDialogVariable(CFmtStr(\"class%d\", i + 1), g_pVGuiLocalize->Find(g_aPlayerClassNames[iClass]));\n\t\t\t}\n\t\t\t// draw the bar for this class\n\t\t\tDisplayBarValue(iChart, i, m_aClassStats[i], m_statBarGraph[iChart], m_displayBarGraph[iChart], flMax);\n\t\t}\n\t}\n}\n\n#define MAKEFLAG(x)\t( 1 << x )\n\n#define ALL_CLASSES 0xFFFFFFFF\n\n//-----------------------------------------------------------------------------\n// Purpose: Updates class details\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::UpdateClassDetails()\n{\n\tstruct ClassDetails_t\n\t{\n\t\tTFStatType_t statType;\t\t\t// type of stat\n\t\tint\t\t\t iFlagsClass;\t\t// bit mask of classes to show this stat for\n\t\tconst char * szResourceName;\t// name of label resource\n\t};\n\n\tClassDetails_t classDetails[] =\n\t{\n\t\t{ TFSTAT_POINTSSCORED, ALL_CLASSES, \"#TF_ClassRecord_MostPoints\" },\n\t\t{ TFSTAT_KILLS, ALL_CLASSES, \"#TF_ClassRecord_MostKills\" },\n\t\t{ TFSTAT_KILLASSISTS, ALL_CLASSES, \"#TF_ClassRecord_MostAssists\" },\n\t\t{ TFSTAT_CAPTURES, ALL_CLASSES, \"#TF_ClassRecord_MostCaptures\" },\n\t\t{ TFSTAT_DEFENSES, ALL_CLASSES, \"#TF_ClassRecord_MostDefenses\" },\n\t\t{ TFSTAT_DAMAGE, ALL_CLASSES, \"#TF_ClassRecord_MostDamage\" },\n\t\t{ TFSTAT_BUILDINGSDESTROYED, ALL_CLASSES, \"#TF_ClassRecord_MostDestruction\" },\n\t\t{ TFSTAT_DOMINATIONS, ALL_CLASSES, \"#TF_ClassRecord_MostDominations\" },\n\t\t{ TFSTAT_PLAYTIME, ALL_CLASSES, \"#TF_ClassRecord_LongestLife\" },\n\t\t{ TFSTAT_HEALING, MAKEFLAG(TF_CLASS_MEDIC) | MAKEFLAG(TF_CLASS_ENGINEER), \"#TF_ClassRecord_MostHealing\" },\n\t\t{ TFSTAT_INVULNS, MAKEFLAG(TF_CLASS_MEDIC), \"#TF_ClassRecord_MostInvulns\" },\n\t\t{ TFSTAT_MAXSENTRYKILLS, MAKEFLAG(TF_CLASS_ENGINEER), \"#TF_ClassRecord_MostSentryKills\" },\n\t\t{ TFSTAT_TELEPORTS, MAKEFLAG(TF_CLASS_ENGINEER), \"#TF_ClassRecord_MostTeleports\" },\n\t\t{ TFSTAT_HEADSHOTS, MAKEFLAG(TF_CLASS_SNIPER), \"#TF_ClassRecord_MostHeadshots\" },\n\t\t{ TFSTAT_BACKSTABS, MAKEFLAG(TF_CLASS_SPY), \"#TF_ClassRecord_MostBackstabs\" },\n\t};\n\n\twchar_t *wzWithClassFmt = g_pVGuiLocalize->Find(\"#StatSummary_ScoreAsClassFmt\");\n\twchar_t *wzWithoutClassFmt = L\"%s1\";\n\n\t// display the record for each stat\n\tint iRow = 0;\n\tfor (int i = 0; i < ARRAYSIZE(classDetails); i++)\n\t{\n\t\tTFStatType_t statType = classDetails[i].statType;\n\n\t\tint iClass = TF_CLASS_UNDEFINED;\n\t\tint iMaxVal = 0;\n\n\t\t// if there is a selected class, and if this stat should not be shown for this class, skip this stat\n\t\tif (m_iSelectedClass != TF_CLASS_UNDEFINED && (0 == (classDetails[i].iFlagsClass & MAKEFLAG(m_iSelectedClass))))\n\t\t\tcontinue;\n\n\t\tif (m_iSelectedClass == TF_CLASS_UNDEFINED)\n\t\t{\n\t\t\t// if showing best from any class, look through all player classes to determine the max value of this stat\n\t\t\tfor (int j = 0; j < m_aClassStats.Count(); j++)\n\t\t\t{\n\t\t\t\tif (m_aClassStats[j].max.m_iStat[statType] > iMaxVal)\n\t\t\t\t{\n\t\t\t\t\t// remember max value and class that has max value\n\t\t\t\t\tiMaxVal = m_aClassStats[j].max.m_iStat[statType];\n\t\t\t\t\tiClass = m_aClassStats[j].iPlayerClass;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// show best from selected class\n\t\t\tiClass = m_iSelectedClass;\n\t\t\tfor (int j = 0; j < m_aClassStats.Count(); j++)\n\t\t\t{\n\t\t\t\tif (m_aClassStats[j].iPlayerClass == iClass)\n\t\t\t\t{\n\t\t\t\t\tiMaxVal = m_aClassStats[j].max.m_iStat[statType];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twchar_t wzStatNum[32];\n\t\twchar_t wzStatVal[128];\n\t\tif (TFSTAT_PLAYTIME == statType)\n\t\t{\n\t\t\t// playtime gets displayed as a time string\n\t\t\tg_pVGuiLocalize->ConvertANSIToUnicode(FormatSeconds(iMaxVal), wzStatNum, sizeof(wzStatNum));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// all other stats are just shown as a #\n\t\t\tswprintf_s(wzStatNum, ARRAYSIZE(wzStatNum), L\"%d\", iMaxVal);\n\t\t}\n\n\t\tif (TF_CLASS_UNDEFINED == m_iSelectedClass && iMaxVal > 0)\n\t\t{\n\t\t\t// if we are doing a cross-class view (no single selected class) and the max value is non-zero, show \"# (as )\"\n\t\t\twchar_t *wzLocalizedClassName = g_pVGuiLocalize->Find(g_aPlayerClassNames[iClass]);\n\t\t\tg_pVGuiLocalize->ConstructString(wzStatVal, sizeof(wzStatVal), wzWithClassFmt, 2, wzStatNum, wzLocalizedClassName);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// just show the value\n\t\t\tg_pVGuiLocalize->ConstructString(wzStatVal, sizeof(wzStatVal), wzWithoutClassFmt, 1, wzStatNum);\n\t\t}\n\n\t\t// set the label\n\t\tm_pPlayerData->SetDialogVariable(CFmtStr(\"classrecord%dlabel\", iRow + 1), g_pVGuiLocalize->Find(classDetails[i].szResourceName));\n\t\t// set the value \n\t\tm_pPlayerData->SetDialogVariable(CFmtStr(\"classrecord%dvalue\", iRow + 1), wzStatVal);\n\n\t\tiRow++;\n\t}\n\n\t// if there are any leftover rows for the selected class, fill out the remaining rows with blank labels and values\n\tfor (; iRow < 15; iRow++)\n\t{\n\t\tm_pPlayerData->SetDialogVariable(CFmtStr(\"classrecord%dlabel\", iRow + 1), \"\");\n\t\tm_pPlayerData->SetDialogVariable(CFmtStr(\"classrecord%dvalue\", iRow + 1), \"\");\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Initializes a bar chart combo box\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::InitBarChartComboBox(ComboBox *pComboBox)\n{\n\tstruct BarChartComboInit_t\n\t{\n\t\tTFStatType_t statType;\n\t\tStatDisplay_t statDisplay;\n\t\tconst char *szName;\n\t};\n\n\tBarChartComboInit_t initData[] =\n\t{\n\t\t{ TFSTAT_POINTSSCORED, SHOW_MAX, \"#StatSummary_StatTitle_MostPoints\" },\n\t\t{ TFSTAT_POINTSSCORED, SHOW_AVG, \"#StatSummary_StatTitle_AvgPoints\" },\n\t\t{ TFSTAT_KILLS, SHOW_MAX, \"#StatSummary_StatTitle_MostKills\" },\n\t\t{ TFSTAT_KILLS, SHOW_AVG, \"#StatSummary_StatTitle_AvgKills\" },\n\t\t{ TFSTAT_CAPTURES, SHOW_MAX, \"#StatSummary_StatTitle_MostCaptures\" },\n\t\t{ TFSTAT_CAPTURES, SHOW_AVG, \"#StatSummary_StatTitle_AvgCaptures\" },\n\t\t{ TFSTAT_KILLASSISTS, SHOW_MAX, \"#StatSummary_StatTitle_MostAssists\" },\n\t\t{ TFSTAT_KILLASSISTS, SHOW_AVG, \"#StatSummary_StatTitle_AvgAssists\" },\n\t\t{ TFSTAT_DAMAGE, SHOW_MAX, \"#StatSummary_StatTitle_MostDamage\" },\n\t\t{ TFSTAT_DAMAGE, SHOW_AVG, \"#StatSummary_StatTitle_AvgDamage\" },\n\t\t{ TFSTAT_PLAYTIME, SHOW_TOTAL, \"#StatSummary_StatTitle_TotalPlaytime\" },\n\t\t{ TFSTAT_PLAYTIME, SHOW_MAX, \"#StatSummary_StatTitle_LongestLife\" },\n\t};\n\n\t// set the font\n\tHFont hFont = scheme()->GetIScheme(GetScheme())->GetFont(\"ScoreboardVerySmall\", true);\n\tpComboBox->SetFont(hFont);\n\tpComboBox->RemoveAll();\n\t// add all the options to the combo box\n\tfor (int i = 0; i < ARRAYSIZE(initData); i++)\n\t{\n\t\tKeyValues *pKeyValues = new KeyValues(\"data\");\n\t\tpKeyValues->SetInt(\"stattype\", initData[i].statType);\n\t\tpKeyValues->SetInt(\"statdisplay\", initData[i].statDisplay);\n\t\tpComboBox->AddItem(g_pVGuiLocalize->Find(initData[i].szName), pKeyValues);\n\t}\n\tpComboBox->SetNumberOfEditLines(ARRAYSIZE(initData));\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Helper function that sets the specified dialog variable to\n//\t\t\" (as )\"\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::SetValueAsClass(const char *pDialogVariable, int iValue, int iPlayerClass)\n{\n\tif (iValue > 0)\n\t{\n\t\twchar_t *wzScoreAsClassFmt = g_pVGuiLocalize->Find(\"#StatSummary_ScoreAsClassFmt\");\n\t\twchar_t *wzLocalizedClassName = g_pVGuiLocalize->Find(g_aPlayerClassNames[iPlayerClass]);\n\t\twchar_t wzVal[16];\n\t\twchar_t wzMsg[128];\n#ifdef _WIN32 // TODO: Find a posix equivelant to _itow_s\n\t\t_itow_s(iValue, wzVal, ARRAYSIZE(wzVal), 10);\n#endif\n\t\tg_pVGuiLocalize->ConstructString(wzMsg, sizeof(wzMsg), wzScoreAsClassFmt, 2, wzVal, wzLocalizedClassName);\n\t\tm_pPlayerData->SetDialogVariable(pDialogVariable, wzMsg);\n\t}\n\telse\n\t{\n\t\tm_pPlayerData->SetDialogVariable(pDialogVariable, \"0\");\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Sets the specified bar chart item to the specified value, in range 0->1\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::DisplayBarValue(int iChart, int iBar, ClassStats_t &stats, TFStatType_t statType, StatDisplay_t statDisplay, float flMaxValue)\n{\n\tconst char *szControlSuffix = (0 == iChart ? \"A\" : \"B\");\n\tPanel *pBar = m_pPlayerData->FindChildByName(CFmtStr(\"ClassBar%d%s\", iBar + 1, szControlSuffix));\n\tLabel *pLabel = dynamic_cast(m_pPlayerData->FindChildByName(CFmtStr(\"classbarlabel%d%s\", iBar + 1, szControlSuffix)));\n\tif (!pBar || !pLabel)\n\t\treturn;\n\n\t// get the stat value\n\tfloat flValue = GetDisplayValue(stats, statType, statDisplay);\n\t// calculate the bar size to draw, in the range of 0.0->1.0\n\tfloat flBarRange = SafeCalcFraction(flValue, flMaxValue);\n\t// calculate the # of pixels of bar width to draw\n\tint iBarWidth = max((int)(flBarRange * (float)m_iBarMaxWidth), 1);\n\n\t// Get the text label to draw for this bar. For values of 0, draw nothing, to minimize clutter\n\tconst char *szLabel = (flValue > 0 ? RenderValue(flValue, statType, statDisplay) : \"\");\n\t// draw the label outside the bar if there's room\n\tbool bLabelOutsideBar = true;\n\tconst int iLabelSpacing = 4;\n\tHFont hFont = pLabel->GetFont();\n\tint iLabelWidth = UTIL_ComputeStringWidth(hFont, szLabel);\n\tif (iBarWidth + iLabelWidth + iLabelSpacing > m_iBarMaxWidth)\n\t{\n\t\t// if there's not room outside the bar for the label, draw it inside the bar\n\t\tbLabelOutsideBar = false;\n\t}\n\n\tint xBar, yBar, xLabel, yLabel;\n\tpBar->GetPos(xBar, yBar);\n\tpLabel->GetPos(xLabel, yLabel);\n\n\tm_pPlayerData->SetDialogVariable(CFmtStr(\"classbarlabel%d%s\", iBar + 1, szControlSuffix), szLabel);\n\tif (1 == iChart)\n\t{\n\t\t// drawing code for RH bar chart\n\t\txBar = m_xStartRHBar;\n\t\tpBar->SetBounds(xBar, yBar, iBarWidth, m_iBarHeight);\n\t\tif (bLabelOutsideBar)\n\t\t{\n\t\t\tpLabel->SetPos(xBar + iBarWidth + iLabelSpacing, yLabel);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpLabel->SetPos(xBar + iBarWidth - (iLabelWidth + iLabelSpacing), yLabel);\n\t\t}\n\t}\n\telse\n\t{\n\t\t// drawing code for LH bar chart\n\t\txBar = m_xStartLHBar + m_iBarMaxWidth - iBarWidth;\n\t\tpBar->SetBounds(xBar, yBar, iBarWidth, m_iBarHeight);\n\t\tif (bLabelOutsideBar)\n\t\t{\n\t\t\tpLabel->SetPos(xBar - (iLabelWidth + iLabelSpacing), yLabel);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpLabel->SetPos(xBar + iLabelSpacing, yLabel);\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Calculates a fraction and guards from divide by 0. (Returns 0 if \n//\t\t\tdenominator is 0.)\n//-----------------------------------------------------------------------------\nfloat CTFStatsSummaryDialog::SafeCalcFraction(float flNumerator, float flDemoninator)\n{\n\tif (0 == flDemoninator)\n\t\treturn 0;\n\treturn flNumerator / flDemoninator;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Formats # of seconds into a string\n//-----------------------------------------------------------------------------\nchar *CTFStatsSummaryDialog::FormatSeconds(int seconds)\n{\n\tstatic char string[64];\n\n\tint hours = 0;\n\tint minutes = seconds / 60;\n\n\tif (minutes > 0)\n\t{\n\t\tseconds -= (minutes * 60);\n\t\thours = minutes / 60;\n\n\t\tif (hours > 0)\n\t\t{\n\t\t\tminutes -= (hours * 60);\n\t\t}\n\t}\n\n\tif (hours > 0)\n\t{\n\t\tQ_snprintf(string, sizeof(string), \"%2i:%02i:%02i\", hours, minutes, seconds);\n\t}\n\telse\n\t{\n\t\tQ_snprintf(string, sizeof(string), \"%02i:%02i\", minutes, seconds);\n\t}\n\n\treturn string;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Static sort function that sorts in descending order by play time\n//-----------------------------------------------------------------------------\nint __cdecl CTFStatsSummaryDialog::CompareClassStats(const ClassStats_t *pStats0, const ClassStats_t *pStats1)\n{\t\n\t// sort stats first by right-hand bar graph\n\tTFStatType_t statTypePrimary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_statBarGraph[1];\n\tStatDisplay_t statDisplayPrimary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_displayBarGraph[1];\n\t// then by left-hand bar graph\n\tTFStatType_t statTypeSecondary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_statBarGraph[0];\n\tStatDisplay_t statDisplaySecondary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_displayBarGraph[0];\n\n\tfloat flValPrimary0 = GetDisplayValue((ClassStats_t &)*pStats0, statTypePrimary, statDisplayPrimary);\n\tfloat flValPrimary1 = GetDisplayValue((ClassStats_t &)*pStats1, statTypePrimary, statDisplayPrimary);\n\tfloat flValSecondary0 = GetDisplayValue((ClassStats_t &)*pStats0, statTypeSecondary, statDisplaySecondary);\n\tfloat flValSecondary1 = GetDisplayValue((ClassStats_t &)*pStats1, statTypeSecondary, statDisplaySecondary);\n\n\t// sort in descending order by primary stat value\n\tif (flValPrimary1 > flValPrimary0)\n\t\treturn 1;\n\tif (flValPrimary1 < flValPrimary0)\n\t\treturn -1;\n\n\t// if primary stat values are equal, sort in descending order by secondary stat value\n\tif (flValSecondary1 > flValSecondary0)\n\t\treturn 1;\n\tif (flValSecondary1 < flValSecondary0)\n\t\treturn -1;\n\n\t// if primary & secondary stats are equal, sort by class for consistent sort order\n\treturn (pStats1->iPlayerClass - pStats0->iPlayerClass);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Called when text changes in combo box\n//-----------------------------------------------------------------------------\nvoid CTFStatsSummaryDialog::OnTextChanged(KeyValues *data)\n{\n\tPanel *pPanel = reinterpret_cast(data->GetPtr(\"panel\"));\n\tvgui::ComboBox *pComboBox = dynamic_cast(pPanel);\n\n\tif (m_pBarChartComboBoxA == pComboBox || m_pBarChartComboBoxB == pComboBox)\n\t{\n\t\t// a bar chart combo box changed, update the bar charts\n\n\t\tKeyValues *pUserDataA = m_pBarChartComboBoxA->GetActiveItemUserData();\n\t\tKeyValues *pUserDataB = m_pBarChartComboBoxB->GetActiveItemUserData();\n\t\tif (!pUserDataA || !pUserDataB)\n\t\t\treturn;\n\t\tm_statBarGraph[0] = (TFStatType_t)pUserDataA->GetInt(\"stattype\");\n\t\tm_displayBarGraph[0] = (StatDisplay_t)pUserDataA->GetInt(\"statdisplay\");\n\t\tm_statBarGraph[1] = (TFStatType_t)pUserDataB->GetInt(\"stattype\");\n\t\tm_displayBarGraph[1] = (StatDisplay_t)pUserDataB->GetInt(\"statdisplay\");\n\t\tUpdateBarCharts();\n\t}\n\telse if (m_pClassComboBox == pComboBox)\n\t{\n\t\t// the class selection combo box changed, update class details\n\n\t\tKeyValues *pUserData = m_pClassComboBox->GetActiveItemUserData();\n\t\tif (!pUserData)\n\t\t\treturn;\n\n\t\tm_iSelectedClass = pUserData->GetInt(\"class\", TF_CLASS_UNDEFINED);\n\n\t\tUpdateClassDetails();\n\t}\n\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Returns the stat value for specified display type\n//-----------------------------------------------------------------------------\nfloat CTFStatsSummaryDialog::GetDisplayValue(ClassStats_t &stats, TFStatType_t statType, StatDisplay_t statDisplay)\n{\n\tswitch (statDisplay)\n\t{\n\tcase SHOW_MAX:\n\t\treturn stats.max.m_iStat[statType];\n\t\tbreak;\n\tcase SHOW_TOTAL:\n\t\treturn stats.accumulated.m_iStat[statType];\n\t\tbreak;\n\tcase SHOW_AVG:\n\t\treturn SafeCalcFraction(stats.accumulated.m_iStat[statType], stats.iNumberOfRounds);\n\t\tbreak;\n\tdefault:\n\t\tAssertOnce(false);\n\t\treturn 0;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Gets the text representation of this value\n//-----------------------------------------------------------------------------\nconst char *CTFStatsSummaryDialog::RenderValue(float flValue, TFStatType_t statType, StatDisplay_t statDisplay)\n{\n\tstatic char szValue[64];\n\tif (TFSTAT_PLAYTIME == statType)\n\t{\n\t\t// the playtime stat is shown in seconds\n\t\treturn FormatSeconds((int)flValue);\n\t}\n\telse if (SHOW_AVG == statDisplay)\n\t{\n\t\t// if it's an average, render as a float w/2 decimal places\n\t\tQ_snprintf(szValue, ARRAYSIZE(szValue), \"%.2f\", flValue);\n\t}\n\telse\n\t{\n\t\t// otherwise, render as an integer\n\t\tQ_snprintf(szValue, ARRAYSIZE(szValue), \"%d\", (int)flValue);\n\t}\n\n\treturn szValue;\n}\n\n<|start_filename|>src/game/shared/econ/econ_item_system.h<|end_filename|>\n#ifndef ECON_ITEM_SYSTEM_H\n#define ECON_ITEM_SYSTEM_H\n\n#ifdef _WIN32\n#pragma once\n#endif\n\n#include \"econ_item_schema.h\"\n\nclass CEconSchemaParser;\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nclass CEconItemSchema\n{\n\tfriend class CEconSchemaParser;\n\tfriend class CTFInventory;\npublic:\n\tCEconItemSchema();\n\t~CEconItemSchema();\n\n\tbool Init( void );\n\tvoid Precache( void );\n\n\tCEconItemDefinition* GetItemDefinition( int id );\n\tEconAttributeDefinition *GetAttributeDefinition( int id );\n\tEconAttributeDefinition *GetAttributeDefinitionByName( const char* name );\n\tEconAttributeDefinition *GetAttributeDefinitionByClass( const char* name );\n\tint GetAttributeIndex( const char *classname );\n\nprotected:\n\tCUtlDict< int, unsigned short >\t\t\t\t\tm_GameInfo;\n\tCUtlDict< EconQuality, unsigned short >\t\t\tm_Qualities;\n\tCUtlDict< EconColor, unsigned short >\t\t\tm_Colors;\n\tCUtlDict< KeyValues *, unsigned short >\t\t\tm_PrefabsValues;\n\tCUtlMap< int, CEconItemDefinition * >\t\t\tm_Items;\n\tCUtlMap< int, EconAttributeDefinition * >\t\tm_Attributes;\n\nprivate:\n\tbool m_bInited;\n};\n\nCEconItemSchema *GetItemSchema();\n\n#endif // ECON_ITEM_SYSTEM_H\n\n\n<|start_filename|>src/game/server/tf/tf_obj.cpp<|end_filename|>\n//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//\n//\n// Purpose: Base Object built by players\n//\n// $NoKeywords: $\n//=============================================================================//\n#include \"cbase.h\"\n#include \"tf_player.h\"\n#include \"tf_team.h\"\n#include \"tf_obj.h\"\n#include \"tf_weapon_wrench.h\"\n#include \"tf_weaponbase.h\"\n#include \"rope.h\"\n#include \"rope_shared.h\"\n#include \"bone_setup.h\"\n#include \"ndebugoverlay.h\"\n#include \"rope_helpers.h\"\n#include \"IEffects.h\"\n#include \"vstdlib/random.h\"\n#include \"tier1/strtools.h\"\n#include \"basegrenade_shared.h\"\n#include \"tf_gamerules.h\"\n#include \"engine/IEngineSound.h\"\n#include \"tf_shareddefs.h\"\n#include \"vguiscreen.h\"\n#include \"hierarchy.h\"\n#include \"func_no_build.h\"\n#include \"func_respawnroom.h\"\n#include \n#include \"ihasbuildpoints.h\"\n#include \"utldict.h\"\n#include \"filesystem.h\"\n#include \"npcevent.h\"\n#include \"tf_shareddefs.h\"\n#include \"animation.h\"\n#include \"effect_dispatch_data.h\"\n#include \"te_effect_dispatch.h\"\n#include \"tf_gamestats.h\"\n#include \"tf_ammo_pack.h\"\n#include \"tf_obj_sapper.h\"\n#include \"particle_parse.h\"\n#include \"tf_fx.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n// Control panels\n#define SCREEN_OVERLAY_MATERIAL \"vgui/screens/vgui_overlay\"\n\n#define ROPE_HANG_DIST\t150\n\nConVar tf_obj_gib_velocity_min( \"tf_obj_gib_velocity_min\", \"100\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );\nConVar tf_obj_gib_velocity_max( \"tf_obj_gib_velocity_max\", \"450\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );\nConVar tf_obj_gib_maxspeed( \"tf_obj_gib_maxspeed\", \"800\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );\n\n\nConVar object_verbose( \"object_verbose\", \"0\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, \"Debug object system.\" );\nConVar obj_damage_factor( \"obj_damage_factor\",\"0\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, \"Factor applied to all damage done to objects\" );\nConVar obj_child_damage_factor( \"obj_child_damage_factor\",\"0.25\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, \"Factor applied to damage done to objects that are built on a buildpoint\" );\nConVar tf_fastbuild(\"tf_fastbuild\", \"0\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );\nConVar tf_obj_ground_clearance( \"tf_obj_ground_clearance\", \"32\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, \"Object corners can be this high above the ground\" );\nConVar tf2c_building_upgrades( \"tf2c_building_upgrades\", \"1\", FCVAR_REPLICATED, \"Toggles the ability to upgrade buildings other than the sentrygun\" );\n\nextern short g_sModelIndexFireball;\n\n// Minimum distance between 2 objects to ensure player movement between them\n#define MINIMUM_OBJECT_SAFE_DISTANCE\t\t100\n\n// Maximum number of a type of objects on a single resource zone\n#define MAX_OBJECTS_PER_ZONE\t\t\t1\n\n// Time it takes a fully healed object to deteriorate\nConVar object_deterioration_time( \"object_deterioration_time\", \"30\", 0, \"Time it takes for a fully-healed object to deteriorate.\" );\n\n// Time after taking damage that an object will still drop resources on death\n#define MAX_DROP_TIME_AFTER_DAMAGE\t\t\t5\n\n#define OBJ_BASE_THINK_CONTEXT\t\t\t\t\"BaseObjectThink\"\n\nBEGIN_DATADESC( CBaseObject )\n\t// keys \n\tDEFINE_KEYFIELD_NOT_SAVED( m_SolidToPlayers,\t\tFIELD_INTEGER, \"SolidToPlayer\" ),\n\tDEFINE_KEYFIELD( m_iDefaultUpgrade, FIELD_INTEGER, \"defaultupgrade\" ),\n\n\t// Inputs\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"Show\", InputShow ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"Hide\", InputHide ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"Enable\", InputEnable ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"Disable\", InputDisable ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"SetHealth\", InputSetHealth ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"AddHealth\", InputAddHealth ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"RemoveHealth\", InputRemoveHealth ),\n\tDEFINE_INPUTFUNC( FIELD_INTEGER, \"SetSolidToPlayer\", InputSetSolidToPlayer ),\n\n\t// Outputs\n\tDEFINE_OUTPUT( m_OnDestroyed, \"OnDestroyed\" ),\n\tDEFINE_OUTPUT( m_OnDamaged, \"OnDamaged\" ),\n\tDEFINE_OUTPUT( m_OnRepaired, \"OnRepaired\" ),\n\tDEFINE_OUTPUT( m_OnBecomingDisabled, \"OnDisabled\" ),\n\tDEFINE_OUTPUT( m_OnBecomingReenabled, \"OnReenabled\" ),\n\tDEFINE_OUTPUT( m_OnObjectHealthChanged, \"OnObjectHealthChanged\" )\nEND_DATADESC()\n\n\nIMPLEMENT_SERVERCLASS_ST( CBaseObject, DT_BaseObject )\n\tSendPropInt( SENDINFO( m_iHealth ), 13 ),\n\tSendPropInt( SENDINFO( m_iMaxHealth ), 13 ),\n\tSendPropBool( SENDINFO( m_bHasSapper ) ),\n\tSendPropInt( SENDINFO( m_iObjectType ), Q_log2( OBJ_LAST ) + 1, SPROP_UNSIGNED ),\n\tSendPropBool( SENDINFO( m_bBuilding ) ),\n\tSendPropBool( SENDINFO( m_bPlacing ) ),\n\tSendPropBool( SENDINFO( m_bCarried ) ),\n\tSendPropBool( SENDINFO( m_bCarryDeploy ) ),\n\tSendPropBool( SENDINFO( m_bMiniBuilding ) ),\n\tSendPropFloat( SENDINFO( m_flPercentageConstructed ), 8, 0, 0.0, 1.0f ),\n\tSendPropInt( SENDINFO( m_fObjectFlags ), OF_BIT_COUNT, SPROP_UNSIGNED ),\n\tSendPropEHandle( SENDINFO( m_hBuiltOnEntity ) ),\n\tSendPropBool( SENDINFO( m_bDisabled ) ),\n\tSendPropEHandle( SENDINFO( m_hBuilder ) ),\n\tSendPropVector( SENDINFO( m_vecBuildMaxs ), -1, SPROP_COORD ),\n\tSendPropVector( SENDINFO( m_vecBuildMins ), -1, SPROP_COORD ),\n\tSendPropInt( SENDINFO( m_iDesiredBuildRotations ), 2, SPROP_UNSIGNED ),\n\tSendPropBool( SENDINFO( m_bServerOverridePlacement ) ),\n\tSendPropInt( SENDINFO( m_iUpgradeLevel ), 3 ),\n\tSendPropInt( SENDINFO( m_iUpgradeMetal ), 10 ),\n\tSendPropInt( SENDINFO( m_iUpgradeMetalRequired ), 10 ),\n\tSendPropInt( SENDINFO( m_iHighestUpgradeLevel ), 3 ),\n\tSendPropInt( SENDINFO( m_iObjectMode ), 2 ),\n\tSendPropBool( SENDINFO( m_bDisposableBuilding ) ),\n\tSendPropBool( SENDINFO( m_bWasMapPlaced ) )\nEND_SEND_TABLE();\n\nbool PlayerIndexLessFunc( const int &lhs, const int &rhs )\t\n{ \n\treturn lhs < rhs; \n}\n\nConVar tf_obj_upgrade_per_hit( \"tf_obj_upgrade_per_hit\", \"25\", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );\n\nextern ConVar tf_cheapobjects;\n\n// This controls whether ropes attached to objects are transmitted or not. It's important that\n// ropes aren't transmitted to guys who don't own them.\nclass CObjectRopeTransmitProxy : public CBaseTransmitProxy\n{\npublic:\n\tCObjectRopeTransmitProxy( CBaseEntity *pRope ) : CBaseTransmitProxy( pRope )\n\t{\n\t}\n\t\n\tvirtual int ShouldTransmit( const CCheckTransmitInfo *pInfo, int nPrevShouldTransmitResult )\n\t{\n\t\t// Don't transmit the rope if it's not even visible.\n\t\tif ( !nPrevShouldTransmitResult )\n\t\t\treturn FL_EDICT_DONTSEND;\n\n\t\t// This proxy only wants to be active while one of the two objects is being placed.\n\t\t// When they're done being placed, the proxy goes away and the rope draws like normal.\n\t\tbool bAnyObjectPlacing = (m_hObj1 && m_hObj1->IsPlacing()) || (m_hObj2 && m_hObj2->IsPlacing());\n\t\tif ( !bAnyObjectPlacing )\n\t\t{\n\t\t\tRelease();\n\t\t\treturn nPrevShouldTransmitResult;\n\t\t}\n\n\t\t// Give control to whichever object is being placed.\n\t\tif ( m_hObj1 && m_hObj1->IsPlacing() )\n\t\t\treturn m_hObj1->ShouldTransmit( pInfo );\n\t\t\n\t\telse if ( m_hObj2 && m_hObj2->IsPlacing() )\n\t\t\treturn m_hObj2->ShouldTransmit( pInfo );\n\t\t\n\t\telse\n\t\t\treturn FL_EDICT_ALWAYS;\n\t}\n\n\n\tCHandle m_hObj1;\n\tCHandle m_hObj2;\n};\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nCBaseObject::CBaseObject()\n{\n\tm_iHealth = m_iMaxHealth = m_flHealth = m_iGoalHealth = 0;\n\tm_flPercentageConstructed = 0;\n\tm_bPlacing = false;\n\tm_bBuilding = false;\n\tm_bCarried = false;\n\tm_bCarryDeploy = false;\n\tm_Activity = ACT_INVALID;\n\tm_bDisabled = false;\n\tm_SolidToPlayers = SOLID_TO_PLAYER_USE_DEFAULT;\n\tm_bPlacementOK = false;\n\tm_aGibs.Purge();\n\tm_iObjectMode = 0;\n\tm_iDefaultUpgrade = 0;\n\tm_bMiniBuilding = false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::UpdateOnRemove( void )\n{\n\tm_bDying = true;\n\n\t/*\n\t// Remove anything left on me\n\tIHasBuildPoints *pBPInterface = dynamic_cast(this);\n\tif ( pBPInterface && pBPInterface->GetNumObjectsOnMe() )\n\t{\n\t\tpBPInterface->RemoveAllObjects();\n\t}\n\t*/\n\n\tDestroyObject();\n\t\n\tif ( GetTeam() )\n\t{\n\t\t((CTFTeam*)GetTeam())->RemoveObject( this );\n\t}\n\n\tDetachObjectFromObject();\n\n\t// Make sure the object isn't in either team's list of objects...\n\t//Assert( !GetGlobalTFTeam(1)->IsObjectOnTeam( this ) );\n\t//Assert( !GetGlobalTFTeam(2)->IsObjectOnTeam( this ) );\n\n\t// Chain at end to mimic destructor unwind order\n\tBaseClass::UpdateOnRemove();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CBaseObject::UpdateTransmitState()\n{\n\treturn SetTransmitState( FL_EDICT_FULLCHECK );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CBaseObject::ShouldTransmit( const CCheckTransmitInfo *pInfo )\n{\n\t// Always transmit to owner\n\tif ( GetBuilder() && pInfo->m_pClientEnt == GetBuilder()->edict() )\n\t\treturn FL_EDICT_ALWAYS;\n\n\t// Placement models only transmit to owners\n\tif ( IsPlacing() )\n\t\treturn FL_EDICT_DONTSEND;\n\n\treturn BaseClass::ShouldTransmit( pInfo );\n}\n\n//-----------------------------------------------------------------------------\n//\n//-----------------------------------------------------------------------------\nbool CBaseObject::CanBeUpgraded( CTFPlayer *pPlayer )\n{\n\t// only engineers\n\tif ( !ClassCanBuild( pPlayer->GetPlayerClass()->GetClassIndex(), GetType() ) )\n\t{\n\t\treturn false;\n\t}\n\n\t// max upgraded\n\tif ( GetUpgradeLevel() >= GetMaxUpgradeLevel() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( IsPlacing() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( IsBuilding() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( IsUpgrading() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( IsRedeploying() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( IsMiniBuilding() )\n\t{\n\t\treturn false;\n\t}\n\n\tif ( !tf2c_building_upgrades.GetBool() && GetType() != OBJ_SENTRYGUN )\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid CBaseObject::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways )\n{\n\t// Are we already marked for transmission?\n\tif ( pInfo->m_pTransmitEdict->Get( entindex() ) )\n\t\treturn;\n\n\tBaseClass::SetTransmit( pInfo, bAlways );\n\n\t// Force our screens to be sent too.\n\tint nTeam = CBaseEntity::Instance( pInfo->m_pClientEnt )->GetTeamNumber();\n\tfor ( int i=0; i < m_hScreens.Count(); i++ )\n\t{\n\t\tCVGuiScreen *pScreen = m_hScreens[i].Get();\n\t\tif ( pScreen && pScreen->IsVisibleToTeam( nTeam ) )\n\t\t\tpScreen->SetTransmit( pInfo, bAlways );\n\t}\n}\n\nvoid CBaseObject::DoWrenchHitEffect( Vector vecHitPos, bool bRepair, bool bUpgrade )\n{\n\tCPVSFilter filter( vecHitPos );\n\tif ( bRepair )\n\t{\n\t\tTE_TFParticleEffect( filter, 0.0f, \"nutsnbolts_repair\", vecHitPos, QAngle( 0, 0, 0 ) );\n\t}\n\telse if ( bUpgrade )\n\t{\n\t\tTE_TFParticleEffect( filter, 0.0f, \"nutsnbolts_upgrade\", vecHitPos, QAngle( 0, 0, 0 ) );\n\t}\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::Precache()\n{\n\tPrecacheMaterial( SCREEN_OVERLAY_MATERIAL );\n\n\tPrecacheScriptSound( GetObjectInfo( ObjectType() )->m_pExplodeSound );\n\n\tconst char *pEffect = GetObjectInfo( ObjectType() )->m_pExplosionParticleEffect;\n\n\tif ( pEffect && pEffect[0] != '\\0' )\n\t{\n\t\tPrecacheParticleSystem( pEffect );\n\t}\n\n\tPrecacheParticleSystem( \"nutsnbolts_build\" );\n\tPrecacheParticleSystem( \"nutsnbolts_upgrade\" );\n\tPrecacheParticleSystem( \"nutsnbolts_repair\" );\n\tCBaseEntity::PrecacheModel( \"models/weapons/w_models/w_toolbox.mdl\" );\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::Spawn( void )\n{\n\tPrecache();\n\n\tCollisionProp()->SetSurroundingBoundsType( USE_BEST_COLLISION_BOUNDS );\n\tSetSolidToPlayers( m_SolidToPlayers, true );\n\n\tm_bHasSapper = false;\n\tm_takedamage = DAMAGE_YES;\n\tm_flHealth = m_iMaxHealth = m_iHealth;\n\tm_iKills = 0;\n\n\tm_iUpgradeLevel = 1;\n\tm_iGoalUpgradeLevel = 1;\n\tm_iUpgradeMetal = 0;\n\n\tm_iUpgradeMetalRequired = GetObjectInfo( ObjectType() )->m_UpgradeCost;\n\tm_iHighestUpgradeLevel = GetMaxUpgradeLevel();\n\t//m_iHighestUpgradeLevel = GetObjectInfo(ObjectType())->m_MaxUpgradeLevel;\n\n\tSetContextThink( &CBaseObject::BaseObjectThink, gpGlobals->curtime + 0.1, OBJ_BASE_THINK_CONTEXT );\n\n\tAddFlag( FL_OBJECT ); // So NPCs will notice it\n\tSetViewOffset( WorldSpaceCenter() - GetAbsOrigin() );\n\n\tif ( !VPhysicsGetObject() )\n\t{\n\t\tVPhysicsInitStatic();\n\t}\n\n\tm_RepairerList.SetLessFunc( PlayerIndexLessFunc );\n\n\tm_iDesiredBuildRotations = 0;\n\tm_flCurrentBuildRotation = 0;\n\n\tif ( MustBeBuiltOnAttachmentPoint() )\n\t{\n\t\tAddEffects( EF_NODRAW );\n\t}\n\n\t// assume valid placement\n\tm_bServerOverridePlacement = true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Gunslinger's Buildings\n//-----------------------------------------------------------------------------\nvoid CBaseObject::MakeMiniBuilding( void )\n{\n\tm_bMiniBuilding = true;\n\n\t// Set the skin\n\tswitch ( GetTeamNumber() )\n\t{\n\tcase TF_TEAM_RED:\n\t\tm_nSkin = 2;\n\t\tbreak;\n\n\tcase TF_TEAM_BLUE:\n\t\tm_nSkin = 3;\n\t\tbreak;\n\n\tdefault:\n\t\tm_nSkin = 2;\n\t\tbreak;\n\t}\n\n\t// Make the model small\n\tSetModelScale( 0.75f );\n\n}\n\nvoid CBaseObject::MakeCarriedObject( CTFPlayer *pPlayer )\n{\n\tif ( pPlayer )\n\t{\n\t\tm_bCarried = true;\n\t\tm_bCarryDeploy = false;\n\t\tDestroyScreens();\n\n\t\t//FollowEntity( pPlayer, true );\n\n\t\t// Save health amount building had before getting picked up. It will only heal back up to it.\n\t\tm_iGoalHealth = GetHealth();\n\n\t\t// Save current upgrade level and reset it. Building will automatically upgrade back once re-deployed.\n\t\tm_iGoalUpgradeLevel = GetUpgradeLevel();\n\t\tm_iUpgradeLevel = 1;\n\n\t\t// Reset placement rotation.\n\t\tm_iDesiredBuildRotations = 0;\n\n\t\tSetModel( GetPlacementModel() );\n\n\t\tpPlayer->m_Shared.SetCarriedObject( this );\n\n\t\t//AddEffects( EF_NODRAW );\n\t\t// StartPlacement already does this but better safe than sorry.\n\t\tAddSolidFlags( FSOLID_NOT_SOLID );\n\n\t\tIGameEvent * event = gameeventmanager->CreateEvent( \"player_carryobject\" );\n\t\tif ( event )\n\t\t{\n\t\t\tevent->SetInt( \"userid\", pPlayer->GetUserID() );\n\t\t\tevent->SetInt( \"object\", ObjectType() );\n\t\t\tevent->SetInt( \"index\", entindex() );\t// object entity index\n\t\t\tgameeventmanager->FireEvent( event, true );\t// don't send to clients\n\t\t}\n\t}\n\n}\n\nvoid CBaseObject::DropCarriedObject( CTFPlayer *pPlayer )\n{\n\tm_bCarried = false;\n\tm_bCarryDeploy = true;\n\n\tif ( pPlayer )\n\t{\n\t\tpPlayer->m_Shared.SetCarriedObject( NULL );\n\t}\n\t//StopFollowingEntity();\n}\n\n//-----------------------------------------------------------------------------\n// Returns information about the various control panels\n//-----------------------------------------------------------------------------\nvoid CBaseObject::GetControlPanelInfo( int nPanelIndex, const char *&pPanelName )\n{\n\tpPanelName = NULL;\n}\n\n//-----------------------------------------------------------------------------\n// Returns information about the various control panels\n//-----------------------------------------------------------------------------\nvoid CBaseObject::GetControlPanelClassName( int nPanelIndex, const char *&pPanelName )\n{\n\tpPanelName = \"vgui_screen\";\n}\n\n//-----------------------------------------------------------------------------\n// This is called by the base object when it's time to spawn the control panels\n//-----------------------------------------------------------------------------\nvoid CBaseObject::SpawnControlPanels()\n{\n\tchar buf[64];\n\n\t// FIXME: Deal with dynamically resizing control panels?\n\n\t// If we're attached to an entity, spawn control panels on it instead of use\n\tCBaseAnimating *pEntityToSpawnOn = this;\n\tchar *pOrgLL = \"controlpanel%d_ll\";\n\tchar *pOrgUR = \"controlpanel%d_ur\";\n\tchar *pAttachmentNameLL = pOrgLL;\n\tchar *pAttachmentNameUR = pOrgUR;\n\tif ( IsBuiltOnAttachment() )\n\t{\n\t\tpEntityToSpawnOn = dynamic_cast((CBaseEntity*)m_hBuiltOnEntity.Get());\n\t\tif ( pEntityToSpawnOn )\n\t\t{\n\t\t\tchar sBuildPointLL[64];\n\t\t\tchar sBuildPointUR[64];\n\t\t\tQ_snprintf( sBuildPointLL, sizeof( sBuildPointLL ), \"bp%d_controlpanel%%d_ll\", m_iBuiltOnPoint );\n\t\t\tQ_snprintf( sBuildPointUR, sizeof( sBuildPointUR ), \"bp%d_controlpanel%%d_ur\", m_iBuiltOnPoint );\n\t\t\tpAttachmentNameLL = sBuildPointLL;\n\t\t\tpAttachmentNameUR = sBuildPointUR;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpEntityToSpawnOn = this;\n\t\t}\n\t}\n\n\tAssert( pEntityToSpawnOn );\n\n\t// Lookup the attachment point...\n\tint nPanel;\n\tfor ( nPanel = 0; true; ++nPanel )\n\t{\n\t\tQ_snprintf( buf, sizeof( buf ), pAttachmentNameLL, nPanel );\n\t\tint nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf);\n\t\tif (nLLAttachmentIndex <= 0)\n\t\t{\n\t\t\t// Try and use my panels then\n\t\t\tpEntityToSpawnOn = this;\n\t\t\tQ_snprintf( buf, sizeof( buf ), pOrgLL, nPanel );\n\t\t\tnLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf);\n\t\t\tif (nLLAttachmentIndex <= 0)\n\t\t\t\treturn;\n\t\t}\n\n\t\tQ_snprintf( buf, sizeof( buf ), pAttachmentNameUR, nPanel );\n\t\tint nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf);\n\t\tif (nURAttachmentIndex <= 0)\n\t\t{\n\t\t\t// Try and use my panels then\n\t\t\tQ_snprintf( buf, sizeof( buf ), pOrgUR, nPanel );\n\t\t\tnURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf);\n\t\t\tif (nURAttachmentIndex <= 0)\n\t\t\t\treturn;\n\t\t}\n\n\t\tconst char *pScreenName = NULL;\n\t\tGetControlPanelInfo( nPanel, pScreenName );\n\t\tif (!pScreenName)\n\t\t\tcontinue;\n\n\t\tconst char *pScreenClassname;\n\t\tGetControlPanelClassName( nPanel, pScreenClassname );\n\t\tif ( !pScreenClassname )\n\t\t\tcontinue;\n\n\t\t// Compute the screen size from the attachment points...\n\t\tmatrix3x4_t\tpanelToWorld;\n\t\tpEntityToSpawnOn->GetAttachment( nLLAttachmentIndex, panelToWorld );\n\n\t\tmatrix3x4_t\tworldToPanel;\n\t\tMatrixInvert( panelToWorld, worldToPanel );\n\n\t\t// Now get the lower right position + transform into panel space\n\t\tVector lr, lrlocal;\n\t\tpEntityToSpawnOn->GetAttachment( nURAttachmentIndex, panelToWorld );\n\t\tMatrixGetColumn( panelToWorld, 3, lr );\n\t\tVectorTransform( lr, worldToPanel, lrlocal );\n\n\t\tfloat flWidth = lrlocal.x;\n\t\tfloat flHeight = lrlocal.y;\n\n\t\tCVGuiScreen *pScreen = CreateVGuiScreen( pScreenClassname, pScreenName, pEntityToSpawnOn, this, nLLAttachmentIndex );\n\t\tpScreen->ChangeTeam( GetTeamNumber() );\n\t\tpScreen->SetActualSize( flWidth, flHeight );\n\t\tpScreen->SetActive( false );\n\t\tpScreen->MakeVisibleOnlyToTeammates( true );\n\t\tpScreen->SetOverlayMaterial( SCREEN_OVERLAY_MATERIAL );\n\t\tpScreen->SetTransparency( true );\n\n\t\t// for now, only input by the owning player\n\t\tpScreen->SetPlayerOwner( GetBuilder(), true );\n\n\t\tint nScreen = m_hScreens.AddToTail( );\n\t\tm_hScreens[nScreen].Set( pScreen );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Called in case was not built by a player but placed by a mapper.\n//-----------------------------------------------------------------------------\nvoid CBaseObject::InitializeMapPlacedObject( void )\n{\n\tm_bWasMapPlaced = true;\n\n\tif ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 )\n\t\tSpawnControlPanels();\n\n\t// Spawn with full health.\n\tSetHealth( GetMaxHealth() );\n\n\t// Go active.\n\tFinishedBuilding();\n\n\t// Add it to team.\n\tCTFTeam *pTFTeam = GetGlobalTFTeam( GetTeamNumber() );\n\n\tif ( pTFTeam && !pTFTeam->IsObjectOnTeam( this ) )\n\t{\n\t\tpTFTeam->AddObject( this );\n\t}\n\n\t// Set the skin\n\tswitch ( GetTeamNumber() )\n\t{\n\tcase TF_TEAM_RED:\n\t\tm_nSkin = 0;\n\t\tbreak;\n\n\tcase TF_TEAM_BLUE:\n\t\tm_nSkin = 1;\n\t\tbreak;\n\n\tdefault:\n\t\tm_nSkin = 1;\n\t\tbreak;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Handle commands sent from vgui panels on the client \n//-----------------------------------------------------------------------------\nbool CBaseObject::ClientCommand( CTFPlayer *pSender, const CCommand &args )\n{\n\t//const char *pCmd = args[0];\n\treturn false;\n}\n\n#define BASE_OBJECT_THINK_DELAY\t0.1\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::BaseObjectThink( void )\n{\n\tSetNextThink( gpGlobals->curtime + BASE_OBJECT_THINK_DELAY, OBJ_BASE_THINK_CONTEXT );\n\n\t// Make sure animation is up to date\n\tDetermineAnimation();\n\n\tDeterminePlaybackRate();\n\n\t// Do nothing while we're being placed\n\tif ( IsPlacing() )\n\t{\n\t\tif ( MustBeBuiltOnAttachmentPoint() )\n\t\t{\n\t\t\tUpdateAttachmentPlacement();\t\n\t\t\tm_bServerOverridePlacement = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_bServerOverridePlacement = EstimateValidBuildPos();\n\n\t\t\tUpdateDesiredBuildRotation( BASE_OBJECT_THINK_DELAY );\n\t\t}\n\n\t\treturn;\n\t}\n\n\t// If we're building, keep going\n\tif ( IsBuilding() )\n\t{\n\t\tBuildingThink();\n\t\treturn;\n\t}\n\telse if ( IsUpgrading() )\n\t{\n\t\tUpgradeThink();\n\t\treturn;\n\t}\n\n\tif ( m_bCarryDeploy )\n\t{\n\t\tif ( m_iUpgradeLevel < m_iGoalUpgradeLevel )\n\t\t{\n\t\t\t// Keep upgrading until we hit our previous upgrade level.\n\t\t\tStartUpgrading();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Finished.\n\t\t\tm_bCarryDeploy = false;\n\t\t}\n\n\t\tif ( IsMiniBuilding() )\n\t\t{\n\t\t\tMakeMiniBuilding();\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nbool CBaseObject::UpdateAttachmentPlacement( CBaseObject *pObject /*= NULL*/ )\n{\n\t// See if we should snap to a build position\n\t// finding one implies it is a valid position\n\tif ( FindSnapToBuildPos( pObject ) )\n\t{\n\t\tm_bPlacementOK = true;\n\n\t\tTeleport( &m_vecBuildOrigin, &GetLocalAngles(), NULL );\n\t}\n\telse\n\t{\n\t\tm_bPlacementOK = false;\n\n\t\t// Clear out previous parent \n\t\tif ( m_hBuiltOnEntity.Get() )\n\t\t{\n\t\t\tm_hBuiltOnEntity = NULL;\n\t\t\tm_iBuiltOnPoint = 0;\n\t\t\tSetParent( NULL );\n\t\t}\n\n\t\t// teleport to builder's origin\n\t\tCTFPlayer *pPlayer = GetOwner();\n\n\t\tif ( pPlayer )\n\t\t{\n\t\t\tTeleport( &pPlayer->WorldSpaceCenter(), &GetLocalAngles(), NULL );\n\t\t}\n\t}\n\n\treturn m_bPlacementOK;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Cheap check to see if we are in any server-defined No-build areas.\n//-----------------------------------------------------------------------------\nbool CBaseObject::EstimateValidBuildPos( void )\n{\n\tCTFPlayer *pPlayer = GetOwner();\n\n\tif ( !pPlayer )\n\t\treturn false;\n\n\t// Calculate build angles\n\tVector forward;\n\tQAngle vecAngles = vec3_angle;\n\tvecAngles.y = pPlayer->EyeAngles().y;\n\n\tQAngle objAngles = vecAngles;\n\n\t//SetAbsAngles( objAngles );\n\t//SetLocalAngles( objAngles );\n\tAngleVectors(vecAngles, &forward );\n\n\t// Adjust build distance based upon object size\n\tVector2D vecObjectRadius;\n\tvecObjectRadius.x = max( fabs( m_vecBuildMins.m_Value.x ), fabs( m_vecBuildMaxs.m_Value.x ) );\n\tvecObjectRadius.y = max( fabs( m_vecBuildMins.m_Value.y ), fabs( m_vecBuildMaxs.m_Value.y ) );\n\n\tVector2D vecPlayerRadius;\n\tVector vecPlayerMins = pPlayer->WorldAlignMins();\n\tVector vecPlayerMaxs = pPlayer->WorldAlignMaxs();\n\tvecPlayerRadius.x = max( fabs( vecPlayerMins.x ), fabs( vecPlayerMaxs.x ) );\n\tvecPlayerRadius.y = max( fabs( vecPlayerMins.y ), fabs( vecPlayerMaxs.y ) );\n\n\tfloat flDistance = vecObjectRadius.Length() + vecPlayerRadius.Length() + 4; // small safety buffer\n\tVector vecBuildOrigin = pPlayer->WorldSpaceCenter() + forward * flDistance;\n\n\t//NDebugOverlay::Cross3D( vecBuildOrigin, 10, 255, 0, 0, false, 0.1 );\n\n\t// Cannot build inside a nobuild brush\n\tif ( PointInNoBuild( vecBuildOrigin, this ) )\n\t\treturn false;\n\n\tif ( PointInRespawnRoom( NULL, vecBuildOrigin ) )\n\t\treturn false;\n\n\tVector vecBuildFarEdge = vecBuildOrigin + forward * ( flDistance + 8.0f );\n\tif ( TestAgainstRespawnRoomVisualizer( pPlayer, vecBuildFarEdge ) )\n\t\treturn false;\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CBaseObject::TestAgainstRespawnRoomVisualizer( CTFPlayer *pPlayer, const Vector &vecEnd )\n{\n\t// Setup the ray.\n\tRay_t ray;\n\tray.Init( pPlayer->WorldSpaceCenter(), vecEnd );\n\n\tCBaseEntity *pEntity = NULL;\n\twhile ( ( pEntity = gEntList.FindEntityByClassnameWithin( pEntity, \"func_respawnroomvisualizer\", pPlayer->WorldSpaceCenter(), ray.m_Delta.Length() ) ) != NULL )\n\t{\n\t\ttrace_t trace;\n\t\tenginetrace->ClipRayToEntity( ray, MASK_ALL, pEntity, &trace );\n\t\tif ( trace.fraction < 1.0f )\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::DeterminePlaybackRate( void )\n{\n\tif ( IsBuilding() )\n\t{\n\t\t// Default half rate, author build anim as if one player is building\n\t\tSetPlaybackRate( GetConstructionMultiplier() * 0.5 );\t\n\t}\n\telse\n\t{\n\t\tSetPlaybackRate( 1.0 );\n\t}\n\n\tStudioFrameAdvance();\n}\n\n#define OBJ_UPGRADE_DURATION\t1.5f\n\n//-----------------------------------------------------------------------------\n// Raises the Sentrygun one level\n//-----------------------------------------------------------------------------\nvoid CBaseObject::StartUpgrading(void)\n{\n\t// Increase level\n\tm_iUpgradeLevel++;\n\n\t// more health\n\tif ( !IsRedeploying() )\n\t{\n\t\tint iMaxHealth = GetMaxHealth();\n\t\tSetMaxHealth( iMaxHealth * 1.2 );\n\t\tSetHealth( iMaxHealth * 1.2 );\n\t}\n\n\t// No ear raping for map placed buildings.\n\tif ( !m_iDefaultUpgrade )\n\t{\n\t\tEmitSound( GetObjectInfo( ObjectType() )->m_pUpgradeSound );\n\t}\n\n\tm_flUpgradeCompleteTime = gpGlobals->curtime + GetObjectInfo( ObjectType() )->m_flUpgradeDuration;\n}\n\nvoid CBaseObject::FinishUpgrading( void )\n{\n\t// No ear raping for map placed buildings.\n\tif ( !m_iDefaultUpgrade )\n\t{\n\t\tEmitSound( GetObjectInfo( ObjectType() )->m_pUpgradeSound );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Playing the upgrade animation\n//-----------------------------------------------------------------------------\nvoid CBaseObject::UpgradeThink(void)\n{\n\tif ( gpGlobals->curtime > m_flUpgradeCompleteTime )\n\t{\n\t\tFinishUpgrading();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nCTFPlayer *CBaseObject::GetOwner()\n{ \n\treturn m_hBuilder; \n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::Activate( void )\n{\n\tBaseClass::Activate();\n\n\tif ( GetBuilder() == NULL )\n\t\tInitializeMapPlacedObject();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::SetBuilder( CTFPlayer *pBuilder )\n{\n\tTRACE_OBJECT( UTIL_VarArgs( \"%0.2f CBaseObject::SetBuilder builder %s\\n\", gpGlobals->curtime, \n\t\tpBuilder ? pBuilder->GetPlayerName() : \"NULL\" ) );\n\n\tm_hBuilder = pBuilder;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint\tCBaseObject::ObjectType( ) const\n{\n\treturn m_iObjectType;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Destroys the object, gives a chance to spawn an explosion\n//-----------------------------------------------------------------------------\nvoid CBaseObject::DetonateObject( void )\n{\n\tCTakeDamageInfo info( this, this, vec3_origin, GetAbsOrigin(), 0, DMG_GENERIC );\n\n\tKilled( info );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Remove this object from it's team and mark for deletion\n//-----------------------------------------------------------------------------\nvoid CBaseObject::DestroyObject( void )\n{\n\tTRACE_OBJECT( UTIL_VarArgs( \"%0.2f CBaseObject::DestroyObject %p:%s\\n\", gpGlobals->curtime, this, GetClassname() ) );\n\n\n\tif ( m_bCarried )\n\t{\n\t\tDropCarriedObject( GetBuilder() );\n\t}\n\n\tif ( GetBuilder() )\n\t{\n\t\tGetBuilder()->OwnedObjectDestroyed( this );\n\t}\n\n\tUTIL_Remove( this );\n\n\tDestroyScreens();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Remove any screens that are active on this object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::DestroyScreens( void )\n{\n\t// Kill the control panels\n\tint i;\n\tfor ( i = m_hScreens.Count(); --i >= 0; )\n\t{\n\t\tDestroyVGuiScreen( m_hScreens[i].Get() );\n\t}\n\tm_hScreens.RemoveAll();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Get the total time it will take to build this object\n//-----------------------------------------------------------------------------\nfloat CBaseObject::GetTotalTime( void )\n{\n\tfloat flBuildTime = GetObjectInfo( ObjectType() )->m_flBuildTime;\n\n\tif ( tf_fastbuild.GetInt() )\n\t\treturn ( min( 2.f, flBuildTime ) );\n\n\treturn flBuildTime;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CBaseObject::GetMaxHealthForCurrentLevel( void )\n{\n\treturn GetBaseHealth() * pow( 1.2, GetUpgradeLevel() - 1 );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Start placing the object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::StartPlacement( CTFPlayer *pPlayer )\n{\n\tAddSolidFlags( FSOLID_NOT_SOLID );\n\n\tm_bPlacing = true;\n\tm_bBuilding = false;\n\tif ( pPlayer )\n\t{\n\t\tSetBuilder( pPlayer );\n\t\tChangeTeam( pPlayer->GetTeamNumber() );\n\t}\n\n\t// needed?\n\tm_nRenderMode = kRenderNormal;\n\t\n\t// Set my build size\n\tCollisionProp()->WorldSpaceAABB( &m_vecBuildMins.GetForModify(), &m_vecBuildMaxs.GetForModify() );\n\tm_vecBuildMins -= Vector( 4,4,0 );\n\tm_vecBuildMaxs += Vector( 4,4,0 );\n\tm_vecBuildMins -= GetAbsOrigin();\n\tm_vecBuildMaxs -= GetAbsOrigin();\n\n\t// Set the skin\n\tswitch ( GetTeamNumber() )\n\t{\n\tcase TF_TEAM_RED:\n\t\tm_nSkin = 0;\n\t\tbreak;\n\n\tcase TF_TEAM_BLUE:\n\t\tm_nSkin = 1;\n\t\tbreak;\n\n\tdefault:\n\t\tm_nSkin = 1;\n\t\tbreak;\n\t}\n\n\tif ( IsMiniBuilding() )\n\t{\n\t\tMakeMiniBuilding();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Stop placing the object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::StopPlacement( void )\n{\n\tUTIL_Remove( this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Find the nearest buildpoint on the specified entity\n//-----------------------------------------------------------------------------\nbool CBaseObject::FindNearestBuildPoint( CBaseEntity *pEntity, CBasePlayer *pBuilder, float &flNearestPoint, Vector &vecNearestBuildPoint, bool bIgnoreLOS /*= false*/ )\n{\n\tbool bFoundPoint = false;\n\n\tIHasBuildPoints *pBPInterface = dynamic_cast(pEntity);\n\tAssert( pBPInterface );\n\n\t// Any empty buildpoints?\n\tfor ( int i = 0; i < pBPInterface->GetNumBuildPoints(); i++ )\n\t{\n\t\t// Can this object build on this point?\n\t\tif ( pBPInterface->CanBuildObjectOnBuildPoint( i, GetType() ) )\n\t\t{\n\t\t\t// Close to this point?\n\t\t\tVector vecBPOrigin;\n\t\t\tQAngle vecBPAngles;\n\t\t\tif ( pBPInterface->GetBuildPoint(i, vecBPOrigin, vecBPAngles) )\n\t\t\t{\n\t\t\t\t// If set to ignore LOS, distance, etc, just pick the first point available.\n\t\t\t\tif ( !bIgnoreLOS )\n\t\t\t\t{\n\t\t\t\t\t// ignore build points outside our view\n\t\t\t\t\tif ( !pBuilder->FInViewCone( vecBPOrigin ) )\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t// Do a trace to make sure we don't place attachments through things (players, world, etc...)\n\t\t\t\t\tVector vecStart = pBuilder->EyePosition();\n\t\t\t\t\ttrace_t trace;\n\t\t\t\t\tUTIL_TraceLine( vecStart, vecBPOrigin, MASK_SOLID, pBuilder, COLLISION_GROUP_NONE, &trace );\n\t\t\t\t\tif ( trace.m_pEnt != pEntity && trace.fraction != 1.0 )\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfloat flDist = (vecBPOrigin - pBuilder->GetAbsOrigin()).Length();\n\n\t\t\t\t// if this is closer, or is the first one in our view, check it out\n\t\t\t\tif ( bIgnoreLOS || flDist < min(flNearestPoint, pBPInterface->GetMaxSnapDistance( i )) )\n\t\t\t\t{\n\t\t\t\t\tflNearestPoint = flDist;\n\t\t\t\t\tvecNearestBuildPoint = vecBPOrigin;\n\t\t\t\t\tm_hBuiltOnEntity = pEntity;\n\t\t\t\t\tm_iBuiltOnPoint = i;\n\n\t\t\t\t\t// Set our angles to the buildpoint's angles\n\t\t\t\t\tSetAbsAngles( vecBPAngles );\n\n\t\t\t\t\tbFoundPoint = true;\n\n\t\t\t\t\tif ( bIgnoreLOS )\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn bFoundPoint;\n}\n\n/*\nclass CTraceFilterIgnorePlayers : public CTraceFilterSimple\n{\npublic:\n\t// It does have a base, but we'll never network anything below here..\n\tDECLARE_CLASS( CTraceFilterIgnorePlayers, CTraceFilterSimple );\n\n\tCTraceFilterIgnorePlayers( const IHandleEntity *passentity, int collisionGroup )\n\t\t: CTraceFilterSimple( passentity, collisionGroup )\n\t{\n\t}\n\n\tvirtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )\n\t{\n\t\tCBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity );\n\n\t\tif ( pEntity->IsPlayer() )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n};\n\n//-----------------------------------------------------------------------------\n// Purpose: Test around this build position to make sure it does not block a path\n//-----------------------------------------------------------------------------\nbool CBaseObject::TestPositionForPlayerBlock( Vector vecBuildOrigin, CBasePlayer *pPlayer )\n{\n\t// find out the status of the 8 regions around this position\n\tint i;\n\tbool bNodeVisited[8];\n\tbool bNodeClear[8];\n\n\t// The first zone that is clear of obstructions\n\tint iFirstClear = -1;\n\n\tVector vHalfPlayerDims = (VEC_HULL_MAX - VEC_HULL_MIN) * 0.5f;\n\n\tVector vBuildDims = m_vecBuildMaxs - m_vecBuildMins;\n\tVector vHalfBuildDims = vBuildDims * 0.5;\n\n\t \n\t// the locations of the 8 test positions\n\t// boxes are adjacent to the object box and are at least as large as \n\t// a player to ensure that a player can pass this location\n\n\t//\t0 1 2\n\t//\t7 X 3\n\t//\t6 5 4\n\n\tstatic int iPositions[8][2] = \n\t{\n\t\t{ -1, -1 },\n\t\t{ 0, -1 },\n\t\t{ 1, -1 },\n\t\t{ 1, 0 },\n\t\t{ 1, 1 },\n\t\t{ 0, 1 },\n\t\t{ -1, 1 },\n\t\t{ -1, 0 }\n\t};\n\n\tCTraceFilterIgnorePlayers traceFilter( this, COLLISION_GROUP_NONE );\n\n\tfor ( i=0;i<8;i++ )\n\t{\n\t\t// mark them all as unvisited\n\t\tbNodeVisited[i] = false;\n\n\t\tVector vecTest = vecBuildOrigin;\t\t\n\t\tvecTest.x += ( iPositions[i][0] * ( vHalfBuildDims.x + vHalfPlayerDims.x ) );\n\t\tvecTest.y += ( iPositions[i][1] * ( vHalfBuildDims.y + vHalfPlayerDims.y ) );\n\n\t\ttrace_t trace;\n\t\tUTIL_TraceHull( vecTest, vecTest, VEC_HULL_MIN, VEC_HULL_MAX, MASK_SOLID_BRUSHONLY, &traceFilter, &trace );\n\n\t\tbNodeClear[i] = ( trace.fraction == 1 && trace.allsolid != 1 && (trace.startsolid != 1) );\n\n\t\t// NDebugOverlay::Box( vecTest, VEC_HULL_MIN, VEC_HULL_MAX, bNodeClear[i] ? 0 : 255, bNodeClear[i] ? 255 : 0, 0, 20, 0.1 );\n\n\t\t// Store off the first clear location\n\t\tif ( iFirstClear < 0 && bNodeClear[i] )\n\t\t{\n\t\t\tiFirstClear = i;\n\t\t}\n\t}\n\n\tif ( iFirstClear < 0 )\n\t{\n\t\t// no clear space\n\t\treturn false;\n\t}\n\n\t// visit all nodes that are adjacent\n\tRecursiveTestBuildSpace( iFirstClear, bNodeClear, bNodeVisited );\n\n\t// if we still have unvisited nodes, return false\n\t// unvisited nodes means that one or more nodes was unreachable from our start position\n\t// ie, two places the player might want to traverse but would not be able to if we built here\n\tfor ( i=0;i<8;i++ )\n\t{\n\t\tif ( bNodeVisited[i] == false && bNodeClear[i] == true )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Test around the build position, one quadrant at a time\n//-----------------------------------------------------------------------------\nvoid CBaseObject::RecursiveTestBuildSpace( int iNode, bool *bNodeClear, bool *bNodeVisited )\n{\n\t// if the node is visited already\n\tif ( bNodeVisited[iNode] == true )\n\t\treturn;\n\n\t// if the test node is blocked\n\tif ( bNodeClear[iNode] == false )\n\t\treturn;\n\n\tbNodeVisited[iNode] = true;\n\n\tint iLeftNode = iNode - 1;\n\tif ( iLeftNode < 0 )\n\t\tiLeftNode = 7;\n\n\tRecursiveTestBuildSpace( iLeftNode, bNodeClear, bNodeVisited );\n\n\tint iRightNode = ( iNode + 1 ) % 8;\n\n\tRecursiveTestBuildSpace( iRightNode, bNodeClear, bNodeVisited );\n}\n*/\n\n//-----------------------------------------------------------------------------\n// Purpose: Move the placement model to the current position. Return false if it's an invalid position\n//-----------------------------------------------------------------------------\nbool CBaseObject::UpdatePlacement( void )\n{\n\tif ( MustBeBuiltOnAttachmentPoint() )\n\t{\n\t\treturn UpdateAttachmentPlacement();\n\t}\n\t\n\t// Finds bsp-valid place for building to be built\n\t// Checks for validity, nearby to other entities, in line of sight\n\tm_bPlacementOK = IsPlacementPosValid();\n\n\tTeleport( &m_vecBuildOrigin, &GetLocalAngles(), NULL );\n\n\treturn m_bPlacementOK;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: See if we should be snapping to a build position\n//-----------------------------------------------------------------------------\nbool CBaseObject::FindSnapToBuildPos( CBaseObject *pObject /*= NULL*/ )\n{\n\tif ( !MustBeBuiltOnAttachmentPoint() )\n\t\treturn false;\n\n\tCTFPlayer *pPlayer = GetOwner();\n\n\tif ( !pPlayer )\n\t{\n\t\treturn false;\n\t}\n\n\tbool bSnappedToPoint = false;\n\tbool bShouldAttachToParent = false;\n\n\tVector vecNearestBuildPoint = vec3_origin;\n\n\t// See if there are any nearby build positions to snap to\n\tfloat flNearestPoint = 9999;\n\tint i;\n\n\tbool bHostileAttachment = IsHostileUpgrade();\n\tint iMyTeam = GetTeamNumber();\n\n\t// If we have an object specified then use that, don't search.\n\tif ( pObject )\n\t{\n\t\tif ( !pObject->IsPlacing() )\n\t\t{\n\t\t\tif ( FindNearestBuildPoint( pObject, pPlayer, flNearestPoint, vecNearestBuildPoint, true ) )\n\t\t\t{\n\t\t\t\tbSnappedToPoint = true;\n\t\t\t\tbShouldAttachToParent = true;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tint nTeamCount = TFTeamMgr()->GetTeamCount();\n\t\tfor ( int iTeam = FIRST_GAME_TEAM; iTeam < nTeamCount; ++iTeam )\n\t\t{\n\t\t\t// Hostile attachments look for enemy objects only\n\t\t\tif ( bHostileAttachment )\n\t\t\t{\n\t\t\t\tif ( iTeam == iMyTeam )\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Friendly attachments look for friendly objects only\n\t\t\telse if ( iTeam != iMyTeam )\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tCTFTeam *pTeam = (CTFTeam *)GetGlobalTeam( iTeam );\n\t\t\tif ( !pTeam )\n\t\t\t\tcontinue;\n\n\t\t\t// look for nearby buildpoints on other objects\n\t\t\tfor ( i = 0; i < pTeam->GetNumObjects(); i++ )\n\t\t\t{\n\t\t\t\tCBaseObject *pTempObject = pTeam->GetObject( i );\n\t\t\t\tAssert( pTempObject );\n\t\t\t\tif ( pTempObject && !pTempObject->IsPlacing() )\n\t\t\t\t{\n\t\t\t\t\tif ( FindNearestBuildPoint( pTempObject, pPlayer, flNearestPoint, vecNearestBuildPoint ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tbSnappedToPoint = true;\n\t\t\t\t\t\tbShouldAttachToParent = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif ( !bSnappedToPoint )\n\t{\n\t\tAddEffects( EF_NODRAW );\n\t}\n\telse\n\t{\n\t\tRemoveEffects( EF_NODRAW );\n\n\t\tif ( bShouldAttachToParent )\n\t\t{\n\t\t\tAttachObjectToObject( m_hBuiltOnEntity.Get(), m_iBuiltOnPoint, vecNearestBuildPoint );\n\t\t}\n\n\t\tm_vecBuildOrigin = vecNearestBuildPoint;\n\t}\n\n\treturn bSnappedToPoint;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Are we currently in a buildable position\n//-----------------------------------------------------------------------------\nbool CBaseObject::IsValidPlacement( void ) const\n{\n\treturn m_bPlacementOK;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nconst char *CBaseObject::GetResponseRulesModifier( void )\n{\n\tswitch ( GetType() )\n\t{\n\tcase OBJ_DISPENSER: return \"objtype:dispenser\"; break;\n\tcase OBJ_TELEPORTER: return \"objtype:teleporter\"; break;\n\tcase OBJ_SENTRYGUN: return \"objtype:sentrygun\"; break;\n\tcase OBJ_ATTACHMENT_SAPPER: return \"objtype:sapper\"; break;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn NULL;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Start building the object\n//-----------------------------------------------------------------------------\nbool CBaseObject::StartBuilding( CBaseEntity *pBuilder )\n{\n\t/*\n\t// find any tf_ammo_boxes that we are colliding with and destroy them ?\n\t// enable if we need to do this\n\tCBaseEntity\t*pList[8];\n\tVector vecMins = m_vecBuildOrigin + m_vecBuildMins;\n\tVector vecMaxs = m_vecBuildOrigin + m_vecBuildMaxs;\n\n\tint count = UTIL_EntitiesInBox( pList, ARRAYSIZE(pList), vecMins, vecMaxs, 0 );\n\tfor ( int i = 0; i < count; i++ )\n\t{\n\t\tif ( pList[i] == this )\n\t\t\tcontinue;\n\n\t\t// if its a tf_ammo_box, remove it\n\t\tCTFAmmoPack *pAmmo = dynamic_cast< CTFAmmoPack * >( pList[i] );\n\n\t\tif ( pAmmo )\n\t\t{\n\t\t\tUTIL_Remove( pAmmo );\n\t\t}\n\t}\n\t*/\n\n\t// Need to add the object to the team now...\n\tCTFTeam *pTFTeam = ( CTFTeam * )GetGlobalTeam( GetTeamNumber() );\n\n\t// Deduct the cost from the player\n\tif ( pBuilder && pBuilder->IsPlayer() )\n\t{\n\t\tCTFPlayer *pTFBuilder = ToTFPlayer( pBuilder );\n\n\t\tif ( IsRedeploying() )\n\t\t{\n\t\t\tpTFBuilder->SpeakConceptIfAllowed( MP_CONCEPT_REDEPLOY_BUILDING, GetResponseRulesModifier() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\tif ( ((CTFPlayer*)pBuilder)->IsPlayerClass( TF_CLASS_ENGINEER ) )\n\t\t\t{\n\t\t\t((CTFPlayer*)pBuilder)->HintMessage( HINT_ENGINEER_USE_WRENCH_ONOWN );\n\t\t\t}\n\t\t\t*/\n\n\t\t\tint iAmountPlayerPaidForMe = pTFBuilder->StartedBuildingObject( m_iObjectType );\n\t\t\tif ( !iAmountPlayerPaidForMe )\n\t\t\t{\n\t\t\t\t// Player couldn't afford to pay for me, so abort\n\t\t\t\tClientPrint( pTFBuilder, HUD_PRINTCENTER, \"Not enough resources.\\n\" );\n\t\t\t\tStopPlacement();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpTFBuilder->SpeakConceptIfAllowed( MP_CONCEPT_BUILDING_OBJECT, GetResponseRulesModifier() );\n\t\t}\n\t}\n\n\t// Add this object to the team's list (because we couldn't add it during\n\t// placement mode)\n\tif ( pTFTeam && !pTFTeam->IsObjectOnTeam( this ) )\n\t{\n\t\tpTFTeam->AddObject( this );\n\t}\n\n\tm_bPlacing = false;\n\tm_bBuilding = true;\n\n\tif ( !IsRedeploying() )\n\t{\n\t\tSetHealth( OBJECT_CONSTRUCTION_STARTINGHEALTH );\n\t}\n\tm_flPercentageConstructed = 0;\n\n\tm_nRenderMode = kRenderNormal; \n\tRemoveSolidFlags( FSOLID_NOT_SOLID );\n\n\t// NOTE: We must spawn the control panels now, instead of during\n\t// Spawn, because until placement is started, we don't actually know\n\t// the position of the control panel because we don't know what it's\n\t// been attached to (could be a vehicle which supplies a different\n\t// place for the control panel)\n\t// NOTE: We must also spawn it before FinishedBuilding can be called\n\tSpawnControlPanels();\n\n\t// Tell the object we've been built on that we exist\n\tif ( IsBuiltOnAttachment() )\n\t{\n\t\tIHasBuildPoints *pBPInterface = dynamic_cast((CBaseEntity*)m_hBuiltOnEntity.Get());\n\t\tAssert( pBPInterface );\n\t\tpBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, this );\n\t}\n\n\t// Start the build animations\n\tm_flTotalConstructionTime = m_flConstructionTimeLeft = GetTotalTime();\n\n\tif ( !IsRedeploying() && pBuilder && pBuilder->IsPlayer() )\n\t{\n\t\tCTFPlayer *pTFBuilder = ToTFPlayer( pBuilder );\n\t\tpTFBuilder->FinishedObject( this );\n\t\tIGameEvent * event = gameeventmanager->CreateEvent( \"player_builtobject\" );\n\t\tif ( event )\n\t\t{\n\t\t\tevent->SetInt( \"userid\", pTFBuilder->GetUserID() );\n\t\t\tevent->SetInt( \"object\", ObjectType() );\n\t\t\tevent->SetInt( \"index\", entindex() );\t// object entity index\n\t\t\tgameeventmanager->FireEvent( event, true );\t// don't send to clients\n\t\t}\n\t}\n\n\tm_vecBuildOrigin = GetAbsOrigin();\n\n\tint contents = UTIL_PointContents( m_vecBuildOrigin );\n\tif ( contents & MASK_WATER )\n\t{\n\t\tSetWaterLevel( 3 );\n\t}\n\n\t// instantly play the build anim\n\tDetermineAnimation();\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Continue construction of this object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::BuildingThink( void )\n{\n\t// Continue construction\n\tRepair( (GetMaxHealth() - OBJECT_CONSTRUCTION_STARTINGHEALTH) / m_flTotalConstructionTime * OBJECT_CONSTRUCTION_INTERVAL );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::SetControlPanelsActive( bool bState )\n{\n\t// Activate control panel screens\n\tfor ( int i = m_hScreens.Count(); --i >= 0; )\n\t{\n\t\tif (m_hScreens[i].Get())\n\t\t{\n\t\t\tm_hScreens[i]->SetActive( bState );\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::FinishedBuilding( void )\n{\n\tSetControlPanelsActive( true );\n\n\t// Only make a shadow if the object doesn't use vphysics\n\tif (!VPhysicsGetObject())\n\t{\n\t\tVPhysicsInitStatic();\n\t}\n\n\tm_bBuilding = false;\n\n\tAttemptToGoActive();\n\n\t// We're done building, add in the stat...\n\t////TFStats()->IncrementStat( (TFStatId_t)(TF_STAT_FIRST_OBJECT_BUILT + ObjectType()), 1 );\n\n\t// Spawn any objects on this one\n\tSpawnObjectPoints();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Objects store health in hacky ways\n//-----------------------------------------------------------------------------\nvoid CBaseObject::SetHealth( float flHealth )\n{\n\tbool changed = m_flHealth != flHealth;\n\n\tm_flHealth = flHealth;\n\tm_iHealth = ceil(m_flHealth);\n\n\t/*\n\t// If we a pose parameter, set the pose parameter to reflect our health\n\tif ( LookupPoseParameter( \"object_health\") >= 0 && GetMaxHealth() > 0 )\n\t{\n\t\tSetPoseParameter( \"object_health\", 100 * ( GetHealth() / (float)GetMaxHealth() ) );\n\t}\n\t*/\n\n\tif ( changed )\n\t{\n\t\t// Set value and fire output\n\t\tm_OnObjectHealthChanged.Set( m_flHealth, this, this );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Override base traceattack to prevent visible effects from team members shooting me\n//-----------------------------------------------------------------------------\nvoid CBaseObject::TraceAttack( const CTakeDamageInfo &inputInfo, const Vector &vecDir, trace_t *ptr )\n{\n\t// Prevent team damage here so blood doesn't appear\n\tif ( inputInfo.GetAttacker() )\n\t{\n\t\tif ( InSameTeam(inputInfo.GetAttacker()) )\n\t\t{\n\t\t\t// Pass Damage to enemy attachments\n\t\t\tint iNumObjects = GetNumObjectsOnMe();\n\t\t\tfor ( int iPoint=iNumObjects-1;iPoint >= 0; --iPoint )\n\t\t\t{\n\t\t\t\tCBaseObject *pObject = GetBuildPointObject( iPoint );\n\n\t\t\t\tif ( pObject && pObject->IsHostileUpgrade() )\n\t\t\t\t{\n\t\t\t\t\tpObject->TraceAttack(inputInfo, vecDir, ptr );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\n\tSpawnBlood( ptr->endpos, vecDir, BloodColor(), inputInfo.GetDamage() );\n\n\tAddMultiDamage( inputInfo, this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Prevent Team Damage\n//-----------------------------------------------------------------------------\nConVar object_show_damage( \"obj_show_damage\", \"0\", 0, \"Show all damage taken by objects.\" );\nConVar object_capture_damage( \"obj_capture_damage\", \"0\", 0, \"Captures all damage taken by objects for dumping later.\" );\n\nCUtlDict g_DamageMap;\n\nvoid Cmd_DamageDump_f(void)\n{\t\n\tCUtlDict g_UniqueColumns;\n\tint idx;\n\n\t// Build the unique columns:\n\tfor( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) )\n\t{\n\t\tchar* szColumnName = strchr(g_DamageMap.GetElementName(idx),',') + 1;\n\n\t\tint ColumnIdx = g_UniqueColumns.Find( szColumnName );\n\n\t\tif( ColumnIdx == g_UniqueColumns.InvalidIndex() ) \n\t\t{\n\t\t\tg_UniqueColumns.Insert( szColumnName, false );\n\t\t}\n\t}\n\n\t// Dump the column names:\n\tFileHandle_t f = filesystem->Open(\"damage.txt\",\"wt+\");\n\n\tfor( idx = g_UniqueColumns.First(); idx != g_UniqueColumns.InvalidIndex(); idx = g_UniqueColumns.Next(idx) )\n\t{\n\t\tfilesystem->FPrintf(f,\"\\t%s\",g_UniqueColumns.GetElementName(idx));\n\t}\n\n\tfilesystem->FPrintf(f,\"\\n\");\n\n \n\tCUtlDict g_CompletedRows;\n\n\t// Dump each row:\n\tbool bDidRow;\n\n\tdo\n\t{\n\t\tbDidRow = false;\n\n\t\tfor( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) )\n\t\t{\n\t\t\tchar szRowName[256];\n\n\t\t\t// Check the Row name of each entry to see if I've done this row yet.\n\t\t\tQ_strncpy(szRowName, g_DamageMap.GetElementName(idx), sizeof( szRowName ) );\n\t\t\t*strchr(szRowName,',') = '\\0';\n\n\t\t\tchar szRowNameComma[256];\n\t\t\tQ_snprintf( szRowNameComma, sizeof( szRowNameComma ), \"%s,\", szRowName );\n\n\t\t\tif( g_CompletedRows.Find(szRowName) == g_CompletedRows.InvalidIndex() )\n\t\t\t{\n\t\t\t\tbDidRow = true;\n\t\t\t\tg_CompletedRows.Insert(szRowName,false);\n\n\n\t\t\t\t// Output the row name:\n\t\t\t\tfilesystem->FPrintf(f,szRowName);\n\n\t\t\t\tfor( int ColumnIdx = g_UniqueColumns.First(); ColumnIdx != g_UniqueColumns.InvalidIndex(); ColumnIdx = g_UniqueColumns.Next( ColumnIdx ) )\n\t\t\t\t{\n\t\t\t\t\tchar szRowNameCommaColumn[256];\n\t\t\t\t\tQ_strncpy( szRowNameCommaColumn, szRowNameComma, sizeof( szRowNameCommaColumn ) );\t\t\t\t\t\n\t\t\t\t\tQ_strncat( szRowNameCommaColumn, g_UniqueColumns.GetElementName( ColumnIdx ), sizeof( szRowNameCommaColumn ), COPY_ALL_CHARACTERS );\n\n\t\t\t\t\tint nDamageAmount = 0;\n\t\t\t\t\t// Fine to reuse idx since we are going to break anyways.\n\t\t\t\t\tfor( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif( !stricmp( g_DamageMap.GetElementName(idx), szRowNameCommaColumn ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnDamageAmount = g_DamageMap[idx];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfilesystem->FPrintf(f,\"\\t%i\",nDamageAmount);\n\n\t\t\t\t}\n\n\t\t\t\tfilesystem->FPrintf(f,\"\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// Grab the row name:\n\n\t} while(bDidRow);\n\n\t// close the file:\n\tfilesystem->Close(f);\n}\n\nstatic ConCommand obj_dump_damage( \"obj_dump_damage\", Cmd_DamageDump_f );\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid ReportDamage( const char* szInflictor, const char* szVictim, float fAmount, int nCurrent, int nMax )\n{\n\tint iAmount = (int)fAmount;\n\n\tif( object_show_damage.GetBool() && iAmount )\n\t{\n\t\tMsg( \"ShowDamage: Object %s taking %0.1f damage from %s ( %i / %i )\\n\", szVictim, fAmount, szInflictor, nCurrent, nMax );\n\t}\n\n\tif( object_capture_damage.GetBool() )\n\t{\n\t\tchar szMangledKey[256];\n\n\t\tQ_snprintf(szMangledKey,sizeof(szMangledKey)/sizeof(szMangledKey[0]),\"%s,%s\",szInflictor,szVictim);\n\t\tint idx = g_DamageMap.Find( szMangledKey );\n\n\t\tif( idx == g_DamageMap.InvalidIndex() )\n\t\t{\n\t\t\tg_DamageMap.Insert( szMangledKey, iAmount );\n\n\t\t} else\n\t\t{\n\t\t\tg_DamageMap[idx] += iAmount;\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Return the first non-hostile object build on this object\n//-----------------------------------------------------------------------------\nCBaseEntity *CBaseObject::GetFirstFriendlyObjectOnMe( void )\n{\n\tCBaseObject *pFirstObject = NULL;\n\n\tIHasBuildPoints *pBPInterface = dynamic_cast(this);\n\tint iNumObjects = pBPInterface->GetNumObjectsOnMe();\n\tfor ( int iPoint=0;iPointIsHostileUpgrade() )\n\t\t{\n\t\t\tpFirstObject = pObject;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn pFirstObject;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Pass the specified amount of damage through to any objects I have built on me\n//-----------------------------------------------------------------------------\nbool CBaseObject::PassDamageOntoChildren( const CTakeDamageInfo &info, float *flDamageLeftOver )\n{\n\tfloat flDamage = info.GetDamage();\n\n\t// Double the amount of damage done (and get around the child damage modifier)\n\tflDamage *= 2;\n\tif ( obj_child_damage_factor.GetFloat() )\n\t{\n\t\tflDamage *= (1 / obj_child_damage_factor.GetFloat());\n\t}\n\n\t// Remove blast damage because child objects (well specifically upgrades)\n\t// want to ignore direct blast damage but still take damage from parent\n\tCTakeDamageInfo childInfo = info;\n\tchildInfo.SetDamage( flDamage );\n\tchildInfo.SetDamageType( info.GetDamageType() & (~DMG_BLAST) );\n\n\tCBaseEntity *pEntity = GetFirstFriendlyObjectOnMe();\n\twhile ( pEntity )\n\t{\n\t\tAssert( pEntity->m_takedamage != DAMAGE_NO );\n\t\t// Do damage to the next object\n\t\tfloat flDamageTaken = pEntity->OnTakeDamage( childInfo );\n\t\t// If we didn't kill it, abort\n\t\tCBaseObject *pObject = dynamic_cast(pEntity);\n\t\tif ( !pObject || !pObject->IsDying() )\n\t\t{\n\t\t\tchar* szInflictor = \"unknown\";\n\t\t\tif( info.GetInflictor() )\n\t\t\t\tszInflictor = (char*)info.GetInflictor()->GetClassname();\n\n\t\t\tReportDamage( szInflictor, GetClassname(), flDamageTaken, GetHealth(), GetMaxHealth() );\n\n\t\t\t*flDamageLeftOver = flDamage;\n\t\t\treturn true;\n\t\t}\n\t\t// Reduce the damage and move on to the next\n\t\tflDamage -= flDamageTaken;\n\t\tpEntity = GetFirstFriendlyObjectOnMe();\n\t}\n\n\t*flDamageLeftOver = flDamage;\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CBaseObject::OnTakeDamage( const CTakeDamageInfo &info )\n{\n\tif ( !IsAlive() )\n\t\treturn info.GetDamage();\n\n\tif ( m_takedamage == DAMAGE_NO )\n\t\treturn 0;\n\t\n\tif ( HasSpawnFlags( SF_OBJ_INVULNERABLE ) )\n\t\treturn 0;\n\n\tif ( IsPlacing() )\n\t\treturn 0;\n\n\t// Check teams\n\tif ( info.GetAttacker() )\n\t{\n\t\tif ( InSameTeam(info.GetAttacker()) )\n\t\t\treturn 0;\n\t}\n\n\tIHasBuildPoints *pBPInterface = dynamic_cast(this);\n\n\tfloat flDamage = info.GetDamage();\n\n\t// Objects build on other objects take less damage\n\tif ( !IsAnUpgrade() && GetParentObject() )\n\t{\n\t\tflDamage *= obj_child_damage_factor.GetFloat();\n\t}\n\n\tif (obj_damage_factor.GetFloat())\n\t{\n\t\tflDamage *= obj_damage_factor.GetFloat();\n\t}\n\n\tbool bFriendlyObjectsAttached = false;\n\tint iNumObjects = pBPInterface->GetNumObjectsOnMe();\n\tfor ( int iPoint=0;iPointIsHostileUpgrade() )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tbFriendlyObjectsAttached = true;\n\t\tbreak;\n\t}\n\n\t// If I have objects on me, I can't be destroyed until they're gone. Ditto if I can't be killed.\n\tbool bWillDieButCant = ( bFriendlyObjectsAttached ) && (( m_flHealth - flDamage ) < 1);\n\tif ( bWillDieButCant )\n\t{\n\t\t// Soak up the damage it would take to drop us to 1 health\n\t\tflDamage = flDamage - m_flHealth;\n\t\tSetHealth( 1 );\n\n\t\t// Pass leftover damage \n\t\tif ( flDamage )\n\t\t{\n\t\t\tif ( PassDamageOntoChildren( info, &flDamage ) )\n\t\t\t\treturn flDamage;\n\t\t}\n\t}\n\tint iOldHealth = m_iHealth;\n\n\tif ( flDamage )\n\t{\n\t\t// Recheck our death possibility, because our objects may have all been blown off us by now\n\t\tbWillDieButCant = ( bFriendlyObjectsAttached ) && (( m_flHealth - flDamage ) < 1);\n\t\tif ( !bWillDieButCant )\n\t\t{\n\t\t\t// Reduce health\n\t\t\tSetHealth( m_flHealth - flDamage );\n\t\t}\n\t}\n\n\tIGameEvent *event = gameeventmanager->CreateEvent( \"npc_hurt\" );\n\n\tif ( event )\n\t{\n\t\tCTFPlayer *pTFAttacker = ToTFPlayer( info.GetAttacker() );\n\t\tCTFWeaponBase *pTFWeapon = dynamic_cast( info.GetWeapon() );\n\n\t\tevent->SetInt( \"entindex\", entindex() );\n\t\tevent->SetInt( \"attacker_player\", pTFAttacker ? pTFAttacker->GetUserID() : 0 );\n\t\tevent->SetInt( \"weaponid\", pTFWeapon ? pTFWeapon->GetWeaponID() : TF_WEAPON_NONE );\n\t\tevent->SetInt( \"damageamount\", iOldHealth - m_iHealth );\n\t\tevent->SetInt( \"health\", max( 0, m_iHealth ) );\n\t\tevent->SetBool( \"crit\", false );\n\t\tevent->SetBool( \"boss\", false );\n\n\t\tgameeventmanager->FireEvent( event );\n\t}\n\n\n\tm_OnDamaged.FireOutput(info.GetAttacker(), this);\n\n\tif ( GetHealth() <= 0 )\n\t{\n\t\tif ( info.GetAttacker() )\n\t\t{\n\t\t\t//TFStats()->IncrementTeamStat( info.GetAttacker()->GetTeamNumber(), TF_TEAM_STAT_DESTROYED_OBJECT_COUNT, 1 );\n\t\t\t//TFStats()->IncrementPlayerStat( info.GetAttacker(), TF_PLAYER_STAT_DESTROYED_OBJECT_COUNT, 1 );\n\t\t}\n\n\t\tm_lifeState = LIFE_DEAD;\n\t\tm_OnDestroyed.FireOutput( info.GetAttacker(), this);\n\t\tKilled( info );\n\n\t\t// Tell our builder to speak about it\n\t\tif ( m_hBuilder )\n\t\t{\n\t\t\tm_hBuilder->SpeakConceptIfAllowed( MP_CONCEPT_LOST_OBJECT, GetResponseRulesModifier() );\n\t\t}\n\t}\n\n\tchar* szInflictor = \"unknown\";\n\tif( info.GetInflictor() )\n\t\tszInflictor = (char*)info.GetInflictor()->GetClassname();\n\n\tReportDamage( szInflictor, GetClassname(), flDamage, GetHealth(), GetMaxHealth() );\n\n\treturn flDamage;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Repair / Help-Construct this object the specified amount\n//-----------------------------------------------------------------------------\nbool CBaseObject::Repair( float flHealth )\n{\n\t// Multiply it by the repair rate\n\tflHealth *= GetConstructionMultiplier();\n\tif ( !flHealth )\n\t\treturn false;\n\n\tif ( IsBuilding() )\n\t{\n\t\t// Reduce the construction time by the correct amount for the health passed in\n\t\tfloat flConstructionTime = flHealth / ((GetMaxHealth() - OBJECT_CONSTRUCTION_STARTINGHEALTH) / m_flTotalConstructionTime);\n\t\tm_flConstructionTimeLeft = max( 0, m_flConstructionTimeLeft - flConstructionTime);\n\t\tm_flConstructionTimeLeft = clamp( m_flConstructionTimeLeft, 0.0f, m_flTotalConstructionTime );\n\t\tm_flPercentageConstructed = 1 - (m_flConstructionTimeLeft / m_flTotalConstructionTime);\n\t\tm_flPercentageConstructed = clamp( m_flPercentageConstructed, 0.0f, 1.0f );\n\n\t\t// Increase health.\n\t\t// Only regenerate up to previous health while re-deploying.\n\t\tint iMaxHealth = IsRedeploying() ? m_iGoalHealth : GetMaxHealth();\n\t\tSetHealth( min( iMaxHealth, m_flHealth + flHealth ) );\n\n\t\t// Return true if we're constructed now\n\t\tif ( m_flConstructionTimeLeft <= 0.0f )\n\t\t{\n\t\t\tFinishedBuilding();\n\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Return true if we're already fully healed\n\t\tif ( GetHealth() >= GetMaxHealth() )\n\t\t\treturn true;\n\n\t\t// Increase health.\n\t\tSetHealth( min( GetMaxHealth(), m_flHealth + flHealth ) );\n\n\t\tm_OnRepaired.FireOutput( this, this);\n\n\t\t// Return true if we're fully healed now\n\t\tif ( GetHealth() == GetMaxHealth() )\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid CBaseObject::OnConstructionHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos )\n{\n\t// Get the player index\n\tint iPlayerIndex = pPlayer->entindex();\n\n\t// The time the repair is going to expire\n\tfloat flRepairExpireTime = gpGlobals->curtime + 1.0;\n\n\t// Update or Add the expire time to the list\n\tint index = m_RepairerList.Find( iPlayerIndex );\n\tif ( index == m_RepairerList.InvalidIndex() )\n\t{\n\t\tm_RepairerList.Insert( iPlayerIndex, flRepairExpireTime );\n\t}\n\telse\n\t{\n\t\tm_RepairerList[index] = flRepairExpireTime;\n\t}\n\n\tCPVSFilter filter( vecHitPos );\n\tTE_TFParticleEffect( filter, 0.0f, \"nutsnbolts_build\", vecHitPos, QAngle( 0,0,0 ) );\n}\n\n\nfloat CBaseObject::GetConstructionMultiplier( void )\n{\n\tfloat flMultiplier = 1.0f;\n\n\t// Minis deploy faster.\n\tif ( IsMiniBuilding() )\n\t\tflMultiplier *= 1.7f;\n\n\t// Re-deploy twice as fast.\n\tif ( IsRedeploying() )\n\t\tflMultiplier *= 2.0f;\n\n\t// expire all the old \n\tint i = m_RepairerList.LastInorder();\n\twhile ( i != m_RepairerList.InvalidIndex() )\n\t{\n\t\tint iThis = i;\n\t\ti = m_RepairerList.PrevInorder( i );\n\t\tif ( m_RepairerList[iThis] < gpGlobals->curtime )\n\t\t{\n\t\t\tm_RepairerList.RemoveAt( iThis );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Each player hitting it builds twice as fast\n\t\t\tflMultiplier *= 2.0;\n\n\t\t\t// Check if this weapon has a build modifier\n\t\t\tCALL_ATTRIB_HOOK_FLOAT_ON_OTHER( UTIL_PlayerByIndex( m_RepairerList.Key( iThis ) ), flMultiplier, mult_construction_value );\n\t\t}\n\t}\n\n\treturn flMultiplier;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Object is exploding because it was killed or detonate\n//-----------------------------------------------------------------------------\nvoid CBaseObject::Explode( void )\n{\n\tconst char *pExplodeSound = GetObjectInfo( ObjectType() )->m_pExplodeSound;\n\n\tif ( pExplodeSound && Q_strlen(pExplodeSound) > 0 )\n\t{\n\t\tEmitSound( pExplodeSound );\n\t}\n\n\tconst char *pExplodeEffect = GetObjectInfo( ObjectType() )->m_pExplosionParticleEffect;\n\tif ( pExplodeEffect && pExplodeEffect[0] != '\\0' )\n\t{\n\t\t// Send to everyone - we're inside prediction for the engy who hit this off, but we \n\t\t// don't predict that the hit will kill this object.\n\t\tCDisablePredictionFiltering disabler;\n\n\t\tVector origin = GetAbsOrigin();\n\t\tQAngle up(-90,0,0);\n\n\t\tCPVSFilter filter( origin );\n\t\tTE_TFParticleEffect( filter, 0.0f, pExplodeEffect, origin, up );\n\t}\n\n\t// create some delicious, metal filled gibs\n\tCreateObjectGibs();\n}\n\nvoid CBaseObject::CreateObjectGibs( void )\n{\n\tif ( m_aGibs.Count() <= 0 )\n\t{\n\t\treturn;\n\t}\n\n\tconst CObjectInfo *pObjectInfo = GetObjectInfo( ObjectType() );\n\n\tint nMetalPerGib = pObjectInfo->m_iMetalToDropInGibs / m_aGibs.Count();\n\n\tint i;\n\tfor ( i=0; iActivateWhenAtRest();\n\n\t\t\t// Fill up the ammo pack.\n\t\t\t// Mini gibs don't give any ammo\n\t\t\tif ( !IsMiniBuilding() ) \n\t\t\t\tpAmmoPack->GiveAmmo( nMetalPerGib, TF_AMMO_METAL );\n\n\t\t\t// Calculate the initial impulse on the weapon.\n\t\t\tVector vecImpulse( random->RandomFloat( -0.5, 0.5 ), random->RandomFloat( -0.5, 0.5 ), random->RandomFloat( 0.75, 1.25 ) );\n\t\t\tVectorNormalize( vecImpulse );\n\t\t\tvecImpulse *= random->RandomFloat( tf_obj_gib_velocity_min.GetFloat(), tf_obj_gib_velocity_max.GetFloat() );\n\n\t\t\tQAngle angImpulse( random->RandomFloat ( -100, -500 ), 0, 0 );\n\n\t\t\t// Cap the impulse.\n\t\t\tfloat flSpeed = vecImpulse.Length();\n\t\t\tif ( flSpeed > tf_obj_gib_maxspeed.GetFloat() )\n\t\t\t{\n\t\t\t\tVectorScale( vecImpulse, tf_obj_gib_maxspeed.GetFloat() / flSpeed, vecImpulse );\n\t\t\t}\n\n\t\t\tif ( pAmmoPack->VPhysicsGetObject() )\n\t\t\t{\n\t\t\t\t// We can probably remove this when the mass on the weapons is correct!\n\t\t\t\t//pAmmoPack->VPhysicsGetObject()->SetMass( 25.0f );\n\t\t\t\tAngularImpulse angImpulse( 0, random->RandomFloat( 0, 100 ), 0 );\n\t\t\t\tpAmmoPack->VPhysicsGetObject()->SetVelocityInstantaneous( &vecImpulse, &angImpulse );\n\t\t\t}\n\n\t\t\tpAmmoPack->SetInitialVelocity( vecImpulse );\n\n\t\t\tswitch (GetTeamNumber())\n\t\t\t{\n\t\t\t\tcase TF_TEAM_RED:\n\t\t\t\t\tpAmmoPack->m_nSkin = 0;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TF_TEAM_BLUE:\n\t\t\t\t\tpAmmoPack->m_nSkin = 1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tpAmmoPack->m_nSkin = 1;\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\t// Give the ammo pack some health, so that trains can destroy it.\n\t\t\tpAmmoPack->SetCollisionGroup( COLLISION_GROUP_DEBRIS );\n\t\t\tpAmmoPack->m_takedamage = DAMAGE_YES;\t\t\n\t\t\tpAmmoPack->SetHealth( 900 );\n\n\t\t\tif ( IsMiniBuilding() )\n\t\t\t{\n\t\t\t\tpAmmoPack->SetModelScale( 0.6f );\n\t\t\t}\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Object has been blown up. Drop resource chunks upto the value of my max health.\n//-----------------------------------------------------------------------------\nvoid CBaseObject::Killed( const CTakeDamageInfo &info )\n{\n\tm_bDying = true;\n\n\t// Find the killer & the scorer\n\tCBaseEntity *pInflictor = info.GetInflictor();\n\tCBaseEntity *pKiller = info.GetAttacker();\n\tCTFPlayer *pScorer = ToTFPlayer( TFGameRules()->GetDeathScorer( pKiller, pInflictor, this ) );\n\tCTFPlayer *pAssister = NULL;\n\n\t// if this object has a sapper on it, and was not killed by the sapper (killed by damage other than crush, since sapper does crushing damage),\n\t// award an assist to the owner of the sapper since it probably contributed to destroying this object\n\tif ( HasSapper() && !( DMG_CRUSH & info.GetDamageType() ) )\n\t{\n\t\tCObjectSapper *pSapper = dynamic_cast( FirstMoveChild() );\n\t\tif ( pSapper )\n\t\t{\n\t\t\t// give an assist to the sapper's owner\n\t\t\tpAssister = pSapper->GetOwner();\n\t\t\tCTF_GameStats.Event_AssistDestroyBuilding( pAssister, this );\n\t\t}\n\t}\n\n\t// Don't do anything if we were detonated or dismantled\n\tif ( pScorer && pInflictor != this )\n\t{\n\t\tIGameEvent * event = gameeventmanager->CreateEvent( \"object_destroyed\" );\n\t\tint iWeaponID = TF_WEAPON_NONE;\n\n\t\t// Work out what killed the player, and send a message to all clients about it\n\t\tconst char *killer_weapon_name = TFGameRules()->GetKillingWeaponName( info, NULL, iWeaponID );\n\t\tconst char *killer_weapon_log_name = NULL;\n\n\t\tif ( iWeaponID && pScorer )\n\t\t{\n\t\t\tCTFWeaponBase *pWeapon = pScorer->Weapon_OwnsThisID( iWeaponID );\n\t\t\tif ( pWeapon )\n\t\t\t{\n\t\t\t\tCEconItemDefinition *pItemDef = pWeapon->GetItem()->GetStaticData();\n\t\t\t\tif ( pItemDef )\n\t\t\t\t{\n\t\t\t\t\tif ( pItemDef->item_iconname[0] )\n\t\t\t\t\t\tkiller_weapon_name = pItemDef->item_iconname;\n\n\t\t\t\t\tif ( pItemDef->item_logname[0] )\n\t\t\t\t\t\tkiller_weapon_log_name = pItemDef->item_logname;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCTFPlayer *pTFPlayer = GetOwner();\n\n\t\tif ( event )\n\t\t{\n\t\t\tif ( pTFPlayer )\n\t\t\t{\n\t\t\t\tevent->SetInt( \"userid\", pTFPlayer->GetUserID() );\n\t\t\t}\n\t\t\tif ( pAssister && ( pAssister != pScorer ) )\n\t\t\t{\n\t\t\t\tevent->SetInt( \"assister\", pAssister->GetUserID() );\n\t\t\t}\n\t\t\t\n\t\t\tevent->SetInt( \"attacker\", pScorer->GetUserID() );\t// attacker\n\t\t\tevent->SetString( \"weapon\", killer_weapon_name );\n\t\t\tevent->SetString( \"weapon_logclassname\", killer_weapon_log_name );\n\t\t\tevent->SetInt( \"priority\", 6 );\t\t// HLTV event priority, not transmitted\n\t\t\tevent->SetInt( \"objecttype\", GetType() );\n\t\t\tevent->SetInt( \"index\", entindex() );\t// object entity index\n\n\t\t\tgameeventmanager->FireEvent( event );\n\t\t}\n\t\tCTFPlayer *pPlayerScorer = ToTFPlayer( pScorer );\n\t\tif ( pPlayerScorer )\n\t\t{\n\t\t\tCTF_GameStats.Event_PlayerDestroyedBuilding( pPlayerScorer, this );\n\t\t\tpPlayerScorer->Event_KilledOther(this, info);\n\t\t}\t\n\t}\n\n\t// Do an explosion.\n\tExplode();\n\n\tUTIL_Remove( this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Indicates this NPC's place in the relationship table.\n//-----------------------------------------------------------------------------\nClass_T\tCBaseObject::Classify( void )\n{\n\treturn CLASS_NONE;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Get the type of this object\n//-----------------------------------------------------------------------------\nint\tCBaseObject::GetType()\n{\n\treturn m_iObjectType;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Get the builder of this object\n//-----------------------------------------------------------------------------\nCTFPlayer *CBaseObject::GetBuilder( void )\n{\n\treturn m_hBuilder;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Return true if the Owning CTeam should clean this object up automatically\n//-----------------------------------------------------------------------------\nbool CBaseObject::ShouldAutoRemove( void )\n{\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : iTeamNum - \n//-----------------------------------------------------------------------------\nvoid CBaseObject::ChangeTeam( int iTeamNum )\n{\n\tCTFTeam *pTeam = ( CTFTeam * )GetGlobalTeam( iTeamNum );\n\tCTFTeam *pExisting = ( CTFTeam * )GetTeam();\n\n\tTRACE_OBJECT( UTIL_VarArgs( \"%0.2f CBaseObject::ChangeTeam old %s new %s\\n\", gpGlobals->curtime, \n\t\tpExisting ? pExisting->GetName() : \"NULL\",\n\t\tpTeam ? pTeam->GetName() : \"NULL\" ) );\n\n\t// Already on this team\n\tif ( GetTeamNumber() == iTeamNum )\n\t\treturn;\n\n\tif ( pExisting )\n\t{\n\t\t// Remove it from current team ( if it's in one ) and give it to new team\n\t\tpExisting->RemoveObject( this );\n\t}\n\t\t\n\t// Change to new team\n\tBaseClass::ChangeTeam( iTeamNum );\n\t\n\t// Add this object to the team's list\n\t// But only if we're not placing it\n\tif ( pTeam && (!m_bPlacing) )\n\t{\n\t\tpTeam->AddObject( this );\n\t}\n\n\t// Setup for our new team's model\n\tCreateBuildPoints();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Return true if I have at least 1 sapper on me\n//-----------------------------------------------------------------------------\nbool CBaseObject::HasSapper( void )\n{\n\treturn m_bHasSapper;\n}\n\nvoid CBaseObject::OnAddSapper( void )\n{\n\t// Assume we can only build 1 sapper per object\n\tAssert( m_bHasSapper == false );\n\n\tm_bHasSapper = true;\n\n\tCTFPlayer *pPlayer = GetBuilder();\n\n\tif ( pPlayer )\n\t{\n\t\t//pPlayer->HintMessage( HINT_OBJECT_YOUR_OBJECT_SAPPED, true );\n\t\tpPlayer->SpeakConceptIfAllowed( MP_CONCEPT_SPY_SAPPER, GetResponseRulesModifier() );\n\t}\n\n\tUpdateDisabledState();\n}\n\nvoid CBaseObject::OnRemoveSapper( void )\n{\n\tm_bHasSapper = false;\n\n\tUpdateDisabledState();\n}\n\nbool CBaseObject::ShowVGUIScreen( int panelIndex, bool bShow )\n{\n\tAssert( panelIndex >= 0 && panelIndex < m_hScreens.Count() );\n\tif ( m_hScreens[panelIndex].Get() )\n\t{\n\t\tm_hScreens[panelIndex]->SetActive( bShow );\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputShow( inputdata_t &inputdata )\n{\n\tRemoveFlag( EF_NODRAW );\n\tSetDisabled( false );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputHide( inputdata_t &inputdata )\n{\n\tAddFlag( EF_NODRAW );\n\tSetDisabled( true );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputEnable( inputdata_t &inputdata )\n{\n\tSetDisabled( false );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputDisable( inputdata_t &inputdata )\n{\n\tAddFlag( EF_NODRAW );\n\tSetDisabled( true );\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: Set the health of the object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputSetHealth( inputdata_t &inputdata )\n{\n\tm_iMaxHealth = inputdata.value.Int();\n\tSetHealth( m_iMaxHealth );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Add health to the object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputAddHealth( inputdata_t &inputdata )\n{\n\tint iHealth = inputdata.value.Int();\n\tSetHealth( min( GetMaxHealth(), m_flHealth + iHealth ) );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Remove health from the object\n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputRemoveHealth( inputdata_t &inputdata )\n{\n\tint iDamage = inputdata.value.Int();\n\n\tSetHealth( m_flHealth - iDamage );\n\tif ( GetHealth() <= 0 )\n\t{\n\t\tm_lifeState = LIFE_DEAD;\n\t\tm_OnDestroyed.FireOutput(this, this);\n\n\t\tCTakeDamageInfo info( inputdata.pCaller, inputdata.pActivator, vec3_origin, GetAbsOrigin(), iDamage, DMG_GENERIC );\n\t\tKilled( info );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : &inputdata - \n//-----------------------------------------------------------------------------\nvoid CBaseObject::InputSetSolidToPlayer( inputdata_t &inputdata )\n{\n\tint ival = inputdata.value.Int();\n\tival = clamp( ival, (int)SOLID_TO_PLAYER_USE_DEFAULT, (int)SOLID_TO_PLAYER_NO );\n\tOBJSOLIDTYPE stp = (OBJSOLIDTYPE)ival;\n\tSetSolidToPlayers( stp );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : \n// Output : did this wrench hit do any work on the object?\n//-----------------------------------------------------------------------------\nbool CBaseObject::InputWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos )\n{\n\tAssert( pPlayer );\n\tif ( !pPlayer )\n\t\treturn false;\n\n\tbool bDidWork = false;\n\n\tif ( HasSapper() )\n\t{\n\t\t// do damage to any attached buildings\n\n\t\t#define WRENCH_DMG_VS_SAPPER\t65\n\n\t\tCTakeDamageInfo info( pPlayer, pPlayer, WRENCH_DMG_VS_SAPPER, DMG_CLUB, TF_DMG_WRENCH_FIX );\n\n\t\tIHasBuildPoints *pBPInterface = dynamic_cast< IHasBuildPoints * >( this );\n\t\tint iNumObjects = pBPInterface->GetNumObjectsOnMe();\n\t\tfor ( int iPoint=0;iPointIsHostileUpgrade() )\n\t\t\t{\n\t\t\t\tint iBeforeHealth = pObject->GetHealth();\n\n\t\t\t\tpObject->TakeDamage( info );\n\n\t\t\t\t// This should always be true\n\t\t\t\tif ( iBeforeHealth != pObject->GetHealth() )\n\t\t\t\t{\n\t\t\t\t\tbDidWork = true;\n\t\t\t\t\tAssert( bDidWork );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if ( IsBuilding() )\n\t{\n\t\tOnConstructionHit( pPlayer, pWrench, vecHitPos );\n\t\tbDidWork = true;\n\t}\n\telse\n\t{\n\t\t// upgrade, refill, repair damage\n\t\tbDidWork = OnWrenchHit( pPlayer, pWrench, vecHitPos );\n\t}\n\n\treturn bDidWork;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CBaseObject::OnWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos )\n{\n\tbool bRepair = false;\n\tbool bUpgrade = false;\n\n\t// If the player repairs it at all, we're done\n\tbRepair = Command_Repair( pPlayer/*, pWrench->GetRepairValue()*/ );\n\n\tif ( !bRepair )\n\t{\n\t\t// no building upgrade for minis.\n\t\tif ( !IsMiniBuilding() )\n\t\t{\n\t\t\t// Don't put in upgrade metal until the object is fully healed\n\t\t\tif ( CanBeUpgraded( pPlayer ) )\n\t\t\t{\n\t\t\t\tbUpgrade = CheckUpgradeOnHit( pPlayer );\n\t\t\t}\n\t\t}\n\t}\n\n\tDoWrenchHitEffect( vecHitPos, bRepair, bUpgrade );\n\n\treturn ( bRepair || bUpgrade );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CBaseObject::CheckUpgradeOnHit( CTFPlayer *pPlayer )\n{\n\tbool bUpgrade = false;\n\n\tint iPlayerMetal = pPlayer->GetAmmoCount( TF_AMMO_METAL );\n\tint iAmountToAdd = min( tf_obj_upgrade_per_hit.GetInt(), iPlayerMetal );\n\n\tif ( iAmountToAdd > ( m_iUpgradeMetalRequired - m_iUpgradeMetal ) )\n\t\tiAmountToAdd = ( m_iUpgradeMetalRequired - m_iUpgradeMetal );\n\n\tif ( tf_cheapobjects.GetBool() == false )\n\t{\n\t\tpPlayer->RemoveAmmo( iAmountToAdd, TF_AMMO_METAL );\n\t}\n\tm_iUpgradeMetal += iAmountToAdd;\n\n\tif ( iAmountToAdd > 0 )\n\t{\n\t\tbUpgrade = true;\n\t}\n\n\tif ( m_iUpgradeMetal >= m_iUpgradeMetalRequired )\n\t{\n\t\tStartUpgrading();\n\n\t\tIGameEvent * event = gameeventmanager->CreateEvent( \"player_upgradedobject\" );\n\t\tif ( event )\n\t\t{\n\t\t\tevent->SetInt( \"userid\", pPlayer->GetUserID() );\n\t\t\tevent->SetInt( \"object\", ObjectType() );\n\t\t\tevent->SetInt( \"index\", entindex() );\t// object entity index\n\t\t\tevent->SetBool( \"isbuilder\", pPlayer == GetBuilder() );\n\t\t\tgameeventmanager->FireEvent( event, true );\t// don't send to clients\n\t\t}\n\n\t\tm_iUpgradeMetal = 0;\n\t}\n\n\treturn bUpgrade;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Separated so it can be triggered by wrench hit or by vgui screen\n//-----------------------------------------------------------------------------\nbool CBaseObject::Command_Repair( CTFPlayer *pActivator )\n{\n\tif ( GetHealth() < GetMaxHealth() )\n\t{\n\t\tint iAmountToHeal = min( 100, GetMaxHealth() - GetHealth() );\n\n\t\t// repair the building\n\t\tint iRepairCost = ceil( (float)( iAmountToHeal ) * 0.2f );\n\t\n\t\tTRACE_OBJECT( UTIL_VarArgs( \"%0.2f CObjectDispenser::Command_Repair ( %d / %d ) - cost = %d\\n\", gpGlobals->curtime, \n\t\t\tGetHealth(),\n\t\t\tGetMaxHealth(),\n\t\t\tiRepairCost ) );\n\n\t\tif ( iRepairCost > 0 )\n\t\t{\n\t\t\tif ( iRepairCost > pActivator->GetBuildResources() )\n\t\t\t{\n\t\t\t\tiRepairCost = pActivator->GetBuildResources();\n\t\t\t}\n\n\t\t\tpActivator->RemoveBuildResources( iRepairCost );\n\n\t\t\tfloat flNewHealth = min( GetMaxHealth(), m_flHealth + ( iRepairCost * 5 ) );\n\t\t\tSetHealth( flNewHealth );\n\t\n\t\t\treturn ( iRepairCost > 0 );\n\t\t}\n\t}\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::PlayStartupAnimation( void )\n{\n\tSetActivity( ACT_OBJ_STARTUP );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::DetermineAnimation( void )\n{\n\tActivity desiredActivity = m_Activity;\n\n\tswitch ( m_Activity )\n\t{\n\tdefault:\n\t\t{\n\t\t\tif ( IsUpgrading() )\n\t\t\t{\n\t\t\t\tdesiredActivity = ACT_OBJ_UPGRADING;\n\t\t\t}\n\t\t\telse if ( IsPlacing() )\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\tif (1 || m_bPlacementOK )\n\t\t\t\t{\n\t\t\t\t\tdesiredActivity = ACT_OBJ_PLACING;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdesiredActivity = ACT_OBJ_IDLE;\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t}\n\t\t\telse if ( IsBuilding() )\n\t\t\t{\n\t\t\t\tdesiredActivity = ACT_OBJ_ASSEMBLING;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdesiredActivity = ACT_OBJ_RUNNING;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase ACT_OBJ_STARTUP:\n\t\t{\n\t\t\tif ( IsActivityFinished() )\n\t\t\t{\n\t\t\t\tdesiredActivity = ACT_OBJ_RUNNING;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tif ( desiredActivity == m_Activity )\n\t\treturn;\n\n\tSetActivity( desiredActivity );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Attach this object to the specified object\n//-----------------------------------------------------------------------------\n\nvoid CBaseObject::AttachObjectToObject( CBaseEntity *pEntity, int iPoint, Vector &vecOrigin )\n{\n\tm_hBuiltOnEntity = pEntity;\n\tm_iBuiltOnPoint = iPoint;\n\n\tif ( m_hBuiltOnEntity.Get() )\n\t{\n\t\t// Parent ourselves to the object\n\t\tCBaseAnimating *pAnimating = dynamic_cast( pEntity );\n\t\tif ( pAnimating && pAnimating->LookupBone( \"weapon_bone\" ) > 0 )\n\t\t{\n\t\t\tFollowEntity( m_hBuiltOnEntity.Get(), true );\n\t\t}\n\n\t\tint iAttachment = 0;\n\t\tIHasBuildPoints *pBPInterface = dynamic_cast( pEntity );\n\t\tAssert( pBPInterface );\n\t\tif ( pBPInterface )\n\t\t{\n\t\t\tiAttachment = pBPInterface->GetBuildPointAttachmentIndex( iPoint );\n\n\t\t\t// re-link to the build points if the sapper is already built\n\t\t\tif ( !( IsPlacing() || IsBuilding() ) )\n\t\t\t{\n\t\t\t\tpBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, this );\n\t\t\t}\n\t\t}\t\t\n\n\t\tSetParent( m_hBuiltOnEntity.Get(), iAttachment );\n\n\t\tif ( iAttachment >= 1 )\n\t\t{\n\t\t\t// Stick right onto the attachment point.\n\t\t\tvecOrigin.Init();\n\t\t\tSetLocalOrigin( vecOrigin );\n\t\t\tSetLocalAngles( QAngle(0,0,0) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSetAbsOrigin( vecOrigin );\n\t\t\tvecOrigin = GetLocalOrigin();\n\t\t}\n\n\t\tSetupAttachedVersion();\n\t}\n\n\tAssert( m_hBuiltOnEntity.Get() == GetMoveParent() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Detach this object from its parent, if it has one\n//-----------------------------------------------------------------------------\nvoid CBaseObject::DetachObjectFromObject( void )\n{\n\tif ( !GetParentObject() )\n\t\treturn;\n\n\t// Clear the build point\n\tIHasBuildPoints *pBPInterface = dynamic_cast(GetParentObject() );\n\tAssert( pBPInterface );\n\tpBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, NULL );\n\n\tSetParent( NULL );\n\tm_hBuiltOnEntity = NULL;\n\tm_iBuiltOnPoint = 0;\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: Spawn any objects specified inside the mdl\n//-----------------------------------------------------------------------------\nvoid CBaseObject::SpawnEntityOnBuildPoint( const char *pEntityName, int iAttachmentNumber )\n{\n\t// Try and spawn the object\n\tCBaseEntity *pEntity = CreateEntityByName( pEntityName );\n\tif ( !pEntity )\n\t\treturn;\n\n\tVector vecOrigin;\n\tQAngle vecAngles;\n\tGetAttachment( iAttachmentNumber, vecOrigin, vecAngles );\n\tpEntity->SetAbsOrigin( vecOrigin );\n\tpEntity->SetAbsAngles( vecAngles );\n\tpEntity->Spawn();\n\t\n\t// If it's an object, finish setting it up\n\tCBaseObject *pObject = dynamic_cast(pEntity);\n\tif ( !pObject )\n\t\treturn;\n\n\t// Add a buildpoint here\n\tint iPoint = AddBuildPoint( iAttachmentNumber );\n\tAddValidObjectToBuildPoint( iPoint, pObject->GetType() );\n\tpObject->SetBuilder( GetBuilder() );\n\tpObject->ChangeTeam( GetTeamNumber() );\n\tpObject->SpawnControlPanels();\n\tpObject->SetHealth( pObject->GetMaxHealth() );\n\tpObject->FinishedBuilding();\n\tpObject->AttachObjectToObject( this, iPoint, vecOrigin );\n\t//pObject->m_fObjectFlags |= OF_CANNOT_BE_DISMANTLED;\n\n\tIHasBuildPoints *pBPInterface = dynamic_cast(this);\n\tAssert( pBPInterface );\n\tpBPInterface->SetObjectOnBuildPoint( iPoint, pObject );\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: Spawn any objects specified inside the mdl\n//-----------------------------------------------------------------------------\nvoid CBaseObject::SpawnObjectPoints( void )\n{\n\tKeyValues *modelKeyValues = new KeyValues(\"\");\n\tif ( !modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )\n\t{\n\t\tmodelKeyValues->deleteThis();\n\t\treturn;\n\t}\n\n\t// Do we have a build point section?\n\tKeyValues *pkvAllObjectPoints = modelKeyValues->FindKey(\"object_points\");\n\tif ( !pkvAllObjectPoints )\n\t{\n\t\tmodelKeyValues->deleteThis();\n\t\treturn;\n\t}\n\n\t// Start grabbing the sounds and slotting them in\n\tKeyValues *pkvObjectPoint;\n\tfor ( pkvObjectPoint = pkvAllObjectPoints->GetFirstSubKey(); pkvObjectPoint; pkvObjectPoint = pkvObjectPoint->GetNextKey() )\n\t{\n\t\t// Find the attachment first\n\t\tconst char *sAttachment = pkvObjectPoint->GetName();\n\t\tint iAttachmentNumber = LookupAttachment( sAttachment );\n\t\tif ( iAttachmentNumber == 0 )\n\t\t{\n\t\t\tMsg( \"ERROR: Model %s specifies object point %s, but has no attachment named %s.\\n\", STRING(GetModelName()), pkvObjectPoint->GetString(), pkvObjectPoint->GetString() );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Now see what we're supposed to spawn there\n\t\t// The count check is because it seems wrong to emit multiple entities on the same point\n\t\tint nCount = 0;\n\t\tKeyValues *pkvObject;\n\t\tfor ( pkvObject = pkvObjectPoint->GetFirstSubKey(); pkvObject; pkvObject = pkvObject->GetNextKey() )\n\t\t{\n\t\t\tSpawnEntityOnBuildPoint( pkvObject->GetName(), iAttachmentNumber );\n\t\t\t++nCount;\n\t\t\tAssert( nCount <= 1 );\n\t\t}\n\t}\n\n\tmodelKeyValues->deleteThis();\n}\n\nbool CBaseObject::IsSolidToPlayers( void ) const\n{\n\tswitch ( m_SolidToPlayers )\n\t{\n\tdefault:\n\t\tbreak;\n\tcase SOLID_TO_PLAYER_USE_DEFAULT:\n\t\t{\n\t\t\tif ( GetObjectInfo( ObjectType() ) )\n\t\t\t{\n\t\t\t\treturn GetObjectInfo( ObjectType() )->m_bSolidToPlayerMovement;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase SOLID_TO_PLAYER_YES:\n\t\treturn true;\n\tcase SOLID_TO_PLAYER_NO:\n\t\treturn false;\n\t}\n\n\treturn false;\n}\n\nvoid CBaseObject::SetSolidToPlayers( OBJSOLIDTYPE stp, bool force )\n{\n\tbool changed = stp != m_SolidToPlayers;\n\tm_SolidToPlayers = stp;\n\n\tif ( changed || force )\n\t{\n\t\tSetCollisionGroup( \n\t\t\tIsSolidToPlayers() ? \n\t\t\t\tTFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT : \n\t\t\t\tTFCOLLISION_GROUP_OBJECT );\n\t}\n}\n\nint CBaseObject::DrawDebugTextOverlays(void) \n{\n\tint text_offset = BaseClass::DrawDebugTextOverlays();\n\n\tif (m_debugOverlays & OVERLAY_TEXT_BIT) \n\t{\n\t\tchar tempstr[512];\n\n\t\tQ_snprintf( tempstr, sizeof( tempstr ),\"Health: %d / %d ( %.1f )\", GetHealth(), GetMaxHealth(), (float)GetHealth() / (float)GetMaxHealth() );\n\t\tEntityText(text_offset,tempstr,0);\n\t\ttext_offset++;\n\n\t\tCTFPlayer *pBuilder = GetBuilder();\n\n\t\tQ_snprintf( tempstr, sizeof( tempstr ),\"Built by: (%d) %s\",\n\t\t\tpBuilder ? pBuilder->entindex() : -1,\n\t\t\tpBuilder ? pBuilder->GetPlayerName() : \"invalid builder\" );\n\t\tEntityText(text_offset,tempstr,0);\n\t\ttext_offset++;\n\n\t\tif ( IsBuilding() )\n\t\t{\n\t\t\tQ_snprintf( tempstr, sizeof( tempstr ),\"Build Rate: %.1f\", GetConstructionMultiplier() );\n\t\t\tEntityText(text_offset,tempstr,0);\n\t\t\ttext_offset++;\n\t\t}\n\t}\n\treturn text_offset;\n\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Change build orientation\n//-----------------------------------------------------------------------------\nvoid CBaseObject::RotateBuildAngles( void )\n{\n\t// rotate the build angles by 90 degrees ( final angle calculated after we network this )\n\tm_iDesiredBuildRotations++;\n\tm_iDesiredBuildRotations = m_iDesiredBuildRotations % 4;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: called on edge cases to see if we need to change our disabled state\n//-----------------------------------------------------------------------------\nvoid CBaseObject::UpdateDisabledState( void )\n{\n\tSetDisabled( HasSapper() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: called when our disabled state changes\n//-----------------------------------------------------------------------------\nvoid CBaseObject::SetDisabled( bool bDisabled )\n{\n\tif ( bDisabled && !m_bDisabled )\n\t{\n\t\tOnStartDisabled();\n\t}\n\telse if ( !bDisabled && m_bDisabled )\n\t{\n\t\tOnEndDisabled();\n\t}\n\n\tm_bDisabled = bDisabled;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::OnStartDisabled( void )\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CBaseObject::OnEndDisabled( void )\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Called when the model changes, find new attachments for the children\n//-----------------------------------------------------------------------------\nvoid CBaseObject::ReattachChildren( void )\n{\n\tint iNumBuildPoints = GetNumBuildPoints();\n\tfor (CBaseEntity *pChild = FirstMoveChild(); pChild; pChild = pChild->NextMovePeer())\n\t{\n\t\t//CBaseObject *pObject = GetBuildPointObject( iPoint );\n\t\tCBaseObject *pObject = dynamic_cast( pChild );\n\n\t\tif ( !pObject )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tAssert( pObject->GetParent() == this );\n\n\t\t// get the type\n\t\tint iObjectType = pObject->GetType();\n\n\t\tbool bReattached = false;\n\n\t\tVector vecDummy;\n\n\t\tfor ( int i = 0; i < iNumBuildPoints && bReattached == false; i++ )\n\t\t{\n\t\t\t// Can this object build on this point?\n\t\t\tif ( CanBuildObjectOnBuildPoint( i, iObjectType ) )\n\t\t\t{\n\t\t\t\tpObject->AttachObjectToObject( this, i, vecDummy );\n\t\t\t\tbReattached = true;\n\t\t\t}\n\t\t}\n\n\t\t// if we can't find an attach for the child, remove it and print an error\n\t\tif ( bReattached == false )\n\t\t{\n\t\t\tpObject->DestroyObject();\n\t\t\tAssert( !\"Couldn't find attachment point on upgraded object for existing child.\\n\" );\n\t\t}\n\t}\n}\n\nvoid CBaseObject::SetModel( const char *pModel )\n{\n\tBaseClass::SetModel( pModel );\n\n\t// Clear out the gib list and create a new one.\n\tm_aGibs.Purge();\n\tBuildGibList( m_aGibs, GetModelIndex(), 1.0f, COLLISION_GROUP_NONE );\n}\n\n\n<|start_filename|>src/game/shared/econ/econ_wearable.cpp<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: \n//\n//========================================================================//\n\n#include \"cbase.h\"\n#include \"econ_wearable.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n\nIMPLEMENT_NETWORKCLASS_ALIASED( EconWearable, DT_EconWearable )\n\nBEGIN_NETWORK_TABLE( CEconWearable, DT_EconWearable )\n#ifdef GAME_DLL\n\tSendPropString( SENDINFO( m_ParticleName ) ),\n\tSendPropBool( SENDINFO( m_bExtraWearable ) ),\n#else\n\tRecvPropString( RECVINFO( m_ParticleName ) ),\n\tRecvPropBool( RECVINFO( m_bExtraWearable ) ),\n#endif\nEND_NETWORK_TABLE()\n\nvoid CEconWearable::Spawn( void )\n{\n\tGetAttributeContainer()->InitializeAttributes( this );\n\n\tPrecache();\n\n\tif ( m_bExtraWearable && m_Item.GetStaticData() )\n\t{\n\t\tSetModel( m_Item.GetStaticData()->extra_wearable );\n\t}\n\telse\n\t{\n\t\tSetModel( m_Item.GetPlayerDisplayModel() );\n\t}\n\n\tBaseClass::Spawn();\n\n\tAddEffects( EF_BONEMERGE );\n\tAddEffects( EF_BONEMERGE_FASTCULL );\n\tSetCollisionGroup( COLLISION_GROUP_WEAPON );\n\tSetBlocksLOS( false );\n}\n\nint CEconWearable::GetSkin( void )\n{\n\tswitch ( GetTeamNumber() )\n\t{\n\t\tcase TF_TEAM_BLUE:\n\t\t\treturn 1;\n\t\t\tbreak;\n\n\t\tcase TF_TEAM_RED:\n\t\t\treturn 0;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\treturn 0;\n\t\t\tbreak;\n\t}\n}\n\nvoid CEconWearable::UpdateWearableBodyGroups( CBasePlayer *pPlayer )\n{\n\tEconItemVisuals *visual = GetItem()->GetStaticData()->GetVisuals( GetTeamNumber() );\n \tfor ( unsigned int i = 0; i < visual->player_bodygroups.Count(); i++ )\n\t{\n\t\tconst char *szBodyGroupName = visual->player_bodygroups.GetElementName(i);\n\n\t\tif ( szBodyGroupName )\n\t\t{\n\t\t\tint iBodyGroup = pPlayer->FindBodygroupByName( szBodyGroupName );\n\t\t\tint iBodyGroupValue = visual->player_bodygroups.Element(i);\n\n\t\t\tpPlayer->SetBodygroup( iBodyGroup, iBodyGroupValue );\n\t\t}\n\t}\n}\n\nvoid CEconWearable::SetParticle(const char* name)\n{\n#ifdef GAME_DLL\n\tQ_snprintf(m_ParticleName.GetForModify(), PARTICLE_MODIFY_STRING_SIZE, name);\n#else\n\tQ_snprintf(m_ParticleName, PARTICLE_MODIFY_STRING_SIZE, name);\n#endif\n}\n\nvoid CEconWearable::GiveTo( CBaseEntity *pEntity )\n{\n#ifdef GAME_DLL\n\tCBasePlayer *pPlayer = ToBasePlayer( pEntity );\n\n\tif ( pPlayer )\n\t{\n\t\tpPlayer->EquipWearable( this );\n\t}\n#endif\n}\n\n#ifdef GAME_DLL\nvoid CEconWearable::Equip( CBasePlayer *pPlayer )\n{\n\tif ( pPlayer )\n\t{\n\t\tFollowEntity( pPlayer, true );\n\t\tSetOwnerEntity( pPlayer );\n\t\tChangeTeam( pPlayer->GetTeamNumber() );\n\n\t\t// Extra wearables don't provide attribute bonuses\n\t\tif ( !IsExtraWearable() )\n\t\t\tReapplyProvision();\n\t}\n}\n\nvoid CEconWearable::UnEquip( CBasePlayer *pPlayer )\n{\n\tif ( pPlayer )\n\t{\n\t\tStopFollowingEntity();\n\n\t\tSetOwnerEntity( NULL );\n\t\tReapplyProvision();\n\t}\n}\n#else\n\nvoid CEconWearable::OnDataChanged( DataUpdateType_t type )\n{\n\tBaseClass::OnDataChanged( type );\n\tif ( type == DATA_UPDATE_DATATABLE_CHANGED )\n\t{\n\t\tif (Q_stricmp(m_ParticleName, \"\") && !m_pUnusualParticle)\n\t\t{\n\t\t\tm_pUnusualParticle = ParticleProp()->Create(m_ParticleName, PATTACH_ABSORIGIN_FOLLOW);\n\t\t}\n\t}\n}\n\nShadowType_t CEconWearable::ShadowCastType( void )\n{\n\tif ( ShouldDraw() )\n\t{\n\t\treturn SHADOWS_RENDER_TO_TEXTURE_DYNAMIC;\n\t}\n\n\treturn SHADOWS_NONE;\n}\n\nbool CEconWearable::ShouldDraw( void )\n{\n\tCBasePlayer *pOwner = ToBasePlayer( GetOwnerEntity() );\n\n\tif ( !pOwner )\n\t\treturn false;\n\n\tif ( !pOwner->ShouldDrawThisPlayer() )\n\t\treturn false;\n\n\tif ( !pOwner->IsAlive() )\n\t\treturn false;\n\n\treturn BaseClass::ShouldDraw();\n}\n\n#endif\n\n\n<|start_filename|>src/game/shared/econ/econ_entity.h<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: \n//\n//===========================================================================//\n\n#ifndef ECON_ENTITY_H\n#define ECON_ENTITY_H\n#ifdef _WIN32\n#pragma once\n#endif\n\n#if defined( CLIENT_DLL )\n#define CEconEntity C_EconEntity\n#endif\n\n#include \"ihasattributes.h\"\n#include \"econ_item_view.h\"\n#include \"attribute_manager.h\"\n\n#ifdef CLIENT_DLL\n#include \"c_tf_viewmodeladdon.h\"\n#endif\n\nstruct wearableanimplayback_t\n{\n\tint iStub;\n};\n\n//-----------------------------------------------------------------------------\n// Purpose: BaseCombatWeapon is derived from this in live tf2.\n//-----------------------------------------------------------------------------\nclass CEconEntity : public CBaseAnimating, public IHasAttributes\n{\n\tDECLARE_CLASS( CEconEntity, CBaseAnimating );\n\tDECLARE_NETWORKCLASS();\n\n#ifdef CLIENT_DLL\n\tDECLARE_PREDICTABLE();\n#endif\n\npublic:\n\tCEconEntity();\n\t~CEconEntity();\n\n#ifdef CLIENT_DLL\n\tvirtual void OnPreDataChanged( DataUpdateType_t );\n\tvirtual void OnDataChanged( DataUpdateType_t );\n\tvirtual void FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options );\n\tvirtual bool OnFireEvent( C_BaseViewModel *pViewModel, const Vector& origin, const QAngle& angles, int event, const char *options );\n\n\tvirtual C_ViewmodelAttachmentModel *GetViewmodelAddon( void ) { return NULL; }\n\n\tvirtual bool OnInternalDrawModel( ClientModelRenderInfo_t *pInfo );\n\tvirtual void ViewModelAttachmentBlending( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask );\n#endif\n\n\tvirtual int TranslateViewmodelHandActivity( int iActivity ) { return iActivity; }\n\n\tvirtual void PlayAnimForPlaybackEvent(wearableanimplayback_t iPlayback) {};\n\n\tvirtual void SetItem( CEconItemView &newItem );\n\tCEconItemView *GetItem();\n\tvirtual bool HasItemDefinition() const;\n\tvirtual int GetItemID();\n\n\tvirtual void GiveTo( CBaseEntity *pEntity );\n\n\tvirtual CAttributeManager *GetAttributeManager() { return &m_AttributeManager; }\n\tvirtual CAttributeContainer *GetAttributeContainer() { return &m_AttributeManager; }\n\tvirtual CBaseEntity *GetAttributeOwner() { return NULL; }\n\tvirtual void ReapplyProvision( void );\n\n\tvoid UpdatePlayerModelToClass( void );\n\n\tvirtual void UpdatePlayerBodygroups( void );\n\n\tvirtual void UpdateOnRemove( void );\n\nprotected:\n\tEHANDLE m_hOldOwner;\n\tCEconItemView m_Item;\n\nprivate:\n\tCNetworkVarEmbedded( CAttributeContainer, m_AttributeManager );\n};\n\n#ifdef CLIENT_DLL\nvoid DrawEconEntityAttachedModels( C_BaseAnimating *pAnimating, C_EconEntity *pEconEntity, ClientModelRenderInfo_t const *pInfo, int iModelType );\n#endif\n#endif\n\n\n<|start_filename|>src/game/client/c_stickybolt.cpp<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: Implements the Sticky Bolt code. This constraints ragdolls to the world\n//\t\t\tafter being hit by a crossbow bolt. If something here is acting funny\n//\t\t\tlet me know - Adrian.\n//\n// $Workfile: $\n// $Date: $\n//\n//-----------------------------------------------------------------------------\n// $Log: $\n//\n// $NoKeywords: $\n//=============================================================================//\n#include \"cbase.h\"\n#include \"c_basetempentity.h\"\n#include \"fx.h\"\n#include \"decals.h\"\n#include \"iefx.h\"\n#include \"engine/IEngineSound.h\"\n#include \"materialsystem/imaterialvar.h\"\n#include \"IEffects.h\"\n#include \"engine/IEngineTrace.h\"\n#include \"vphysics/constraints.h\"\n#include \"engine/ivmodelinfo.h\"\n#include \"tempent.h\"\n#include \"c_te_legacytempents.h\"\n#include \"engine/ivdebugoverlay.h\"\n#include \"c_te_effect_dispatch.h\"\n#include \"c_tf_player.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\nextern IPhysicsSurfaceProps *physprops;\nIPhysicsObject *GetWorldPhysObject( void );\n\nextern ITempEnts* tempents;\n\nclass CRagdollBoltEnumerator : public IPartitionEnumerator\n{\npublic:\n\t//Forced constructor \n\tCRagdollBoltEnumerator( Ray_t& shot, Vector vOrigin )\n\t{\n\t\tm_rayShot = shot;\n\t\tm_vWorld = vOrigin;\n\t}\n\n\t//Actual work code\n\tIterationRetval_t EnumElement( IHandleEntity *pHandleEntity )\n\t{\n\t\tC_BaseEntity *pEnt = ClientEntityList().GetBaseEntityFromHandle( pHandleEntity->GetRefEHandle() );\n\t\tif ( pEnt == NULL )\n\t\t\treturn ITERATION_CONTINUE;\n\n\t\tC_BaseAnimating *pModel = static_cast< C_BaseAnimating * >( pEnt );\n\n\t\tif ( pModel == NULL )\n\t\t\treturn ITERATION_CONTINUE;\n\n\t\ttrace_t tr;\n\t\tenginetrace->ClipRayToEntity( m_rayShot, MASK_SHOT, pModel, &tr );\n\n\t\tIPhysicsObject\t*pPhysicsObject = NULL;\n\t\t\n\t\t//Find the real object we hit.\n\t\tif( tr.physicsbone >= 0 )\n\t\t{\n\t\t\t//Msg( \"\\nPhysics Bone: %i\\n\", tr.physicsbone );\n\t\t\tif ( pModel->m_pRagdoll )\n\t\t\t{\n\t\t\t\tCRagdoll *pCRagdoll = dynamic_cast < CRagdoll * > ( pModel->m_pRagdoll );\n\n\t\t\t\tif ( pCRagdoll )\n\t\t\t\t{\n\t\t\t\t\tragdoll_t *pRagdollT = pCRagdoll->GetRagdoll();\n\n\t\t\t\t\tif ( tr.physicsbone < pRagdollT->listCount )\n\t\t\t\t\t{\n\t\t\t\t\t\tpPhysicsObject = pRagdollT->list[tr.physicsbone].pObject;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( pPhysicsObject == NULL )\n\t\t\treturn ITERATION_CONTINUE;\n\n\t\tif ( tr.fraction < 1.0 )\n\t\t{\n\t\t\tIPhysicsObject *pReference = GetWorldPhysObject();\n\n\t\t\tif ( pReference == NULL || pPhysicsObject == NULL )\n\t\t\t\t return ITERATION_CONTINUE;\n\t\t\t\n\t\t\tfloat flMass = pPhysicsObject->GetMass();\n\t\t\tpPhysicsObject->SetMass( flMass * 2 );\n\n\t\t\tconstraint_ballsocketparams_t ballsocket;\n\t\t\tballsocket.Defaults();\n\t\t\n\t\t\tpReference->WorldToLocal( &ballsocket.constraintPosition[0], m_vWorld );\n\t\t\tpPhysicsObject->WorldToLocal( &ballsocket.constraintPosition[1], tr.endpos );\n\t\n\t\t\tphysenv->CreateBallsocketConstraint( pReference, pPhysicsObject, NULL, ballsocket );\n\n\t\t\t//Play a sound\n\t\t\t/*CPASAttenuationFilter filter( pEnt );\n\n\t\t\tEmitSound_t ep;\n\t\t\tep.m_nChannel = CHAN_VOICE;\n\t\t\tep.m_pSoundName = \"Weapon_Crossbow.BoltSkewer\";\n\t\t\tep.m_flVolume = 1.0f;\n\t\t\tep.m_SoundLevel = SNDLVL_NORM;\n\t\t\tep.m_pOrigin = &pEnt->GetAbsOrigin();\n\n\t\t\tC_BaseEntity::EmitSound( filter, SOUND_FROM_WORLD, ep );*/\n\t\n\t\t\treturn ITERATION_STOP;\n\t\t}\n\n\t\treturn ITERATION_CONTINUE;\n\t}\n\nprivate:\n\tRay_t\tm_rayShot;\n\tVector m_vWorld;\n};\n\nvoid CreateCrossbowBolt( const Vector &vecOrigin, const Vector &vecDirection )\n{\n\t//model_t *pModel = (model_t *)engine->LoadModel( \"models/crossbow_bolt.mdl\" );\n\n\t//repurpose old crossbow collision code for huntsman collisions\n\tmodel_t *pModel = (model_t *)engine->LoadModel( \"models/weapons/w_models/w_arrow.mdl\" );\n\n\tQAngle vAngles;\n\n\tVectorAngles( vecDirection, vAngles );\n\n\ttempents->SpawnTempModel( pModel, vecOrigin - vecDirection * 8, vAngles, Vector( 0, 0, 0 ), 30.0f, FTENT_NONE );\n\n}\n\nvoid StickRagdollNow( const Vector &vecOrigin, const Vector &vecDirection )\n{\n\tRay_t\tshotRay;\n\ttrace_t tr;\n\t\n\tUTIL_TraceLine( vecOrigin, vecOrigin + vecDirection * 16, MASK_SOLID_BRUSHONLY, NULL, COLLISION_GROUP_NONE, &tr );\n\n\tif ( tr.surface.flags & SURF_SKY )\n\t\treturn;\n\n\tVector vecEnd = vecOrigin - vecDirection * 128;\n\n\tshotRay.Init( vecOrigin, vecEnd );\n\n\tCRagdollBoltEnumerator\tragdollEnum( shotRay, vecOrigin );\n\tpartition->EnumerateElementsAlongRay( PARTITION_CLIENT_RESPONSIVE_EDICTS, shotRay, false, &ragdollEnum );\n\t\n\tCreateCrossbowBolt( vecOrigin, vecDirection );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : &data - \n//-----------------------------------------------------------------------------\nvoid StickyBoltCallback( const CEffectData &data )\n{\n\t StickRagdollNow( data.m_vOrigin, data.m_vNormal );\n}\n\nDECLARE_CLIENT_EFFECT( \"BoltImpact\", StickyBoltCallback );\n\n<|start_filename|>src/game/shared/econ/econ_item_view.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"econ_item_view.h\"\n#include \"econ_item_system.h\"\n#include \"activitylist.h\"\n\n#ifdef CLIENT_DLL\n#include \"dt_utlvector_recv.h\"\n#else\n#include \"dt_utlvector_send.h\"\n#endif\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n#define MAX_ATTRIBUTES_SENT 20\n\n#ifdef CLIENT_DLL\nBEGIN_RECV_TABLE_NOBASE(CEconItemView, DT_ScriptCreatedItem)\n\tRecvPropInt(RECVINFO(m_iItemDefinitionIndex)),\n\tRecvPropInt(RECVINFO(m_iEntityQuality)),\n\tRecvPropInt(RECVINFO(m_iEntityLevel)),\n\tRecvPropInt(RECVINFO(m_iItemID)),\n\tRecvPropInt(RECVINFO(m_iInventoryPosition)),\n\tRecvPropInt(RECVINFO(m_iTeamNumber)),\n\tRecvPropBool(RECVINFO(m_bOnlyIterateItemViewAttributes)),\n\tRecvPropUtlVector( \n\tRECVINFO_UTLVECTOR( m_AttributeList ),\n\tMAX_ATTRIBUTES_SENT,\n\tRecvPropDataTable( NULL, 0, 0, &REFERENCE_RECV_TABLE( DT_EconItemAttribute ) ) )\nEND_RECV_TABLE()\n#else\nBEGIN_SEND_TABLE_NOBASE(CEconItemView, DT_ScriptCreatedItem)\n\tSendPropInt(SENDINFO(m_iItemDefinitionIndex)),\n\tSendPropInt(SENDINFO(m_iEntityQuality)),\n\tSendPropInt(SENDINFO(m_iEntityLevel)),\n\tSendPropInt(SENDINFO(m_iItemID)),\n\tSendPropInt(SENDINFO(m_iInventoryPosition)),\n\tSendPropInt(SENDINFO(m_iTeamNumber)),\n\tSendPropBool(SENDINFO(m_bOnlyIterateItemViewAttributes)),\n\tSendPropUtlVector( \n\tSENDINFO_UTLVECTOR( m_AttributeList ),\n\tMAX_ATTRIBUTES_SENT,\n\tSendPropDataTable( NULL, 0, &REFERENCE_SEND_TABLE( DT_EconItemAttribute ) ) )\nEND_SEND_TABLE()\n#endif\n\n#define FIND_ELEMENT(map, key, val)\t\t\t\t\t\t\\\n\t\tunsigned int index = map.Find(key);\t\t\t\t\\\n\t\tif (index != map.InvalidIndex())\t\t\t\t\t\t\\\n\t\t\tval = map.Element(index)\t\t\t\t\n\n#define FIND_ELEMENT_STRING(map, key, val)\t\t\t\t\t\t\\\n\t\tunsigned int index = map.Find(key);\t\t\t\t\t\t\\\n\t\tif (index != map.InvalidIndex())\t\t\t\t\t\t\t\t\\\n\t\t\tQ_snprintf(val, sizeof(val), map.Element(index))\n\n\nCEconItemView::CEconItemView()\n{\n\tInit( -1 );\n}\n\n\nCEconItemView::CEconItemView( int iItemID )\n{\n\tInit( iItemID );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CEconItemView::Init( int iItemID )\n{\n\tSetItemDefIndex( iItemID );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CEconItemView::SetItemDefIndex( int iItemID )\n{\n\tm_iItemDefinitionIndex = iItemID;\n\t//m_pItemDef = GetItemSchema()->GetItemDefinition( m_iItemDefinitionIndex );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nint CEconItemView::GetItemDefIndex( void ) const\n{\n\treturn m_iItemDefinitionIndex;\n}\n\nCEconItemDefinition *CEconItemView::GetStaticData( void ) const\n{\n\treturn GetItemSchema()->GetItemDefinition( m_iItemDefinitionIndex );\n}\n\nconst char *CEconItemView::GetWorldDisplayModel( int iClass/* = 0*/ ) const\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\tconst char *pszModelName = NULL;\n\n\tif ( pStatic )\n\t{\n\t\tpszModelName = pStatic->model_world;\n\n\t\t// Assuming we're using same model for both 1st person and 3rd person view.\n\t\tif ( !pszModelName[0] && pStatic->attach_to_hands == 1 )\n\t\t{\n\t\t\tpszModelName = pStatic->model_player;\n\t\t}\n\t}\n\n\treturn pszModelName;\n}\n\nconst char *CEconItemView::GetPlayerDisplayModel( int iClass/* = 0*/ ) const\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tif ( pStatic->model_player_per_class[iClass][0] != '\\0' )\n\t\t\treturn pStatic->model_player_per_class[iClass];\n\n\t\treturn pStatic->model_player;\n\t}\n\n\treturn NULL;\n}\n\nconst char* CEconItemView::GetEntityName()\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\treturn pStatic->item_class;\n\t}\n\n\treturn NULL;\n}\n\nbool CEconItemView::IsCosmetic()\n{\n\tbool result = false;\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tFIND_ELEMENT( pStatic->tags, \"is_cosmetic\", result );\n\t}\n\n\treturn result;\n}\n\nint CEconItemView::GetAnimationSlot( void )\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\treturn pStatic->anim_slot;\n\t}\n\n\treturn -1;\n}\n\nActivity CEconItemView::GetActivityOverride( int iTeamNumber, Activity actOriginalActivity )\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tint iOverridenActivity = ACT_INVALID;\n\n\t\tEconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNumber );\n\t\tFIND_ELEMENT( pVisuals->animation_replacement, actOriginalActivity, iOverridenActivity );\n\n\t\tif ( iOverridenActivity != ACT_INVALID )\n\t\t\treturn (Activity)iOverridenActivity;\n\t}\n\n\treturn actOriginalActivity;\n}\n\nconst char *CEconItemView::GetActivityOverride( int iTeamNumber, const char *name )\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tint iOriginalAct = ActivityList_IndexForName( name );\n\t\tint iOverridenAct = ACT_INVALID;\n\t\tEconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNumber );\n\n\t\tFIND_ELEMENT( pVisuals->animation_replacement, iOriginalAct, iOverridenAct );\n\n\t\tif ( iOverridenAct != ACT_INVALID )\n\t\t\treturn ActivityList_NameForIndex( iOverridenAct );\n\t}\n\n\treturn name;\n}\n\nconst char *CEconItemView::GetSoundOverride( int iIndex, int iTeamNum /*= 0*/ ) const\n{\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tEconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNum );\n\t\treturn pVisuals->aWeaponSounds[iIndex];\n\t}\n\n\treturn NULL;\n}\n\nbool CEconItemView::HasCapability( const char* name )\n{\n\tbool result = false;\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tFIND_ELEMENT( pStatic->capabilities, name, result );\n\t}\n\n\treturn result;\n}\n\nbool CEconItemView::HasTag( const char* name )\n{\n\tbool result = false;\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic )\n\t{\n\t\tFIND_ELEMENT( pStatic->tags, name, result );\n\t}\n\n\treturn result;\n}\n\nbool CEconItemView::AddAttribute( CEconItemAttribute *pAttribute )\n{\n\t// Make sure this attribute exists.\n\tEconAttributeDefinition *pAttribDef = pAttribute->GetStaticData();\n\n\tif ( pAttribDef )\n\t{\n\t\tm_AttributeList.AddToTail( *pAttribute );\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid CEconItemView::SkipBaseAttributes( bool bSkip )\n{\n\tm_bOnlyIterateItemViewAttributes = bSkip;\n}\n\nCEconItemAttribute *CEconItemView::IterateAttributes( string_t strClass )\n{\n\t// Returning the first attribute found.\n\t// This is not how live TF2 does this but this will do for now.\n\tfor ( int i = 0; i < m_AttributeList.Count(); i++ )\n\t{\n\t\tCEconItemAttribute *pAttribute = &m_AttributeList[i];\n\n\t\tif ( pAttribute->m_strAttributeClass == strClass )\n\t\t{\n\t\t\treturn pAttribute;\n\t\t}\n\t}\n\n\tCEconItemDefinition *pStatic = GetStaticData();\n\n\tif ( pStatic && !m_bOnlyIterateItemViewAttributes )\n\t{\n\t\treturn pStatic->IterateAttributes( strClass );\n\t}\n\n\treturn NULL;\n}\n\n\n<|start_filename|>src/game/shared/econ/attribute_manager.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"attribute_manager.h\"\n#include \"econ_item_schema.h\"\n\n#ifdef CLIENT_DLL\n#include \"prediction.h\"\n#endif\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n#define ATTRIB_REAPPLY_PARITY_BITS 3\n\nBEGIN_NETWORK_TABLE_NOBASE( CAttributeManager, DT_AttributeManager )\n#ifdef CLIENT_DLL\n\tRecvPropEHandle( RECVINFO( m_hOuter ) ),\n\tRecvPropInt( RECVINFO( m_iReapplyProvisionParity ) ),\n#else\n\tSendPropEHandle( SENDINFO( m_hOuter ) ),\n\tSendPropInt( SENDINFO( m_iReapplyProvisionParity ), ATTRIB_REAPPLY_PARITY_BITS, SPROP_UNSIGNED ),\n#endif\nEND_NETWORK_TABLE()\n\nCAttributeManager::CAttributeManager()\n{\n\tm_bParsingMyself = false;\n\tm_iReapplyProvisionParity = 0;\n}\n\n#ifdef CLIENT_DLL\nvoid CAttributeManager::OnPreDataChanged( DataUpdateType_t updateType )\n{\n\tm_iOldReapplyProvisionParity = m_iReapplyProvisionParity;\n}\n\nvoid CAttributeManager::OnDataChanged( DataUpdateType_t updateType )\n{\n\t// If parity ever falls out of sync we can catch up here.\n\tif ( m_iReapplyProvisionParity != m_iOldReapplyProvisionParity )\n\t{\n\t\tif ( m_hOuter )\n\t\t{\n\t\t\tIHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr();\n\t\t\tpAttributes->ReapplyProvision();\n\t\t\tm_iOldReapplyProvisionParity = m_iReapplyProvisionParity;\n\t\t}\n\t}\n}\n\n#endif\n\nvoid CAttributeManager::AddProvider( CBaseEntity *pEntity )\n{\n\tm_AttributeProviders.AddToTail( pEntity );\n}\n\nvoid CAttributeManager::RemoveProvider( CBaseEntity *pEntity )\n{\n\tm_AttributeProviders.FindAndRemove( pEntity );\n}\n\nvoid CAttributeManager::ProviteTo( CBaseEntity *pEntity )\n{\n\tif ( !pEntity || !m_hOuter.Get() )\n\t\treturn;\n\n\tIHasAttributes *pAttributes = pEntity->GetHasAttributesInterfacePtr();\n\n\tif ( pAttributes )\n\t{\n\t\tpAttributes->GetAttributeManager()->AddProvider( m_hOuter.Get() );\n\t}\n\n#ifdef CLIENT_DLL\n\tif ( prediction->InPrediction() )\n#endif\n\tm_iReapplyProvisionParity = ( m_iReapplyProvisionParity + 1 ) & ( ( 1 << ATTRIB_REAPPLY_PARITY_BITS ) - 1 );\n}\n\nvoid CAttributeManager::StopProvidingTo( CBaseEntity *pEntity )\n{\n\tif ( !pEntity || !m_hOuter.Get() )\n\t\treturn;\n\n\tIHasAttributes *pAttributes = pEntity->GetHasAttributesInterfacePtr();\n\n\tif ( pAttributes )\n\t{\n\t\tpAttributes->GetAttributeManager()->RemoveProvider( m_hOuter.Get() );\n\t}\n\n#ifdef CLIENT_DLL\n\tif ( prediction->InPrediction() )\n#endif\n\tm_iReapplyProvisionParity = ( m_iReapplyProvisionParity + 1 ) & ( ( 1 << ATTRIB_REAPPLY_PARITY_BITS ) - 1 );\n}\n\nvoid CAttributeManager::InitializeAttributes( CBaseEntity *pEntity )\n{\n\tAssert( pEntity->GetHasAttributesInterfacePtr() != NULL );\n\n\tm_hOuter.Set( pEntity );\n\tm_bParsingMyself = false;\n}\n\nfloat CAttributeManager::ApplyAttributeFloat( float flValue, const CBaseEntity *pEntity, string_t strAttributeClass )\n{\n\tif ( m_bParsingMyself || m_hOuter.Get() == NULL )\n\t{\n\t\treturn flValue;\n\t}\n\n\t// Safeguard to prevent potential infinite loops.\n\tm_bParsingMyself = true;\n\n\tfor ( int i = 0; i < m_AttributeProviders.Count(); i++ )\n\t{\n\t\tCBaseEntity *pProvider = m_AttributeProviders[i].Get();\n\n\t\tif ( !pProvider || pProvider == pEntity )\n\t\t\tcontinue;\n\n\t\tIHasAttributes *pAttributes = pProvider->GetHasAttributesInterfacePtr();\n\n\t\tif ( pAttributes )\n\t\t{\n\t\t\tflValue = pAttributes->GetAttributeManager()->ApplyAttributeFloat( flValue, pEntity, strAttributeClass );\n\t\t}\n\t}\n\n\tIHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr();\n\tCBaseEntity *pOwner = pAttributes->GetAttributeOwner();\n\n\tif ( pOwner )\n\t{\n\t\tIHasAttributes *pOwnerAttrib = pOwner->GetHasAttributesInterfacePtr();\n\t\tif ( pOwnerAttrib )\n\t\t{\n\t\t\tflValue = pOwnerAttrib->GetAttributeManager()->ApplyAttributeFloat( flValue, pEntity, strAttributeClass );\n\t\t}\n\t}\n\n\tm_bParsingMyself = false;\n\n\treturn flValue;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Search for an attribute on our providers.\n//-----------------------------------------------------------------------------\nstring_t CAttributeManager::ApplyAttributeString( string_t strValue, const CBaseEntity *pEntity, string_t strAttributeClass )\n{\n\tif ( m_bParsingMyself || m_hOuter.Get() == NULL )\n\t{\n\t\treturn strValue;\n\t}\n\t// Safeguard to prevent potential infinite loops.\n\tm_bParsingMyself = true;\n\tfor ( int i = 0; i < m_AttributeProviders.Count(); i++ )\n\t{\n\t\tCBaseEntity *pProvider = m_AttributeProviders[i].Get();\n\t\tif ( !pProvider || pProvider == pEntity )\n\t\t\tcontinue;\n\t\tIHasAttributes *pAttributes = pProvider->GetHasAttributesInterfacePtr();\n\t\tif ( pAttributes )\n\t\t{\n\t\t\tstrValue = pAttributes->GetAttributeManager()->ApplyAttributeString( strValue, pEntity, strAttributeClass );\n\t\t}\n\t}\n\tIHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr();\n\tCBaseEntity *pOwner = pAttributes->GetAttributeOwner();\n\tif ( pOwner )\n\t{\n\t\tIHasAttributes *pOwnerAttrib = pOwner->GetHasAttributesInterfacePtr();\n\t\tif ( pOwnerAttrib )\n\t\t{\n\t\t\tstrValue = pOwnerAttrib->GetAttributeManager()->ApplyAttributeString( strValue, pEntity, strAttributeClass );\n\t\t}\n\t}\n\tm_bParsingMyself = false;\n\treturn strValue;\n}\n\n\nBEGIN_NETWORK_TABLE_NOBASE( CAttributeContainer, DT_AttributeContainer )\n#ifdef CLIENT_DLL\n\tRecvPropEHandle( RECVINFO( m_hOuter ) ),\n\tRecvPropInt( RECVINFO( m_iReapplyProvisionParity ) ),\n#else\n\tSendPropEHandle( SENDINFO( m_hOuter ) ),\n\tSendPropInt( SENDINFO( m_iReapplyProvisionParity ), ATTRIB_REAPPLY_PARITY_BITS, SPROP_UNSIGNED ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef CLIENT_DLL\nBEGIN_PREDICTION_DATA_NO_BASE( CAttributeContainer )\n\tDEFINE_PRED_FIELD( m_iReapplyProvisionParity, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ),\nEND_PREDICTION_DATA()\n#endif\n\nCAttributeContainer::CAttributeContainer()\n{\n\n}\n\nfloat CAttributeContainer::ApplyAttributeFloat( float flValue, const CBaseEntity *pEntity, string_t strAttributeClass )\n{\n\tif ( m_bParsingMyself || m_hOuter.Get() == NULL )\n\t\treturn flValue;\n\n\tm_bParsingMyself = true;;\n\n\t// This should only ever be used by econ entities.\n\tCEconEntity *pEconEnt = assert_cast( m_hOuter.Get() );\n\tCEconItemView *pItem = pEconEnt->GetItem();\n\n\tCEconItemAttribute *pAttribute = pItem->IterateAttributes( strAttributeClass );\n\n\tif ( pAttribute )\n\t{\n\t\tEconAttributeDefinition *pStatic = pAttribute->GetStaticData();\n\n\t\tswitch ( pStatic->description_format )\n\t\t{\n\t\tcase ATTRIB_FORMAT_ADDITIVE:\n\t\tcase ATTRIB_FORMAT_ADDITIVE_PERCENTAGE:\n\t\t\tflValue += pAttribute->value;\n\t\t\tbreak;\n\t\tcase ATTRIB_FORMAT_PERCENTAGE:\n\t\tcase ATTRIB_FORMAT_INVERTED_PERCENTAGE:\n\t\t\tflValue *= pAttribute->value;\n\t\t\tbreak;\n\t\tcase ATTRIB_FORMAT_OR:\n\t\tdefault:\n\t\t{\n\t\t\t// Oh, man...\n\t\t\tint iValue = (int)flValue;\n\t\t\tint iAttrib = (int)pAttribute->value;\n\t\t\tiValue |= iAttrib;\n\t\t\tflValue = (float)iValue;\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t}\n\n\tm_bParsingMyself = false;\n\n\treturn BaseClass::ApplyAttributeFloat( flValue, pEntity, strAttributeClass );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Search for an attribute and apply its value.\n//-----------------------------------------------------------------------------\nstring_t CAttributeContainer::ApplyAttributeString( string_t strValue, const CBaseEntity *pEntity, string_t strAttributeClass )\n{\n\tif ( m_bParsingMyself || m_hOuter.Get() == NULL )\n\t\treturn strValue;\n\tm_bParsingMyself = true;;\n\t// This should only ever be used by econ entities.\n\tCEconEntity *pEconEnt = assert_cast( m_hOuter.Get() );\n\tCEconItemView *pItem = pEconEnt->GetItem();\n\tCEconItemAttribute *pAttribute = pItem->IterateAttributes( strAttributeClass );\n\tif ( pAttribute )\n\t{\n\t\tstrValue = AllocPooledString( pAttribute->value_string.Get() );\n\t}\n\tm_bParsingMyself = false;\n\treturn BaseClass::ApplyAttributeString( strValue, pEntity, strAttributeClass );\n}\n\n\n<|start_filename|>src/game/client/tf/vgui/panels/tf_itemtooltippanel.h<|end_filename|>\n#ifndef TF_ITEMMODELTOOLTIPPANEL_H\n#define TF_ITEMMODELTOOLTIPPANEL_H\n\n#include \"tf_dialogpanelbase.h\"\n#include \"tf_tooltippanel.h\"\n\nclass CTFAdvModelPanel;\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nclass CTFItemToolTipPanel : public CTFToolTipPanel\n{\n\tDECLARE_CLASS_SIMPLE( CTFItemToolTipPanel, CTFToolTipPanel );\n\npublic:\n\tCTFItemToolTipPanel( vgui::Panel* parent, const char *panelName );\n\tvirtual bool Init();\n\tvirtual ~CTFItemToolTipPanel();\n\tvirtual void PerformLayout();\n\tvirtual void ApplySchemeSettings( vgui::IScheme *pScheme );\n\tvirtual void OnChildSettingsApplied( KeyValues *pInResourceData, Panel *pChild );\n\tvirtual void Show();\n\tvirtual void Hide();\n\tvirtual void ShowToolTip( CEconItemDefinition *pItemData );\n\tvirtual void HideToolTip();\n\nprivate:\n\tint iItemID;\n\tCExLabel\t*m_pTitle;\n\tCExLabel\t*m_pClassName;\n\tCExLabel\t*m_pAttributeText;\n\tCTFAdvModelPanel *m_pClassModelPanel;\n\tCUtlVector m_pAttributes;\n\tColor\tm_colorTitle;\n};\n\n#endif // TF_ITEMMODELTOOLTIPPANEL_H\n\n<|start_filename|>src/game/shared/tf/tf_projectile_stunball.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"tf_projectile_stunball.h\"\n#include \"tf_gamerules.h\"\n#include \"effect_dispatch_data.h\"\n#include \"tf_weapon_bat.h\"\n\n#ifdef GAME_DLL\n#include \"tf_fx.h\"\n#include \"tf_gamestats.h\"\n#else\n#include \"particles_new.h\"\n#endif\n\n\n#define TF_STUNBALL_MODEL\t \"models/weapons/w_models/w_baseball.mdl\"\n#define TF_STUNBALL_LIFETIME 15.0f\n\nConVar tf_scout_stunball_base_duration( \"tf_scout_stunball_base_duration\", \"6.0\", FCVAR_NOTIFY | FCVAR_REPLICATED, \"Modifies stun duration of stunball\" );\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFStunBall, DT_TFStunBall )\n\nBEGIN_NETWORK_TABLE( CTFStunBall, DT_TFStunBall )\n#ifdef CLIENT_DLL\n\tRecvPropBool( RECVINFO( m_bCritical ) ),\n#else\n\tSendPropBool( SENDINFO( m_bCritical ) ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef GAME_DLL\nBEGIN_DATADESC( CTFStunBall )\nEND_DATADESC()\n#endif\n\nLINK_ENTITY_TO_CLASS( tf_projectile_stunball, CTFStunBall );\nPRECACHE_REGISTER( tf_projectile_stunball );\n\nCTFStunBall::CTFStunBall()\n{\n}\n\nCTFStunBall::~CTFStunBall()\n{\n#ifdef CLIENT_DLL\n\tParticleProp()->StopEmission();\n#endif\n}\n\n#ifdef GAME_DLL\nCTFStunBall *CTFStunBall::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo )\n{\n\tCTFStunBall *pStunBall = static_cast( CBaseEntity::CreateNoSpawn( \"tf_projectile_stunball\", vecOrigin, vecAngles, pOwner ) );\n\n\tif ( pStunBall )\n\t{\n\t\t// Set scorer.\n\t\tpStunBall->SetScorer( pScorer );\n\n\t\t// Set firing weapon.\n\t\tpStunBall->SetLauncher( pWeapon );\n\n\t\tDispatchSpawn( pStunBall );\n\n\t\tpStunBall->InitGrenade( vecVelocity, angVelocity, pOwner, weaponInfo );\n\n\t\tpStunBall->ApplyLocalAngularVelocityImpulse( angVelocity );\n\t}\n\n\treturn pStunBall;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFStunBall::Precache( void )\n{\n\tPrecacheModel( TF_STUNBALL_MODEL );\n\tPrecacheScriptSound( \"TFPlayer.StunImpactRange\" );\n\tPrecacheScriptSound( \"TFPlayer.StunImpact\" );\n\n\tPrecacheTeamParticles( \"stunballtrail_%s\", false );\n\tPrecacheTeamParticles( \"stunballtrail_%s_crit\", false );\n\n\tBaseClass::Precache();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFStunBall::Spawn( void )\n{\n\tSetModel( TF_STUNBALL_MODEL );\n\tSetDetonateTimerLength( TF_STUNBALL_LIFETIME );\n\n\tBaseClass::Spawn();\n\tSetTouch( &CTFStunBall::StunBallTouch );\n\n\tCreateTrail();\n\n\t// Pumpkin Bombs\n\tAddFlag( FL_GRENADE );\n\n\t// Don't collide with anything for a short time so that we never get stuck behind surfaces\n\tSetCollisionGroup( TFCOLLISION_GROUP_NONE );\n\n\tAddSolidFlags( FSOLID_TRIGGER );\n\n\tm_flCreationTime = gpGlobals->curtime;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::Explode( trace_t *pTrace, int bitsDamageType )\n{\n\tm_takedamage = DAMAGE_NO;\n\n\t// Pull out of the wall a bit\n\tif ( pTrace->fraction != 1.0 )\n\t{\n\t\tSetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) );\n\t}\n\n\tCTFWeaponBase *pWeapon = dynamic_cast< CTFWeaponBase * >( m_hLauncher.Get() );\n\n\t// Pull out a bit.\n\tif ( pTrace->fraction != 1.0 )\n\t{\n\t\tSetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) );\n\t}\n\n\t// Damage.\n\tCTFPlayer *pAttacker = dynamic_cast< CTFPlayer * >( GetThrower() );\n\tCTFPlayer *pPlayer = dynamic_cast< CTFPlayer * >( m_hEnemy.Get() );\n\n\t// Make sure the player is stunnable\n\tif ( pPlayer && pAttacker && CanStun( pPlayer ) )\n\t{\n\t\tfloat flAirTime = gpGlobals->curtime - m_flCreationTime;\n\t\tfloat flStunDuration = tf_scout_stunball_base_duration.GetFloat();\n\t\tVector vecDir = GetAbsOrigin();\n\t\tVectorNormalize( vecDir );\n\n\t\t// Do damage.\n\t\tCTakeDamageInfo info( this, pAttacker, pWeapon, GetDamage(), GetDamageType(), TF_DMG_CUSTOM_BASEBALL );\n\t\tCalculateBulletDamageForce( &info, pWeapon ? pWeapon->GetTFWpnData().iAmmoType : 0, vecDir, GetAbsOrigin() );\n\t\tinfo.SetReportedPosition( pAttacker ? pAttacker->GetAbsOrigin() : vec3_origin );\n\t\tpPlayer->DispatchTraceAttack( info, vecDir, pTrace );\n\t\tApplyMultiDamage();\n\n\t\tif ( flAirTime > 0.1f )\n\t\t{\n\n\t\t\tint iBonus = 1;\n\t\t\tif ( flAirTime >= 1.0f )\n\t\t\t{\n\t\t\t\t// Maximum stun is base duration + 1 second\n\t\t\t\tflAirTime = 1.0f;\n\t\t\t\tflStunDuration += 1.0f;\n\n\t\t\t\t// 2 points for moonshots\n\t\t\t\tiBonus++;\n\n\t\t\t\t// Big stun\n\t\t\t\tpPlayer->m_Shared.StunPlayer(flStunDuration * ( flAirTime ), 0.0f, 0.75f, TF_STUNFLAGS_BIGBONK, pAttacker );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Small stun\n\t\t\t\tpPlayer->m_Shared.StunPlayer(flStunDuration * ( flAirTime ), 0.8f, 0.0f, TF_STUNFLAGS_SMALLBONK, pAttacker );\n\t\t\t}\n\n\t\t\tpAttacker->SpeakConceptIfAllowed( MP_CONCEPT_STUNNED_TARGET );\n\n\t\t\t// Bonus points.\n\t\t\tIGameEvent *event_bonus = gameeventmanager->CreateEvent( \"player_bonuspoints\" );\n\t\t\tif ( event_bonus )\n\t\t\t{\n\t\t\t\tevent_bonus->SetInt( \"player_entindex\", pPlayer->entindex() );\n\t\t\t\tevent_bonus->SetInt( \"source_entindex\", pAttacker->entindex() );\n\t\t\t\tevent_bonus->SetInt( \"points\", iBonus );\n\n\t\t\t\tgameeventmanager->FireEvent( event_bonus );\n\t\t\t}\n\t\t\tCTF_GameStats.Event_PlayerAwardBonusPoints( pAttacker, pPlayer, iBonus );\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::StunBallTouch( CBaseEntity *pOther )\n{\n\t// Verify a correct \"other.\"\n\tif ( !pOther->IsSolid() || pOther->IsSolidFlagSet( FSOLID_VOLUME_CONTENTS ) )\n\t\treturn;\n\n\ttrace_t pTrace;\n\tVector velDir = GetAbsVelocity();\n\tVectorNormalize( velDir );\n\tVector vecSpot = GetAbsOrigin() - velDir * 32;\n\tUTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_NONE, &pTrace );\n\n\tCTFPlayer *pPlayer = dynamic_cast< CTFPlayer * >( pOther );\n\n\t// Make us solid once we reach our owner\n\tif ( GetCollisionGroup() == TFCOLLISION_GROUP_NONE )\n\t{\n\t\tif ( pOther == GetThrower() )\n\t\t\tSetCollisionGroup( COLLISION_GROUP_PROJECTILE );\n\n\t\treturn;\n\t}\n\n\t// Stun the person we hit\n\tif ( pPlayer && ( gpGlobals->curtime - m_flCreationTime > 0.2f || GetTeamNumber() != pPlayer->GetTeamNumber() ) )\n\t{\n\t\tif ( !m_bTouched )\n\t\t{\n\t\t\t// Save who we hit for calculations\n\t\t\tm_hEnemy = pOther;\n\t\t\tm_hSpriteTrail->SUB_FadeOut();\n\t\t\tExplode( &pTrace, GetDamageType() );\n\n\t\t\t// Die a little bit after the hit\n\t\t\tSetDetonateTimerLength( 3.0f );\n\t\t\tm_bTouched = true;\n\t\t}\n\n\t\tCTFWeaponBase *pWeapon = pPlayer->Weapon_GetWeaponByType( TF_WPN_TYPE_MELEE );\n\t\tif ( pWeapon && pWeapon->PickedUpBall( pPlayer ) )\n\t\t{\n\t\t\tUTIL_Remove( this );\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Check if this player can be stunned\n//-----------------------------------------------------------------------------\nbool CTFStunBall::CanStun( CTFPlayer *pOther )\n{\n\t// Dead players can't be stunned\n\tif ( !pOther->IsAlive() )\n\t\treturn false;\n\n\t// Don't stun team members\n\tif ( GetTeamNumber() == pOther->GetTeamNumber() )\n\t\treturn false;\n\n\t// Don't stun players we can't damage\n\tif ( pOther->m_Shared.InCond( TF_COND_INVULNERABLE ) || pOther->m_Shared.InCond( TF_COND_PHASE ) )\n\t\treturn false;\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::Detonate()\n{\n\tUTIL_Remove( this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )\n{\n\tBaseClass::VPhysicsCollision( index, pEvent );\n\n\tint otherIndex = !index;\n\tCBaseEntity *pHitEntity = pEvent->pEntities[otherIndex];\n\n\tif ( !pHitEntity )\n\t{\n\t\treturn;\n\t}\n\n\t// we've touched a surface\n\tm_bTouched = true;\n\t\n\t// Handle hitting skybox (disappear).\n\tsurfacedata_t *pprops = physprops->GetSurfaceData( pEvent->surfaceProps[otherIndex] );\n\tif ( pprops->game.material == 'X' )\n\t{\n\t\t// uncomment to destroy ball upon hitting sky brush\n\t\t//SetThink( &CTFGrenadePipebombProjectile::SUB_Remove );\n\t\t//SetNextThink( gpGlobals->curtime );\n\t\treturn;\n\t}\n\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFStunBall::SetScorer( CBaseEntity *pScorer )\n{\n\tm_Scorer = pScorer;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nCBasePlayer *CTFStunBall::GetAssistant( void )\n{\n\treturn dynamic_cast( m_Scorer.Get() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir )\n{\n\tIPhysicsObject *pPhysicsObject = VPhysicsGetObject();\n\tif ( pPhysicsObject )\n\t{\n\t\tVector vecOldVelocity, vecVelocity;\n\n\t\tpPhysicsObject->GetVelocity( &vecOldVelocity, NULL );\n\n\t\tfloat flVel = vecOldVelocity.Length();\n\n\t\tvecVelocity = vecDir;\n\t\tvecVelocity *= flVel;\n\t\tAngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) );\n\n\t\t// Now change grenade's direction.\n\t\tpPhysicsObject->SetVelocityInstantaneous( &vecVelocity, &angVelocity );\n\t}\n\n\tCBaseCombatCharacter *pBCC = pDeflectedBy->MyCombatCharacterPointer();\n\n\tIncremenentDeflected();\n\tm_hDeflectOwner = pDeflectedBy;\n\tSetThrower( pBCC );\n\tChangeTeam( pDeflectedBy->GetTeamNumber() );\n\n\t// Change trail color.\n\tif ( m_hSpriteTrail.Get() )\n\t{\n\t\tUTIL_Remove( m_hSpriteTrail.Get() );\n\t}\n\n\tCreateTrail();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint\tCTFStunBall::GetDamageType()\n{\n\tint iDmgType = BaseClass::GetDamageType();\n\n\tif ( m_bCritical )\n\t{\n\t\tiDmgType |= DMG_CRITICAL;\n\t}\n\tif ( m_iDeflected > 0 )\n\t{\n\t\tiDmgType |= DMG_MINICRITICAL;\n\t}\n\n\treturn iDmgType;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nconst char *CTFStunBall::GetTrailParticleName( void )\n{\n\treturn ConstructTeamParticle( \"effects/baseballtrail_%s.vmt\", GetTeamNumber(), false, g_aTeamNamesShort );\n}\n\n// ----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::CreateTrail( void )\n{\n\tCSpriteTrail *pTrail = CSpriteTrail::SpriteTrailCreate( GetTrailParticleName(), GetAbsOrigin(), true );\n\n\tif ( pTrail )\n\t{\n\t\tpTrail->FollowEntity( this );\n\t\tpTrail->SetTransparency( kRenderTransAlpha, 255, 255, 255, 128, kRenderFxNone );\n\t\tpTrail->SetStartWidth( 9.0f );\n\t\tpTrail->SetTextureResolution( 0.01f );\n\t\tpTrail->SetLifeTime( 0.4f );\n\t\tpTrail->TurnOn();\n\n\t\tpTrail->SetContextThink( &CBaseEntity::SUB_Remove, gpGlobals->curtime + 5.0f, \"RemoveThink\" );\n\n\t\tm_hSpriteTrail.Set( pTrail );\n\t}\n}\n#else\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::OnDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnDataChanged( updateType );\n\n\tif ( updateType == DATA_UPDATE_CREATED )\n\t{\n\t\tm_flCreationTime = gpGlobals->curtime;\n\t\tCreateTrails();\n\t}\n\n\tif ( m_iOldTeamNum && m_iOldTeamNum != m_iTeamNum )\n\t{\n\t\tParticleProp()->StopEmission();\n\t\tCreateTrails();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFStunBall::CreateTrails( void )\n{\n\tif ( IsDormant() )\n\treturn;\n\n\tif ( m_bCritical )\n\t{\n\t\tconst char *pszEffectName = ConstructTeamParticle( \"stunballtrail_%s_crit\", GetTeamNumber(), false );\n\t\tParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW );\n\t}\n\telse\n\t{\n\t\tconst char *pszEffectName = ConstructTeamParticle( \"stunballtrail_%s\", GetTeamNumber(), false );\n\t\tParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Don't draw if we haven't yet gone past our original spawn point\n//-----------------------------------------------------------------------------\nint CTFStunBall::DrawModel( int flags )\n{\n\tif ( gpGlobals->curtime - m_flCreationTime < 0.1f )\n\t\treturn 0;\n\n\treturn BaseClass::DrawModel( flags );\n}\n#endif\n\n<|start_filename|>src/game/shared/tf/tf_wearable.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"tf_wearable.h\"\n\n#ifdef GAME_DLL\n#include \"tf_player.h\"\n#endif\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFWearable, DT_TFWearable );\n\nBEGIN_NETWORK_TABLE( CTFWearable, DT_TFWearable )\nEND_NETWORK_TABLE()\n\nLINK_ENTITY_TO_CLASS( tf_wearable, CTFWearable );\nPRECACHE_REGISTER( tf_wearable );\n\n#ifdef GAME_DLL\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFWearable::Equip( CBasePlayer *pPlayer )\n{\n\tBaseClass::Equip( pPlayer );\n\tUpdateModelToClass();\n\n\t// player_bodygroups\n\tUpdatePlayerBodygroups();\n}\n\n//---------------------------------------------------------------------------- -\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFWearable::UpdateModelToClass( void )\n{\n\tif ( m_bExtraWearable && m_Item.GetStaticData() )\n\t{\n\t\tSetModel( m_Item.GetStaticData()->extra_wearable );\n\t}\n\telse \n\t{\n\t\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\n\t\tif ( pOwner )\n\t\t{\n\t\t\tconst char *pszModel = m_Item.GetPlayerDisplayModel( pOwner->GetPlayerClass()->GetClassIndex() );\n\n\t\t\tif ( pszModel[0] != '\\0' )\n\t\t\t{\n\t\t\t\tSetModel( pszModel );\n\t\t\t}\n\t\t}\n\t}\n}\n\n#endif // GAME_DLL\n\n\n<|start_filename|>src/game/client/tf/tf_hud_crosshair.cpp<|end_filename|>\n//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//\n//\n// Purpose: \n//\n//=============================================================================//\n\n#include \"cbase.h\"\n#include \"hudelement.h\"\n#include \n#include \n#include \"clientmode.h\"\n#include \"c_tf_player.h\"\n#include \"tf_hud_crosshair.h\"\n#include \"materialsystem/imaterial.h\"\n#include \"materialsystem/imesh.h\"\n#include \"materialsystem/imaterialvar.h\"\n#include \"mathlib/mathlib.h\"\n#include \"basecombatweapon_shared.h\"\n\nConVar cl_crosshair_red( \"cl_crosshair_red\", \"200\", FCVAR_ARCHIVE );\nConVar cl_crosshair_green( \"cl_crosshair_green\", \"200\", FCVAR_ARCHIVE );\nConVar cl_crosshair_blue( \"cl_crosshair_blue\", \"200\", FCVAR_ARCHIVE );\nConVar cl_crosshair_alpha( \"cl_crosshair_alpha\", \"200\", FCVAR_ARCHIVE );\n\nConVar cl_crosshair_file( \"cl_crosshair_file\", \"\", FCVAR_ARCHIVE );\n\nConVar cl_crosshair_scale( \"cl_crosshair_scale\", \"32.0\", FCVAR_ARCHIVE );\nConVar cl_crosshair_approach_speed( \"cl_crosshair_approach_speed\", \"0.015\" );\n\nConVar cl_dynamic_crosshair( \"cl_dynamic_crosshair\", \"1\", FCVAR_ARCHIVE );\n\nConVar tf2v_revolver_scale_crosshair( \"tf2v_revolver_scale_crosshair\", \"1\", FCVAR_ARCHIVE, \"Toggle the crosshair size scaling on the ambassador\" );\n\nusing namespace vgui;\n\nDECLARE_HUDELEMENT(CHudTFCrosshair);\n\nCHudTFCrosshair::CHudTFCrosshair(const char *pElementName) :\n\tCHudCrosshair(\"CHudCrosshair\")\n{\n\tvgui::Panel *pParent = g_pClientMode->GetViewport();\n\tSetParent(pParent);\n\n\tm_pCrosshair = 0;\n\tm_szPreviousCrosshair[0] = '\\0';\n\n\tm_pFrameVar = NULL;\n\tm_flAccuracy = 0.1;\n\n\tm_clrCrosshair = Color(0, 0, 0, 0);\n\n\tm_vecCrossHairOffsetAngle.Init();\n\n\tSetHiddenBits(HIDEHUD_PLAYERDEAD | HIDEHUD_CROSSHAIR);\n}\n\nvoid CHudTFCrosshair::ApplySchemeSettings(IScheme *scheme)\n{\n\tBaseClass::ApplySchemeSettings( scheme );\n\n\tSetSize( ScreenWidth(), ScreenHeight() );\n}\n\nvoid CHudTFCrosshair::LevelShutdown(void)\n{\n\t// forces m_pFrameVar to recreate next map\n\tm_szPreviousCrosshair[0] = '\\0';\n\n\tif (m_pCrosshairOverride)\n\t{\n\t\tdelete m_pCrosshairOverride;\n\t\tm_pCrosshairOverride = NULL;\n\t}\n\n\tif ( m_pFrameVar )\n\t{\n\t\tdelete m_pFrameVar;\n\t\tm_pFrameVar = NULL;\n\t}\n}\n\nvoid CHudTFCrosshair::Init()\n{\n\tm_iCrosshairTextureID = vgui::surface()->CreateNewTextureID();\n}\n\nvoid CHudTFCrosshair::SetCrosshair(CHudTexture *texture, Color& clr)\n{\n\tm_pCrosshair = texture;\n\tm_clrCrosshair = clr;\n}\n\nbool CHudTFCrosshair::ShouldDraw()\n{\n\tC_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();\n\n\tif ( !pPlayer )\n\t\treturn false;\n\n\tCTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon();\n\n\tif ( !pWeapon )\n\t\treturn false;\n\n\tif ( pPlayer->m_Shared.InCond( TF_COND_TAUNTING ) || pPlayer->m_Shared.InCond( TF_COND_STUNNED ) || pPlayer->m_Shared.IsLoser() )\n\t\treturn false;\n\n\treturn pWeapon->ShouldDrawCrosshair();\n}\n\nvoid CHudTFCrosshair::Paint()\n{\n\tC_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();\n\n\tif ( !pPlayer )\n\t\treturn;\n\n\tconst char *crosshairfile = cl_crosshair_file.GetString();\n\tCTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon();\n\n\tif ( !pWeapon )\n\t\treturn;\n\n\tif ( crosshairfile[0] == '\\0' )\n\t{\n\t\tm_pCrosshair = pWeapon->GetWpnData().iconCrosshair;\n\t\tBaseClass::Paint();\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tif ( Q_stricmp( m_szPreviousCrosshair, crosshairfile ) != 0 )\n\t\t{\n\t\t\tchar buf[256];\n\t\t\tQ_snprintf( buf, sizeof( buf ), \"vgui/crosshairs/%s\", crosshairfile );\n\n\t\t\tvgui::surface()->DrawSetTextureFile( m_iCrosshairTextureID, buf, true, false );\n\n\t\t\tif ( m_pCrosshairOverride )\n\t\t\t{\n\t\t\t\tdelete m_pCrosshairOverride;\n\t\t\t}\n\n\t\t\tm_pCrosshairOverride = vgui::surface()->DrawGetTextureMatInfoFactory( m_iCrosshairTextureID );\n\n\t\t\tif ( !m_pCrosshairOverride )\n\t\t\t\treturn;\n\n\t\t\tif ( m_pFrameVar )\n\t\t\t{\n\t\t\t\tdelete m_pFrameVar;\n\t\t\t}\n\n\t\t\tbool bFound = false;\n\t\t\tm_pFrameVar = m_pCrosshairOverride->FindVarFactory( \"$frame\", &bFound );\n\t\t\tAssert( bFound );\n\n\t\t\tm_nNumFrames = m_pCrosshairOverride->GetNumAnimationFrames();\n\n\t\t\t// save the name to compare with the cvar in the future\n\t\t\tQ_strncpy( m_szPreviousCrosshair, crosshairfile, sizeof( m_szPreviousCrosshair ) );\n\t\t}\n\n\t\tColor clr( cl_crosshair_red.GetInt(), cl_crosshair_green.GetInt(), cl_crosshair_blue.GetInt(), 255 );\n\n\t\tfloat x, y;\n\t\tbool bBehindCamera;\n\t\tGetDrawPosition( &x, &y, &bBehindCamera, m_vecCrossHairOffsetAngle );\n\n\t\tif ( bBehindCamera )\n\t\t\treturn;\n\n\t\tint screenWide, screenTall;\n\t\tGetHudSize( screenWide, screenTall );\n\n\t\tint iWidth, iHeight;\n\n\t\t// Ambassador crosshair scaling\n\t\tfloat flCrosshairScale = 1.0f;\n\t\tif ( pWeapon->GetWeaponID() == TF_WEAPON_REVOLVER )\n\t\t{\n\t\t\tint iMode = 0;\n\t\t\tCALL_ATTRIB_HOOK_INT_ON_OTHER( pWeapon, iMode, set_weapon_mode );\n\t\t\tif ( iMode == 1 && tf2v_revolver_scale_crosshair.GetBool() )\n\t\t\t{\n\t\t\t\tfloat flFireInterval = min( gpGlobals->curtime - pWeapon->GetLastFireTime(), 1.25f );\n\t\t\t\tflCrosshairScale = clamp( ( flFireInterval / 1.25f ), 0.334, 1.0f );\n\t\t\t}\n\t\t}\n\n\t\tiWidth = iHeight = cl_crosshair_scale.GetInt() / flCrosshairScale;\n\t\tint iX = (int)( x + 0.5f );\n\t\tint iY = (int)( y + 0.5f );\n\n\t\tvgui::surface()->DrawSetColor( clr );\n\t\tvgui::surface()->DrawSetTexture( m_iCrosshairTextureID );\n\t\tvgui::surface()->DrawTexturedRect( iX - iWidth, iY - iHeight, iX + iWidth, iY + iHeight );\n\t\tvgui::surface()->DrawSetTexture( 0 );\n\t}\n\n\t/*\n\tif (m_pFrameVar)\n\t{\n\t\tif (cl_dynamic_crosshair.GetBool() == false)\n\t\t{\n\t\t\tm_pFrameVar->SetIntValue(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon();\n\n\t\t\tif (!pWeapon)\n\t\t\t\treturn;\n\n\t\t\tfloat accuracy = 5;//pWeapon->GetWeaponAccuracy(pPlayer->GetAbsVelocity().Length2D());\n\n\t\t\tfloat flMin = 0.02;\n\n\t\t\tfloat flMax = 0.125;\n\n\t\t\taccuracy = clamp(accuracy, flMin, flMax);\n\n\t\t\t// approach this accuracy from our current accuracy\n\t\t\tm_flAccuracy = Approach(accuracy, m_flAccuracy, cl_crosshair_approach_speed.GetFloat());\n\n\t\t\tfloat flFrame = RemapVal(m_flAccuracy, flMin, flMax, 0, m_nNumFrames - 1);\n\n\t\t\tm_pFrameVar->SetIntValue((int)flFrame);\n\t\t}\n\t}\n\n*/\n}\n\n\n\n<|start_filename|>src/game/client/tf/vgui/controls/tf_advitembutton.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"tf_advitembutton.h\"\n#include \"vgui_controls/Frame.h\"\n#include \n#include \n#include \n#include \"vgui_controls/Button.h\"\n#include \"vgui_controls/ImagePanel.h\"\n#include \"tf_controls.h\"\n#include \n#include \n#include \"basemodelpanel.h\"\n#include \"panels/tf_dialogpanelbase.h\"\n#include \"inputsystem/iinputsystem.h\"\n#include \"tf_inventory.h\"\n\nusing namespace vgui;\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\nDECLARE_BUILD_FACTORY_DEFAULT_TEXT(CTFAdvItemButton, CTFAdvItemButtonBase);\n\n//-----------------------------------------------------------------------------\n// Purpose: Constructor\n//-----------------------------------------------------------------------------\nCTFAdvItemButton::CTFAdvItemButton(vgui::Panel *parent, const char *panelName, const char *text) : CTFAdvButton(parent, panelName, text)\n{\n\tInit();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Destructor\n//-----------------------------------------------------------------------------\nCTFAdvItemButton::~CTFAdvItemButton()\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFAdvItemButton::Init()\n{\n\tBaseClass::Init();\n\tm_pItemDefinition = NULL;\n\tm_iLoadoutSlot = TF_LOADOUT_SLOT_PRIMARY;\n\tpButton->SetContentAlignment(CTFAdvButtonBase::GetAlignment(\"south\"));\n\tpButton->SetTextInset(0, -10);\n}\n\nvoid CTFAdvItemButton::PerformLayout()\n{\n\tint inset = YRES(45);\n\tint wide = GetWide() - inset;\n\tSetImageSize(wide, wide);\n\tSetImageInset(inset / 2, -1 * wide / 5);\n\tSetShouldScaleImage(true);\n\n\tBaseClass::PerformLayout();\n};\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFAdvItemButton::SendAnimation(MouseState flag)\n{\n\tBaseClass::SendAnimation(flag);\n\tswitch (flag)\n\t{\n\tcase MOUSE_DEFAULT:\n\t\tif ( m_pItemDefinition )\n\t\t\tMAINMENU_ROOT->ShowItemToolTip( m_pItemDefinition );\n\t\tbreak;\n\tcase MOUSE_ENTERED:\n\t\tif ( m_pItemDefinition )\n\t\t\tMAINMENU_ROOT->ShowItemToolTip( m_pItemDefinition );\n\t\tbreak;\n\tcase MOUSE_EXITED:\n\t\tif ( m_pItemDefinition )\n\t\t\tMAINMENU_ROOT->HideItemToolTip();\n\t\tbreak;\n\tcase MOUSE_PRESSED:\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid CTFAdvItemButton::SetItemDefinition(CEconItemDefinition *pItemData)\n{\n\tm_pItemDefinition = pItemData;\n\n\tchar szIcon[128];\n\tQ_snprintf(szIcon, sizeof(szIcon), \"../%s_large\", pItemData->image_inventory);\n\tSetImage(szIcon);\n\n\tpButton->SetText( pItemData->GenerateLocalizedFullItemName() );\n}\n\nvoid CTFAdvItemButton::SetLoadoutSlot( int iSlot, int iPreset )\n{\n\tm_iLoadoutSlot = iSlot;\n\n\tchar szCommand[64];\n\tQ_snprintf( szCommand, sizeof( szCommand ), \"loadout %d %d\", iSlot, iPreset );\n\tSetCommandString( szCommand );\n}\n\n\n<|start_filename|>src/game/shared/econ/econ_item_schema.h<|end_filename|>\n#ifndef ECON_ITEM_SCHEMA_H\n#define ECON_ITEM_SCHEMA_H\n\n#ifdef _WIN32\n#pragma once\n#endif\n\n#include \"tf_shareddefs.h\"\n\nenum\n{\n\tATTRIB_FORMAT_INVALID = -1,\n\tATTRIB_FORMAT_PERCENTAGE = 0,\n\tATTRIB_FORMAT_INVERTED_PERCENTAGE,\n\tATTRIB_FORMAT_ADDITIVE,\n\tATTRIB_FORMAT_ADDITIVE_PERCENTAGE,\n\tATTRIB_FORMAT_OR,\n};\n\t\nenum\n{\n\tATTRIB_EFFECT_INVALID = -1,\n\tATTRIB_EFFECT_UNUSUAL = 0,\n\tATTRIB_EFFECT_STRANGE,\n\tATTRIB_EFFECT_NEUTRAL,\n\tATTRIB_EFFECT_POSITIVE,\n\tATTRIB_EFFECT_NEGATIVE,\n};\n\nenum\n{\n\tQUALITY_NORMAL,\n\tQUALITY_GENUINE,\n\tQUALITY_RARITY2,\n\tQUALITY_VINTAGE,\n\tQUALITY_RARITY3,\n\tQUALITY_UNUSUAL,\n\tQUALITY_UNIQUE,\n\tQUALITY_COMMUNITY,\n\tQUALITY_VALVE,\n\tQUALITY_SELFMADE,\n\tQUALITY_CUSTOMIZED,\n\tQUALITY_STRANGE,\n\tQUALITY_COMPLETED,\n\tQUALITY_HUNTED,\n\tQUALITY_COLLECTOR,\n\tQUALITY_DECORATED,\n};\n\nextern const char *g_szQualityColorStrings[];\nextern const char *g_szQualityLocalizationStrings[];\n\n#define CALL_ATTRIB_HOOK_INT(value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, this)\n\n#define CALL_ATTRIB_HOOK_FLOAT(value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, this)\n\n#define CALL_ATTRIB_HOOK_STRING(value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, this)\n\n#define CALL_ATTRIB_HOOK_INT_ON_OTHER(ent, value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, ent)\n\n#define CALL_ATTRIB_HOOK_FLOAT_ON_OTHER(ent, value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, ent)\n\n#define CALL_ATTRIB_HOOK_STRING_ON_OTHER(ent, value, name)\t\t\t\\\n\t\tvalue = CAttributeManager::AttribHookValue(value, #name, ent)\n\n#define CLEAR_STR(name)\t\t\\\n\t\tname[0] = '\\0'\n\nstruct EconQuality\n{\n\tEconQuality()\n\t{\n\t\tvalue = 0;\n\t}\n\n\tint value;\n};\n\nstruct EconColor\n{\n\tEconColor()\n\t{\n\t\tCLEAR_STR(color_name);\n\t}\n\n\tchar color_name[128];\n};\n\nstruct EconAttributeDefinition\n{\n\tEconAttributeDefinition()\n\t{\n\t\tCLEAR_STR(name);\n\t\tCLEAR_STR(attribute_class);\n\t\tCLEAR_STR(description_string);\n\t\tstring_attribute = false;\n\t\tdescription_format = -1;\n\t\thidden = false;\n\t\teffect_type = -1;\n\t\tstored_as_integer = false;\n\t}\n\n\tchar name[128];\n\tchar attribute_class[128];\n\tchar description_string[128];\n\tbool string_attribute;\n\tint description_format;\n\tint effect_type;\n\tbool hidden;\n\tbool stored_as_integer;\n};\n\n// Live TF2 uses flags instead of view_model and world_model\nstruct attachedmodel_t\n{\n\tchar attachment[128]; // not sure what this does\n\tchar model[128];\n\tint view_model;\n\tint world_model;\n};\n\n// Client specific.\n#ifdef CLIENT_DLL\nEXTERN_RECV_TABLE( DT_EconItemAttribute );\n// Server specific.\n#else\nEXTERN_SEND_TABLE( DT_EconItemAttribute );\n#endif\n\nclass CEconItemAttribute\n{\npublic:\n\tDECLARE_EMBEDDED_NETWORKVAR();\n\tDECLARE_CLASS_NOBASE( CEconItemAttribute );\n\n\tEconAttributeDefinition *GetStaticData( void );\n\n\tCEconItemAttribute()\n\t{\n\t\tInit( -1, 0.0f );\n\t}\n\tCEconItemAttribute( int iIndex, float flValue )\n\t{\n\t\tInit( iIndex, flValue );\n\t}\n\tCEconItemAttribute( int iIndex, float flValue, const char *pszAttributeClass )\n\t{\n\t\tInit( iIndex, flValue, pszAttributeClass );\n\t}\n\tCEconItemAttribute( int iIndex, const char *pszValue, const char *pszAttributeClass )\n\t{\n\t\tInit( iIndex, pszValue, pszAttributeClass );\n\t}\n\n\tvoid Init( int iIndex, float flValue, const char *pszAttributeClass = NULL );\n\tvoid Init( int iIndex, const char *iszValue, const char *pszAttributeClass = NULL );\n\npublic:\n\tCNetworkVar( int, m_iAttributeDefinitionIndex );\n\tCNetworkVar( float, value ); // m_iRawValue32\n\tCNetworkString( value_string, 128 );\n\tCNetworkString( attribute_class, 128 );\n\tstring_t m_strAttributeClass;\n};\n\nstruct EconItemStyle\n{\n\tEconItemStyle()\n\t{\n\t\tCLEAR_STR(name);\n\t\tCLEAR_STR(model_player);\n\t\tCLEAR_STR(image_inventory);\n\t\tskin_red = 0;\n\t\tskin_blu = 0;\n\t\tselectable = false;\n\t}\n\n\tint skin_red;\n\tint skin_blu;\n\tbool selectable;\n\tchar name[128];\n\tchar model_player[128];\n\tchar image_inventory[128];\n\tCUtlDict< const char*, unsigned short > model_player_per_class;\n};\n\nclass EconItemVisuals\n{\npublic:\n\tEconItemVisuals();\n\npublic:\n\tCUtlDict< bool, unsigned short > player_bodygroups;\n\tCUtlMap< int, int > animation_replacement;\n\tCUtlDict< const char*, unsigned short > playback_activity;\n\tCUtlDict< const char*, unsigned short > misc_info;\n\tCUtlVector< attachedmodel_t > attached_models;\n\tchar aWeaponSounds[NUM_SHOOT_SOUND_TYPES][MAX_WEAPON_STRING];\n\tchar custom_particlesystem[128];\n\t//CUtlDict< EconItemStyle*, unsigned short > styles;\n};\n\nclass CEconItemDefinition\n{\npublic:\n\tCEconItemDefinition()\n\t{\n\t\tCLEAR_STR(name);\n\t\tused_by_classes = 0;\n\n\t\tfor ( int i = 0; i < TF_CLASS_COUNT_ALL; i++ )\n\t\t\titem_slot_per_class[i] = -1;\n\n\t\tshow_in_armory = false;\n\t\tCLEAR_STR(item_class);\n\t\tCLEAR_STR(item_type_name);\n\t\tCLEAR_STR(item_name);\n\t\tCLEAR_STR(item_description);\n\t\titem_slot = -1;\n\t\tanim_slot = -1;\n\t\titem_quality = QUALITY_NORMAL;\n\t\tbaseitem = false;\n\t\tpropername = false;\n\t\tCLEAR_STR(item_logname);\n\t\tCLEAR_STR(item_iconname);\n\t\tmin_ilevel = 0;\n\t\tmax_ilevel = 0;\n\t\tCLEAR_STR(image_inventory);\n\t\timage_inventory_size_w = 0;\n\t\timage_inventory_size_h = 0;\n\t\tCLEAR_STR(model_player);\n\t\tCLEAR_STR(model_world);\n\t\tmemset( model_player_per_class, 0, sizeof( model_player_per_class ) );\n\t\tattach_to_hands = 0;\n\t\tCLEAR_STR(extra_wearable);\n\t\tact_as_wearable = false;\n\t\thide_bodygroups_deployed_only = 0;\n\t}\n\n\tEconItemVisuals *GetVisuals( int iTeamNum = TEAM_UNASSIGNED );\n\tint GetLoadoutSlot( int iClass = TF_CLASS_UNDEFINED );\n\tconst wchar_t *GenerateLocalizedFullItemName( void );\n\tconst wchar_t *GenerateLocalizedItemNameNoQuality( void );\n\tCEconItemAttribute *IterateAttributes( string_t strClass );\n\npublic:\n\tchar name[128];\n\tCUtlDict< bool, unsigned short > capabilities;\n\tCUtlDict< bool, unsigned short > tags;\n\tint used_by_classes;\n\tint item_slot_per_class[TF_CLASS_COUNT_ALL];\n\tbool show_in_armory;\n\tchar item_class[128];\n\tchar item_type_name[128];\n\tchar item_name[128];\n\tchar item_description[128];\n\tint item_slot;\n\tint anim_slot;\n\tint item_quality;\n\tbool baseitem;\n\tbool propername;\n\tchar item_logname[128];\n\tchar item_iconname[128];\n\tint\t min_ilevel;\n\tint\t max_ilevel;\n\tchar image_inventory[128];\n\tint\t image_inventory_size_w;\n\tint\t image_inventory_size_h;\n\tchar model_player[128];\n\tchar model_world[128];\n\tchar model_player_per_class[TF_CLASS_COUNT_ALL][128];\n\tchar extra_wearable[128];\n\tint attach_to_hands;\n\tbool act_as_wearable;\n\tint hide_bodygroups_deployed_only;\n\tCUtlVector attributes;\n\tEconItemVisuals visual[TF_TEAM_COUNT];\n};\n\n#endif // ECON_ITEM_SCHEMA_H\n\n\n<|start_filename|>src/game/server/tf/tf_obj_dispenser.cpp<|end_filename|>\n//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//\n//\n// Purpose: Engineer's Dispenser\n//\n// $NoKeywords: $\n//=============================================================================//\n#include \"cbase.h\"\n#include \"tf_obj_dispenser.h\"\n#include \"engine/IEngineSound.h\"\n#include \"tf_player.h\"\n#include \"tf_team.h\"\n#include \"vguiscreen.h\"\n#include \"world.h\"\n#include \"explode.h\"\n#include \"triggers.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\n// Ground placed version\n#define DISPENSER_MODEL_PLACEMENT\t\t\t\"models/buildables/dispenser_blueprint.mdl\"\n// *_UPGRADE models are models used during the upgrade transition\n// Valve fucked up the naming of the models. the _light ones (which should be the transition models)\n// are actually the ones that are set AFTER the upgrade transition.\n\n#define DISPENSER_MODEL_LEVEL_1\t\t\t\t\"models/buildables/dispenser_light.mdl\"\n#define DISPENSER_MODEL_LEVEL_1_UPGRADE\t\t\"models/buildables/dispenser.mdl\"\n#define DISPENSER_MODEL_LEVEL_2\t\t\t\t\"models/buildables/dispenser_lvl2_light.mdl\"\n#define DISPENSER_MODEL_LEVEL_2_UPGRADE\t\t\"models/buildables/dispenser_lvl2.mdl\"\n#define DISPENSER_MODEL_LEVEL_3\t\t\t\t\"models/buildables/dispenser_lvl3_light.mdl\"\n#define DISPENSER_MODEL_LEVEL_3_UPGRADE\t\t\"models/buildables/dispenser_lvl3.mdl\"\n\n#define DISPENSER_MINS\t\t\tVector( -20, -20, 0 )\n#define DISPENSER_MAXS\t\t\tVector( 20, 20, 55 )\t// tweak me\n\n#define DISPENSER_TRIGGER_MINS\t\t\tVector( -70, -70, 0 )\n#define DISPENSER_TRIGGER_MAXS\t\t\tVector( 70, 70, 50 )\t// tweak me\n\n#define REFILL_CONTEXT\t\t\t\"RefillContext\"\n#define DISPENSE_CONTEXT\t\t\"DispenseContext\"\n\n//-----------------------------------------------------------------------------\n// Purpose: SendProxy that converts the Healing list UtlVector to entindices\n//-----------------------------------------------------------------------------\nvoid SendProxy_HealingList( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID )\n{\n\tCObjectDispenser *pDispenser = (CObjectDispenser*)pStruct;\n\n\t// If this assertion fails, then SendProxyArrayLength_HealingArray must have failed.\n\tAssert( iElement < pDispenser->m_hHealingTargets.Size() );\n\n\tCBaseEntity *pEnt = pDispenser->m_hHealingTargets[iElement].Get();\n\tEHANDLE hOther = pEnt;\n\n\tSendProxy_EHandleToInt( pProp, pStruct, &hOther, pOut, iElement, objectID );\n}\n\nint SendProxyArrayLength_HealingArray( const void *pStruct, int objectID )\n{\n\tCObjectDispenser *pDispenser = (CObjectDispenser*)pStruct;\n\treturn pDispenser->m_hHealingTargets.Count();\n}\n\nIMPLEMENT_SERVERCLASS_ST( CObjectDispenser, DT_ObjectDispenser )\n\tSendPropInt( SENDINFO( m_iAmmoMetal ), 10 ),\n\tSendPropBool(SENDINFO(m_bStealthed)),\n\tSendPropArray2( \n\t\tSendProxyArrayLength_HealingArray,\n\t\tSendPropInt(\"healing_array_element\", 0, SIZEOF_IGNORE, NUM_NETWORKED_EHANDLE_BITS, SPROP_UNSIGNED, SendProxy_HealingList), \n\t\tMAX_PLAYERS, \n\t\t0, \n\t\t\"healing_array\"\n\t\t)\n\nEND_SEND_TABLE()\n\nBEGIN_DATADESC( CObjectDispenser )\n\tDEFINE_KEYFIELD( m_szTriggerName, FIELD_STRING, \"touch_trigger\" ),\n\tDEFINE_THINKFUNC( RefillThink ),\n\tDEFINE_THINKFUNC( DispenseThink ),\nEND_DATADESC()\n\n\nLINK_ENTITY_TO_CLASS( obj_dispenser, CObjectDispenser );\nPRECACHE_REGISTER( obj_dispenser );\n\n#define DISPENSER_MAX_HEALTH\t150\n\n// How much of each ammo gets added per refill\n#define DISPENSER_REFILL_METAL_AMMO\t40\n\n\n// How much ammo is given our per use\n#define DISPENSER_DROP_PRIMARY\t\t40\n#define DISPENSER_DROP_SECONDARY\t40\n#define DISPENSER_DROP_METAL\t\t40\n\nConVar obj_dispenser_heal_rate( \"obj_dispenser_heal_rate\", \"10.0\", FCVAR_CHEAT |FCVAR_DEVELOPMENTONLY );\n\nextern ConVar tf_cheapobjects;\n\nclass CDispenserTouchTrigger : public CBaseTrigger\n{\n\tDECLARE_CLASS( CDispenserTouchTrigger, CBaseTrigger );\n\npublic:\n\tCDispenserTouchTrigger() {}\n\n\tvoid Spawn( void )\n\t{\n\t\tBaseClass::Spawn();\n\t\tAddSpawnFlags( SF_TRIGGER_ALLOW_CLIENTS );\n\t\tInitTrigger();\n\t}\n\n\tvirtual void StartTouch( CBaseEntity *pEntity )\n\t{\n\t\tCBaseEntity *pParent = GetOwnerEntity();\n\n\t\tif ( pParent )\n\t\t{\n\t\t\tpParent->StartTouch( pEntity );\n\t\t}\n\t}\n\n\tvirtual void EndTouch( CBaseEntity *pEntity )\n\t{\n\t\tCBaseEntity *pParent = GetOwnerEntity();\n\n\t\tif ( pParent )\n\t\t{\n\t\t\tpParent->EndTouch( pEntity );\n\t\t}\n\t}\n};\n\nLINK_ENTITY_TO_CLASS( dispenser_touch_trigger, CDispenserTouchTrigger );\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nCObjectDispenser::CObjectDispenser()\n{\n\tSetMaxHealth( DISPENSER_MAX_HEALTH );\n\tm_iHealth = DISPENSER_MAX_HEALTH;\n\tUseClientSideAnimation();\n\n\tm_hTouchingEntities.Purge();\n\n\tSetType( OBJ_DISPENSER );\n}\n\nCObjectDispenser::~CObjectDispenser()\n{\n\tif ( m_hTouchTrigger.Get() )\n\t{\n\t\tUTIL_Remove( m_hTouchTrigger );\n\t}\n\n\tint iSize = m_hHealingTargets.Count();\n\tfor ( int i = iSize-1; i >= 0; i-- )\n\t{\n\t\tEHANDLE hOther = m_hHealingTargets[i];\n\n\t\tStopHealing( hOther );\n\t}\n\n\tStopSound( \"Building_Dispenser.Idle\" );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::Spawn()\n{\n\tSetModel( GetPlacementModel() );\n\tSetSolid( SOLID_BBOX );\n\n\tUTIL_SetSize(this, DISPENSER_MINS, DISPENSER_MAXS);\n\tm_takedamage = DAMAGE_YES;\n\n\tm_iAmmoMetal = 0;\n\tm_bStealthed = false;\n\tm_flNextStealthThink = 0.0f;\n\n\tBaseClass::Spawn();\n}\n\nvoid CObjectDispenser::MakeCarriedObject( CTFPlayer *pPlayer )\n{\n\tStopSound( \"Building_Dispenser.Idle\" );\n\n\t// Remove our healing trigger.\n\tif ( m_hTouchTrigger.Get() )\n\t{\n\t\tUTIL_Remove( m_hTouchTrigger );\n\t\tm_hTouchTrigger = NULL;\n\t}\n\n\t// Stop healing everyone.\n\tfor ( int i = m_hTouchingEntities.Count() - 1; i >= 0; i-- )\n\t{\n\t\tEHANDLE hEnt = m_hTouchingEntities[i];\n\n\t\tCBaseEntity *pOther = hEnt.Get();\n\n\t\tif ( pOther )\n\t\t{\n\t\t\tEndTouch( pOther );\n\t\t}\n\t}\n\n\t// Stop all thinking, we'll resume it once we get re-deployed.\n\tSetContextThink( NULL, 0, DISPENSE_CONTEXT );\n\tSetContextThink( NULL, 0, REFILL_CONTEXT );\n\n\tBaseClass::MakeCarriedObject( pPlayer );\n}\n\nvoid CObjectDispenser::DropCarriedObject( CTFPlayer *pPlayer )\n{\n\tBaseClass::DropCarriedObject( pPlayer );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Start building the object\n//-----------------------------------------------------------------------------\nbool CObjectDispenser::StartBuilding( CBaseEntity *pBuilder )\n{\n\tSetModel( DISPENSER_MODEL_LEVEL_1_UPGRADE );\n\n\tCreateBuildPoints();\n\n\treturn BaseClass::StartBuilding( pBuilder );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::InitializeMapPlacedObject( void )\n{\n\t// Must set model here so we can add control panels.\n\tSetModel( DISPENSER_MODEL_LEVEL_1 );\n\tBaseClass::InitializeMapPlacedObject();\n}\n\nvoid CObjectDispenser::SetModel( const char *pModel )\n{\n\tBaseClass::SetModel( pModel );\n\tUTIL_SetSize( this, DISPENSER_MINS, DISPENSER_MAXS );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Finished building\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::OnGoActive( void )\n{\n\t/*\n\tCTFPlayer *pBuilder = GetBuilder();\n\n\tAssert( pBuilder );\n\n\tif ( !pBuilder )\n\t\treturn;\n\t*/\n\tSetModel( DISPENSER_MODEL_LEVEL_1 );\n\tCreateBuildPoints();\n\n\tif ( !m_bCarryDeploy )\n\t{\n\t\t// Put some ammo in the Dispenser\n\t\tm_iAmmoMetal = 25;\n\t}\n\n\t// Begin thinking\n\tSetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 3, REFILL_CONTEXT );\n\tSetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT );\n\n\tm_flNextAmmoDispense = gpGlobals->curtime + 0.5;\n\n\tCDispenserTouchTrigger *pTriggerEnt;\n\n\tif ( m_szTriggerName != NULL_STRING )\n\t{\n\t\tpTriggerEnt = dynamic_cast< CDispenserTouchTrigger* >( gEntList.FindEntityByName( NULL, m_szTriggerName ) );\n\t\tif ( pTriggerEnt )\n\t\t{\t\n\t\t\tpTriggerEnt->SetOwnerEntity( this );\n\t\t\tm_hTouchTrigger = pTriggerEnt;\n\t\t}\n\t}\n\telse\n\t{\n\t\tpTriggerEnt = dynamic_cast< CDispenserTouchTrigger* >( CBaseEntity::Create( \"dispenser_touch_trigger\", GetAbsOrigin(), vec3_angle, this ) );\n\t\tif ( pTriggerEnt )\n\t\t{\n\t\t\tpTriggerEnt->SetSolid( SOLID_BBOX );\n\t\t\tUTIL_SetSize( pTriggerEnt, Vector( -70,-70,-70 ), Vector( 70,70,70 ) );\n\t\t\tm_hTouchTrigger = pTriggerEnt;\n\t\t}\n\t}\n\n\tBaseClass::OnGoActive();\n\n\tEmitSound( \"Building_Dispenser.Idle\" );\n}\n\n//-----------------------------------------------------------------------------\n// Spawn the vgui control screens on the object\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::GetControlPanelInfo( int nPanelIndex, const char *&pPanelName )\n{\n\t// Panels 0 and 1 are both control panels for now\n\tif ( nPanelIndex == 0 || nPanelIndex == 1 )\n\t{\n\t\tswitch (GetTeamNumber())\n\t\t{\n\t\t\tcase TF_TEAM_RED:\n\t\t\t\tpPanelName = \"screen_obj_dispenser_red\";\n\t\t\t\tbreak;\n\n\t\t\tcase TF_TEAM_BLUE:\n\t\t\t\tpPanelName = \"screen_obj_dispenser_blue\";\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tpPanelName = \"screen_obj_dispenser_blue\";\n\t\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tBaseClass::GetControlPanelInfo( nPanelIndex, pPanelName );\n\t}\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::Precache()\n{\n\tBaseClass::Precache();\n\n\tint iModelIndex;\n\n\tPrecacheModel( DISPENSER_MODEL_PLACEMENT );\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_1 );\n\tPrecacheGibsForModel( iModelIndex );\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_1_UPGRADE );\n\tPrecacheGibsForModel( iModelIndex );\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_2 );\n\tPrecacheGibsForModel(iModelIndex);\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_2_UPGRADE );\n\tPrecacheGibsForModel(iModelIndex);\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_3 );\n\tPrecacheGibsForModel(iModelIndex);\n\n\tiModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_3_UPGRADE );\n\tPrecacheGibsForModel(iModelIndex);\n\n\tPrecacheVGuiScreen( \"screen_obj_dispenser_blue\" );\n\tPrecacheVGuiScreen( \"screen_obj_dispenser_red\" );\n\tPrecacheVGuiScreen( \"screen_obj_dispenser_green\" );\n\tPrecacheVGuiScreen( \"screen_obj_dispenser_yellow\" );\n\n\n\tPrecacheScriptSound( \"Building_Dispenser.Idle\" );\n\tPrecacheScriptSound( \"Building_Dispenser.GenerateMetal\" );\n\tPrecacheScriptSound( \"Building_Dispenser.Heal\" );\n\n\tPrecacheTeamParticles(\"dispenser_heal_%s\");\n}\n\n#define DISPENSER_UPGRADE_DURATION\t1.5f\n\n//-----------------------------------------------------------------------------\n// Hit by a friendly engineer's wrench\n//-----------------------------------------------------------------------------\nbool CObjectDispenser::OnWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos )\n{\n\tbool bDidWork = false;\n\n\tbDidWork = BaseClass::OnWrenchHit( pPlayer, pWrench, vecHitPos );\n\n\treturn bDidWork;\n}\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\nbool CObjectDispenser::IsUpgrading( void ) const\n{\n\treturn m_bIsUpgrading;\n}\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\nchar *CObjectDispenser::GetPlacementModel( void )\n{\n\treturn DISPENSER_MODEL_PLACEMENT;\n}\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\nint CObjectDispenser::GetMaxUpgradeLevel(void)\n{\n\treturn 3;\n}\n\n//-----------------------------------------------------------------------------\n// If detonated, do some damage\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::DetonateObject( void )\n{\n\t/*\n\tfloat flDamage = min( 100 + m_iAmmoMetal, 250 );\n\n\tExplosionCreate( \n\t\tGetAbsOrigin(),\n\t\tGetAbsAngles(),\n\t\tGetBuilder(),\n\t\tflDamage,\t//magnitude\n\t\tflDamage,\t\t//radius\n\t\t0,\n\t\t0.0f,\t\t\t\t//explosion force\n\t\tthis,\t\t\t\t//inflictor\n\t\tDMG_BLAST | DMG_HALF_FALLOFF);\n\t*/\n\n\tBaseClass::DetonateObject();\n}\n\n//-----------------------------------------------------------------------------\n// Handle commands sent from vgui panels on the client \n//-----------------------------------------------------------------------------\nbool CObjectDispenser::ClientCommand( CTFPlayer *pPlayer, const CCommand &args )\n{\n\tconst char *pCmd = args[0];\n\tif ( FStrEq( pCmd, \"use\" ) )\n\t{\n\t\t// I can't do anything if I'm not active\n\t\tif ( !ShouldBeActive() ) \n\t\t\treturn true;\n\n\t\t// player used the dispenser\n\t\tif ( DispenseAmmo( pPlayer ) )\n\t\t{\n\t\t\tCSingleUserRecipientFilter filter( pPlayer );\n\t\t\tpPlayer->EmitSound( filter, pPlayer->entindex(), \"BaseCombatCharacter.AmmoPickup\" );\n\t\t}\n\n\t\treturn true;\n\t}\n\telse if ( FStrEq( pCmd, \"repair\" ) )\n\t{\n\t\tCommand_Repair( pPlayer );\n\t\treturn true;\n\t}\n\n\treturn BaseClass::ClientCommand( pPlayer, args );\n}\n\n//-----------------------------------------------------------------------------\n// Raises the dispenser one level\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::StartUpgrading( void )\n{\n\tResetHealingTargets();\n\n\tBaseClass::StartUpgrading();\n\n\tswitch( GetUpgradeLevel() )\n\t{\n\tcase 1:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_1_UPGRADE );\n\t\tbreak;\n\tcase 2:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_2_UPGRADE );\n\t\tbreak;\n\tcase 3:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_3_UPGRADE );\n\t\tbreak;\n\tdefault:\n\t\tAssert(0);\n\t\tbreak;\n\t}\n\n\tm_bIsUpgrading = true;\n\n\t// Start upgrade anim instantly\n\tDetermineAnimation();\n}\n\nvoid CObjectDispenser::FinishUpgrading( void )\n{\n\tswitch( GetUpgradeLevel() )\n\t{\n\tcase 1:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_1 );\n\t\tbreak;\n\tcase 2:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_2 );\n\t\tbreak;\n\tcase 3:\n\t\tSetModel( DISPENSER_MODEL_LEVEL_3 );\n\t\tbreak;\n\tdefault:\n\t\tAssert(0);\n\t\tbreak;\n\t}\n\n\tm_bIsUpgrading = false;\n\n\tSetActivity( ACT_RESET );\n\n\tBaseClass::FinishUpgrading();\n}\n\nbool CObjectDispenser::DispenseAmmo( CTFPlayer *pPlayer )\n{\n\tint iTotalPickedUp = 0;\n\tfloat flAmmoRate = g_flDispenserAmmoRates[GetUpgradeLevel() - 1];\n\n\t// primary\n\tint iPrimary = pPlayer->GiveAmmo( floor( pPlayer->GetMaxAmmo( TF_AMMO_PRIMARY ) * flAmmoRate ), TF_AMMO_PRIMARY, false, TF_AMMO_SOURCE_DISPENSER );\n\tiTotalPickedUp += iPrimary;\n\n\t// secondary\n\tint iSecondary = pPlayer->GiveAmmo( floor( pPlayer->GetMaxAmmo( TF_AMMO_SECONDARY ) * flAmmoRate ), TF_AMMO_SECONDARY, false, TF_AMMO_SOURCE_DISPENSER );\n\tiTotalPickedUp += iSecondary;\n\n\t// Cart dispenser has infinite metal.\n\tint iMetalToGive = DISPENSER_DROP_METAL + 10 * ( GetUpgradeLevel() - 1 );\n\n\tif ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 )\n\t\tiMetalToGive = min( m_iAmmoMetal, iMetalToGive );\n\n\tint iMetal = pPlayer->GiveAmmo( iMetalToGive, TF_AMMO_METAL, false, TF_AMMO_SOURCE_DISPENSER );\n\tiTotalPickedUp += iMetal;\n\n\tif ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 )\n\t\tm_iAmmoMetal -= iMetal;\n\n\tif ( iTotalPickedUp > 0 )\n\t{\n\t\tif (pPlayer->m_Shared.InCond(TF_COND_STEALTHED))\n\t\t{\n\t\t\tCRecipientFilter filter;\n\t\t\tfilter.AddRecipient(pPlayer);\n\t\t\tEmitSound(filter, entindex(), \"BaseCombatCharacter.AmmoPickup\");\n\t\t}\n\t\telse\n\t\t\tEmitSound( \"BaseCombatCharacter.AmmoPickup\" );\n\t\treturn true;\n\t}\n\n\t// return false if we didn't pick up anything\n\treturn false;\n}\n\nint CObjectDispenser::GetBaseHealth( void )\n{\n return DISPENSER_MAX_HEALTH;\n}\n\nfloat CObjectDispenser::GetDispenserRadius( void )\n{\n\tfloat flRadius = 64.0f;\n\n\tif ( GetOwner() )\n\t\tCALL_ATTRIB_HOOK_FLOAT_ON_OTHER( GetOwner(), flRadius, mult_dispenser_radius );\n\n\treturn flRadius;\n}\n\nfloat CObjectDispenser::GetHealRate( void )\n{\n\treturn g_flDispenserHealRates[ GetUpgradeLevel() - 1 ];\n}\n\nvoid CObjectDispenser::RefillThink( void )\n{\n\tif ( GetObjectFlags() & OF_IS_CART_OBJECT )\n\t\treturn;\n\n\tif ( IsDisabled() || IsUpgrading() || IsRedeploying() )\n\t{\n\t\t// Hit a refill time while disabled, so do the next refill ASAP.\n\t\tSetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 0.1, REFILL_CONTEXT );\n\t\treturn;\n\t}\n\n\t// Auto-refill half the amount as tfc, but twice as often\n\tif ( m_iAmmoMetal < DISPENSER_MAX_METAL_AMMO )\n\t{\n\t\tm_iAmmoMetal = min( m_iAmmoMetal + DISPENSER_MAX_METAL_AMMO * ( 0.1 + 0.025 * ( GetUpgradeLevel() - 1 ) ), DISPENSER_MAX_METAL_AMMO );\n\t\tEmitSound( \"Building_Dispenser.GenerateMetal\" );\n\t}\n\n\tSetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 6, REFILL_CONTEXT );\n}\n\n//-----------------------------------------------------------------------------\n// Generate ammo over time\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::DispenseThink( void )\n{\n\tif ( IsDisabled() || IsUpgrading() || IsRedeploying() )\n\t{\n\t\t// Don't heal or dispense ammo\n\t\tSetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT );\n\n\t\t// stop healing everyone\n\t\tfor ( int i=m_hHealingTargets.Count()-1; i>=0; i-- )\n\t\t{\n\t\t\tEHANDLE hEnt = m_hHealingTargets[i];\n\n\t\t\tCBaseEntity *pOther = hEnt.Get();\n\n\t\t\tif ( pOther )\n\t\t\t{\n\t\t\t\tStopHealing( pOther );\n\t\t\t}\n\t\t}\n\n\t\treturn;\n\t}\n\n\tif ( m_flNextAmmoDispense <= gpGlobals->curtime )\n\t{\n\t\tint iNumNearbyPlayers = 0;\n\n\t\t// find players in sphere, that are visible\n\t\tstatic float flRadius = GetDispenserRadius();\n\t\tVector vecOrigin = GetAbsOrigin() + Vector(0,0,32);\n\n\t\tCBaseEntity *pListOfNearbyEntities[32];\n\t\tint iNumberOfNearbyEntities = UTIL_EntitiesInSphere( pListOfNearbyEntities, 32, vecOrigin, flRadius, FL_CLIENT );\n\t\tfor (int i=0;iIsAlive() || !CouldHealTarget(pPlayer) )\n\t\t\t\tcontinue;\n\n\t\t\tDispenseAmmo( pPlayer );\n\n\t\t\tiNumNearbyPlayers++;\n\t\t}\n\n\t\t// Try to dispense more often when no players are around so we \n\t\t// give it as soon as possible when a new player shows up\n\t\tm_flNextAmmoDispense = gpGlobals->curtime + ( ( iNumNearbyPlayers > 0 ) ? 1.0 : 0.1 );\n\t}\t\n\n\tResetHealingTargets();\n\n\tSetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::ResetHealingTargets( void )\n{\n\t// for each player in touching list\n\tint iSize = m_hTouchingEntities.Count();\n\tfor (int i = iSize - 1; i >= 0; i--)\n\t{\n\t\tEHANDLE hOther = m_hTouchingEntities[i];\n\n\t\tCBaseEntity *pEnt = hOther.Get();\n\t\tbool bHealingTarget = IsHealingTarget(pEnt);\n\t\tbool bValidHealTarget = CouldHealTarget(pEnt);\n\n\t\tCTFPlayer *pPlayer;\n\t\tpPlayer = ToTFPlayer(pEnt);\n\t\tif (pPlayer)\n\t\t{\n\t\t\tif (pPlayer->m_Shared.InCond(TF_COND_STEALTHED) && m_flNextStealthThink < gpGlobals->curtime)\n\t\t\t{\n\t\t\t\tm_bStealthed = true;\n\t\t\t\tNetworkStateChanged();\n\t\t\t\tm_flNextStealthThink = gpGlobals->curtime + 1.0f;\n\t\t\t}\n\t\t}\n\n\t\tif ( bHealingTarget && !bValidHealTarget )\n\t\t{\n\t\t\t// if we can't see them, remove them from healing list\n\t\t\t// does nothing if we are not healing them already\n\t\t\tStopHealing( pEnt );\n\t\t}\n\t\telse if ( !bHealingTarget && bValidHealTarget )\n\t\t{\n\t\t\t// if we can see them, add to healing list\t\n\t\t\t// does nothing if we are healing them already\n\t\t\tStartHealing( pEnt );\n\t\t}\t\n\t}\n\n\tif (m_flNextStealthThink < gpGlobals->curtime)\n\t{\n\t\tif (m_bStealthed)\n\t\t\tNetworkStateChanged();\n\t\tm_bStealthed = false;\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::StartTouch( CBaseEntity *pOther )\n{\n\t// add to touching entities\n\tEHANDLE hOther = pOther;\n\tm_hTouchingEntities.AddToTail( hOther );\n\n\tif ( !IsBuilding() && !IsDisabled() && !IsRedeploying() && CouldHealTarget( pOther ) && !IsHealingTarget( pOther ) )\n\t{\n\t\t// try to start healing them\n\t\tStartHealing( pOther );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::EndTouch( CBaseEntity *pOther )\n{\n\t// remove from touching entities\n\tEHANDLE hOther = pOther;\n\tm_hTouchingEntities.FindAndRemove( hOther );\n\n\t// remove from healing list\n\tStopHealing( pOther );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Try to start healing this target\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::StartHealing( CBaseEntity *pOther )\n{\n\tAddHealingTarget( pOther );\n\n\tCTFPlayer *pPlayer = ToTFPlayer( pOther );\n\n\tif ( pPlayer )\n\t{\n\t\tpPlayer->m_Shared.Heal( GetOwner(), GetHealRate(), true );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Stop healing this target\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::StopHealing( CBaseEntity *pOther )\n{\n\tbool bFound = false;\n\n\tEHANDLE hOther = pOther;\n\tbFound = m_hHealingTargets.FindAndRemove( hOther );\n\tNetworkStateChanged();\n\n\tif ( bFound )\n\t{\n\t\tCTFPlayer *pPlayer = ToTFPlayer( pOther );\n\n\t\tif ( pPlayer )\n\t\t{\n\t\t\tpPlayer->m_Shared.StopHealing( GetOwner() );\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Is this a valid heal target? and not already healing them?\n//-----------------------------------------------------------------------------\nbool CObjectDispenser::CouldHealTarget( CBaseEntity *pTarget )\n{\n\tif ( !HasSpawnFlags( SF_IGNORE_LOS ) && !pTarget->FVisible( this, MASK_BLOCKLOS ) )\n\t\treturn false;\n\n\tif ( pTarget->IsPlayer() && pTarget->IsAlive() )\n\t{\n\t\tCTFPlayer *pTFPlayer = ToTFPlayer( pTarget );\n\n\t\t// don't heal enemies unless they are disguised as our team\n\t\tint iTeam = GetTeamNumber();\n\t\tint iPlayerTeam = pTFPlayer->GetTeamNumber();\n\n\t\tif ( iPlayerTeam != iTeam && pTFPlayer->m_Shared.InCond( TF_COND_DISGUISED ) && !HasSpawnFlags( SF_NO_DISGUISED_SPY_HEALING ) )\n\t\t{\n\t\t\tiPlayerTeam = pTFPlayer->m_Shared.GetDisguiseTeam();\n\t\t}\n\n\t\tif ( iPlayerTeam != iTeam )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::AddHealingTarget( CBaseEntity *pOther )\n{\n\t// add to tail\n\tEHANDLE hOther = pOther;\n\tm_hHealingTargets.AddToTail( hOther );\n\tNetworkStateChanged();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CObjectDispenser::RemoveHealingTarget( CBaseEntity *pOther )\n{\n\t// remove\n\tEHANDLE hOther = pOther;\n\tm_hHealingTargets.FindAndRemove( hOther );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Are we healing this target already\n//-----------------------------------------------------------------------------\nbool CObjectDispenser::IsHealingTarget( CBaseEntity *pTarget )\n{\n\tEHANDLE hOther = pTarget;\n\treturn m_hHealingTargets.HasElement( hOther );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CObjectDispenser::DrawDebugTextOverlays( void ) \n{\n\tint text_offset = BaseClass::DrawDebugTextOverlays();\n\n\tif (m_debugOverlays & OVERLAY_TEXT_BIT) \n\t{\n\t\tchar tempstr[512];\n\t\tQ_snprintf( tempstr, sizeof( tempstr ),\"Metal: %d\", m_iAmmoMetal );\n\t\tEntityText(text_offset,tempstr,0);\n\t\ttext_offset++;\n\t}\n\treturn text_offset;\n}\n\n\nIMPLEMENT_SERVERCLASS_ST( CObjectCartDispenser, DT_ObjectCartDispenser )\nEND_SEND_TABLE()\n\nBEGIN_DATADESC( CObjectCartDispenser )\n\tDEFINE_KEYFIELD( m_szTriggerName, FIELD_STRING, \"touch_trigger\" ),\nEND_DATADESC()\n\nLINK_ENTITY_TO_CLASS( mapobj_cart_dispenser, CObjectCartDispenser );\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectCartDispenser::Spawn( void )\n{\n\tSetObjectFlags( OF_IS_CART_OBJECT );\n\n\tm_takedamage = DAMAGE_NO;\n\n\tm_iUpgradeLevel = 1;\n\tm_iUpgradeMetal = 0;\n\n\tAddFlag( FL_OBJECT ); \n\n\tm_iAmmoMetal = 0;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectCartDispenser::SetModel( const char *pModel )\n{\n\t// Deliberately skip dispenser since it has some stuff we don't want.\n\tCBaseObject::SetModel( pModel );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CObjectCartDispenser::OnGoActive( void )\n{\n\t// Hacky: base class needs a model to init some things properly so we gotta clear it here.\n\tBaseClass::OnGoActive();\n\tSetModel( \"\" );\n}\n\n\n<|start_filename|>src/game/shared/tf/tf_projectile_arrow.cpp<|end_filename|>\n//=============================================================================//\n//\n// Purpose:\n//\n//=============================================================================//\n\n#include \"cbase.h\"\n#include \"tf_projectile_arrow.h\"\n#include \"effect_dispatch_data.h\"\n\n#ifdef GAME_DLL\n#include \"SpriteTrail.h\"\n#include \"props_shared.h\"\n#include \"debugoverlay_shared.h\"\n#include \"te_effect_dispatch.h\"\n#include \"decals.h\"\n#include \"bone_setup.h\"\n#endif\n\n#ifdef GAME_DLL\nConVar tf_debug_arrows( \"tf_debug_arrows\", \"0\", FCVAR_CHEAT );\n#endif\n\nconst char *g_pszArrowModels[] =\n{\n\t\"models/weapons/w_models/w_arrow.mdl\",\n\t\"models/weapons/w_models/w_syringe_proj.mdl\",\n\t\"models/weapons/w_models/w_repair_claw.mdl\",\n\t//\"models/weapons/w_models/w_arrow_xmas.mdl\",\n};\n\nIMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_Arrow, DT_TFProjectile_Arrow )\n\nBEGIN_NETWORK_TABLE( CTFProjectile_Arrow, DT_TFProjectile_Arrow )\n#ifdef CLIENT_DLL\n\tRecvPropBool( RECVINFO( m_bCritical ) ),\n\tRecvPropBool( RECVINFO( m_bFlame ) ),\n\tRecvPropInt( RECVINFO( m_iType ) ),\n#else\n\tSendPropBool( SENDINFO( m_bCritical ) ),\n\tSendPropBool( SENDINFO( m_bFlame ) ),\n\tSendPropInt( SENDINFO( m_iType ), 3, SPROP_UNSIGNED ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef GAME_DLL\nBEGIN_DATADESC( CTFProjectile_Arrow )\n\tDEFINE_ENTITYFUNC( ArrowTouch )\nEND_DATADESC()\n#endif\n\nLINK_ENTITY_TO_CLASS( tf_projectile_arrow, CTFProjectile_Arrow );\nPRECACHE_REGISTER( tf_projectile_arrow );\n\nCTFProjectile_Arrow::CTFProjectile_Arrow()\n{\n}\n\nCTFProjectile_Arrow::~CTFProjectile_Arrow()\n{\n#ifdef CLIENT_DLL\n\tParticleProp()->StopEmission();\n\tbEmitting = false;\n#else\n\tm_bCollideWithTeammates = false;\n#endif\n}\n\n#ifdef GAME_DLL\n\nCTFProjectile_Arrow *CTFProjectile_Arrow::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, float flSpeed, float flGravity, bool bFlame, CBaseEntity *pOwner, CBaseEntity *pScorer, int iType )\n{\n\tCTFProjectile_Arrow *pArrow = static_cast( CBaseEntity::CreateNoSpawn( \"tf_projectile_arrow\", vecOrigin, vecAngles, pOwner ) );\n\n\tif ( pArrow )\n\t{\n\t\t// Set team.\n\t\tpArrow->ChangeTeam( pOwner->GetTeamNumber() );\n\n\t\t// Set scorer.\n\t\tpArrow->SetScorer( pScorer );\n\n\t\t// Set firing weapon.\n\t\tpArrow->SetLauncher( pWeapon );\n\n\t\t// Set arrow type.\n\t\tpArrow->SetType( iType );\n\n\t\t// Set flame arrow.\n\t\tpArrow->SetFlameArrow( bFlame );\n\n\t\t// Spawn.\n\t\tDispatchSpawn( pArrow );\n\n\t\t// Setup the initial velocity.\n\t\tVector vecForward, vecRight, vecUp;\n\t\tAngleVectors( vecAngles, &vecForward, &vecRight, &vecUp );\n\n\t\tCALL_ATTRIB_HOOK_FLOAT_ON_OTHER( pWeapon, flSpeed, mult_projectile_speed );\n\n\t\tVector vecVelocity = vecForward * flSpeed;\n\t\tpArrow->SetAbsVelocity( vecVelocity );\n\t\tpArrow->SetupInitialTransmittedGrenadeVelocity( vecVelocity );\n\n\t\t// Setup the initial angles.\n\t\tQAngle angles;\n\t\tVectorAngles( vecVelocity, angles );\n\t\tpArrow->SetAbsAngles( angles );\n\n\t\tpArrow->SetGravity( flGravity );\n\n\t\treturn pArrow;\n\t}\n\n\treturn pArrow;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::Precache( void )\n{\n\t// Precache all arrow models we have.\n\tfor ( int i = 0; i < ARRAYSIZE( g_pszArrowModels ); i++ )\n\t{\n\t\tint iIndex = PrecacheModel( g_pszArrowModels[i] );\n\t\tPrecacheGibsForModel( iIndex );\n\t}\n\n\tfor ( int i = FIRST_GAME_TEAM; i < TF_TEAM_COUNT; i++ )\n\t{\n\t\tPrecacheModel( ConstructTeamParticle( \"effects/arrowtrail_%s.vmt\", i, false, g_aTeamNamesShort ) );\n\t\tPrecacheModel( ConstructTeamParticle( \"effects/healingtrail_%s.vmt\", i, false, g_aTeamNamesShort ) );\n\t\tPrecacheModel( ConstructTeamParticle( \"effects/repair_claw_trail_%s.vmt\", i, false, g_aTeamParticleNames ) );\n\t}\n\n\t// Precache flame effects\n\tPrecacheParticleSystem( \"flying_flaming_arrow\" );\n\n\tPrecacheScriptSound( \"Weapon_Arrow.ImpactFlesh\" );\n\tPrecacheScriptSound( \"Weapon_Arrow.ImpactMetal\" );\n\tPrecacheScriptSound( \"Weapon_Arrow.ImpactWood\" );\n\tPrecacheScriptSound( \"Weapon_Arrow.ImpactConcrete\" );\n\tPrecacheScriptSound( \"Weapon_Arrow.Nearmiss\" );\n\n\tBaseClass::Precache();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::Spawn( void )\n{\n\tswitch ( m_iType )\n\t{\n\tcase TF_PROJECTILE_BUILDING_REPAIR_BOLT:\n\t\tSetModel( g_pszArrowModels[2] );\n\t\tbreak;\n\tcase TF_PROJECTILE_HEALING_BOLT:\n\tcase TF_PROJECTILE_FESTITIVE_HEALING_BOLT:\n\t\tSetModel( g_pszArrowModels[1] );\n\t\tbreak;\n\tdefault:\n\t\tSetModel( g_pszArrowModels[0] );\n\t\tbreak;\n\t}\n\n\tBaseClass::Spawn();\n\n#ifdef TF_ARROW_FIX\n\tSetSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER );\n#endif\n\n\tSetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_CUSTOM );\n\tSetGravity( 0.3f ); // TODO: Check again later.\n\n\tUTIL_SetSize( this, -Vector( 1, 1, 1 ), Vector( 1, 1, 1 ) );\n\n\tCreateTrail();\n\n\tSetTouch( &CTFProjectile_Arrow::ArrowTouch );\n\tSetThink(&CTFProjectile_Arrow::FlyThink);\n\tSetNextThink(gpGlobals->curtime);\n\n\t// TODO: Set skin here...\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::SetScorer( CBaseEntity *pScorer )\n{\n\tm_Scorer = pScorer;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nCBasePlayer *CTFProjectile_Arrow::GetScorer( void )\n{\n\treturn dynamic_cast( m_Scorer.Get() );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::ArrowTouch( CBaseEntity *pOther )\n{\n\t// Verify a correct \"other.\"\n\tAssert( pOther );\n\tif ( pOther->IsSolidFlagSet( FSOLID_TRIGGER | FSOLID_VOLUME_CONTENTS ) )\n\t{\n\t\treturn;\n\t}\n\n\t// Handle hitting skybox (disappear).\n\ttrace_t *pTrace = const_cast( &CBaseEntity::GetTouchTrace() );\n\tif ( pTrace->surface.flags & SURF_SKY )\n\t{\n\t\tUTIL_Remove( this );\n\t\treturn;\n\t}\n\n\t// Invisible.\n\tSetModelName( NULL_STRING );\n\tAddSolidFlags( FSOLID_NOT_SOLID );\n\tm_takedamage = DAMAGE_NO;\n\n\t// Damage.\n\tCBaseEntity *pAttacker = GetOwnerEntity();\n\tIScorer *pScorerInterface = dynamic_cast( pAttacker );\n\tif ( pScorerInterface )\n\t{\n\t\tpAttacker = pScorerInterface->GetScorer();\n\t}\n\n\tVector vecOrigin = GetAbsOrigin();\n\tVector vecDir = GetAbsVelocity();\n\tCTFPlayer *pPlayer = ToTFPlayer( pOther );\n\tCTFWeaponBase *pWeapon = dynamic_cast( m_hLauncher.Get() );\n\ttrace_t trHit, tr;\n\ttrHit = *pTrace;\n\tconst char* pszImpactSound = NULL;\n\tbool bPlayerImpact = false;\n\n\tif ( pPlayer )\n\t{\n\t\t// Determine where we should land\n\t\tVector vecDir = GetAbsVelocity();\n\t\tVectorNormalizeFast( vecDir );\n\t\tCStudioHdr *pStudioHdr = pPlayer->GetModelPtr();\n\t\tif ( !pStudioHdr )\n\t\t\treturn;\n\n\t\tmstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pPlayer->GetHitboxSet() );\n\t\tif ( !set )\n\t\t\treturn;\n\n\t\t// Oh boy... we gotta figure out the closest hitbox on player model to land a hit on.\n\n\t\tQAngle angHit;\n\t\tfloat flClosest = FLT_MAX;\n\t\tmstudiobbox_t *pBox = NULL, *pCurrentBox = NULL;\n\t\t//int bone = -1;\n\t\t//int group = 0;\n\t\t//Msg( \"\\nNum of Hitboxes: %i\", set->numhitboxes );\n\n\t\tfor ( int i = 0; i < set->numhitboxes; i++ )\n\t\t{\n\t\t\tpCurrentBox = set->pHitbox( i );\n\t\t\t//Msg( \"\\nGroup: %i\", pBox->group );\n\n\t\t\tVector boxPosition;\n\t\t\tQAngle boxAngles;\n\t\t\tpPlayer->GetBonePosition( pCurrentBox->bone, boxPosition, boxAngles );\n\t\t\tVector vecCross = CrossProduct( vecOrigin + vecDir * 16, boxPosition );\n\n\t\t\ttrace_t tr;\n\t\t\tUTIL_TraceLine( vecOrigin, boxPosition, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );\n\n\t\t\tfloat flLengthSqr = ( boxPosition - vecCross ).LengthSqr();\n\t\t\tif ( flLengthSqr < flClosest )\n\t\t\t{\n\t\t\t\t//Msg( \"\\nCLOSER: %i\", pBox->group );\n\t\t\t\t//group = pBox->group;\n\t\t\t\tflClosest = flLengthSqr;\n\t\t\t\ttrHit = tr;\n\t\t\t\tpBox = pCurrentBox;\n\t\t\t}\n\t\t}\n\t\t//Msg(\"\\nClosest: %i\\n\", group);\n\n\t\tif ( tf_debug_arrows.GetBool() )\n\t\t{\n\t\t\t//Msg(\"\\nHitBox: %i\\nHitgroup: %i\\n\", trHit.hitbox, trHit.hitgroup);\n\t\t\tNDebugOverlay::Line( trHit.startpos, trHit.endpos, 0, 255, 0, true, 5.0f );\n\t\t\tNDebugOverlay::Line( vecOrigin, vecOrigin + vecDir * 16, 255, 0, 0, true, 5.0f );\n\t\t}\n\t\tpszImpactSound = \"Weapon_Arrow.ImpactFlesh\";\n\t\tbPlayerImpact = true;\n\n\t\tif ( !PositionArrowOnBone( pBox , pPlayer ) )\n\t\t{\n\t\t\t// This shouldn't happen\n\t\t\tUTIL_Remove( this );\n\t\t\treturn;\n\t\t}\n\n\t\tVector vecOrigin;\n\t\tQAngle vecAngles;\n\t\tint bone, iPhysicsBone;\n\t\tGetBoneAttachmentInfo( pBox, pPlayer, vecOrigin, vecAngles, bone, iPhysicsBone );\n\n\t\t// TODO: Redo the whole \"BoltImpact\" logic\n\n\t\t// CTFProjectile_Arrow::CheckRagdollPinned\n\t\tif( GetDamage() > pPlayer->GetHealth() )\n\t\t{\n\t\t\t// pPlayer->StopRagdollDeathAnim();\n\t\t\tVector vForward;\n\n\t\t\tAngleVectors( GetAbsAngles(), &vForward );\n\t\t\tVectorNormalize ( vForward );\n\n\t\t\tUTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vForward * 256, MASK_BLOCKLOS, pOther, COLLISION_GROUP_NONE, &tr );\n\n\t\t\tif ( tr.fraction != 1.0f )\n\t\t\t{\n\t\t\t\t//NDebugOverlay::Box( tr.endpos, Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 255, 0, 0, 10 );\n\t\t\t\t//NDebugOverlay::Box( GetAbsOrigin(), Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 0, 255, 0, 10 );\n\n\t\t\t\tif ( tr.m_pEnt == NULL || ( tr.m_pEnt && tr.m_pEnt->GetMoveType() == MOVETYPE_NONE ) )\n\t\t\t\t{\n\t\t\t\t\tCEffectData\tdata;\n\n\t\t\t\t\tdata.m_vOrigin = tr.endpos;\n\t\t\t\t\tdata.m_vNormal = vForward;\n\t\t\t\t\tdata.m_nEntIndex = tr.fraction != 1.0f;\n\t\t\t\n\t\t\t\t\tDispatchEffect( \"BoltImpact\", data );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\tIGameEvent *event = gameeventmanager->CreateEvent( \"arrow_impact\" );\n\t\t\t\n\t\t\tif ( event )\n\t\t\t{\n\t\t\t\tevent->SetInt( \"attachedEntity\", pOther->entindex() );\n\t\t\t\tevent->SetInt( \"shooter\", pAttacker->entindex() );\n\t\t\t\tevent->SetInt( \"boneIndexAttached\", bone );\n\t\t\t\tevent->SetFloat( \"bonePositionX\", vecOrigin.x );\n\t\t\t\tevent->SetFloat( \"bonePositionY\", vecOrigin.y );\n\t\t\t\tevent->SetFloat( \"bonePositionZ\", vecOrigin.z );\n\t\t\t\tevent->SetFloat( \"boneAnglesX\", vecAngles.x );\n\t\t\t\tevent->SetFloat( \"boneAnglesY\", vecAngles.y );\n\t\t\t\tevent->SetFloat( \"boneAnglesZ\", vecAngles.z );\n\t\t\t\t\n\t\t\t\tgameeventmanager->FireEvent( event );\n\t\t\t}\n\t\t}\n\t}\n\telse if ( pOther->GetMoveType() == MOVETYPE_NONE )\n\t{\t\n\t\tsurfacedata_t *psurfaceData = physprops->GetSurfaceData( trHit.surface.surfaceProps );\n\t\tint iMaterial = psurfaceData->game.material;\n\t\tbool bArrowSound = false;\n\n\t\tif ( ( iMaterial == CHAR_TEX_CONCRETE ) || ( iMaterial == CHAR_TEX_TILE ) )\n\t\t{\n\t\t\tpszImpactSound = \"Weapon_Arrow.ImpactConcrete\";\n\t\t\tbArrowSound = true;\n\t\t}\n\t\telse if ( iMaterial == CHAR_TEX_WOOD )\n\t\t{\n\t\t\tpszImpactSound = \"Weapon_Arrow.ImpactWood\";\n\t\t\tbArrowSound = true;\n\t\t}\n\t\telse if ( ( iMaterial == CHAR_TEX_METAL ) || ( iMaterial == CHAR_TEX_VENT ) )\n\t\t{\n\t\t\tpszImpactSound = \"Weapon_Arrow.ImpactMetal\";\n\t\t\tbArrowSound = true;\n\t\t}\n\n\t\tVector vForward;\n\n\t\tAngleVectors( GetAbsAngles(), &vForward );\n\t\tVectorNormalize ( vForward );\n\n\t\tUTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vForward * 256, MASK_BLOCKLOS, pOther, COLLISION_GROUP_NONE, &tr );\n\n\t\tif ( tr.fraction != 1.0f )\n\t\t{\n\t\t\t//NDebugOverlay::Box( tr.endpos, Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 255, 0, 0, 10 );\n\t\t\t//NDebugOverlay::Box( GetAbsOrigin(), Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 0, 255, 0, 10 );\n\n\t\t\tif ( tr.m_pEnt == NULL || ( tr.m_pEnt && tr.m_pEnt->GetMoveType() == MOVETYPE_NONE ) )\n\t\t\t{\n\t\t\t\tCEffectData\tdata;\n\n\t\t\t\tdata.m_vOrigin = tr.endpos;\n\t\t\t\tdata.m_vNormal = vForward;\n\t\t\t\tdata.m_nEntIndex = tr.fraction != 1.0f;\n\t\t\t\tDispatchEffect( \"BoltImpact\", data );\n\t\t\t}\n\t\t}\n\n\t\t// If we didn't play a collision sound already, play a bullet collision sound for this prop\n\t\tif( !bArrowSound )\n\t\t{\n\t\t\tUTIL_ImpactTrace( &trHit, DMG_BULLET );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tUTIL_ImpactTrace( &trHit, DMG_BULLET, \"ImpactArrow\" );\n\t\t}\n\n\t\t//UTIL_Remove( this );\n\t}\n\telse\n\t{\n\t\t// TODO: Figure out why arrow gibs sometimes cause crashes\n\t\t//BreakArrow();\n\t\tUTIL_Remove( this );\n\t}\n\n\t// Play sound\n\tif ( pszImpactSound )\n\t{\n\t\tPlayImpactSound( ToTFPlayer( pAttacker ), pszImpactSound, bPlayerImpact );\n\t}\n\n\tint iCustomDamage = m_bFlame ? TF_DMG_CUSTOM_BURNING_ARROW : TF_DMG_CUSTOM_NONE;\n\n\t// Do damage.\n\tCTakeDamageInfo info( this, pAttacker, pWeapon, GetDamage(), GetDamageType(), iCustomDamage );\n\tCalculateBulletDamageForce( &info, pWeapon ? pWeapon->GetTFWpnData().iAmmoType : 0, vecDir, vecOrigin );\n\tinfo.SetReportedPosition( pAttacker ? pAttacker->GetAbsOrigin() : vec3_origin );\n\tpOther->DispatchTraceAttack( info, vecDir, &trHit );\n\tApplyMultiDamage();\n\n\t// Remove.\n\tUTIL_Remove( this );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::FlyThink(void)\n{\n\tQAngle angles;\n\n\tVectorAngles(GetAbsVelocity(), angles);\n\n\tSetAbsAngles(angles);\n\n\tSetNextThink(gpGlobals->curtime + 0.1f);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint\tCTFProjectile_Arrow::GetDamageType()\n{\n\tint iDmgType = BaseClass::GetDamageType();\n\n\t// Buff banner mini-crit calculations\n\tCTFWeaponBase *pWeapon = ( CTFWeaponBase * )m_hLauncher.Get();\n\tif ( pWeapon )\n\t{\n\t\tpWeapon->CalcIsAttackMiniCritical();\n\t\tif ( pWeapon->IsCurrentAttackAMiniCrit() )\n\t\t{\n\t\t\tiDmgType |= DMG_MINICRITICAL;\n\t\t}\n\t}\n\n\tif ( m_bCritical )\n\t{\n\t\tiDmgType |= DMG_CRITICAL;\n\t}\n\tif ( CanHeadshot() )\n\t{\n\t\tiDmgType |= DMG_USE_HITLOCATIONS;\n\t}\n\tif ( m_bFlame == true )\n\t{\n\t\tiDmgType |= DMG_IGNITE;\t\n\t}\n\tif ( m_iDeflected > 0 )\n\t{\n\t\tiDmgType |= DMG_MINICRITICAL;\n\t}\n\n\treturn iDmgType;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir )\n{\n\t// Get arrow's speed.\n\tfloat flVel = GetAbsVelocity().Length();\n\n\tQAngle angForward;\n\tVectorAngles( vecDir, angForward );\n\n\t// Now change arrow's direction.\n\tSetAbsAngles( angForward );\n\tSetAbsVelocity( vecDir * flVel );\n\n\t// And change owner.\n\tIncremenentDeflected();\n\tSetOwnerEntity( pDeflectedBy );\n\tChangeTeam( pDeflectedBy->GetTeamNumber() );\n\tSetScorer( pDeflectedBy );\n\n\t// Change trail color.\n\tif ( m_hSpriteTrail.Get() )\n\t{\n\t\tUTIL_Remove( m_hSpriteTrail.Get() );\n\t}\n\n\tCreateTrail();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CTFProjectile_Arrow::CanHeadshot( void )\n{\n\treturn ( m_iType == TF_PROJECTILE_ARROW || m_iType == TF_PROJECTILE_FESTITIVE_ARROW );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nconst char *CTFProjectile_Arrow::GetTrailParticleName( void )\n{\n\tconst char *pszFormat = NULL;\n\tbool bLongTeamName = false;\n\n\tswitch( m_iType )\n\t{\n\tcase TF_PROJECTILE_BUILDING_REPAIR_BOLT:\n\t\tpszFormat = \"effects/repair_claw_trail_%s.vmt\";\n\t\tbLongTeamName = true;\n\t\tbreak;\n\tcase TF_PROJECTILE_HEALING_BOLT:\n\tcase TF_PROJECTILE_FESTITIVE_HEALING_BOLT:\n\t\tpszFormat = \"effects/healingtrail_%s.vmt\";\n\t\tbreak;\n\tdefault:\n\t\tpszFormat = \"effects/arrowtrail_%s.vmt\";\n\t\tbreak;\n\t}\n\n\treturn ConstructTeamParticle( pszFormat, GetTeamNumber(), false, bLongTeamName ? g_aTeamParticleNames : g_aTeamNamesShort );\n}\n\n// ---------------------------------------------------------------------------- -\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::CreateTrail( void )\n{\n\tCSpriteTrail *pTrail = CSpriteTrail::SpriteTrailCreate( GetTrailParticleName(), GetAbsOrigin(), true );\n\n\tif ( pTrail )\n\t{\n\t\tpTrail->FollowEntity( this );\n\t\tpTrail->SetTransparency( kRenderTransAlpha, -1, -1, -1, 255, kRenderFxNone );\n\t\tpTrail->SetStartWidth( m_iType == TF_PROJECTILE_BUILDING_REPAIR_BOLT ? 5.0f : 3.0f );\n\t\tpTrail->SetTextureResolution( 0.01f );\n\t\tpTrail->SetLifeTime( 0.3f );\n\t\tpTrail->TurnOn();\n\n\t\tpTrail->SetContextThink( &CBaseEntity::SUB_Remove, gpGlobals->curtime + 3.0f, \"RemoveThink\" );\n\n\t\tm_hSpriteTrail.Set( pTrail );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::UpdateOnRemove( void )\n{\n\tUTIL_Remove( m_hSpriteTrail.Get() );\n\n\tBaseClass::UpdateOnRemove();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Sends to the client information for arrow gibs\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::BreakArrow( void )\n{\n\tSetMoveType( MOVETYPE_NONE, MOVECOLLIDE_DEFAULT );\n\tSetAbsVelocity( vec3_origin );\n\tSetSolidFlags( FSOLID_NOT_SOLID );\n\tAddEffects( EF_NODRAW );\n\n\tSetContextThink( &CTFProjectile_Arrow::RemoveThink, gpGlobals->curtime + 3.0, \"ARROW_REMOVE_THINK\" );\n\n\tCRecipientFilter pFilter;\n\tpFilter.AddRecipientsByPVS( GetAbsOrigin() );\n\t\n\tUserMessageBegin( pFilter, \"BreakModel\" );\n\tWRITE_SHORT( GetModelIndex() );\n\tWRITE_VEC3COORD( GetAbsOrigin() );\n\tWRITE_ANGLES( GetAbsAngles() );\n\tMessageEnd();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CTFProjectile_Arrow::PositionArrowOnBone(mstudiobbox_t *pbox, CBaseAnimating *pAnim )\n{\n\tmatrix3x4_t *bones[MAXSTUDIOBONES];\n\n\tCStudioHdr *pStudioHdr = pAnim->GetModelPtr();\t\n\tif ( !pStudioHdr )\n\t\treturn false;\n\n\tmstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pAnim->GetHitboxSet() );\n\n\tif ( !set->numhitboxes || pbox->bone > 127 )\n\t\treturn false;\n\n\tCBoneCache *pCache = pAnim->GetBoneCache();\n\tif ( !pCache )\n\t\treturn false;\n\n\tpCache->ReadCachedBonePointers( bones, pStudioHdr->numbones() );\n\t\n\tVector vecMins, vecMaxs, vecResult;\n\tTransformAABB( *bones[pbox->bone], pbox->bbmin, pbox->bbmax, vecMins, vecMaxs );\n\tvecResult = vecMaxs - vecMins;\n\n\t// This is a mess\n\tSetAbsOrigin( ( ( ( vecResult ) * 0.60000002f ) + vecMins ) + ( ( ( rand() / RAND_MAX ) * vecResult ) * -0.2f ) );\n\n\treturn true;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::GetBoneAttachmentInfo( mstudiobbox_t *pbox, CBaseAnimating *pAnim, Vector &vecOrigin, QAngle &vecAngles, int &bone, int &iPhysicsBone )\n{\n\tbone = pbox->bone;\n\tiPhysicsBone = pAnim->GetPhysicsBone( bone );\n\t//pAnim->GetBonePosition( bone, vecOrigin, vecAngles );\n\n\tmatrix3x4_t arrowToWorld, boneToWorld, invBoneToWorld, boneToWorldTransform;\n\tMatrixCopy( EntityToWorldTransform(), arrowToWorld );\n\tpAnim->GetBoneTransform( bone, boneToWorld );\n\n\tMatrixInvert( boneToWorld, invBoneToWorld );\n\tConcatTransforms( invBoneToWorld, arrowToWorld, boneToWorldTransform );\n\tMatrixAngles( boneToWorldTransform, vecAngles );\n\tMatrixGetColumn( boneToWorldTransform, 3, vecOrigin );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::CheckRagdollPinned( Vector &, Vector &, int, int, CBaseEntity *, int, int )\n{\n}\n\n// ----------------------------------------------------------------------------\n// Purpose: Play the impact sound to nearby players of the recipient and the attacker\n//-----------------------------------------------------------------------------\nvoid CTFProjectile_Arrow::PlayImpactSound( CTFPlayer *pAttacker, const char *pszImpactSound, bool bIsPlayerImpact /*= false*/ )\n{\n\tif ( pAttacker )\n\t{\n\t\tCRecipientFilter filter;\n\t\tfilter.AddRecipientsByPAS( GetAbsOrigin() );\n\n\t\t// Only play the sound locally to the attacker if it's a player impact\n\t\tif ( bIsPlayerImpact )\n\t\t{\n\t\t\tfilter.RemoveRecipient( pAttacker );\n\t\t\tCSingleUserRecipientFilter filterAttacker( pAttacker );\n\t\t\tEmitSound( filterAttacker, pAttacker->entindex(), pszImpactSound );\n\t\t}\n\n\t\tEmitSound( filter, entindex(), pszImpactSound );\n\t}\n}\n\n#else\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Arrow::OnDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnDataChanged( updateType );\n\n\tif ( updateType == DATA_UPDATE_CREATED )\n\t{\n\t\tSetNextClientThink( gpGlobals->curtime + 0.1f );\t\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Arrow::ClientThink( void )\n{\n\tif ( m_bAttachment && m_flDieTime < gpGlobals->curtime )\n\t{\n\t\t// Die\n\t\tSetNextClientThink( CLIENT_THINK_NEVER );\n\t\tRemove();\n\t\treturn;\n\t}\n\n\tif ( m_bFlame && !bEmitting )\n\t{\n\t\tLight();\n\t\tSetNextClientThink( CLIENT_THINK_NEVER );\n\t\treturn;\n\t}\n\n\tSetNextClientThink( gpGlobals->curtime + 0.1f );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Arrow::Light( void )\n{\n\tif ( IsDormant() || !m_bFlame )\n\t\treturn;\n\n\tParticleProp()->Create( \"flying_flaming_arrow\", PATTACH_ABSORIGIN_FOLLOW );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid C_TFProjectile_Arrow::NotifyBoneAttached( C_BaseAnimating* attachTarget )\n{\n\tBaseClass::NotifyBoneAttached( attachTarget );\n\n\tm_bAttachment = true;\n\tSetNextClientThink( CLIENT_THINK_ALWAYS );\n}\n#endif\n\n\n<|start_filename|>src/game/shared/tf/tf_shareddefs.h<|end_filename|>\n\n//====== Copyright © 1996-2006, Valve Corporation, All rights reserved. =======\n//\n// Purpose: \n//\n//=============================================================================\n#ifndef TF_SHAREDDEFS_H\n#define TF_SHAREDDEFS_H\n#ifdef _WIN32\n#pragma once\n#endif\n\n#include \"shareddefs.h\"\n#include \"mp_shareddefs.h\"\n\n// Using MAP_DEBUG mode?\n#ifdef MAP_DEBUG\n\t#define MDEBUG(x) x\n#else\n\t#define MDEBUG(x)\n#endif\n\n//-----------------------------------------------------------------------------\n// Teams.\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_TEAM_RED = LAST_SHARED_TEAM+1,\n\tTF_TEAM_BLUE,\n\tTF_TEAM_COUNT\n};\n\n#define TF_TEAM_AUTOASSIGN (TF_TEAM_COUNT + 1 )\n\nextern const char *g_aTeamNames[TF_TEAM_COUNT];\nextern const char *g_aTeamNamesShort[TF_TEAM_COUNT];\nextern const char *g_aTeamParticleNames[TF_TEAM_COUNT];\nextern color32 g_aTeamColors[TF_TEAM_COUNT];\nextern color32 g_aTeamSkinColors[TF_TEAM_COUNT];\n\nconst char *GetTeamParticleName( int iTeam, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames );\nconst char *ConstructTeamParticle( const char *pszFormat, int iTeam, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames );\nvoid PrecacheTeamParticles( const char *pszFormat, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames );\n\n#define CONTENTS_REDTEAM\tCONTENTS_TEAM1\n#define CONTENTS_BLUETEAM\tCONTENTS_TEAM2\n\t\t\t\n// Team roles\nenum \n{\n\tTEAM_ROLE_NONE = 0,\n\tTEAM_ROLE_DEFENDERS,\n\tTEAM_ROLE_ATTACKERS,\n\n\tNUM_TEAM_ROLES,\n};\n\n//-----------------------------------------------------------------------------\n// CVar replacements\n//-----------------------------------------------------------------------------\n#define TF_DAMAGE_CRIT_CHANCE\t\t\t\t0.02f\n#define TF_DAMAGE_CRIT_CHANCE_RAPID\t\t\t0.02f\n#define TF_DAMAGE_CRIT_DURATION_RAPID\t\t2.0f\n#define TF_DAMAGE_CRIT_CHANCE_MELEE\t\t\t0.10f\n\n#define TF_DAMAGE_CRITMOD_MAXTIME\t\t\t20\n#define TF_DAMAGE_CRITMOD_MINTIME\t\t\t2\n#define TF_DAMAGE_CRITMOD_DAMAGE\t\t\t800\n#define TF_DAMAGE_CRITMOD_MAXMULT\t\t\t6\n\n#define TF_DAMAGE_CRIT_MULTIPLIER\t\t\t3.0f\n#define TF_DAMAGE_MINICRIT_MULTIPLIER\t\t1.35f\n\n\n//-----------------------------------------------------------------------------\n// TF-specific viewport panels\n//-----------------------------------------------------------------------------\n#define PANEL_CLASS_BLUE\t\t\"class_blue\"\n#define PANEL_CLASS_RED\t\t\t\"class_red\"\n#define PANEL_MAPINFO\t\t\t\"mapinfo\"\n#define PANEL_ROUNDINFO\t\t\t\"roundinfo\"\n#define PANEL_ARENATEAMSELECT \"arenateamselect\"\n\n// file we'll save our list of viewed intro movies in\n#define MOVIES_FILE\t\t\t\t\"viewed.res\"\n\n//-----------------------------------------------------------------------------\n// Used in calculating the health percentage of a player\n//-----------------------------------------------------------------------------\n#define TF_HEALTH_UNDEFINED\t\t1\n\n//-----------------------------------------------------------------------------\n// Used to mark a spy's disguise attribute (team or class) as \"unused\"\n//-----------------------------------------------------------------------------\n#define TF_SPY_UNDEFINED\t\tTEAM_UNASSIGNED\n\n#define COLOR_TF_BLUE\tColor( 64, 64, 255, 255 )\n#define COLOR_TF_RED\tColor( 255, 64, 64, 255 )\n#define COLOR_TF_SPECTATOR Color( 245, 229, 196, 255 )\n\n\n//-----------------------------------------------------------------------------\n// Player Classes.\n//-----------------------------------------------------------------------------\n#define TF_CLASS_COUNT\t\t\t( TF_CLASS_COUNT_ALL - 1 )\n\n#define TF_FIRST_NORMAL_CLASS\t( TF_CLASS_UNDEFINED + 1 )\n\n#define\tTF_CLASS_MENU_BUTTONS\t( TF_CLASS_RANDOM + 1 )\n\nenum\n{\n\tTF_CLASS_UNDEFINED = 0,\n\n\tTF_CLASS_SCOUT,\t\t\t// TF_FIRST_NORMAL_CLASS\n TF_CLASS_SNIPER,\n TF_CLASS_SOLDIER,\n\tTF_CLASS_DEMOMAN,\n\tTF_CLASS_MEDIC,\n\tTF_CLASS_HEAVYWEAPONS,\n\tTF_CLASS_PYRO,\n\tTF_CLASS_SPY,\n\tTF_CLASS_ENGINEER,\t\t// TF_CLASS_COUNT\n\tTF_CLASS_COUNT_ALL,\n\n\tTF_CLASS_RANDOM\n};\n\nextern const char *g_aPlayerClassNames[];\t\t\t\t// localized class names\nextern const char *g_aPlayerClassNames_NonLocalized[];\t// non-localized class names\n\nextern const char *g_aDominationEmblems[];\nextern const char *g_aPlayerClassEmblems[];\nextern const char *g_aPlayerClassEmblemsDead[];\n\n//-----------------------------------------------------------------------------\n// For entity_capture_flags to use when placed in the world\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_FLAGTYPE_CTF = 0,\n\tTF_FLAGTYPE_ATTACK_DEFEND,\n\tTF_FLAGTYPE_TERRITORY_CONTROL,\n\tTF_FLAGTYPE_INVADE,\n\tTF_FLAGTYPE_KINGOFTHEHILL,\n};\n\n//-----------------------------------------------------------------------------\n// For the game rules to determine which type of game we're playing\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_GAMETYPE_UNDEFINED = 0,\n\tTF_GAMETYPE_CTF,\n\tTF_GAMETYPE_CP,\n\tTF_GAMETYPE_ESCORT,\n\tTF_GAMETYPE_ARENA,\n\tTF_GAMETYPE_MVM,\n\tTF_GAMETYPE_RD,\n\tTF_GAMETYPE_PASSTIME,\n\tTF_GAMETYPE_PD,\n\tTF_GAMETYPE_MEDIEVAL,\n};\nextern const char *g_aGameTypeNames[];\t// localized gametype names\n\n//-----------------------------------------------------------------------------\n// Buildings.\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_BUILDING_SENTRY\t\t\t\t= (1<<0),\n\tTF_BUILDING_DISPENSER\t\t\t= (1<<1),\n\tTF_BUILDING_TELEPORT\t\t\t= (1<<2),\n};\n\n//-----------------------------------------------------------------------------\n// Items.\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_ITEM_UNDEFINED\t\t= 0,\n\tTF_ITEM_CAPTURE_FLAG\t= (1<<0),\n\tTF_ITEM_HEALTH_KIT\t\t= (1<<1),\n\tTF_ITEM_ARMOR\t\t\t= (1<<2),\n\tTF_ITEM_AMMO_PACK\t\t= (1<<3),\n\tTF_ITEM_GRENADE_PACK\t= (1<<4),\n};\n\n//-----------------------------------------------------------------------------\n// Ammo.\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_AMMO_DUMMY = 0,\t// Dummy index to make the CAmmoDef indices correct for the other ammo types.\n\tTF_AMMO_PRIMARY,\n\tTF_AMMO_SECONDARY,\n\tTF_AMMO_METAL,\n\tTF_AMMO_GRENADES1,\n\tTF_AMMO_GRENADES2,\n\tTF_AMMO_COUNT\n};\n\nenum EAmmoSource\n{\n\tTF_AMMO_SOURCE_AMMOPACK = 0, // Default, used for ammopacks\n\tTF_AMMO_SOURCE_RESUPPLY, // Maybe?\n\tTF_AMMO_SOURCE_DISPENSER,\n\tTF_AMMO_SOURCE_COUNT\n};\n\n//-----------------------------------------------------------------------------\n// Grenade Launcher mode (for pipebombs).\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_GL_MODE_REGULAR = 0,\n\tTF_GL_MODE_REMOTE_DETONATE,\n\tTF_GL_MODE_FIZZLE\n};\n\n//-----------------------------------------------------------------------------\n// Weapon Types\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_WPN_TYPE_PRIMARY = 0,\n\tTF_WPN_TYPE_SECONDARY,\n\tTF_WPN_TYPE_MELEE,\n\tTF_WPN_TYPE_GRENADE,\n\tTF_WPN_TYPE_BUILDING,\n\tTF_WPN_TYPE_PDA,\n\tTF_WPN_TYPE_ITEM1,\n\tTF_WPN_TYPE_ITEM2,\n\tTF_WPN_TYPE_MELEE_ALLCLASS, // In live tf2 this is equal to 10, however keep it at 8 just in case it screws something else up\n\tTF_WPN_TYPE_SECONDARY2,\n\tTF_WPN_TYPE_PRIMARY2,\n\tTF_WPN_TYPE_COUNT\n};\n\nextern const char *g_AnimSlots[];\nextern const char *g_LoadoutSlots[];\n\n//-----------------------------------------------------------------------------\n// Loadout slots\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_LOADOUT_SLOT_PRIMARY = 0,\n\tTF_LOADOUT_SLOT_SECONDARY,\n\tTF_LOADOUT_SLOT_MELEE,\n\tTF_LOADOUT_SLOT_PDA1,\n\tTF_LOADOUT_SLOT_PDA2,\n\tTF_LOADOUT_SLOT_BUILDING,\n\tTF_LOADOUT_SLOT_HAT,\n\tTF_LOADOUT_SLOT_MISC,\n\tTF_LOADOUT_SLOT_ACTION,\n\tTF_LOADOUT_SLOT_COUNT\n};\n\nextern const char *g_aAmmoNames[];\n\n//-----------------------------------------------------------------------------\n// Weapons.\n//-----------------------------------------------------------------------------\n#define TF_PLAYER_WEAPON_COUNT\t\t5\n#define TF_PLAYER_GRENADE_COUNT\t\t2\n#define TF_PLAYER_BUILDABLE_COUNT\t4\n\n#define TF_WEAPON_PRIMARY_MODE\t\t0\n#define TF_WEAPON_SECONDARY_MODE\t1\n\n#define TF_WEAPON_GRENADE_FRICTION\t\t\t\t\t\t0.6f\n#define TF_WEAPON_GRENADE_GRAVITY\t\t\t\t\t\t0.81f\n#define TF_WEAPON_GRENADE_INITPRIME\t\t\t\t\t\t0.8f\n#define TF_WEAPON_GRENADE_CONCUSSION_TIME\t\t\t\t15.0f\n#define TF_WEAPON_GRENADE_MIRV_BOMB_COUNT\t\t\t\t4\n#define TF_WEAPON_GRENADE_CALTROP_TIME\t\t\t\t\t8.0f\n\n#define TF_WEAPON_PIPEBOMB_WORLD_COUNT\t\t\t\t\t15\n#define TF_WEAPON_PIPEBOMB_COUNT\t\t\t\t\t\t8\n#define TF_WEAPON_PIPEBOMB_INTERVAL\t\t\t\t\t\t0.6f\n\n#define TF_WEAPON_ROCKET_INTERVAL\t\t\t\t\t\t0.8f\n\n#define TF_WEAPON_FLAMETHROWER_INTERVAL\t\t\t\t\t0.15f\n#define TF_WEAPON_FLAMETHROWER_ROCKET_INTERVAL\t\t\t0.8f\n\n#define TF_WEAPON_ZOOM_FOV\t\t\t\t\t\t\t\t20\n\nenum\n{\n\tTF_WEAPON_NONE = 0,\n\tTF_WEAPON_BAT,\n\tTF_WEAPON_BOTTLE,\n\tTF_WEAPON_FIREAXE,\n\tTF_WEAPON_CLUB,\n\tTF_WEAPON_CROWBAR,\n\tTF_WEAPON_KNIFE,\n\tTF_WEAPON_FISTS,\n\tTF_WEAPON_SHOVEL,\n\tTF_WEAPON_WRENCH,\n\tTF_WEAPON_BONESAW,\n\tTF_WEAPON_SHOTGUN_PRIMARY,\n\tTF_WEAPON_SHOTGUN_SOLDIER,\n\tTF_WEAPON_SHOTGUN_HWG,\n\tTF_WEAPON_SHOTGUN_PYRO,\n\tTF_WEAPON_SCATTERGUN,\n\tTF_WEAPON_SNIPERRIFLE,\n\tTF_WEAPON_MINIGUN,\n\tTF_WEAPON_SMG,\n\tTF_WEAPON_SYRINGEGUN_MEDIC,\n\tTF_WEAPON_TRANQ,\n\tTF_WEAPON_ROCKETLAUNCHER,\n\tTF_WEAPON_GRENADELAUNCHER,\n\tTF_WEAPON_PIPEBOMBLAUNCHER,\n\tTF_WEAPON_FLAMETHROWER,\n\tTF_WEAPON_GRENADE_NORMAL,\n\tTF_WEAPON_GRENADE_CONCUSSION,\n\tTF_WEAPON_GRENADE_NAIL,\n\tTF_WEAPON_GRENADE_MIRV,\n\tTF_WEAPON_GRENADE_MIRV_DEMOMAN,\n\tTF_WEAPON_GRENADE_NAPALM,\n\tTF_WEAPON_GRENADE_GAS,\n\tTF_WEAPON_GRENADE_EMP,\n\tTF_WEAPON_GRENADE_CALTROP,\n\tTF_WEAPON_GRENADE_PIPEBOMB,\n\tTF_WEAPON_GRENADE_SMOKE_BOMB,\n\tTF_WEAPON_GRENADE_HEAL,\n\tTF_WEAPON_PISTOL,\n\tTF_WEAPON_PISTOL_SCOUT,\n\tTF_WEAPON_REVOLVER,\n\tTF_WEAPON_NAILGUN,\n\tTF_WEAPON_PDA,\n\tTF_WEAPON_PDA_ENGINEER_BUILD,\n\tTF_WEAPON_PDA_ENGINEER_DESTROY,\n\tTF_WEAPON_PDA_SPY,\n\tTF_WEAPON_BUILDER,\n\tTF_WEAPON_MEDIGUN,\n\tTF_WEAPON_GRENADE_MIRVBOMB,\n\tTF_WEAPON_FLAMETHROWER_ROCKET,\n\tTF_WEAPON_GRENADE_DEMOMAN,\n\tTF_WEAPON_SENTRY_BULLET,\n\tTF_WEAPON_SENTRY_ROCKET,\n\tTF_WEAPON_DISPENSER,\n\tTF_WEAPON_INVIS,\n\tTF_WEAPON_FLAG, // ADD NEW WEAPONS AFTER THIS\n\tTF_WEAPON_FLAREGUN,\n\tTF_WEAPON_LUNCHBOX,\n\tTF_WEAPON_LUNCHBOX_DRINK,\n\tTF_WEAPON_COMPOUND_BOW,\n\tTF_WEAPON_JAR,\n\tTF_WEAPON_LASER_POINTER,\n\tTF_WEAPON_HANDGUN_SCOUT_PRIMARY,\n\tTF_WEAPON_STICKBOMB, \n\tTF_WEAPON_BAT_WOOD,\n\tTF_WEAPON_ROBOT_ARM,\n\tTF_WEAPON_BUFF_ITEM,\n\n\tTF_WEAPON_COUNT\n};\n\nextern const char *g_aWeaponNames[];\nextern int g_aWeaponDamageTypes[];\nextern const Vector g_vecFixedWpnSpreadPellets[];\n\nint GetWeaponId( const char *pszWeaponName );\n#ifdef GAME_DLL\nint GetWeaponFromDamage( const CTakeDamageInfo &info );\n#endif\nint GetBuildableId( const char *pszBuildableName );\n\nconst char *WeaponIdToAlias( int iWeapon );\nconst char *WeaponIdToClassname( int iWeapon );\nconst char *TranslateWeaponEntForClass( const char *pszName, int iClass );\n\nenum\n{\n\tTF_PROJECTILE_NONE,\n\tTF_PROJECTILE_BULLET,\n\tTF_PROJECTILE_ROCKET,\n\tTF_PROJECTILE_PIPEBOMB,\n\tTF_PROJECTILE_PIPEBOMB_REMOTE,\n\tTF_PROJECTILE_SYRINGE,\n\tTF_PROJECTILE_FLARE,\n\tTF_PROJECTILE_JAR,\n\tTF_PROJECTILE_ARROW,\n\tTF_PROJECTILE_FLAME_ROCKET,\n\tTF_PROJECTILE_JAR_MILK,\n\tTF_PROJECTILE_HEALING_BOLT,\n\tTF_PROJECTILE_ENERGY_BALL,\n\tTF_PROJECTILE_ENERGY_RING,\n\tTF_PROJECTILE_PIPEBOMB_REMOTE_PRACTICE,\n\tTF_PROJECTILE_CLEAVER,\n\tTF_PROJECTILE_STICKY_BALL,\n\tTF_PROJECTILE_CANNONBALL,\n\tTF_PROJECTILE_BUILDING_REPAIR_BOLT,\n\tTF_PROJECTILE_FESTITIVE_ARROW,\n\tTF_PROJECTILE_THROWABLE,\n\tTF_PROJECTILE_SPELLFIREBALL,\n\tTF_PROJECTILE_FESTITIVE_URINE,\n\tTF_PROJECTILE_FESTITIVE_HEALING_BOLT,\n\tTF_PROJECTILE_BREADMONSTER_JARATE,\n\tTF_PROJECTILE_BREADMONSTER_MADMILK,\n\tTF_PROJECTILE_GRAPPLINGHOOK,\n\tTF_PROJECTILE_SENTRY_ROCKET,\n\tTF_PROJECTILE_BREAD_MONSTER,\n\n\tTF_NUM_PROJECTILES\n};\n\nextern const char *g_szProjectileNames[];\n\n//-----------------------------------------------------------------------------\n// Attributes.\n//-----------------------------------------------------------------------------\n#define TF_PLAYER_VIEW_OFFSET\tVector( 0, 0, 64.0 ) //--> see GetViewVectors()\n\n//-----------------------------------------------------------------------------\n// TF Player Condition.\n//-----------------------------------------------------------------------------\n\n// Burning\n#define TF_BURNING_FREQUENCY\t\t0.5f\n#define TF_BURNING_FLAME_LIFE\t\t10.0\n#define TF_BURNING_FLAME_LIFE_PYRO\t0.25\t\t// pyro only displays burning effect momentarily\n#define TF_BURNING_DMG\t\t\t\t3\n\n// disguising\n#define TF_TIME_TO_CHANGE_DISGUISE 0.5\n#define TF_TIME_TO_DISGUISE 2.0\n#define TF_TIME_TO_SHOW_DISGUISED_FINISHED_EFFECT 5.0\n\n\n#define SHOW_DISGUISE_EFFECT 1\n#define TF_DISGUISE_TARGET_INDEX_NONE\t( MAX_PLAYERS + 1 )\n#define TF_PLAYER_INDEX_NONE\t\t\t( MAX_PLAYERS + 1 )\n\n// Most of these conds aren't actually implemented but putting them here for compatibility.\nenum\n{\n\tTF_COND_AIMING = 0,\t\t// Sniper aiming, Heavy minigun.\n\tTF_COND_ZOOMED,\n\tTF_COND_DISGUISING,\n\tTF_COND_DISGUISED,\n\tTF_COND_STEALTHED,\n\tTF_COND_INVULNERABLE,\n\tTF_COND_TELEPORTED,\n\tTF_COND_TAUNTING,\n\tTF_COND_INVULNERABLE_WEARINGOFF,\n\tTF_COND_STEALTHED_BLINK,\n\tTF_COND_SELECTED_TO_TELEPORT,\n\tTF_COND_CRITBOOSTED,\n\tTF_COND_TMPDAMAGEBONUS,\n\tTF_COND_FEIGN_DEATH,\n\tTF_COND_PHASE,\n\tTF_COND_STUNNED,\n\tTF_COND_OFFENSEBUFF,\n\tTF_COND_SHIELD_CHARGE,\n\tTF_COND_DEMO_BUFF,\n\tTF_COND_ENERGY_BUFF,\n\tTF_COND_RADIUSHEAL,\n\tTF_COND_HEALTH_BUFF,\n\tTF_COND_BURNING,\n\tTF_COND_HEALTH_OVERHEALED,\n\tTF_COND_URINE,\n\tTF_COND_BLEEDING,\n\tTF_COND_DEFENSEBUFF,\n\tTF_COND_MAD_MILK,\n\tTF_COND_MEGAHEAL,\n\tTF_COND_REGENONDAMAGEBUFF,\n\tTF_COND_MARKEDFORDEATH,\n\tTF_COND_NOHEALINGDAMAGEBUFF,\n\tTF_COND_SPEED_BOOST,\n\tTF_COND_CRITBOOSTED_PUMPKIN,\n\tTF_COND_CRITBOOSTED_USER_BUFF,\n\tTF_COND_CRITBOOSTED_DEMO_CHARGE,\n\tTF_COND_SODAPOPPER_HYPE,\n\tTF_COND_CRITBOOSTED_FIRST_BLOOD,\n\tTF_COND_CRITBOOSTED_BONUS_TIME,\n\tTF_COND_CRITBOOSTED_CTF_CAPTURE,\n\tTF_COND_CRITBOOSTED_ON_KILL,\n\tTF_COND_CANNOT_SWITCH_FROM_MELEE,\n\tTF_COND_DEFENSEBUFF_NO_CRIT_BLOCK,\n\tTF_COND_REPROGRAMMED,\n\tTF_COND_CRITBOOSTED_RAGE_BUFF,\n\tTF_COND_DEFENSEBUFF_HIGH,\n\tTF_COND_SNIPERCHARGE_RAGE_BUFF,\n\tTF_COND_DISGUISE_WEARINGOFF,\n\tTF_COND_MARKEDFORDEATH_SILENT,\n\tTF_COND_DISGUISED_AS_DISPENSER,\n\tTF_COND_SAPPED,\n\tTF_COND_INVULNERABLE_HIDE_UNLESS_DAMAGE,\n\tTF_COND_INVULNERABLE_USER_BUFF,\n\tTF_COND_HALLOWEEN_BOMB_HEAD,\n\tTF_COND_HALLOWEEN_THRILLER,\n\tTF_COND_RADIUSHEAL_ON_DAMAGE,\n\tTF_COND_CRITBOOSTED_CARD_EFFECT,\n\tTF_COND_INVULNERABLE_CARD_EFFECT,\n\tTF_COND_MEDIGUN_UBER_BULLET_RESIST,\n\tTF_COND_MEDIGUN_UBER_BLAST_RESIST,\n\tTF_COND_MEDIGUN_UBER_FIRE_RESIST,\n\tTF_COND_MEDIGUN_SMALL_BULLET_RESIST,\n\tTF_COND_MEDIGUN_SMALL_BLAST_RESIST,\n\tTF_COND_MEDIGUN_SMALL_FIRE_RESIST,\n\tTF_COND_STEALTHED_USER_BUFF,\n\tTF_COND_MEDIGUN_DEBUFF,\n\tTF_COND_STEALTHED_USER_BUFF_FADING,\n\tTF_COND_BULLET_IMMUNE,\n\tTF_COND_BLAST_IMMUNE,\n\tTF_COND_FIRE_IMMUNE,\n\tTF_COND_PREVENT_DEATH,\n\tTF_COND_MVM_BOT_STUN_RADIOWAVE,\n\tTF_COND_HALLOWEEN_SPEED_BOOST,\n\tTF_COND_HALLOWEEN_QUICK_HEAL,\n\tTF_COND_HALLOWEEN_GIANT,\n\tTF_COND_HALLOWEEN_TINY,\n\tTF_COND_HALLOWEEN_IN_HELL,\n\tTF_COND_HALLOWEEN_GHOST_MODE,\n\tTF_COND_MINICRITBOOSTED_ON_KILL,\n\tTF_COND_OBSCURED_SMOKE,\n\tTF_COND_PARACHUTE_DEPLOYED,\n\tTF_COND_BLASTJUMPING,\n\tTF_COND_HALLOWEEN_KART,\n\tTF_COND_HALLOWEEN_KART_DASH,\n\tTF_COND_BALLOON_HEAD,\n\tTF_COND_MELEE_ONLY,\n\tTF_COND_SWIMMING_CURSE,\n\tTF_COND_FREEZE_INPUT,\n\tTF_COND_HALLOWEEN_KART_CAGE,\n\tTF_COND_DONOTUSE_0,\n\tTF_COND_RUNE_STRENGTH,\n\tTF_COND_RUNE_HASTE,\n\tTF_COND_RUNE_REGEN,\n\tTF_COND_RUNE_RESIST,\n\tTF_COND_RUNE_VAMPIRE,\n\tTF_COND_RUNE_WARLOCK,\n\tTF_COND_RUNE_PRECISION,\n\tTF_COND_RUNE_AGILITY,\n\tTF_COND_GRAPPLINGHOOK,\n\tTF_COND_GRAPPLINGHOOK_SAFEFALL,\n\tTF_COND_GRAPPLINGHOOK_LATCHED,\n\tTF_COND_GRAPPLINGHOOK_BLEEDING,\n\tTF_COND_AFTERBURN_IMMUNE,\n\tTF_COND_RUNE_KNOCKOUT,\n\tTF_COND_RUNE_IMBALANCE,\n\tTF_COND_CRITBOOSTED_RUNE_TEMP,\n\tTF_COND_PASSTIME_INTERCEPTION,\n\n\t// TF2V conds\n\tTF_COND_NO_MOVE,\n\tTF_COND_DISGUISE_HEALTH_OVERHEALED,\n\n\tTF_COND_LAST\n};\n\nextern int condition_to_attribute_translation[];\n\nint ConditionExpiresFast( int nCond );\n\n//-----------------------------------------------------------------------------\n// Mediguns.\n//-----------------------------------------------------------------------------\nenum\n{\n\tTF_MEDIGUN_STOCK = 0,\n\tTF_MEDIGUN_KRITZKRIEG,\n\tTF_MEDIGUN_QUICKFIX,\n\tTF_MEDIGUN_VACCINATOR,\n\tTF_MEDIGUN_OVERHEALER,\n\tTF_MEDIGUN_COUNT\n};\n\nenum medigun_charge_types\n{\n\tTF_CHARGE_NONE = -1,\n\tTF_CHARGE_INVULNERABLE = 0,\n\tTF_CHARGE_CRITBOOSTED,\n\t// TODO:\n#if 0\n\tTF_CHARGE_MEGAHEAL,\n\tTF_CHARGE_BULLET_RESIST,\n\tTF_CHARGE_BLAST_RESIST,\n\tTF_CHARGE_FIRE_RESIST,\n#endif\n\tTF_CHARGE_COUNT\n};\n\ntypedef struct\n{\n\tint condition_enable;\n\tint condition_disable;\n\tconst char *sound_enable;\n\tconst char *sound_disable;\n} MedigunEffects_t;\n\nextern MedigunEffects_t g_MedigunEffects[];\n\n//-----------------------------------------------------------------------------\n// TF Player State.\n//-----------------------------------------------------------------------------\nenum \n{\n\tTF_STATE_ACTIVE = 0,\t\t// Happily running around in the game.\n\tTF_STATE_WELCOME,\t\t\t// First entering the server (shows level intro screen).\n\tTF_STATE_OBSERVER,\t\t\t// Game observer mode.\n\tTF_STATE_DYING,\t\t\t\t// Player is dying.\n\tTF_STATE_COUNT\n};\n\n//-----------------------------------------------------------------------------\n// TF FlagInfo State.\n//-----------------------------------------------------------------------------\n#define TF_FLAGINFO_NONE\t\t0\n#define TF_FLAGINFO_STOLEN\t\t(1<<0)\n#define TF_FLAGINFO_DROPPED\t\t(1<<1)\n\nenum {\n\tTF_FLAGEVENT_PICKUP = 1,\n\tTF_FLAGEVENT_CAPTURE,\n\tTF_FLAGEVENT_DEFEND,\n\tTF_FLAGEVENT_DROPPED\n};\n\n//-----------------------------------------------------------------------------\n// Class data\n//-----------------------------------------------------------------------------\n#define TF_MEDIC_REGEN_TIME\t\t\t1.0\t\t// Number of seconds between each regen.\n#define TF_MEDIC_REGEN_AMOUNT\t\t1 \t\t// Amount of health regenerated each regen.\n\n//-----------------------------------------------------------------------------\n// Assist-damage constants\n//-----------------------------------------------------------------------------\n#define TF_TIME_ASSIST_KILL\t\t\t\t3.0f\t// Time window for a recent damager to get credit for an assist for a kill\n#define TF_TIME_ENV_DEATH_KILL_CREDIT\t5.0f\t// Time window for a recent damager to get credit for an environmental kill\n#define TF_TIME_SUICIDE_KILL_CREDIT\t\t10.0f\t// Time window for a recent damager to get credit for a kill if target suicides\n\n//-----------------------------------------------------------------------------\n// Domination/nemesis constants\n//-----------------------------------------------------------------------------\n#define TF_KILLS_DOMINATION\t\t\t\t4\t\t// # of unanswered kills to dominate another player\n\n//-----------------------------------------------------------------------------\n// TF Hints\n//-----------------------------------------------------------------------------\nenum\n{\n\tHINT_FRIEND_SEEN = 0,\t\t\t\t// #Hint_spotted_a_friend\n\tHINT_ENEMY_SEEN,\t\t\t\t\t// #Hint_spotted_an_enemy\n\tHINT_ENEMY_KILLED,\t\t\t\t\t// #Hint_killing_enemies_is_good\n\tHINT_AMMO_EXHAUSTED,\t\t\t\t// #Hint_out_of_ammo\n\tHINT_TURN_OFF_HINTS,\t\t\t\t// #Hint_turn_off_hints\n\tHINT_PICKUP_AMMO,\t\t\t\t\t// #Hint_pickup_ammo\n\tHINT_CANNOT_TELE_WITH_FLAG,\t\t\t// #Hint_Cannot_Teleport_With_Flag\n\tHINT_CANNOT_CLOAK_WITH_FLAG,\t\t// #Hint_Cannot_Cloak_With_Flag\n\tHINT_CANNOT_DISGUISE_WITH_FLAG,\t\t// #Hint_Cannot_Disguise_With_Flag\n\tHINT_CANNOT_ATTACK_WHILE_CLOAKED,\t// #Hint_Cannot_Attack_While_Cloaked\n\tHINT_CLASSMENU,\t\t\t\t\t\t// #Hint_ClassMenu\n\n\t// Grenades\n\tHINT_GREN_CALTROPS,\t\t\t\t\t// #Hint_gren_caltrops\n\tHINT_GREN_CONCUSSION,\t\t\t\t// #Hint_gren_concussion\n\tHINT_GREN_EMP,\t\t\t\t\t\t// #Hint_gren_emp\n\tHINT_GREN_GAS,\t\t\t\t\t\t// #Hint_gren_gas\n\tHINT_GREN_MIRV,\t\t\t\t\t\t// #Hint_gren_mirv\n\tHINT_GREN_NAIL,\t\t\t\t\t\t// #Hint_gren_nail\n\tHINT_GREN_NAPALM,\t\t\t\t\t// #Hint_gren_napalm\n\tHINT_GREN_NORMAL,\t\t\t\t\t// #Hint_gren_normal\n\n\t// Weapon alt-fires\n\tHINT_ALTFIRE_SNIPERRIFLE,\t\t\t// #Hint_altfire_sniperrifle\n\tHINT_ALTFIRE_FLAMETHROWER,\t\t\t// #Hint_altfire_flamethrower\n\tHINT_ALTFIRE_GRENADELAUNCHER,\t\t// #Hint_altfire_grenadelauncher\n\tHINT_ALTFIRE_PIPEBOMBLAUNCHER,\t\t// #Hint_altfire_pipebomblauncher\n\tHINT_ALTFIRE_ROTATE_BUILDING,\t\t// #Hint_altfire_rotate_building\n\n\t// Class specific\n\t// Soldier\n\tHINT_SOLDIER_RPG_RELOAD,\t\t\t// #Hint_Soldier_rpg_reload\n\n\t// Engineer\n\tHINT_ENGINEER_USE_WRENCH_ONOWN,\t\t// \"#Hint_Engineer_use_wrench_onown\",\n\tHINT_ENGINEER_USE_WRENCH_ONOTHER,\t// \"#Hint_Engineer_use_wrench_onother\",\n\tHINT_ENGINEER_USE_WRENCH_FRIEND,\t// \"#Hint_Engineer_use_wrench_onfriend\",\n\tHINT_ENGINEER_BUILD_SENTRYGUN,\t\t// \"#Hint_Engineer_build_sentrygun\"\n\tHINT_ENGINEER_BUILD_DISPENSER,\t\t// \"#Hint_Engineer_build_dispenser\"\n\tHINT_ENGINEER_BUILD_TELEPORTERS,\t// \"#Hint_Engineer_build_teleporters\"\n\tHINT_ENGINEER_PICKUP_METAL,\t\t\t// \"#Hint_Engineer_pickup_metal\"\n\tHINT_ENGINEER_REPAIR_OBJECT,\t\t// \"#Hint_Engineer_repair_object\"\n\tHINT_ENGINEER_METAL_TO_UPGRADE,\t\t// \"#Hint_Engineer_metal_to_upgrade\"\n\tHINT_ENGINEER_UPGRADE_SENTRYGUN,\t// \"#Hint_Engineer_upgrade_sentrygun\"\n\n\tHINT_OBJECT_HAS_SAPPER,\t\t\t\t// \"#Hint_object_has_sapper\"\n\n\tHINT_OBJECT_YOUR_OBJECT_SAPPED,\t\t// \"#Hint_object_your_object_sapped\"\n\tHINT_OBJECT_ENEMY_USING_DISPENSER,\t// \"#Hint_enemy_using_dispenser\"\n\tHINT_OBJECT_ENEMY_USING_TP_ENTRANCE,\t// \"#Hint_enemy_using_tp_entrance\"\n\tHINT_OBJECT_ENEMY_USING_TP_EXIT,\t// \"#Hint_enemy_using_tp_exit\"\n\n\tNUM_HINTS\n};\nextern const char *g_pszHintMessages[];\n\n\n\n/*======================*/\n// Menu stuff //\n/*======================*/\n\n#define MENU_DEFAULT\t\t\t\t1\n#define MENU_TEAM \t\t\t\t\t2\n#define MENU_CLASS \t\t\t\t\t3\n#define MENU_MAPBRIEFING\t\t\t4\n#define MENU_INTRO \t\t\t\t\t5\n#define MENU_CLASSHELP\t\t\t\t6\n#define MENU_CLASSHELP2 \t\t\t7\n#define MENU_REPEATHELP \t\t\t8\n\n#define MENU_SPECHELP\t\t\t\t9\n\n\n#define MENU_SPY\t\t\t\t\t12\n#define MENU_SPY_SKIN\t\t\t\t13\n#define MENU_SPY_COLOR\t\t\t\t14\n#define MENU_ENGINEER\t\t\t\t15\n#define MENU_ENGINEER_FIX_DISPENSER\t16\n#define MENU_ENGINEER_FIX_SENTRYGUN\t17\n#define MENU_ENGINEER_FIX_MORTAR\t18\n#define MENU_DISPENSER\t\t\t\t19\n#define MENU_CLASS_CHANGE\t\t\t20\n#define MENU_TEAM_CHANGE\t\t\t21\n\n#define MENU_REFRESH_RATE \t\t\t25\n\n#define MENU_VOICETWEAK\t\t\t\t50\n\n// Additional classes\n// NOTE: adding them onto the Class_T's in baseentity.h is cheesy, but so is\n// having an #ifdef for each mod in baseentity.h.\n#define CLASS_TFGOAL\t\t\t\t((Class_T)NUM_AI_CLASSES)\n#define CLASS_TFGOAL_TIMER\t\t\t((Class_T)(NUM_AI_CLASSES+1))\n#define CLASS_TFGOAL_ITEM\t\t\t((Class_T)(NUM_AI_CLASSES+2))\n#define CLASS_TFSPAWN\t\t\t\t((Class_T)(NUM_AI_CLASSES+3))\n#define CLASS_MACHINE\t\t\t\t((Class_T)(NUM_AI_CLASSES+4))\n\n// TeamFortress State Flags\n#define TFSTATE_GRENPRIMED\t\t0x000001 // Whether the player has a primed grenade\n#define TFSTATE_RELOADING\t\t0x000002 // Whether the player is reloading\n#define TFSTATE_ALTKILL\t\t\t0x000004 // #TRUE if killed with a weapon not in self.weapon: NOT USED ANYMORE\n#define TFSTATE_RANDOMPC\t\t0x000008 // Whether Playerclass is random, new one each respawn\n#define TFSTATE_INFECTED\t\t0x000010 // set when player is infected by the bioweapon\n#define TFSTATE_INVINCIBLE\t\t0x000020 // Player has permanent Invincibility (Usually by GoalItem)\n#define TFSTATE_INVISIBLE\t\t0x000040 // Player has permanent Invisibility (Usually by GoalItem)\n#define TFSTATE_QUAD\t\t\t0x000080 // Player has permanent Quad Damage (Usually by GoalItem)\n#define TFSTATE_RADSUIT\t\t\t0x000100 // Player has permanent Radsuit (Usually by GoalItem)\n#define TFSTATE_BURNING\t\t\t0x000200 // Is on fire\n#define TFSTATE_GRENTHROWING\t0x000400 // is throwing a grenade\n#define TFSTATE_AIMING\t\t\t0x000800 // is using the laser sight\n#define TFSTATE_ZOOMOFF\t\t\t0x001000 // doesn't want the FOV changed when zooming\n#define TFSTATE_RESPAWN_READY\t0x002000 // is waiting for respawn, and has pressed fire\n#define TFSTATE_HALLUCINATING\t0x004000 // set when player is hallucinating\n#define TFSTATE_TRANQUILISED\t0x008000 // set when player is tranquilised\n#define TFSTATE_CANT_MOVE\t\t0x010000 // player isn't allowed to move\n#define TFSTATE_RESET_FLAMETIME 0x020000 // set when the player has to have his flames increased in health\n#define TFSTATE_HIGHEST_VALUE\tTFSTATE_RESET_FLAMETIME\n\n// items\n#define IT_SHOTGUN\t\t\t\t(1<<0)\n#define IT_SUPER_SHOTGUN\t\t(1<<1) \n#define IT_NAILGUN\t\t\t\t(1<<2) \n#define IT_SUPER_NAILGUN\t\t(1<<3) \n#define IT_GRENADE_LAUNCHER\t\t(1<<4) \n#define IT_ROCKET_LAUNCHER\t\t(1<<5) \n#define IT_LIGHTNING\t\t\t(1<<6) \n#define IT_EXTRA_WEAPON\t\t\t(1<<7) \n\n#define IT_SHELLS\t\t\t\t(1<<8) \n#define IT_BULLETS\t\t\t\t(1<<9) \n#define IT_ROCKETS\t\t\t\t(1<<10) \n#define IT_CELLS\t\t\t\t(1<<11) \n#define IT_AXE\t\t\t\t\t(1<<12) \n\n#define IT_ARMOR1\t\t\t\t(1<<13) \n#define IT_ARMOR2\t\t\t\t(1<<14) \n#define IT_ARMOR3\t\t\t\t(1<<15) \n#define IT_SUPERHEALTH\t\t\t(1<<16) \n\n#define IT_KEY1\t\t\t\t\t(1<<17) \n#define IT_KEY2\t\t\t\t\t(1<<18) \n\n#define IT_INVISIBILITY\t\t\t(1<<19) \n#define IT_INVULNERABILITY\t\t(1<<20) \n#define IT_SUIT\t\t\t\t\t(1<<21)\n#define IT_QUAD\t\t\t\t\t(1<<22) \n#define IT_HOOK\t\t\t\t\t(1<<23)\n\n#define IT_KEY3\t\t\t\t\t(1<<24)\t// Stomp invisibility\n#define IT_KEY4\t\t\t\t\t(1<<25)\t// Stomp invulnerability\n#define IT_LAST_ITEM\t\t\tIT_KEY4\n\n/*==================================================*/\n/* New Weapon Related Defines\t\t */\n/*==================================================*/\n\n// Medikit\n#define WEAP_MEDIKIT_OVERHEAL 50 // Amount of superhealth over max_health the medikit will dispense\n#define WEAP_MEDIKIT_HEAL\t200 // Amount medikit heals per hit\n\n//--------------\n// TF Specific damage flags\n//--------------\n//#define DMG_UNUSED\t\t\t\t\t(DMG_LASTGENERICFLAG<<2)\n// We can't add anymore dmg flags, because we'd be over the 32 bit limit.\n// So lets re-use some of the old dmg flags in TF\n#define DMG_USE_HITLOCATIONS\t(DMG_AIRBOAT)\n#define DMG_HALF_FALLOFF\t\t(DMG_RADIATION)\n#define DMG_CRITICAL\t\t\t(DMG_ACID)\n#define DMG_MINICRITICAL\t\t(DMG_PHYSGUN)\n#define DMG_RADIUS_MAX\t\t\t(DMG_ENERGYBEAM)\n#define DMG_IGNITE\t\t\t\t(DMG_PLASMA)\n#define DMG_USEDISTANCEMOD\t\t(DMG_SLOWBURN)\t\t// NEED TO REMOVE CALTROPS\n#define DMG_NOCLOSEDISTANCEMOD\t(DMG_POISON)\n\n#define TF_DMG_SENTINEL_VALUE\t0xFFFFFFFF\n\n// This can only ever be used on a TakeHealth call, since it re-uses a dmg flag that means something else\n#define DMG_IGNORE_MAXHEALTH\t(DMG_BULLET)\n\n// Special Damage types\nenum\n{\n\tTF_DMG_CUSTOM_NONE, // TODO: Remove this at some point\n\n\tTF_DMG_CUSTOM_HEADSHOT,\n\tTF_DMG_CUSTOM_BACKSTAB,\n\tTF_DMG_CUSTOM_BURNING,\n\tTF_DMG_WRENCH_FIX,\n\tTF_DMG_CUSTOM_MINIGUN,\n\tTF_DMG_CUSTOM_SUICIDE,\n\tTF_DMG_CUSTOM_TAUNTATK_HADOUKEN,\n\tTF_DMG_CUSTOM_BURNING_FLARE,\n\tTF_DMG_CUSTOM_TAUNTATK_HIGH_NOON,\n\tTF_DMG_CUSTOM_TAUNTATK_GRAND_SLAM,\n\tTF_DMG_CUSTOM_PENETRATE_MY_TEAM,\n\tTF_DMG_CUSTOM_PENETRATE_ALL_PLAYERS,\n\tTF_DMG_CUSTOM_TAUNTATK_FENCING,\n\tTF_DMG_CUSTOM_PENETRATE_NONBURNING_TEAMMATE,\n\tTF_DMG_CUSTOM_TAUNTATK_ARROW_STAB,\n\tTF_DMG_CUSTOM_TELEFRAG,\n\tTF_DMG_CUSTOM_BURNING_ARROW,\n\tTF_DMG_CUSTOM_FLYINGBURN,\n\tTF_DMG_CUSTOM_PUMPKIN_BOMB,\n\tTF_DMG_CUSTOM_DECAPITATION,\n\tTF_DMG_CUSTOM_TAUNTATK_GRENADE,\n\tTF_DMG_CUSTOM_BASEBALL,\n\tTF_DMG_CUSTOM_CHARGE_IMPACT,\n\tTF_DMG_CUSTOM_TAUNTATK_BARBARIAN_SWING,\n\tTF_DMG_CUSTOM_AIR_STICKY_BURST,\n\tTF_DMG_CUSTOM_DEFENSIVE_STICKY,\n\tTF_DMG_CUSTOM_PICKAXE,\n\tTF_DMG_CUSTOM_ROCKET_DIRECTHIT,\n\tTF_DMG_CUSTOM_TAUNTATK_UBERSLICE,\n\tTF_DMG_CUSTOM_PLAYER_SENTRY,\n\tTF_DMG_CUSTOM_STANDARD_STICKY,\n\tTF_DMG_CUSTOM_SHOTGUN_REVENGE_CRIT,\n\tTF_DMG_CUSTOM_TAUNTATK_ENGINEER_GUITAR_SMASH,\n\tTF_DMG_CUSTOM_BLEEDING,\n\tTF_DMG_CUSTOM_GOLD_WRENCH,\n\tTF_DMG_CUSTOM_CARRIED_BUILDING,\n\tTF_DMG_CUSTOM_COMBO_PUNCH,\n\tTF_DMG_CUSTOM_TAUNTATK_ENGINEER_ARM_KILL,\n\tTF_DMG_CUSTOM_FISH_KILL,\n\tTF_DMG_CUSTOM_TRIGGER_HURT,\n\tTF_DMG_CUSTOM_DECAPITATION_BOSS,\n\tTF_DMG_CUSTOM_STICKBOMB_EXPLOSION,\n\tTF_DMG_CUSTOM_AEGIS_ROUND,\n\tTF_DMG_CUSTOM_FLARE_EXPLOSION,\n\tTF_DMG_CUSTOM_BOOTS_STOMP,\n\tTF_DMG_CUSTOM_PLASMA,\n\tTF_DMG_CUSTOM_PLASMA_CHARGED,\n\tTF_DMG_CUSTOM_PLASMA_GIB,\n\tTF_DMG_CUSTOM_PRACTICE_STICKY,\n\tTF_DMG_CUSTOM_EYEBALL_ROCKET,\n\tTF_DMG_CUSTOM_HEADSHOT_DECAPITATION,\n\tTF_DMG_CUSTOM_TAUNTATK_ARMAGEDDON,\n\tTF_DMG_CUSTOM_FLARE_PELLET,\n\tTF_DMG_CUSTOM_CLEAVER,\n\tTF_DMG_CUSTOM_CLEAVER_CRIT,\n\tTF_DMG_CUSTOM_SAPPER_RECORDER_DEATH,\n\tTF_DMG_CUSTOM_MERASMUS_PLAYER_BOMB,\n\tTF_DMG_CUSTOM_MERASMUS_GRENADE,\n\tTF_DMG_CUSTOM_MERASMUS_ZAP,\n\tTF_DMG_CUSTOM_MERASMUS_DECAPITATION,\n\tTF_DMG_CUSTOM_CANNONBALL_PUSH,\n\tTF_DMG_CUSTOM_TAUNTATK_ALLCLASS_GUITAR_RIFF,\n\tTF_DMG_CUSTOM_THROWABLE,\n\tTF_DMG_CUSTOM_THROWABLE_KILL,\n\tTF_DMG_CUSTOM_SPELL_TELEPORT,\n\tTF_DMG_CUSTOM_SPELL_SKELETON,\n\tTF_DMG_CUSTOM_SPELL_MIRV,\n\tTF_DMG_CUSTOM_SPELL_METEOR,\n\tTF_DMG_CUSTOM_SPELL_LIGHTNING,\n\tTF_DMG_CUSTOM_SPELL_FIREBALL,\n\tTF_DMG_CUSTOM_SPELL_MONOCULUS,\n\tTF_DMG_CUSTOM_SPELL_BLASTJUMP,\n\tTF_DMG_CUSTOM_SPELL_BATS,\n\tTF_DMG_CUSTOM_SPELL_TINY,\n\tTF_DMG_CUSTOM_KART,\n\tTF_DMG_CUSTOM_GIANT_HAMMER,\n\tTF_DMG_CUSTOM_RUNE_REFLECT,\n\tTF_DMG_CUSTOM_DRAGONS_FURY_IGNITE,\n\tTF_DMG_CUSTOM_DRAGONS_FURY_BONUS_BURNIN,\n\tTF_DMG_CUSTOM_SLAP_KILL,\n\tTF_DMG_CUSTOM_CROC,\n\tTF_DMG_CUSTOM_TAUNTATK_GASBLAST,\n\tTF_DMG_CUSTOM_AXTINGUISHER_BOOSTED,\n};\n\n#define TF_JUMP_ROCKET\t( 1 << 0 )\n#define TF_JUMP_STICKY\t( 1 << 1 )\n#define TF_JUMP_OTHER\t( 1 << 2 )\n\nenum\n{\n\tTF_COLLISIONGROUP_GRENADES = LAST_SHARED_COLLISION_GROUP,\n\tTFCOLLISION_GROUP_OBJECT,\n\tTFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT,\n\tTFCOLLISION_GROUP_COMBATOBJECT,\n\tTFCOLLISION_GROUP_ROCKETS,\t\t// Solid to players, but not player movement. ensures touch calls are originating from rocket\n\tTFCOLLISION_GROUP_RESPAWNROOMS,\n\tTFCOLLISION_GROUP_PUMPKIN_BOMB, // Bombs\n\tTFCOLLISION_GROUP_ARROWS, // Arrows\n\tTFCOLLISION_GROUP_NONE, // Collides with nothing\n};\n\n//-----------------\n// TF Objects Info\n//-----------------\n\n#define SENTRYGUN_UPGRADE_COST\t\t\t130\n#define SENTRYGUN_UPGRADE_METAL\t\t\t200\n#define SENTRYGUN_EYE_OFFSET_LEVEL_1\tVector( 0, 0, 32 )\n#define SENTRYGUN_EYE_OFFSET_LEVEL_2\tVector( 0, 0, 40 )\n#define SENTRYGUN_EYE_OFFSET_LEVEL_3\tVector( 0, 0, 46 )\n#define SENTRYGUN_MAX_SHELLS_1\t\t\t150\n#define SENTRYGUN_MAX_SHELLS_2\t\t\t200\n#define SENTRYGUN_MAX_SHELLS_3\t\t\t200\n#define SENTRYGUN_MAX_ROCKETS\t\t\t20\n\n// Dispenser's maximum carrying capability\n#define DISPENSER_MAX_METAL_AMMO\t\t400\n#define\tMAX_DISPENSER_HEALING_TARGETS\t32\n\n//--------------------------------------------------------------------------\n// OBJECTS\n//--------------------------------------------------------------------------\nenum\n{\n\tOBJ_DISPENSER=0,\n\tOBJ_TELEPORTER,\n\tOBJ_SENTRYGUN,\n\n\t// Attachment Objects\n\tOBJ_ATTACHMENT_SAPPER,\n\n\t// If you add a new object, you need to add it to the g_ObjectInfos array \n\t// in tf_shareddefs.cpp, and add it's data to the scripts/object.txt\n\n\tOBJ_LAST,\n};\n\n// Warning levels for buildings in the building hud, in priority order\ntypedef enum\n{\n\tBUILDING_HUD_ALERT_NONE = 0,\n\tBUILDING_HUD_ALERT_LOW_AMMO,\n\tBUILDING_HUD_ALERT_LOW_HEALTH,\n\tBUILDING_HUD_ALERT_VERY_LOW_AMMO,\n\tBUILDING_HUD_ALERT_VERY_LOW_HEALTH,\n\tBUILDING_HUD_ALERT_SAPPER,\t\n\n\tMAX_BUILDING_HUD_ALERT_LEVEL\n} BuildingHudAlert_t;\n\ntypedef enum\n{\n\tBUILDING_DAMAGE_LEVEL_NONE = 0,\t\t// 100%\n\tBUILDING_DAMAGE_LEVEL_LIGHT,\t\t// 75% - 99%\n\tBUILDING_DAMAGE_LEVEL_MEDIUM,\t\t// 50% - 76%\n\tBUILDING_DAMAGE_LEVEL_HEAVY,\t\t// 25% - 49%\t\n\tBUILDING_DAMAGE_LEVEL_CRITICAL,\t\t// 0% - 24%\n\n\tMAX_BUILDING_DAMAGE_LEVEL\n} BuildingDamageLevel_t;\n\n//--------------\n// Scoring\n//--------------\n\n#define TF_SCORE_KILL\t\t\t\t\t\t\t1\n#define TF_SCORE_DEATH\t\t\t\t\t\t\t0\n#define TF_SCORE_CAPTURE\t\t\t\t\t\t2\n#define TF_SCORE_DEFEND\t\t\t\t\t\t\t1\n#define TF_SCORE_DESTROY_BUILDING\t\t\t\t1\n#define TF_SCORE_HEADSHOT_PER_POINT\t\t\t\t2\n#define TF_SCORE_BACKSTAB\t\t\t\t\t\t1\n#define TF_SCORE_INVULN\t\t\t\t\t\t\t1\n#define TF_SCORE_REVENGE\t\t\t\t\t\t1\n#define TF_SCORE_KILL_ASSISTS_PER_POINT\t\t\t2\n#define TF_SCORE_TELEPORTS_PER_POINT\t\t\t2\t\n#define TF_SCORE_HEAL_HEALTHUNITS_PER_POINT\t\t600\n#define TF_SCORE_DAMAGE_PER_POINT\t\t\t\t600\n#define TF_SCORE_BONUS_PER_POINT\t\t\t\t1\n\n//-------------------------\n// Shared Teleporter State\n//-------------------------\nenum\n{\n\tTELEPORTER_STATE_BUILDING = 0,\t\t\t\t// Building, not active yet\n\tTELEPORTER_STATE_IDLE,\t\t\t\t\t\t// Does not have a matching teleporter yet\n\tTELEPORTER_STATE_READY,\t\t\t\t\t\t// Found match, charged and ready\n\tTELEPORTER_STATE_SENDING,\t\t\t\t\t// Teleporting a player away\n\tTELEPORTER_STATE_RECEIVING,\t\t\t\t\t\n\tTELEPORTER_STATE_RECEIVING_RELEASE,\n\tTELEPORTER_STATE_RECHARGING,\t\t\t\t// Waiting for recharge\n\tTELEPORTER_STATE_UPGRADING\n};\n\n#define OBJECT_MODE_NONE\t\t\t0\n#define TELEPORTER_TYPE_ENTRANCE\t0\n#define TELEPORTER_TYPE_EXIT\t\t1\n\n#define TELEPORTER_RECHARGE_TIME\t\t\t\t10\t\t// seconds to recharge\n\nextern float g_flTeleporterRechargeTimes[];\nextern float g_flDispenserAmmoRates[];\nextern float g_flDispenserCloakRates[];\nextern float g_flDispenserHealRates[];\n\n//-------------------------\n// Shared Sentry State\n//-------------------------\nenum\n{\n\tSENTRY_STATE_INACTIVE = 0,\n\tSENTRY_STATE_SEARCHING,\n\tSENTRY_STATE_ATTACKING,\n\tSENTRY_STATE_UPGRADING,\n\tSENTRY_STATE_WRANGLED,\n\tSENTRY_STATE_WRANGLED_RECOVERY,\n\n\tSENTRY_NUM_STATES,\n};\n\n//--------------------------------------------------------------------------\n// OBJECT FLAGS\n//--------------------------------------------------------------------------\nenum\n{\n\tOF_ALLOW_REPEAT_PLACEMENT\t\t\t\t= 0x01,\n\tOF_MUST_BE_BUILT_ON_ATTACHMENT\t\t\t= 0x02,\n\tOF_IS_CART_OBJECT\t\t\t\t\t\t= 0x04, //I'm not sure what the exact name is, but live tf2 uses it for the payload bomb dispenser object\n\n\tOF_BIT_COUNT\t= 4\n};\n\n//--------------------------------------------------------------------------\n// Builder \"weapon\" states\n//--------------------------------------------------------------------------\nenum \n{\n\tBS_IDLE = 0,\n\tBS_SELECTING,\n\tBS_PLACING,\n\tBS_PLACING_INVALID\n};\n\n\n//--------------------------------------------------------------------------\n// Builder object id...\n//--------------------------------------------------------------------------\nenum\n{\n\tBUILDER_OBJECT_BITS = 8,\n\tBUILDER_INVALID_OBJECT = ((1 << BUILDER_OBJECT_BITS) - 1)\n};\n\n// Analyzer state\nenum\n{\n\tAS_INACTIVE = 0,\n\tAS_SUBVERTING,\n\tAS_ANALYZING\n};\n\n// Max number of objects a team can have\n#define MAX_OBJECTS_PER_PLAYER\t4\n//#define MAX_OBJECTS_PER_TEAM\t128\n\n// sanity check that commands send via user command are somewhat valid\n#define MAX_OBJECT_SCREEN_INPUT_DISTANCE\t100\n\n//--------------------------------------------------------------------------\n// BUILDING\n//--------------------------------------------------------------------------\n// Build checks will return one of these for a player\nenum\n{\n\tCB_CAN_BUILD,\t\t\t// Player is allowed to build this object\n\tCB_CANNOT_BUILD,\t\t// Player is not allowed to build this object\n\tCB_LIMIT_REACHED,\t\t// Player has reached the limit of the number of these objects allowed\n\tCB_NEED_RESOURCES,\t\t// Player doesn't have enough resources to build this object\n\tCB_NEED_ADRENALIN,\t\t// Commando doesn't have enough adrenalin to build a rally flag\n\tCB_UNKNOWN_OBJECT,\t\t// Error message, tried to build unknown object\n};\n\n// Build animation events\n#define TF_OBJ_ENABLEBODYGROUP\t\t\t6000\n#define TF_OBJ_DISABLEBODYGROUP\t\t\t6001\n#define TF_OBJ_ENABLEALLBODYGROUPS\t\t6002\n#define TF_OBJ_DISABLEALLBODYGROUPS\t\t6003\n#define TF_OBJ_PLAYBUILDSOUND\t\t\t6004\n\n#define TF_AE_CIGARETTE_THROW\t\t\t7000\n\n#define OBJECT_COST_MULTIPLIER_PER_OBJECT\t\t\t3\n#define OBJECT_UPGRADE_COST_MULTIPLIER_PER_LEVEL\t3\n\n//--------------------------------------------------------------------------\n// Powerups\n//--------------------------------------------------------------------------\nenum\n{\n\tPOWERUP_BOOST,\t\t// Medic, buff station\n\tPOWERUP_EMP,\t\t// Technician\n\tPOWERUP_RUSH,\t\t// Rally flag\n\tPOWERUP_POWER,\t\t// Object power\n\tMAX_POWERUPS\n};\n\n//--------------------------------------------------------------------------\n// Stun\n//--------------------------------------------------------------------------\n#define TF_STUNFLAG_SLOWDOWN\t\t\t(1<<0) // activates slowdown modifier\n#define TF_STUNFLAG_BONKSTUCK\t\t\t(1<<1) // bonk sound, stuck\n#define TF_STUNFLAG_LIMITMOVEMENT\t\t(1<<2) // disable forward/backward movement\n#define TF_STUNFLAG_CHEERSOUND\t\t\t(1<<3) // cheering sound\n#define TF_STUNFLAG_NOSOUNDOREFFECT\t\t(1<<4) // no sound or particle\n#define TF_STUNFLAG_THIRDPERSON\t\t\t(1<<5) // panic animation\n#define TF_STUNFLAG_GHOSTEFFECT\t\t\t(1<<6) // ghost particles\n#define TF_STUNFLAG_BONKEFFECT\t\t\t(1<<7) // sandman particles\n#define TF_STUNFLAG_RESISTDAMAGE\t\t(1<<8) // damage resist modifier\n\t\nenum\n{\n\tTF_STUNFLAGS_LOSERSTATE\t\t= TF_STUNFLAG_THIRDPERSON | TF_STUNFLAG_SLOWDOWN | TF_STUNFLAG_NOSOUNDOREFFECT, // Currently unused\n\tTF_STUNFLAGS_GHOSTSCARE\t\t= TF_STUNFLAG_THIRDPERSON |TF_STUNFLAG_GHOSTEFFECT, // Ghost stun\n\tTF_STUNFLAGS_SMALLBONK\t\t= TF_STUNFLAG_THIRDPERSON | TF_STUNFLAG_SLOWDOWN | TF_STUNFLAG_BONKEFFECT, // Half stun\n\tTF_STUNFLAGS_NORMALBONK\t\t= TF_STUNFLAG_BONKSTUCK, // Full stun\n\tTF_STUNFLAGS_BIGBONK\t\t= TF_STUNFLAG_CHEERSOUND | TF_STUNFLAG_BONKSTUCK | TF_STUNFLAG_RESISTDAMAGE | TF_STUNFLAG_BONKEFFECT, // Moonshot\n\tTF_STUNFLAGS_COUNT // This doesn't really work with flags\n};\n\n//--------------------------------------------------------------------------\n// Holiday\n//--------------------------------------------------------------------------\nenum\n{\n\tkHoliday_None,\n\tkHoliday_TF2Birthday,\n\tkHoliday_Halloween,\n\tkHoliday_Christmas,\n\tkHoliday_CommunityUpdate,\n\tkHoliday_EOTL,\n\tkHoliday_ValentinesDay,\n\tkHoliday_MeetThePyro,\n\tkHoliday_FullMoon,\n\tkHoliday_HalloweenOrFullMoon,\n\tkHoliday_HalloweenOrFullMoonOrValentines,\n\tkHoliday_AprilFools,\n\n\tkHolidayCount,\n};\n\n//--------------------------------------------------------------------------\n// Rage\n//--------------------------------------------------------------------------\nenum\n{\n\tTF_BUFF_OFFENSE = 1,\n\tTF_BUFF_DEFENSE,\n\tTF_BUFF_REGENONDAMAGE,\n};\n\n\n#define\tMAX_CABLE_CONNECTIONS 4\n\nbool IsObjectAnUpgrade( int iObjectType );\nbool IsObjectAVehicle( int iObjectType );\nbool IsObjectADefensiveBuilding( int iObjectType );\n\nclass CHudTexture;\n\n#define OBJECT_MAX_GIB_MODELS\t9\n\nclass CObjectInfo\n{\npublic:\n\tCObjectInfo( char *pObjectName );\n\tCObjectInfo( const CObjectInfo& obj ) {}\n\t~CObjectInfo();\n\n\t// This is initialized by the code and matched with a section in objects.txt\n\tchar\t*m_pObjectName;\n\n\t// This stuff all comes from objects.txt\n\tchar\t*m_pClassName;\t\t\t\t\t// Code classname (in LINK_ENTITY_TO_CLASS).\n\tchar\t*m_pStatusName;\t\t\t\t\t// Shows up when crosshairs are on the object.\n\tfloat\tm_flBuildTime;\n\tint\t\tm_nMaxObjects;\t\t\t\t\t// Maximum number of objects per player\n\tint\t\tm_Cost;\t\t\t\t\t\t\t// Base object resource cost\n\tfloat\tm_CostMultiplierPerInstance;\t// Cost multiplier\n\tint\t\tm_UpgradeCost;\t\t\t\t\t// Base object resource cost for upgrading\n\tfloat\tm_flUpgradeDuration;\n\tint\t\tm_MaxUpgradeLevel;\t\t\t\t// Max object upgrade level\n\tchar\t*m_pBuilderWeaponName;\t\t\t// Names shown for each object onscreen when using the builder weapon\n\tchar\t*m_pBuilderPlacementString;\t\t// String shown to player during placement of this object\n\tint\t\tm_SelectionSlot;\t\t\t\t// Weapon selection slots for objects\n\tint\t\tm_SelectionPosition;\t\t\t// Weapon selection positions for objects\n\tbool\tm_bSolidToPlayerMovement;\n\tbool\tm_bUseItemInfo;\n\tchar *m_pViewModel;\t\t\t\t\t// View model to show in builder weapon for this object\n\tchar *m_pPlayerModel;\t\t\t\t// World model to show attached to the player\n\tint\t\tm_iDisplayPriority;\t\t\t\t// Priority for ordering in the hud display ( higher is closer to top )\n\tbool\tm_bVisibleInWeaponSelection;\t// should show up and be selectable via the weapon selection?\n\tchar\t*m_pExplodeSound;\t\t\t\t// gamesound to play when object explodes\n\tchar\t*m_pExplosionParticleEffect;\t// particle effect to play when object explodes\n\tbool\tm_bAutoSwitchTo;\t\t\t\t// should we let players switch back to the builder weapon representing this?\n\tchar\t*m_pUpgradeSound;\t\t\t\t// gamesound to play when upgrading\n\tint\t\tm_BuildCount;\t\t\t\t\t// ???\n\tbool\tm_bRequiresOwnBuilder;\t\t\t// ???\n\n\tCUtlVector< const char * > m_AltModes;\n\n\t// HUD weapon selection menu icon ( from hud_textures.txt )\n\tchar\t*m_pIconActive;\n\tchar\t*m_pIconInactive;\n\tchar\t*m_pIconMenu;\n\n\t// HUD building status icon\n\tchar\t*m_pHudStatusIcon;\n\n\t// gibs\n\tint\t\tm_iMetalToDropInGibs;\n};\n\n// Loads the objects.txt script.\nclass IBaseFileSystem;\nvoid LoadObjectInfos( IBaseFileSystem *pFileSystem );\n\n// Get a CObjectInfo from a TFOBJ_ define.\nconst CObjectInfo* GetObjectInfo( int iObject );\n\n// Object utility funcs\nbool\tClassCanBuild( int iClass, int iObjectType );\nint\t\tCalculateObjectCost( int iObjectType, bool bMini = false /*, int iNumberOfObjects, int iTeam, bool bLast = false*/ );\nint\t\tCalculateObjectUpgrade( int iObjectType, int iObjectLevel );\n\n// Shell ejections\nenum\n{\n\tEJECTBRASS_PISTOL,\n\tEJECTBRASS_MINIGUN,\n};\n\n// Win panel styles\nenum\n{\n\tWINPANEL_BASIC = 0,\n};\n\n#define TF_DEATH_ANIMATION_TIME\t\t\t2.0\n\n// Taunt attack types\nenum\n{\n\tTAUNTATK_NONE,\n \tTAUNTATK_PYRO_HADOUKEN,\n \tTAUNTATK_HEAVY_EAT, // 1st Nom\n \tTAUNTATK_HEAVY_RADIAL_BUFF, // 2nd Nom gives hp\n \tTAUNTATK_SCOUT_DRINK,\n \tTAUNTATK_HEAVY_HIGH_NOON, // POW!\n \tTAUNTATK_SCOUT_GRAND_SLAM, // Sandman\n \tTAUNTATK_MEDIC_INHALE, // Oktoberfest\n \tTAUNTATK_SPY_FENCING_SLASH_A, // Just lay\n \tTAUNTATK_SPY_FENCING_SLASH_B, // Your weapon down\n \tTAUNTATK_SPY_FENCING_STAB, // And walk away.\n \tTAUNTATK_RPS_KILL,\n \tTAUNTATK_SNIPER_ARROW_STAB_IMPALE, // Stab stab\n \tTAUNTATK_SNIPER_ARROW_STAB_KILL, // STAB\n \tTAUNTATK_SOLDIER_GRENADE_KILL, // Equalizer\n \tTAUNTATK_DEMOMAN_BARBARIAN_SWING,\n \tTAUNTATK_MEDIC_UBERSLICE_IMPALE, // I'm going to saw\n \tTAUNTATK_MEDIC_UBERSLICE_KILL, // THROUGH YOUR BONES!\n \tTAUNTATK_FLIP_LAND_PARTICLE,\n \tTAUNTATK_RPS_PARTICLE,\n \tTAUNTATK_HIGHFIVE_PARTICLE,\n \tTAUNTATK_ENGINEER_GUITAR_SMASH,\n \tTAUNTATK_ENGINEER_ARM_IMPALE, // Grinder Start\n \tTAUNTATK_ENGINEER_ARM_KILL, // Grinder Kill\n \tTAUNTATK_ENGINEER_ARM_BLEND, // Grinder Loop\n \tTAUNTATK_SOLDIER_GRENADE_KILL_WORMSIGN,\n \tTAUNTATK_SHOW_ITEM,\n \tTAUNTATK_MEDIC_RELEASE_DOVES,\n \tTAUNTATK_PYRO_ARMAGEDDON,\n \tTAUNTATK_PYRO_SCORCHSHOT,\n \tTAUNTATK_ALLCLASS_GUITAR_RIFF,\n \tTAUNTATK_MEDIC_HEROIC_TAUNT,\n\tTAUNTATK_PYRO_GASBLAST,\n};\n\ntypedef enum\n{\n\tHUD_NOTIFY_YOUR_FLAG_TAKEN,\n\tHUD_NOTIFY_YOUR_FLAG_DROPPED,\n\tHUD_NOTIFY_YOUR_FLAG_RETURNED,\n\tHUD_NOTIFY_YOUR_FLAG_CAPTURED,\n\n\tHUD_NOTIFY_ENEMY_FLAG_TAKEN,\n\tHUD_NOTIFY_ENEMY_FLAG_DROPPED,\n\tHUD_NOTIFY_ENEMY_FLAG_RETURNED,\n\tHUD_NOTIFY_ENEMY_FLAG_CAPTURED,\n\n\tHUD_NOTIFY_TOUCHING_ENEMY_CTF_CAP,\n\n\tHUD_NOTIFY_NO_INVULN_WITH_FLAG,\n\tHUD_NOTIFY_NO_TELE_WITH_FLAG,\n\n\tHUD_NOTIFY_SPECIAL,\n\n\tHUD_NOTIFY_GOLDEN_WRENCH,\n\n\tHUD_NOTIFY_RD_ROBOT_ATTACKED,\n\n\tHUD_NOTIFY_HOW_TO_CONTROL_GHOST,\n\tHUD_NOTIFY_HOW_TO_CONTROL_KART,\n\n\tHUD_NOTIFY_PASSTIME_HOWTO,\n\tHUD_NOTIFY_PASSTIME_BALL_BASKET,\n\tHUD_NOTIFY_PASSTIME_BALL_ENDZONE,\n\tHUD_NOTIFY_PASSTIME_SCORE,\n\tHUD_NOTIFY_PASSTIME_FRIENDLY_SCORE,\n\tHUD_NOTIFY_PASSTIME_ENEMY_SCORE,\n\tHUD_NOTIFY_PASSTIME_NO_TELE,\n\tHUD_NOTIFY_PASSTIME_NO_CARRY,\n\tHUD_NOTIFY_PASSTIME_NO_INVULN,\n\tHUD_NOTIFY_PASSTIME_NO_DISGUISE,\n\tHUD_NOTIFY_PASSTIME_NO_CLOAK,\n\tHUD_NOTIFY_PASSTIME_NO_OOB,\n\tHUD_NOTIFY_PASSTIME_NO_HOLSTER,\n\tHUD_NOTIFY_PASSTIME_NO_TAUNT,\n\n\tNUM_STOCK_NOTIFICATIONS\n} HudNotification_t;\n\nclass CTraceFilterIgnorePlayers : public CTraceFilterSimple\n{\npublic:\n\t// It does have a base, but we'll never network anything below here..\n\tDECLARE_CLASS( CTraceFilterIgnorePlayers, CTraceFilterSimple );\n\n\tCTraceFilterIgnorePlayers( const IHandleEntity *passentity, int collisionGroup )\n\t\t: CTraceFilterSimple( passentity, collisionGroup )\n\t{\n\t}\n\n\tvirtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )\n\t{\n\t\tCBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity );\n\t\treturn pEntity && !pEntity->IsPlayer();\n\t}\n};\n\nclass CTraceFilterIgnoreTeammatesAndTeamObjects : public CTraceFilterSimple\n{\npublic:\n\t// It does have a base, but we'll never network anything below here..\n\tDECLARE_CLASS( CTraceFilterIgnoreTeammatesAndTeamObjects, CTraceFilterSimple );\n\n\tCTraceFilterIgnoreTeammatesAndTeamObjects( const IHandleEntity *passentity, int collisionGroup, int teamNumber )\n\t\t: CTraceFilterSimple( passentity, collisionGroup )\n\t{\n\t\tm_iTeamNumber = teamNumber;\n\t}\n\n\tvirtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )\n\t{\n\t\tCBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity );\n\n\t\tif ( pEntity && pEntity->GetTeamNumber() == m_iTeamNumber )\n\t\t\treturn false;\n\n\t\treturn BaseClass::ShouldHitEntity( pServerEntity, contentsMask );\n\t}\n\nprivate:\n\tint m_iTeamNumber;\n};\n\n// Unused\n#define TF_DEATH_FIRST_BLOOD\t0x0010\n#define TF_DEATH_FEIGN_DEATH\t0x0020\n#define TF_DEATH_GIB\t\t\t0x0080\n#define TF_DEATH_PURGATORY\t\t0x0100\n#define TF_DEATH_AUSTRALIUM\t\t0x0400\n\n#define HUD_ALERT_SCRAMBLE_TEAMS 0\n\n#define TF_CAMERA_DIST 64\n#define TF_CAMERA_DIST_RIGHT 30\n#define TF_CAMERA_DIST_UP 0\n\n#endif // TF_SHAREDDEFS_H\n\n\n<|start_filename|>src/game/shared/tf/tf_weapon_medigun.cpp<|end_filename|>\n//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//\n//\n// Purpose:\t\t\tThe Medic's Medikit weapon\n//\t\t\t\t\t\n//\n// $Workfile: $\n// $Date: $\n// $NoKeywords: $\n//=============================================================================//\n#include \"cbase.h\"\n#include \"in_buttons.h\"\n#include \"engine/IEngineSound.h\"\n#include \"tf_gamerules.h\"\n\n#if defined( CLIENT_DLL )\n#include \n#include \n#include \"particles_simple.h\"\n#include \"c_tf_player.h\"\n#include \"soundenvelope.h\"\n#else\n#include \"ndebugoverlay.h\"\n#include \"tf_player.h\"\n#include \"tf_team.h\"\n#include \"tf_gamestats.h\"\n#include \"ilagcompensationmanager.h\"\n#endif\n\n#include \"tf_weapon_medigun.h\"\n\n// memdbgon must be the last include file in a .cpp file!!!\n#include \"tier0/memdbgon.h\"\n\nconst char *g_pszMedigunHealSounds[TF_MEDIGUN_COUNT] =\n{\n\t\"WeaponMedigun.Healing\",\n\t\"WeaponMedigun.Healing\",\n\t\"Weapon_Quick_Fix.Healing\",\n\t\"WeaponMedigun_Vaccinator.Healing\",\n\t\"WeaponMedigun.Healing\"\n};\n\n// Buff ranges\nConVar weapon_medigun_damage_modifier( \"weapon_medigun_damage_modifier\", \"1.5\", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, \"Scales the damage a player does while being healed with the medigun.\" );\nConVar weapon_medigun_construction_rate( \"weapon_medigun_construction_rate\", \"10\", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, \"Constructing object health healed per second by the medigun.\" );\nConVar weapon_medigun_charge_rate( \"weapon_medigun_charge_rate\", \"40\", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, \"Amount of time healing it takes to fully charge the medigun.\" );\nConVar weapon_medigun_chargerelease_rate( \"weapon_medigun_chargerelease_rate\", \"8\", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, \"Amount of time it takes the a full charge of the medigun to be released.\" );\n\n#if defined (CLIENT_DLL)\nConVar tf_medigun_autoheal( \"tf_medigun_autoheal\", \"0\", FCVAR_CLIENTDLL | FCVAR_ARCHIVE | FCVAR_USERINFO, \"Setting this to 1 will cause the Medigun's primary attack to be a toggle instead of needing to be held down.\" );\n#endif\n\n#if !defined (CLIENT_DLL)\nConVar tf_medigun_lagcomp( \"tf_medigun_lagcomp\", \"1\", FCVAR_DEVELOPMENTONLY );\n#endif\n\n#ifdef CLIENT_DLL\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid RecvProxy_HealingTarget( const CRecvProxyData *pData, void *pStruct, void *pOut )\n{\n\tCWeaponMedigun *pMedigun = ((CWeaponMedigun*)(pStruct));\n\tif ( pMedigun != NULL )\n\t{\n\t\tpMedigun->ForceHealingTargetUpdate();\n\t}\n\n\tRecvProxy_IntToEHandle( pData, pStruct, pOut );\n}\n#endif\n\nLINK_ENTITY_TO_CLASS( tf_weapon_medigun, CWeaponMedigun );\nPRECACHE_WEAPON_REGISTER( tf_weapon_medigun );\n\nIMPLEMENT_NETWORKCLASS_ALIASED( WeaponMedigun, DT_WeaponMedigun )\n\nBEGIN_NETWORK_TABLE( CWeaponMedigun, DT_WeaponMedigun )\n#if !defined( CLIENT_DLL )\n\tSendPropFloat( SENDINFO( m_flChargeLevel ), 0, SPROP_NOSCALE | SPROP_CHANGES_OFTEN ),\n\tSendPropEHandle( SENDINFO( m_hHealingTarget ) ),\n\tSendPropBool( SENDINFO( m_bHealing ) ),\n\tSendPropBool( SENDINFO( m_bAttacking ) ),\n\tSendPropBool( SENDINFO( m_bChargeRelease ) ),\n\tSendPropBool( SENDINFO( m_bHolstered ) ),\n#else\n\tRecvPropFloat( RECVINFO(m_flChargeLevel) ),\n\tRecvPropEHandle( RECVINFO( m_hHealingTarget ), RecvProxy_HealingTarget ),\n\tRecvPropBool( RECVINFO( m_bHealing ) ),\n\tRecvPropBool( RECVINFO( m_bAttacking ) ),\n\tRecvPropBool( RECVINFO( m_bChargeRelease ) ),\n\tRecvPropBool( RECVINFO( m_bHolstered ) ),\n#endif\nEND_NETWORK_TABLE()\n\n#ifdef CLIENT_DLL\nBEGIN_PREDICTION_DATA( CWeaponMedigun )\n\n\tDEFINE_PRED_FIELD( m_bHealing, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ),\n\tDEFINE_PRED_FIELD( m_bAttacking, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ),\n\tDEFINE_PRED_FIELD( m_bHolstered, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ),\n\tDEFINE_PRED_FIELD( m_hHealingTarget, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ),\n\n\tDEFINE_FIELD( m_flHealEffectLifetime, FIELD_FLOAT ),\n\n\tDEFINE_PRED_FIELD( m_flChargeLevel, FIELD_FLOAT, FTYPEDESC_INSENDTABLE ),\n\tDEFINE_PRED_FIELD( m_bChargeRelease, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ),\n\n//\tDEFINE_PRED_FIELD( m_bPlayingSound, FIELD_BOOLEAN ),\n//\tDEFINE_PRED_FIELD( m_bUpdateHealingTargets, FIELD_BOOLEAN ),\n\nEND_PREDICTION_DATA()\n#endif\n\n#define PARTICLE_PATH_VEL\t\t\t\t140.0\n#define NUM_PATH_PARTICLES_PER_SEC\t\t300.0f\n#define NUM_MEDIGUN_PATH_POINTS\t\t8\n\nextern ConVar tf_max_health_boost;\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nCWeaponMedigun::CWeaponMedigun( void )\n{\n\tWeaponReset();\n\n\tSetPredictionEligible( true );\n}\n\nCWeaponMedigun::~CWeaponMedigun()\n{\n#ifdef CLIENT_DLL\n\tif ( m_pChargedSound )\n\t{\n\t\tCSoundEnvelopeController::GetController().SoundDestroy( m_pChargedSound );\n\t}\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::WeaponReset( void )\n{\n\tBaseClass::WeaponReset();\n\n\tm_flHealEffectLifetime = 0;\n\n\tm_bHealing = false;\n\tm_bAttacking = false;\n\tm_bHolstered = true;\n\tm_bChargeRelease = false;\n\n\tm_bCanChangeTarget = true;\n\n\tm_flNextBuzzTime = 0;\n\tm_flReleaseStartedAt = 0;\n\tm_flChargeLevel = 0.0f;\n\n\tRemoveHealingTarget( true );\n\n#if defined( CLIENT_DLL )\n\tm_bPlayingSound = false;\n\tm_bUpdateHealingTargets = false;\n\tm_bOldChargeRelease = false;\n\n\tUpdateEffects();\n\tManageChargeEffect();\n\n\tm_pChargeEffect = NULL;\n\tm_pChargedSound = NULL;\n#endif\n\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::Precache()\n{\n\tBaseClass::Precache();\n\n\tint iType = GetMedigunType();\n\n\tPrecacheScriptSound( g_pszMedigunHealSounds[iType] );\n\n\tPrecacheScriptSound( \"WeaponMedigun.NoTarget\" );\n\tPrecacheScriptSound( \"WeaponMedigun.Charged\" );\n\tPrecacheScriptSound( \"WeaponMedigun.HealingDetach\" );\n\n\tPrecacheTeamParticles( \"medicgun_invulnstatus_fullcharge_%s\" );\n\tPrecacheTeamParticles( \"medicgun_beam_%s\" );\n\tPrecacheTeamParticles( \"medicgun_beam_%s_invun\" );\n\n\t// Precache charge sounds.\n\tfor ( int i = 0; i < TF_CHARGE_COUNT; i++ )\n\t{\n\t\tPrecacheScriptSound( g_MedigunEffects[i].sound_enable );\n\t\tPrecacheScriptSound( g_MedigunEffects[i].sound_disable );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::Deploy( void )\n{\n\tif ( BaseClass::Deploy() )\n\t{\n\t\tm_bHolstered = false;\n\n#ifdef GAME_DLL\n\t\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\t\tif ( m_bChargeRelease && pOwner )\n\t\t{\n\t\t\tpOwner->m_Shared.RecalculateChargeEffects();\n\t\t}\n#endif\n\n#ifdef CLIENT_DLL\n\t\tManageChargeEffect();\n#endif\n\n\t\tm_flNextTargetCheckTime = gpGlobals->curtime;\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::Holster( CBaseCombatWeapon *pSwitchingTo )\n{\n\tRemoveHealingTarget( true );\n\tm_bAttacking = false;\n\tm_bHolstered = true;\n\n\n\n#ifdef GAME_DLL\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( pOwner )\n\t{\n\t\tpOwner->m_Shared.RecalculateChargeEffects( true );\n\t}\n#endif\n\n#ifdef CLIENT_DLL\n\tUpdateEffects();\n\tManageChargeEffect();\n#endif\n\n\treturn BaseClass::Holster( pSwitchingTo );\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::UpdateOnRemove( void )\n{\n\tRemoveHealingTarget( true );\n\tm_bAttacking = false;\n\tm_bChargeRelease = false;\n\tm_bHolstered = true;\n\n#ifndef CLIENT_DLL\n\tCTFPlayer *pOwner = GetTFPlayerOwner();\n\tif ( pOwner )\n\t{\n\t\tpOwner->m_Shared.RecalculateChargeEffects( true );\n\t}\n#else\n\tif ( m_bPlayingSound )\n\t{\n\t\tm_bPlayingSound = false;\n\t\tStopHealSound();\n\t}\n\n\tUpdateEffects();\n\tManageChargeEffect();\n#endif\n\n\tBaseClass::UpdateOnRemove();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nfloat CWeaponMedigun::GetTargetRange( void )\n{\n\treturn (float)m_pWeaponInfo->GetWeaponData( m_iWeaponMode ).m_flRange;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nfloat CWeaponMedigun::GetStickRange( void )\n{\n\treturn (GetTargetRange() * 1.2);\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nfloat CWeaponMedigun::GetHealRate( void )\n{\n\tfloat flHealRate = (float)m_pWeaponInfo->GetWeaponData( m_iWeaponMode ).m_nDamage;\n\tCALL_ATTRIB_HOOK_FLOAT( flHealRate, mult_medigun_healrate );\n\treturn flHealRate;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nint CWeaponMedigun::GetMedigunType( void )\n{\n\tint iType = 0;\n\tCALL_ATTRIB_HOOK_INT( iType, set_weapon_mode );\n\n\tif ( iType >= 0 && iType < TF_MEDIGUN_COUNT )\n\t\treturn iType;\n\n\tAssertMsg( 0, \"Invalid medigun type!\\n\" );\n\treturn TF_MEDIGUN_STOCK;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nmedigun_charge_types CWeaponMedigun::GetChargeType( void )\n{\n\tint iChargeType = TF_CHARGE_INVULNERABLE;\n\tCALL_ATTRIB_HOOK_INT( iChargeType, set_charge_type );\n\n\tif ( iChargeType > TF_CHARGE_NONE && iChargeType < TF_CHARGE_COUNT )\n\t\treturn (medigun_charge_types)iChargeType;\n\n\tAssertMsg( 0, \"Invalid charge type!\\n\" );\n\treturn TF_CHARGE_NONE;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nconst char *CWeaponMedigun::GetHealSound( void )\n{\n\treturn g_pszMedigunHealSounds[GetMedigunType()];\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::HealingTarget( CBaseEntity *pTarget )\n{\n\tif ( pTarget == m_hHealingTarget )\n\t\treturn true;\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::AllowedToHealTarget( CBaseEntity *pTarget )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn false;\n\n\tCTFPlayer *pTFPlayer = ToTFPlayer( pTarget );\n\tif ( !pTFPlayer )\n\t\treturn false;\n\n\tbool bStealthed = pTFPlayer->m_Shared.InCond( TF_COND_STEALTHED );\n\tbool bDisguised = pTFPlayer->m_Shared.InCond( TF_COND_DISGUISED );\n\n\t// We can heal teammates and enemies that are disguised as teammates\n\tif ( !bStealthed &&\n\t\t( pTFPlayer->InSameTeam( pOwner ) ||\n\t\t( bDisguised && pTFPlayer->m_Shared.GetDisguiseTeam() == pOwner->GetTeamNumber() ) ) )\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::CouldHealTarget( CBaseEntity *pTarget )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn false;\n\n\tif ( pTarget->IsPlayer() && pTarget->IsAlive() && !HealingTarget(pTarget) )\n\t\treturn AllowedToHealTarget( pTarget );\n\n\treturn false;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::MaintainTargetInSlot()\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\tCBaseEntity *pTarget = m_hHealingTarget;\n\tAssert( pTarget );\n\n\t// Make sure the guy didn't go out of range.\n\tbool bLostTarget = true;\n\tVector vecSrc = pOwner->Weapon_ShootPosition( );\n\tVector vecTargetPoint = pTarget->WorldSpaceCenter();\n\tVector vecPoint;\n\n\t// If it's brush built, use absmins/absmaxs\n\tpTarget->CollisionProp()->CalcNearestPoint( vecSrc, &vecPoint );\n\n\tfloat flDistance = (vecPoint - vecSrc).Length();\n\tif ( flDistance < GetStickRange() )\n\t{\n\t\tif ( m_flNextTargetCheckTime > gpGlobals->curtime )\n\t\t\treturn;\n\n\t\tm_flNextTargetCheckTime = gpGlobals->curtime + 1.0f;\n\n\t\ttrace_t tr;\n\t\tCMedigunFilter drainFilter( pOwner );\n\n\t\tVector vecAiming;\n\t\tpOwner->EyeVectors( &vecAiming );\n\n\t\tVector vecEnd = vecSrc + vecAiming * GetTargetRange();\n\t\tUTIL_TraceLine( vecSrc, vecEnd, (MASK_SHOT & ~CONTENTS_HITBOX), pOwner, DMG_GENERIC, &tr );\n\n\t\t// Still visible?\n\t\tif ( tr.m_pEnt == pTarget )\n\t\t\treturn;\n\n\t\tUTIL_TraceLine( vecSrc, vecTargetPoint, MASK_SHOT, &drainFilter, &tr );\n\n\t\t// Still visible?\n\t\tif (( tr.fraction == 1.0f) || (tr.m_pEnt == pTarget))\n\t\t\treturn;\n\n\t\t// If we failed, try the target's eye point as well\n\t\tUTIL_TraceLine( vecSrc, pTarget->EyePosition(), MASK_SHOT, &drainFilter, &tr );\n\t\tif (( tr.fraction == 1.0f) || (tr.m_pEnt == pTarget))\n\t\t\treturn;\n\t}\n\n\t// We've lost this guy\n\tif ( bLostTarget )\n\t{\n\t\tRemoveHealingTarget();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::FindNewTargetForSlot()\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\tVector vecSrc = pOwner->Weapon_ShootPosition( );\n\tif ( m_hHealingTarget )\n\t{\n\t\tRemoveHealingTarget();\n\t}\n\n\t// In Normal mode, we heal players under our crosshair\n\tVector vecAiming;\n\tpOwner->EyeVectors( &vecAiming );\n\n\t// Find a player in range of this player, and make sure they're healable.\n\tVector vecEnd = vecSrc + vecAiming * GetTargetRange();\n\ttrace_t tr;\n\n\tUTIL_TraceLine( vecSrc, vecEnd, (MASK_SHOT & ~CONTENTS_HITBOX), pOwner, DMG_GENERIC, &tr );\n\tif ( tr.fraction != 1.0 && tr.m_pEnt )\n\t{\n\t\tif ( CouldHealTarget( tr.m_pEnt ) )\n\t\t{\n#ifdef GAME_DLL\n\t\t\tpOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_STARTEDHEALING );\n\t\t\tif ( tr.m_pEnt->IsPlayer() )\n\t\t\t{\n\t\t\t\tCTFPlayer *pTarget = ToTFPlayer( tr.m_pEnt );\n\t\t\t\tpTarget->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_STARTEDHEALING );\n\t\t\t}\n\n\t\t\t// Start the heal target thinking.\n\t\t\tSetContextThink( &CWeaponMedigun::HealTargetThink, gpGlobals->curtime, s_pszMedigunHealTargetThink );\n#endif\n\n\t\t\tm_hHealingTarget.Set( tr.m_pEnt );\n\t\t\tm_flNextTargetCheckTime = gpGlobals->curtime + 1.0f;\n\t\t}\t\t\t\n\t}\n}\n\n#ifdef GAME_DLL\n//-----------------------------------------------------------------------------\n// Purpose:\n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::HealTargetThink( void )\n{\t\n\t// Verify that we still have a valid heal target.\n\tCBaseEntity *pTarget = m_hHealingTarget;\n\tif ( !pTarget || !pTarget->IsAlive() )\n\t{\n\t\tSetContextThink( NULL, 0, s_pszMedigunHealTargetThink );\n\t\treturn;\n\t}\n\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\tfloat flTime = gpGlobals->curtime - pOwner->GetTimeBase();\n\tif ( flTime > 5.0f || !AllowedToHealTarget(pTarget) )\n\t{\n\t\tRemoveHealingTarget( false );\n\t}\n\n\tSetNextThink( gpGlobals->curtime + 0.2f, s_pszMedigunHealTargetThink );\n}\n#endif\n\n//-----------------------------------------------------------------------------\n// Purpose: Returns a pointer to a healable target\n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::FindAndHealTargets( void )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn false;\n\n\tbool bFound = false;\n\n\t// Maintaining beam to existing target?\n\tCBaseEntity *pTarget = m_hHealingTarget;\n\tif ( pTarget && pTarget->IsAlive() )\n\t{\n\t\tMaintainTargetInSlot();\n\t}\n\telse\n\t{\t\n\t\tFindNewTargetForSlot();\n\t}\n\n\tCBaseEntity *pNewTarget = m_hHealingTarget;\n\tif ( pNewTarget && pNewTarget->IsAlive() )\n\t{\n\t\tCTFPlayer *pTFPlayer = ToTFPlayer( pNewTarget );\n\n#ifdef GAME_DLL\n\t\t// HACK: For now, just deal with players\n\t\tif ( pTFPlayer )\n\t\t{\n\t\t\tif ( pTarget != pNewTarget && pNewTarget->IsPlayer() )\n\t\t\t{\n\t\t\t\tpTFPlayer->m_Shared.Heal( pOwner, GetHealRate() );\n\t\t\t}\n\n\t\t\tpTFPlayer->m_Shared.RecalculateChargeEffects( false );\n\t\t}\n\n\t\tif ( m_flReleaseStartedAt && m_flReleaseStartedAt < (gpGlobals->curtime + 0.2) )\n\t\t{\n\t\t\t// When we start the release, everyone we heal rockets to full health\n\t\t\tpNewTarget->TakeHealth( pNewTarget->GetMaxHealth(), DMG_GENERIC );\n\t\t}\n#endif\n\t\n\t\tbFound = true;\n\n\t\t// Charge up our power if we're not releasing it, and our target\n\t\t// isn't receiving any benefit from our healing.\n\t\tif ( !m_bChargeRelease )\n\t\t{\n\t\t\tif ( pTFPlayer )\n\t\t\t{\n\t\t\t\tint iBoostMax = floor( pTFPlayer->m_Shared.GetMaxBuffedHealth() * 0.95);\n\n\t\t\t\tif ( weapon_medigun_charge_rate.GetFloat() )\n\t\t\t\t{\n\t\t\t\t\tfloat flChargeAmount = gpGlobals->frametime / weapon_medigun_charge_rate.GetFloat();\n\n\t\t\t\t\tCALL_ATTRIB_HOOK_FLOAT( flChargeAmount, mult_medigun_uberchargerate );\n\n\t\t\t\t\tif ( TFGameRules() && TFGameRules()->InSetup() )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Build charge at triple rate during setup\n\t\t\t\t\t\tflChargeAmount *= 3.0f;\n\t\t\t\t\t}\n\t\t\t\t\telse if ( pNewTarget->GetHealth() >= iBoostMax )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Reduced charge for healing fully healed guys\n\t\t\t\t\t\tflChargeAmount *= 0.5f;\n\t\t\t\t\t}\n\n\t\t\t\t\tint iTotalHealers = pTFPlayer->m_Shared.GetNumHealers();\n\t\t\t\t\tif ( iTotalHealers > 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tflChargeAmount /= (float)iTotalHealers;\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat flNewLevel = min( m_flChargeLevel + flChargeAmount, 1.0 );\n#ifdef GAME_DLL\n\t\t\t\t\tif ( flNewLevel >= 1.0 && m_flChargeLevel < 1.0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tpOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEREADY );\n\n\t\t\t\t\t\tif ( pTFPlayer )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEREADY );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t\tm_flChargeLevel = flNewLevel;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn bFound;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::AddCharge( float flAmount )\n{\n\tfloat flChargeRate = 1.0f;\n\tCALL_ATTRIB_HOOK_FLOAT( flChargeRate, mult_medigun_uberchargerate );\n\tif ( !flChargeRate ) // Can't earn uber.\n\t\treturn;\n\n\tfloat flNewLevel = min( m_flChargeLevel + flAmount, 1.0 );\n\n#ifdef GAME_DLL\n\tCTFPlayer *pPlayer = GetTFPlayerOwner();\n\tCTFPlayer *pHealingTarget = ToTFPlayer( m_hHealingTarget );\n\n\tif ( !m_bChargeRelease && flNewLevel >= 1.0 && m_flChargeLevel < 1.0 )\n\t{\n\t\tif ( pPlayer )\n\t\t{\n\t\t\tpPlayer->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEREADY );\n\t\t}\n\n\t\tif ( pHealingTarget )\n\t\t{\n\t\t\tpHealingTarget->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEREADY );\n\t\t}\n\t}\n#endif\n\n\tm_flChargeLevel = flNewLevel;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::ItemHolsterFrame( void )\n{\n\tBaseClass::ItemHolsterFrame();\n\n\tDrainCharge();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::DrainCharge( void )\n{\n\t// If we're in charge release mode, drain our charge\n\tif ( m_bChargeRelease )\n\t{\n\t\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\t\tif ( !pOwner )\n\t\t\treturn;\n\n\t\tfloat flChargeAmount = gpGlobals->frametime / weapon_medigun_chargerelease_rate.GetFloat();\n\t\tm_flChargeLevel = max( m_flChargeLevel - flChargeAmount, 0.0 );\n\t\tif ( !m_flChargeLevel )\n\t\t{\n\t\t\tm_bChargeRelease = false;\n\t\t\tm_flReleaseStartedAt = 0;\n\n#ifdef GAME_DLL\n\t\t\t/*\n\t\t\tif ( m_bHealingSelf )\n\t\t\t{\n\t\t\t\tm_bHealingSelf = false;\n\t\t\t\tpOwner->m_Shared.StopHealing( pOwner );\n\t\t\t}\n\t\t\t*/\n\n\t\t\tpOwner->m_Shared.RecalculateChargeEffects();\n#endif\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Overloaded to handle the hold-down healing\n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::ItemPostFrame( void )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\t// If we're lowered, we're not allowed to fire\n\tif ( CanAttack() == false )\n\t{\n\t\tRemoveHealingTarget( true );\n\t\treturn;\n\t}\n\n#if !defined( CLIENT_DLL )\n\tif ( AppliesModifier() )\n\t{\n\t\tm_DamageModifier.SetModifier( weapon_medigun_damage_modifier.GetFloat() );\n\t}\n#endif\n\n\t// Try to start healing\n\tm_bAttacking = false;\n\tif ( pOwner->GetMedigunAutoHeal() )\n\t{\n\t\tif ( pOwner->m_nButtons & IN_ATTACK )\n\t\t{\n\t\t\tif ( m_bCanChangeTarget )\n\t\t\t{\n\t\t\t\tRemoveHealingTarget();\n#if defined( CLIENT_DLL )\n\t\t\t\tm_bPlayingSound = false;\n\t\t\t\tStopHealSound();\n#endif\n\t\t\t\t// can't change again until we release the attack button\n\t\t\t\tm_bCanChangeTarget = false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_bCanChangeTarget = true;\n\t\t}\n\n\t\tif ( m_bHealing || ( pOwner->m_nButtons & IN_ATTACK ) )\n\t\t{\n\t\t\tPrimaryAttack();\n\t\t\tm_bAttacking = true;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( /*m_bChargeRelease || */ pOwner->m_nButtons & IN_ATTACK )\n\t\t{\n\t\t\tPrimaryAttack();\n\t\t\tm_bAttacking = true;\n\t\t}\n \t\telse if ( m_bHealing )\n \t\t{\n \t\t\t// Detach from the player if they release the attack button.\n \t\t\tRemoveHealingTarget();\n \t\t}\n\t}\n\n\tif ( pOwner->m_nButtons & IN_ATTACK2 )\n\t{\n\t\tSecondaryAttack();\n\t}\n\n\tWeaponIdle();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nbool CWeaponMedigun::Lower( void )\n{\n\t// Stop healing if we are\n\tif ( m_bHealing )\n\t{\n\t\tRemoveHealingTarget( true );\n\t\tm_bAttacking = false;\n\n#ifdef CLIENT_DLL\n\t\tUpdateEffects();\n#endif\n\t}\n\n\treturn BaseClass::Lower();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::RemoveHealingTarget( bool bSilent )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n#ifdef GAME_DLL\n\tif ( m_hHealingTarget )\n\t{\n\t\t// HACK: For now, just deal with players\n\t\tif ( m_hHealingTarget->IsPlayer() )\n\t\t{\n\t\t\tCTFPlayer *pTFPlayer = ToTFPlayer( m_hHealingTarget );\n\t\t\tpTFPlayer->m_Shared.StopHealing( pOwner );\n\t\t\tpTFPlayer->m_Shared.RecalculateChargeEffects( false );\n\n\t\t\tif ( !bSilent )\n\t\t\t{\n\t\t\t\tpOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_STOPPEDHEALING, pTFPlayer->IsAlive() ? \"healtarget:alive\" : \"healtarget:dead\" );\n\t\t\t\tpTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_STOPPEDHEALING );\n\t\t\t}\n\t\t}\n\t}\n\n\t// Stop thinking - we no longer have a heal target.\n\tSetContextThink( NULL, 0, s_pszMedigunHealTargetThink );\n#endif\n\n\tm_hHealingTarget.Set( NULL );\n\n\t// Stop the welding animation\n\tif ( m_bHealing && !bSilent )\n\t{\n\t\tSendWeaponAnim( ACT_MP_ATTACK_STAND_POSTFIRE );\n\t\tpOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_POST );\n\t}\n\n#ifndef CLIENT_DLL\n\tm_DamageModifier.RemoveModifier();\n#endif\n\tm_bHealing = false;\n\n}\n\n\n//-----------------------------------------------------------------------------\n// Purpose: Attempt to heal any player within range of the medikit\n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::PrimaryAttack( void )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\n\tif ( !CanAttack() )\n\t\treturn;\n\n#ifdef GAME_DLL\n\t/*\n\t// Start boosting ourself if we're not\n\tif ( m_bChargeRelease && !m_bHealingSelf )\n\t{\n\t\tpOwner->m_Shared.Heal( pOwner, GetHealRate() * 2 );\n\t\tm_bHealingSelf = true;\n\t}\n\t*/\n#endif\n\n#if !defined (CLIENT_DLL)\n\tif ( tf_medigun_lagcomp.GetBool() )\n\t\tlagcompensation->StartLagCompensation( pOwner, pOwner->GetCurrentCommand() );\n#endif\n\n\tif ( FindAndHealTargets() )\n\t{\n\t\t// Start the animation\n\t\tif ( !m_bHealing )\n\t\t{\n#ifdef GAME_DLL\n\t\t\tpOwner->SpeakWeaponFire();\n#endif\n\n\t\t\tSendWeaponAnim( ACT_MP_ATTACK_STAND_PREFIRE );\n\t\t\tpOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_PRE );\n\t\t}\n\n\t\tm_bHealing = true;\n\t}\n\telse\n\t{\n\t\tRemoveHealingTarget();\n\t}\n\t\n#if !defined (CLIENT_DLL)\n\tif ( tf_medigun_lagcomp.GetBool() )\n\t\tlagcompensation->FinishLagCompensation( pOwner );\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Burn charge level to generate invulnerability\n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::SecondaryAttack( void )\n{\n\tCTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pOwner )\n\t\treturn;\n\n\tif ( !CanAttack() )\n\t\treturn;\n\n\t// Ensure they have a full charge and are not already in charge release mode\n\tif ( m_flChargeLevel < 1.0 || m_bChargeRelease )\n\t{\n#ifdef CLIENT_DLL\n\t\t// Deny, flash\n\t\tif ( !m_bChargeRelease && m_flFlashCharge <= 0 )\n\t\t{\n\t\t\tm_flFlashCharge = 10;\n\t\t\tpOwner->EmitSound( \"Player.DenyWeaponSelection\" );\n\t\t}\n#endif\n\t\treturn;\n\t}\n\n\tif ( pOwner->HasTheFlag() )\n\t{\n#ifdef GAME_DLL\n\t\tCSingleUserRecipientFilter filter( pOwner );\n\t\tTFGameRules()->SendHudNotification( filter, HUD_NOTIFY_NO_INVULN_WITH_FLAG );\n#endif\n\t\tpOwner->EmitSound( \"Player.DenyWeaponSelection\" );\n\t\treturn;\n\t}\n\n\t// Start super charge\n\tm_bChargeRelease = true;\n\tm_flReleaseStartedAt = 0;//gpGlobals->curtime;\n\n#ifdef GAME_DLL\n\tCTF_GameStats.Event_PlayerInvulnerable( pOwner );\n\tpOwner->m_Shared.RecalculateChargeEffects();\n\n\tpOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEDEPLOYED );\n\n\tif ( m_hHealingTarget && m_hHealingTarget->IsPlayer() )\n\t{\n\t\tCTFPlayer *pTFPlayer = ToTFPlayer( m_hHealingTarget );\n\t\tpTFPlayer->m_Shared.RecalculateChargeEffects();\n\t\tpTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEDEPLOYED );\n\t}\n\n\tIGameEvent * event = gameeventmanager->CreateEvent( \"player_chargedeployed\" );\n\tif ( event )\n\t{\n\t\tevent->SetInt( \"userid\", pOwner->GetUserID() );\n\n\t\tgameeventmanager->FireEvent( event, true );\t// don't send to clients\n\t}\n#endif\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Idle tests to see if we're facing a valid target for the medikit\n//\t\t\tIf so, move into the \"heal-able\" animation. \n//\t\t\tOtherwise, move into the \"not-heal-able\" animation.\n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::WeaponIdle( void )\n{\n\tif ( HasWeaponIdleTimeElapsed() )\n\t{\n\t\t// Loop the welding animation\n\t\tif ( m_bHealing )\n\t\t{\n\t\t\tSendWeaponAnim( ACT_VM_PRIMARYATTACK );\n\t\t\treturn;\n\t\t}\n\n\t\treturn BaseClass::WeaponIdle();\n\t}\n}\n\n#if defined( CLIENT_DLL )\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::StopHealSound( bool bStopHealingSound, bool bStopNoTargetSound )\n{\n\tif ( bStopHealingSound )\n\t{\n\t\tStopSound( GetHealSound() );\n\n\t\tCLocalPlayerFilter filter;\n\t\tEmitSound( filter, entindex(), \"WeaponMedigun.HealingDetach\" );\n\t}\n\n\tif ( bStopNoTargetSound )\n\t{\n\t\tStopSound( \"WeaponMedigun.NoTarget\" );\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::ManageChargeEffect( void )\n{\n\tbool bOwnerTaunting = false;\n\n\tif ( GetTFPlayerOwner() && ( GetTFPlayerOwner()->m_Shared.InCond( TF_COND_TAUNTING ) == true || GetTFPlayerOwner()->m_Shared.InCond( TF_COND_STUNNED ) == true) )\n\t{\n\t\tbOwnerTaunting = true;\n\t}\n\n\tif ( GetTFPlayerOwner() && bOwnerTaunting == false && m_bHolstered == false && ( m_flChargeLevel >= 1.0f || m_bChargeRelease == true ) )\n\t{\n\t\tC_BaseEntity *pEffectOwner = GetWeaponForEffect();\n\n\t\tif ( pEffectOwner && m_pChargeEffect == NULL )\n\t\t{\n\t\t\tconst char *pszEffectName = ConstructTeamParticle( \"medicgun_invulnstatus_fullcharge_%s\", GetTFPlayerOwner()->GetTeamNumber() );\n\n\t\t\tm_pChargeEffect = pEffectOwner->ParticleProp()->Create( pszEffectName, PATTACH_POINT_FOLLOW, \"muzzle\" );\n\t\t\tm_hChargeEffectHost = pEffectOwner;\n\t\t}\n\n\t\tif ( m_pChargedSound == NULL )\n\t\t{\n\t\t\tCLocalPlayerFilter filter;\n\n\t\t\tCSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();\n\n\t\t\tm_pChargedSound = controller.SoundCreate( filter, entindex(), \"WeaponMedigun.Charged\" );\n\t\t\tcontroller.Play( m_pChargedSound, 1.0, 100 );\n\t\t}\n\t}\n\telse\n\t{\n\t\tC_BaseEntity *pEffectOwner = m_hChargeEffectHost.Get();\n\n\t\tif ( m_pChargeEffect != NULL )\n\t\t{\n\t\t\tif ( pEffectOwner )\n\t\t\t{\n\t\t\t\tpEffectOwner->ParticleProp()->StopEmission( m_pChargeEffect );\n\t\t\t\tm_hChargeEffectHost = NULL;\n\t\t\t}\n\n\t\t\tm_pChargeEffect = NULL;\n\t\t}\n\n\t\tif ( m_pChargedSound != NULL )\n\t\t{\n\t\t\tCSoundEnvelopeController::GetController().SoundDestroy( m_pChargedSound );\n\t\t\tm_pChargedSound = NULL;\n\t\t}\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n// Input : updateType - \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::OnDataChanged( DataUpdateType_t updateType )\n{\n\tBaseClass::OnDataChanged( updateType );\n\n\tif ( m_bUpdateHealingTargets )\n\t{\n\t\tUpdateEffects();\n\t\tm_bUpdateHealingTargets = false;\n\t}\n\n\t// Think?\n\tif ( m_bHealing )\n\t{\n\t\tClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_ALWAYS );\n\t}\n\telse\n\t{\n\t\tClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_NEVER );\n\t\tif ( m_bPlayingSound )\n\t\t{\n\t\t\tm_bPlayingSound = false;\n\t\t\tStopHealSound( true, false );\n\t\t}\n\n\t\t// Are they holding the attack button but not healing anyone? Give feedback.\n\t\tif ( IsActiveByLocalPlayer() && GetOwner() && GetOwner()->IsAlive() && m_bAttacking && GetOwner() == C_BasePlayer::GetLocalPlayer() && CanAttack() == true )\n\t\t{\n\t\t\tif ( gpGlobals->curtime >= m_flNextBuzzTime )\n\t\t\t{\n\t\t\t\tCLocalPlayerFilter filter;\n\t\t\t\tEmitSound( filter, entindex(), \"WeaponMedigun.NoTarget\" );\n\t\t\t\tm_flNextBuzzTime = gpGlobals->curtime + 0.5f;\t// only buzz every so often.\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStopHealSound( false, true );\t// Stop the \"no target\" sound.\n\t\t}\n\t}\n\n\tManageChargeEffect();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::ClientThink()\n{\n\tC_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();\n\tif ( !pLocalPlayer )\n\t\treturn;\n\n\t// Don't show it while the player is dead. Ideally, we'd respond to m_bHealing in OnDataChanged,\n\t// but it stops sending the weapon when it's holstered, and it gets holstered when the player dies.\n\tCTFPlayer *pFiringPlayer = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pFiringPlayer || pFiringPlayer->IsPlayerDead() || pFiringPlayer->IsDormant() )\n\t{\n\t\tClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_NEVER );\n\n\t\tif ( m_bPlayingSound )\n\t\t{\n\t\t\tm_bPlayingSound = false;\n\t\t\tStopHealSound();\n\t\t}\n\t\treturn;\n\t}\n\t\t\n\t// If the local player is the guy getting healed, let him know \n\t// who's healing him, and their charge level.\n\tif( m_hHealingTarget != NULL )\n\t{\n\t\tif ( pLocalPlayer == m_hHealingTarget )\n\t\t{\n\t\t\tpLocalPlayer->SetHealer( pFiringPlayer, m_flChargeLevel );\n\t\t}\n\n\t\tif ( !m_bPlayingSound )\n\t\t{\n\t\t\tm_bPlayingSound = true;\n\t\t\tCLocalPlayerFilter filter;\n\t\t\tEmitSound( filter, entindex(), GetHealSound() );\n\t\t}\n\t}\n\n\tif ( m_bOldChargeRelease != m_bChargeRelease )\n\t{\n\t\tm_bOldChargeRelease = m_bChargeRelease;\n\t\tForceHealingTargetUpdate();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nvoid CWeaponMedigun::UpdateEffects( void )\n{\n\tCTFPlayer *pFiringPlayer = ToTFPlayer( GetOwnerEntity() );\n\tif ( !pFiringPlayer )\n\t\treturn;\n\n\tC_BaseEntity *pEffectOwner = m_hHealingTargetEffect.hOwner.Get();\n\n\t// Remove all the effects\n\tif ( m_hHealingTargetEffect.pEffect && pEffectOwner )\n\t{\n\t\tpEffectOwner->ParticleProp()->StopEmission( m_hHealingTargetEffect.pEffect );\n\t\tpEffectOwner->ParticleProp()->StopEmission( m_hHealingTargetEffect.pCustomEffect );\n\t}\n\n\tm_hHealingTargetEffect.hOwner = NULL;\n\tm_hHealingTargetEffect.pTarget = NULL;\n\tm_hHealingTargetEffect.pEffect = NULL;\n\tm_hHealingTargetEffect.pCustomEffect = NULL;\n\n\tpEffectOwner = GetWeaponForEffect();\n\n\t// Don't add targets if the medic is dead\n\tif ( !pEffectOwner || pFiringPlayer->IsPlayerDead() )\n\t\treturn;\n\n\t// Add our targets\n\t// Loops through the healing targets, and make sure we have an effect for each of them\n\tif ( m_hHealingTarget )\n\t{\n\t\tif ( m_hHealingTargetEffect.pTarget == m_hHealingTarget )\n\t\t\treturn;\n\n\t\tconst char *pszFormat = IsReleasingCharge() ? \"medicgun_beam_%s_invun\" : \"medicgun_beam_%s\";\n\t\tconst char *pszEffectName = ConstructTeamParticle( pszFormat, GetTeamNumber() );\n\n\t\tCNewParticleEffect *pEffect = pEffectOwner->ParticleProp()->Create( pszEffectName, PATTACH_POINT_FOLLOW, \"muzzle\" );\n\t\tpEffectOwner->ParticleProp()->AddControlPoint( pEffect, 1, m_hHealingTarget, PATTACH_ABSORIGIN_FOLLOW, NULL, Vector(0,0,50) );\n\n\t\tCEconItemDefinition *pStatic = m_Item.GetStaticData();\n\t\tif ( pStatic )\n\t\t{\n\t\t\tEconItemVisuals *pVisuals =\tpStatic->GetVisuals( GetTeamNumber() );\n\t\t\tif ( pVisuals )\n\t\t\t{\n\t\t\t\tconst char *pszCustomEffectName = pVisuals->custom_particlesystem;\n\t\t\t\tif ( pszCustomEffectName[0] != '\\0' )\n\t\t\t\t{\n\t\t\t\t\tCNewParticleEffect *pCustomEffect = pEffectOwner->ParticleProp()->Create( pszCustomEffectName, PATTACH_POINT_FOLLOW, \"muzzle\" );\n\t\t\t\t\tpEffectOwner->ParticleProp()->AddControlPoint( pCustomEffect, 1, m_hHealingTarget, PATTACH_ABSORIGIN_FOLLOW, NULL, Vector(0,0,50) );\n\n\t\t\t\t\tm_hHealingTargetEffect.pCustomEffect = pCustomEffect;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm_hHealingTargetEffect.hOwner = pEffectOwner;\n\t\tm_hHealingTargetEffect.pTarget = m_hHealingTarget;\n\t\tm_hHealingTargetEffect.pEffect = pEffect;\n\t}\n}\n#endif\n\n\n<|start_filename|>src/game/shared/econ/econ_wearable.h<|end_filename|>\n//========= Copyright Valve Corporation, All rights reserved. ============//\n//\n// Purpose: \n//\n//========================================================================//\n\n#ifndef ECON_WEARABLE_H\n#define ECON_WEARABLE_H\n#ifdef _WIN32\n#pragma once\n#endif\n\n#ifdef CLIENT_DLL\n#include \"particles_new.h\"\n#endif\n\n#define MAX_WEARABLES_SENT_FROM_SERVER\t5\n#define PARTICLE_MODIFY_STRING_SIZE\t\t128\n\n#if defined( CLIENT_DLL )\n#define CEconWearable C_EconWearable\n#endif\n\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nclass CEconWearable : public CEconEntity\n{\n\tDECLARE_CLASS( CEconWearable, CEconEntity );\n\tDECLARE_NETWORKCLASS();\n\npublic:\n\n\tvirtual void\t\t\tSpawn( void );\n\tvirtual bool\t\t\tIsWearable( void ) { return true; }\n\tvirtual int\t\t\t\tGetSkin(void);\n\tvirtual void\t\t\tSetParticle(const char* name);\n\tvirtual void\t\t\tUpdateWearableBodyGroups( CBasePlayer *pPlayer );\n\tvirtual void\t\t\tGiveTo( CBaseEntity *pEntity );\n\n#ifdef GAME_DLL\n\tvirtual void\t\t\tEquip( CBasePlayer *pPlayer );\n\tvirtual void\t\t\tUnEquip( CBasePlayer *pPlayer );\n\tvirtual void\t\t\tSetExtraWearable( bool bExtraWearable ) { m_bExtraWearable = bExtraWearable; }\n\tvirtual bool\t\t\tIsExtraWearable( void ) { return m_bExtraWearable; }\n#else\n\tvirtual void\t\t\tOnDataChanged(DataUpdateType_t type);\n\tvirtual\tShadowType_t\tShadowCastType( void );\n\tvirtual bool\t\t\tShouldDraw( void );\n#endif\n\nprotected:\n\n#ifdef GAME_DLL\n\tCNetworkVar( bool, m_bExtraWearable );\n#else\n\tbool m_bExtraWearable;\n#endif\n\nprivate:\n\n#ifdef GAME_DLL\n\tCNetworkString(m_ParticleName, PARTICLE_MODIFY_STRING_SIZE);\n#else\n\tchar m_ParticleName[PARTICLE_MODIFY_STRING_SIZE];\n\tCNewParticleEffect *m_pUnusualParticle;\n#endif\n\n};\n\n#endif\n\n\n<|start_filename|>src/game/client/tf/tf_notificationmanager.cpp<|end_filename|>\n#include \"cbase.h\"\n#include \"tf_notificationmanager.h\"\n#include \"tf_mainmenu.h\"\n#include \"filesystem.h\"\n#include \"script_parser.h\"\n#include \"tf_gamerules.h\"\n#include \"tf_hud_notification_panel.h\"\n//#include \"public\\steam\\matchmakingtypes.h\"\n\nstatic CTFNotificationManager g_TFNotificationManager;\nCTFNotificationManager *GetNotificationManager()\n{\n\treturn &g_TFNotificationManager;\n}\n\nCON_COMMAND_F(tf2c_updateserverlist, \"Check for the messages\", FCVAR_DEVELOPMENTONLY)\n{\n\tGetNotificationManager()->UpdateServerlistInfo();\n}\n\nConVar tf2c_updatefrequency(\"tf2c_updatefrequency\", \"15\", FCVAR_DEVELOPMENTONLY, \"Updatelist update frequency (seconds)\");\n\nbool ServerLessFunc(const int &lhs, const int &rhs)\n{\n\treturn lhs < rhs;\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: constructor\n//-----------------------------------------------------------------------------\nCTFNotificationManager::CTFNotificationManager() : CAutoGameSystemPerFrame(\"CTFNotificationManager\")\n{\n\tif (!filesystem)\n\t\treturn;\n\n\tm_bInited = false;\n\tInit();\n}\n\nCTFNotificationManager::~CTFNotificationManager()\n{\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Initializer\n//-----------------------------------------------------------------------------\nbool CTFNotificationManager::Init()\n{\n\tif (!m_bInited)\n\t{\n\t\tm_SteamHTTP = steamapicontext->SteamHTTP();\n\t\tm_mapServers.SetLessFunc(ServerLessFunc);\n\t\tfUpdateLastCheck = tf2c_updatefrequency.GetFloat() * -1;\n\t\tbCompleted = false;\n\t\tm_bInited = true;\n\n\t\thRequest = 0;\n\t\tMatchMakingKeyValuePair_t filter;\n\t\tQ_strncpy(filter.m_szKey, \"gamedir\", sizeof(filter.m_szKey));\n\t\tQ_strncpy(filter.m_szValue, \"tf2vintage\", sizeof(filter.m_szKey)); // change \"tf2vintage\" to engine->GetGameDirectory() before the release\n\t\tm_vecServerFilters.AddToTail(filter);\n\t}\n\treturn true;\n}\n\nvoid CTFNotificationManager::Update(float frametime)\n{\n\tif (!MAINMENU_ROOT->InGame() && gpGlobals->curtime - fUpdateLastCheck > tf2c_updatefrequency.GetFloat())\n\t{\n\t\tfUpdateLastCheck = gpGlobals->curtime;\n\t\tUpdateServerlistInfo();\n\t}\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: Event handler\n//-----------------------------------------------------------------------------\nvoid CTFNotificationManager::FireGameEvent(IGameEvent *event)\n{\n}\n\nvoid CTFNotificationManager::UpdateServerlistInfo()\n{\t\n\tISteamMatchmakingServers *pMatchmaking = steamapicontext->SteamMatchmakingServers();\n\n\tif ( !pMatchmaking || pMatchmaking->IsRefreshing( hRequest ) )\n\t\treturn;\n\n\tMatchMakingKeyValuePair_t *pFilters;\n\tint nFilters = GetServerFilters(&pFilters);\n\thRequest = pMatchmaking->RequestInternetServerList( engine->GetAppID(), &pFilters, nFilters, this );\n}\n\ngameserveritem_t CTFNotificationManager::GetServerInfo(int index) \n{ \n\treturn m_mapServers[index];\n};\n\nvoid CTFNotificationManager::ServerResponded(HServerListRequest hRequest, int iServer)\n{\n\tgameserveritem_t *pServerItem = steamapicontext->SteamMatchmakingServers()->GetServerDetails(hRequest, iServer);\n\tint index = m_mapServers.Find(iServer);\n\tif (index == m_mapServers.InvalidIndex())\n\t{\n\t\tm_mapServers.Insert(iServer, *pServerItem);\n\t\t//Msg(\"%i SERVER %s (%s): PING %i, PLAYERS %i/%i, MAP %s\\n\", iServer, pServerItem->GetName(), pServerItem->m_NetAdr.GetQueryAddressString(),\n\t\t\t//pServerItem->m_nPing, pServerItem->m_nPlayers, pServerItem->m_nMaxPlayers, pServerItem->m_szMap);\n\t}\n\telse\n\t{\n\t\tm_mapServers[index] = *pServerItem;\n\t}\n}\n\nvoid CTFNotificationManager::RefreshComplete(HServerListRequest hRequest, EMatchMakingServerResponse response)\n{\n\tMAINMENU_ROOT->SetServerlistSize(m_mapServers.Count());\t\n\tMAINMENU_ROOT->OnServerInfoUpdate();\n}\n\n//-----------------------------------------------------------------------------\n// Purpose: \n//-----------------------------------------------------------------------------\nuint32 CTFNotificationManager::GetServerFilters(MatchMakingKeyValuePair_t **pFilters)\n{\n\t*pFilters = m_vecServerFilters.Base();\n\treturn m_vecServerFilters.Count();\n}\n\nchar* CTFNotificationManager::GetVersionString()\n{\n\tchar verString[30];\n\tif (g_pFullFileSystem->FileExists(\"version.txt\"))\n\t{\n\t\tFileHandle_t fh = filesystem->Open(\"version.txt\", \"r\", \"MOD\");\n\t\tint file_len = filesystem->Size(fh);\n\t\tchar* GameInfo = new char[file_len + 1];\n\n\t\tfilesystem->Read((void*)GameInfo, file_len, fh);\n\t\tGameInfo[file_len] = 0; // null terminator\n\n\t\tfilesystem->Close(fh);\n\n\t\tQ_snprintf(verString, sizeof(verString), GameInfo + 8);\n\n\t\tdelete[] GameInfo;\n\t}\n\n\tchar *szResult = (char*)malloc(sizeof(verString));\n\tQ_strncpy(szResult, verString, sizeof(verString));\n\treturn szResult;\n}"},"max_stars_repo_name":{"kind":"string","value":"AnthonyPython/TF2Vintage_razorback"}}},{"rowIdx":240,"cells":{"content":{"kind":"string","value":"<|start_filename|>Makefile<|end_filename|>\n.PHONY: fmt\nfmt:\n\tpoetry run isort .\n\tpoetry run black .\n\n.PHONY: chk\nchk:\n\tpoetry run isort -c .\n\tpoetry run black --check --diff .\n"},"max_stars_repo_name":{"kind":"string","value":"jobteaser-oss/PyAthena"}}},{"rowIdx":241,"cells":{"content":{"kind":"string","value":"<|start_filename|>examples/export-4.html<|end_filename|>\n\n\n\n \n \n \n ADR Documents\n\n \n\n\n
\n
\n ADR\n \n
\n
\n
\n
\n \n\n
\n
\n

Architecture Decision Record: Use ADRs

\n

Context

\n

Arachne has several very explicit goals that make the practice and\ndiscipline of architecture very important:

\n
    \n
  • We want to think deeply about all our architectural decisions,\nexploring all alternatives and making a careful, considered,\nwell-researched choice.
  • \n
  • We want to be as transparent as possible in our decision-making\nprocess.
  • \n
  • We don't want decisions to be made unilaterally in a\nvacuum. Specifically, we want to give our steering group the\nopportunity to review every major decision.
  • \n
  • Despite being a geographically and temporally distributed team, we\nwant our contributors to have a strong shared understanding of the\ntechnical rationale behind decisions.
  • \n
  • We want to be able to revisit prior decisions to determine fairly if\nthey still make sense, and if the motivating circumstances or\nconditions have changed.
  • \n
\n

Decision

\n

We will document every architecture-level decision for Arachne and its\ncore modules with an\nArchitecture Decision Record. These\nare a well structured, relatively lightweight way to capture\narchitectural proposals. They can serve as an artifact for discussion,\nand remain as an enduring record of the context and motivation of past\ndecisions.

\n

The workflow will be:

\n
    \n
  1. A developer creates an ADR document outlining an approach for a\nparticular question or problem. The ADR has an initial status of &quot;proposed.&quot;
  2. \n
  3. The developers and steering group discuss the ADR. During this\nperiod, the ADR should be updated to reflect additional context,\nconcerns raised, and proposed changes.
  4. \n
  5. Once consensus is reached, ADR can be transitioned to either an\n&quot;accepted&quot; or &quot;rejected&quot; state.
  6. \n
  7. Only after an ADR is accepted should implementing code be committed\nto the master branch of the relevant project/module.
  8. \n
  9. If a decision is revisited and a different conclusion is reached, a\nnew ADR should be created documenting the context and rationale for\nthe change. The new ADR should reference the old one, and once the\nnew one is accepted, the old one should (in its &quot;status&quot; section)\nbe updated to point to the new one. The old ADR should not be\nremoved or otherwise modified except for the annotation pointing to\nthe new ADR.
  10. \n
\n

Status

\n

Accepted

\n

Consequences

\n
    \n
  1. Developers must write an ADR and submit it for review before\nselecting an approach to any architectural decision -- that is, any\ndecision that affects the way Arachne or an Arachne application is\nput together at a high level.
  2. \n
  3. We will have a concrete artifact around which to focus discussion,\nbefore finalizing decisions.
  4. \n
  5. If we follow the process, decisions will be made deliberately, as a group.
  6. \n
  7. The master branch of our repositories will reflect the high-level\nconsensus of the steering group.
  8. \n
  9. We will have a useful persistent record of why the system is the way it is.
  10. \n
\n

Architecture Decision Record: Configuration

\n

Context

\n

Arachne has a number of goals.

\n
    \n
  1. It needs to be modular. Different software packages, written by\ndifferent developers, should be usable and swappable in the same\napplication with a minimum of effort.

  2. \n
  3. Arachne applications need to be transparent and\nintrospectable. It should always be as clear as possible what is\ngoing on at any given moment, and why the application is behaving\nin the way it does.

  4. \n
  5. As a general-purpose web framework, it needs to provide a strong\nset of default settings which are also highly overridable, and\nconfigurable to suit the unique needs of users.

  6. \n
\n

Also, it is a good development practice (particularly in Clojure) to\ncode to a specific information model (that is, data) rather than to\nparticular functions or APIs. Along with other benefits, this helps\nseparate (avoids &quot;complecting&quot;) the intended operation and its\nimplementation.

\n

Documenting the full rationale for this &quot;data first&quot; philosophy is\nbeyond the scope of this document, but some resources that explain it (among other things) are:

\n\n

Finally, one weakness of many existing Clojure libraries, especially\nweb development libraries, is the way in which they overload the\nClojure runtime (particularly vars and reified namespaces) to store\ninformation about the webapp. Because both the Clojure runtime and\nmany web application entities (e.g servers) are stateful, this causes\na variety of issues, particularly with reloading namespaces. Therefore,\nas much as possible, we would like to avoid entangling information\nabout an Arachne application with the Clojure runtime itself.

\n

Decision

\n

Arachne will take the &quot;everything is data&quot; philosophy to its logical\nextreme, and encode as much information about the application as\npossible in a single, highly general data structure. This will include\nnot just data that is normally thought of as &quot;config&quot; data, but the\nstructure and definition of the application itself. Everything that\ndoes not have to be arbitrary executable code will be\nreflected in the application config value.

\n

Some concrete examples include (but are not limited to):

\n
    \n
  • Dependency injection components
  • \n
  • Runtime entities (servers, caches, connections, pools, etc)
  • \n
  • HTTP routes and middleware
  • \n
  • Persistence schemas and migrations
  • \n
  • Locations of static and dynamic assets
  • \n
\n

This configuration value will have a schema that defines what types\nof entities can exist in the configuration, and what their expected\nproperties are.

\n

Each distinct module will have the ability to contribute to the schema\nand define entity types specific to its own domain. Modules may\ninteract by referencing entity types and properties defined in other\nmodules.

\n

Although it has much in common with a fully general in-memory\ndatabase, the configuration value will be a single immutable value,\nnot a stateful data store. This will avoid many of the complexities\nof state and change, and will eliminate the temptation to use the\nconfiguration itself as dynamic storage for runtime data.

\n

Status

\n

Proposed

\n

Consequences

\n
    \n
  • Applications will be defined comprehensively and declaratively by a\nrich data structure, before the application even starts.
  • \n
  • The config schema provides an explicit, reliable contract and set of\nextension points, which can be used by other modules to modify\nentities or behaviors.
  • \n
  • It will be easy to understand and inspect an application by\ninspecting or querying its configuration. It will be possible to\nwrite tools to make exploring and visualizing applications even easier.
  • \n
  • Developers will need to carefully decide what types of things are\nappropriate to encode statically in the configuration, and what must\nbe dynamic at runtime.
  • \n
\n

Architecture Decision Record: Datomic-based Configuration

\n

Context

\n

ADR-002 indicates that we will store the\nentire application config in a single rich data structure with a schema.

\n

Config as Database

\n

This implies that it should be possible to easily search, query and\nupdate the configuration value. It also implies that the configuration\nvalue is general enough to store arbitrary data; we don't know what\nkinds of things users or module authors will need to include.

\n

If what we need is a system that allows you to define, query, and\nupdate arbitrary data with a schema, then we are looking for a\ndatabase.

\n

Required data store characteristics:

\n
    \n
  1. It must be available under a permissive open source\nlicense. Anything else will impose unwanted restrictions on who can\nuse Arachne.
  2. \n
  3. It can operate embedded in a JVM process. We do not want to force\nusers to install anything else or run multiple processes just to\nget Arachne to work.
  4. \n
  5. The database must be serializable. It must be possible to write the\nentire configuration to disk, and then reconstitute it in the same\nexact state in a separate process.
  6. \n
  7. Because modules build up the schema progressively, the schema must\nbe inherently extensible. It should be possible for modules to\nprogressively add both new entity types and new attributes to\nexisting entity types.
  8. \n
  9. It should be usable from Clojure without a painful impedance mismatch.
  10. \n
\n

Configuration as Ontology

\n

As an extension of the rationale discussed in\nADR-002, it is useful to enumerate the\npossible use cases of the configuration and configuration schema\ntogether.

\n
    \n
  • The configuration is read by the application during bootstrap and\ncontrols the behavior of the application.
  • \n
  • The configuration schema defines what types of values the\napplication can or will read to modify its structure and behavior at\nboot time and run time.
  • \n
  • The configuration is how an application author communicates their\nintent about how their application should fit together and run, at a\nhigher, more conceptual level than code.
  • \n
  • The configuration schema is how module authors communicate to\napplication authors what settings, entities and structures\nare available for them to use in their applications.
  • \n
  • The configuration schema is how module authors communicate to other\npotential module authors what their extension points are; module\nextenders can safely read or write any entities/attributes declared\nby the modules upon which they depend.
  • \n
  • The configuration schema can be used to validate a particular\nconfiguration, and explain where and how it deviates from what is\nactually supported.
  • \n
  • The configuration can be exposed (via user interfaces of various\ntypes) to end users for analytics and debugging, explaining the\nstructure of their application and why things are the way they are.
  • \n
  • A serialization of the configuration, together with a particular\ncodebase (identified by a git SHA) form a precise, complete, 100%\nreproducible definition of the behavior of an application.
  • \n
\n

To the extent that the configuration schema expresses and communicates\nthe &quot;categories of being&quot; or &quot;possibility space&quot; of an application, it\nis a formal Ontology. This is\na desirable characteristic, and to the degree that it is practical to\ndo so, it will be useful to learn from or re-use existing work around\nformal ontological systems.

\n

Implementation Options

\n

There are instances of four broad categories of data stores that match\nthe first three of the data store characteristics defined above.

\n
    \n
  • Relational (Derby, HSQLDB, etc)
  • \n
  • Key/value (BerkelyDB, hashtables, etc)
  • \n
  • RDF/RDFs/OWL stores (Jena)
  • \n
  • Datomic-style (Datascript)
  • \n
\n

We can eliminate relational solutions fairly quickly; SQL schemas are\nnot generally extensible or flexible, failing condition #4. In\naddition, they do not fare well on #5 -- using SQL for queries and updates\nis not particularly fluent in Clojure.

\n

Similarly, we can eliminate key/value style data stores. In general,\nthese do not have schemas at all (or at least, not the type of rich\nschema that provides a meaningful data contract or ontology, which is the point\nfor Arachne.)

\n

This leaves solutions based on the RDF stack, and Datomic-style data\nstores. Both are viable options which would provide unique benefits\nfor Arachne, and both have different drawbacks.

\n

Explaining the core technical characteristics of RDF/OWL and Datomic\nis beyond the scope of this document; please see the\nJena and\nDatomic documentation for more\ndetails. More information on RDF, OWL and the Semantic web in general:

\n\n

RDF

\n

The clear choice for a JVM-based, permissively licensed,\nstandards-compliant RDF API is Apache Jena.

\n

Benefits for Arachne

\n
    \n
  • OWL is a good fit insofar as Arachne's goal is to define an\nontology of applications. The point of the configuration schema is\nfirst and foremost to serve as unambiguous communication regarding\nthe types of entities that can exist in an application, and what the\npossible relationships between them are. By definition, this is\ndefining an ontology, and is the exact use case which OWL is\ndesigned to address.
  • \n
  • Information model is a good fit for Clojure: tuples and declarative logic.
  • \n
  • Open and extensible by design.
  • \n
  • Well researched by very smart people, likely to avoid common\nmistakes that would result from building an ontology-like system\nourselves.
  • \n
  • Existing technology, well known beyond the Clojure\necosystem. Existing tools could work with Arachne project\nconfigurations out of the box.
  • \n
  • The open-world assumption is a good fit for Arachne's per-module\nschema modeling, since modules cannot know what other modules might\nbe present in the application.
  • \n
  • We're likely to want to introduce RDFs/OWL to the application\nanyway, at some point, as an abstract entity meta-schema (note: this\nhas not been firmly decided yet.)
  • \n
\n

Tradeoffs for Arachne (with mitigations)

\n
    \n
  • OWL is complex. Learning to use it effectively is a skill in its own\nright and it might be asking a lot to require of module authors.
  • \n
  • OWLs representation of some common concepts can be verbose and/or\nconvoluted in ways that would make schema more difficult to\nread/write. (e.g, Restriction classes)
  • \n
  • OWL is not a schema. Although the open world assumption is valid and\ngood when writing ontologies, it means that OWL inferencing is\nincapable of performing many of the kind of validations we would\nwant to apply once we do have a complete configuration and want to\ncheck it for correctness. For example, open-world reasoning can\nnever validate a owl:minCardinality rule.\n
      \n
    • Mitigation: Although OWL inferencing cannot provide closed-world\nvalidation of a given RDF dataset, such tools do exist. Some\nmechanisms for validating a particular closed set of RDF triples\ninclude:\n
        \n
      1. Writing SPARQL queries that catch various types of validation errors.
      2. \n
      3. Deriving validation errors using Jena's rules engine.
      4. \n
      5. Using an existing RDF validator such as\nEyeball\n(although, unfortunately, Eyeball does not seem to be well\nmaintained.)
      6. \n
    • \n
    • For Clojure, it would be possible to validate a given OWL class\nby generating a specification using clojure.spec that could be\napplied to concrete instances of the class in their map form.
    • \n
  • \n
  • Jena's API is aggressively object oriented and at odds with Clojure\nidioms.\n
      \n
    • Mitigation: Write a data-oriented wrapper (note: I have a\nworking proof of concept already.)
    • \n
  • \n
  • SPARQL is a string-based query language, as opposed to a composable data API.\n
      \n
    • Mitigation: It is possible to hook into Jena's ARQ query engine\nat the object layer, and expose a data-oriented API from there,\nwith SPARQL semantics but an API similar to Datomic datalog.
    • \n
  • \n
  • OWL inferencing is known to have performance issues with complex\ninferences. While Arachne configurations are tiny (as knowledge bases\ngo), and we are unlikely to use the more esoteric derivations, it is\nunknown whether this will cause problems with the kinds of\nontologies we do need.\n
      \n
    • Mitigation: We could restrict ourselves to the OWL DL or even\nOWL Lite sub-languages, which have more tractable inferencing\nrules.
    • \n
  • \n
  • Jena's APIs are such that it is impossible to write an immutable\nversion of a RDF model (at least without breaking most of Jena's\nAPI.) It's trivial to write a data-oriented wrapper, but intractable\nto write a persistent immutable one.
  • \n
\n

Datomic

\n

Note that Datomic itself does not satisfy the first requirement; it is\nclosed-source, proprietary software. There is an open source\nproject, Datascript, which emulates Datomic's APIs (without any of the\nstorage elements). Either one would work for Arachne, since Arachne\nonly needs the subset of features they both support. In, fact, if\nArachne goes the Datomic-inspired route, we would probably want to\nsupport both: Datomic, for those who have an existing investment\nthere, and Datascript for those who desire open source all the way.

\n

Benefits for Arachne

\n
    \n
  • Well known to most Clojurists
  • \n
  • Highly idiomatic to use from Clojure
  • \n
  • There is no question that it would be performant and technically\nsuitable for Arachne-sized data.
  • \n
  • Datomic's schema is a real validating schema; data transacted to\nDatomic must always be valid.
  • \n
  • Datomic Schema is open and extensible.
  • \n
\n

Tradeoffs for Arachne (with mitigations)

\n
    \n
  • The expressivity of Datomic's schema is anemic compared to RDFs/OWL;\nfor example, it has no built-in notion of types. It is focused\ntowards data storage and integrity rather than defining a public\nontology, which would be useful for Arachne.\n
      \n
    • Mitigation: If we did want something more ontologically focused,\nit is possible to build an ontology system on top of Datomic\nusing meta-attributes and Datalog rules. Examples of such\nsystems already exist.
    • \n
  • \n
  • If we did build our own ontology system on top of Datomic (or use an\nexisting one) we would still be responsible for &quot;getting it right&quot;,\nensuring that it meets any potential use case for Arachne while\nmaintaining internal and logical consistency.\n
      \n
    • Mitigation: we could still use the work that has been done in\nthe OWL world and re-implement a subset of axioms and\nderivations on top of Datomic.
    • \n
  • \n
  • Any ontological system built on top of Datomic would be novel to\nmodule authors, and therefore would require careful, extensive\ndocumentation regarding its capabilities and usage.
  • \n
  • To satisfy users of Datomic as well as those who have a requirement\nfor open source, it will be necessary to abstract across both\nDatomic and Datascript.\n
      \n
    • Mitigation: This work is already done (provided users stay\nwithin the subset of features that is supported by both\nproducts.)
    • \n
  • \n
\n

Decision

\n

The steering group decided the RDF/OWL approach is too high-risk to\nwrap in Clojure and implement at this time, while the rewards are\nmostly intangible &quot;openness&quot; and &quot;interoperability&quot; rather than\nsomething that will help move Arachne forward in the short term.

\n

Therefore, we will use a Datomic style schema for Arachne's configuration.

\n

Users may use either Datomic Pro, Datomic Free or Datascript at\nruntime in their applications. We will provide a &quot;multiplexer&quot;\nconfiguration implementation that utilizes both, and asserts that the\nresults are equal: this can be used by module authors to ensure they\nstay within the subset of features supported by both platforms.

\n

Before Arachne leaves &quot;alpha&quot; status (that is, before it is declared\nready for experimental production use or for the release of\nthird-party modules), we will revisit the question of whether OWL\nwould be more appropriate, and whether we have encountered issues that\nOWL would have made easier. If so, and if time allows, we reserve the\noption to either refactor the configuration layer to use Jena as a\nprimary store (porting existing modules), or provide an OWL\nview/rendering of an ontology stored in Datomic.

\n

Status

\n

Proposed

\n

Consequences

\n
    \n
  • It will be possible to write schemas that precisely define the\nconfiguration data that modules consume.
  • \n
  • The configuration system will be open and extensible to additional\nmodules by adding additional attributes and meta-attributes.
  • \n
  • The system will not provide an ontologically oriented view of the\nsystem's data without additional work.
  • \n
  • Additional work will be required to validate configuration with\nrespect to requirements that Datomic does not support natively (e.g,\nrequired attributes.)
  • \n
  • Every Arachne application must include either Datomic Free, Datomic\nPro or Datascript as a dependency.
  • \n
  • We will need to keep our eyes open to look for situations where a\nmore formal ontology system might be a better choice.
  • \n
\n

Architecture Decision Record: Module Structure &amp; Loading

\n

Context

\n

Arachne needs to be as modular as possible. Not only do we want the\ncommunity to be able to contribute new abilities and features that\nintegrate well with the core and with eachother, we want some of the\nbasic functionality of Arachne to be swappable for alternatives as\nwell.

\n

ADR-002 specifies that one role of modules\nis to contribute schema to the application config. Other roles of\nmodules would include providing code (as any library does), and\nquerying and updating the config during the startup\nprocess. Additionally, since modules can depend upon each other, they\nmust specify which modules they depend upon.

\n

Ideally there will be as little overhead as possible for creating and\nconsuming modules.

\n

Some of the general problems associated with plugin/module systems include:

\n
    \n
  • Finding and downloading the implementation of the module.
  • \n
  • Discovering and activating the correct set of installed modules.
  • \n
  • Managing module versions and dependencies.
  • \n
\n

There are some existing systems for modularity in the Java\necosystem. The most notable is OSGi, which provides not only a module\nsystem addressing the concerns above, but also service runtime with\nclasspath isolation, dynamic loading and unloading and lazy\nactivation.

\n

OSGi (and other systems of comparable scope) are overkill for\nArachne. Although they come with benefits, they are very heavyweight\nand carry a high complexity burden, not just for Arachne development\nbut also for end users. Specifically, Arachne applications will be\ndrastically simpler if (at runtime) they exist as a straightforward\ncodebase in a single classloader space. Features like lazy loading and\ndynamic start-stop are likewise out of scope; the goal is for an\nArachne runtime itself to be lightweight enough that starting and\nstopping when modules change is not an issue.

\n

Decision

\n

Arachne will not be responsible for packaging, distribution or\ndownloading of modules. These jobs will be delegated to an external\ndependency management &amp; packaging tool. Initially, that tool will be\nMaven/Leiningen/Boot, or some other tool that works with Maven\nartifact repositories, since that is currently the standard for JVM\nprojects.

\n

Modules that have a dependency on another module must specify a\ndependency using Maven (or other dependency management tool.)

\n

Arachne will provide no versioning system beyond what the packaging\ntool provides.

\n

Each module JAR will contain a special arachne-modules.edn file at\nthe root of its classpath. This data file (when read) contains a\nsequence of module definition maps.

\n

Each module definition map contains the following information:

\n
    \n
  • The formal name of the module (as a namespaced symbol.)
  • \n
  • A list of dependencies of the module (as a set of namespaced\nsymbols.) Module dependencies must form a directed acyclic graph;\ncircular dependencies are not allowed.
  • \n
  • A namespace qualified symbol that resolves to the module's schema\nfunction. A schema function is a function with no arguments that\nreturns transactable data containing the schema of the module.
  • \n
  • A namespace qualified symbol that resolves to the module's\nconfigure function. A configure function is a function that takes a\nconfiguration value and returns an updated configuration.
  • \n
\n

When an application is defined, the user must specify a set of module\nnames to use (exact mechanism TBD.) Only the specified modules (and\ntheir dependencies) will be considered by Arachne. In other words,\nmerely including a module as a dependency in the package manager is\nnot sufficient to activate it and cause it to be used in an\napplication.

\n

Status

\n

Proposed

\n

Consequences

\n
    \n
  • Creating a basic module is lightweight, requiring only:\n
      \n
    • writing a short EDN file
    • \n
    • writing a function that returns schema
    • \n
    • writing a function that queries and/or updates a configuration
    • \n
  • \n
  • From a user's point of view, consuming modules will use the same\nfamiliar mechanisms as consuming a library.
  • \n
  • Arachne is not responsible for getting code on the classpath; that\nis a separate concern.
  • \n
  • We will need to think of a straightforward, simple way for\napplication authors to specify the modules they want to be active.
  • \n
  • Arachne is not responsible for any complexities of publishing,\ndownloading or versioning modules
  • \n
  • Module versioning has all of the drawbacks of the package manager's\n(usually Maven), including the pain of resolving conflicting\nversions. This situation with respect to dependency version\nmanagement will be effectively the same as it is now with Clojure\nlibraries.
  • \n
  • A single dependency management artifact can contain several Arachne\nmodules (whether this is ever desirable is another question.)
  • \n
  • Although Maven is currently the default dependency/packaging tool\nfor the Clojure ecosystem, Arachne is not specified to use only\nMaven. If an alternative system gains traction, it will be possible\nto package and publish Arachne modules using that.
  • \n
\n

Architecture Decision Record: User Facing Configuration

\n

Context

\n

Per ADR-003, Arachne uses\nDatomic-shaped data for configuration. Although this is a flexible,\nextensible data structure which is a great fit for programmatic\nmanipulation, in its literal form it is quite verbose.

\n

It is quite difficult to understand the structure of Datomic data by\nreading its native textual representation, and it is similarly hard to\nwrite, containing enough repeated elements that copying and pasting\nquickly becomes the default.

\n

One of Arachne's core values is ease of use and a fluent experience\nfor developers. Since much of a developer's interaction with Arachne\nwill be writing to the config, it is of paramount importance that\nthere be some easy way to create configuration data.

\n

The question is, what is the best way for developers of Arachne\napplications to interact with their application's configuration?

\n

Option: Raw Datomic Txdata

\n

This would require end users to write Datomic transaction data by hand\nin order to configure their application.

\n

This is the &quot;simplest&quot; option, and has the fewest moving\nparts. However, as mentioned above, it is very far from ideal for\nhuman interactions.

\n

Option: Custom EDN data formats

\n

In this scenario, users would write EDN data in some some nested\nstructure of maps, sets, seqs and primitives. This is currently the\nmost common way to configure Clojure applications.

\n

Each module would then need to provide a mapping from the EDN config\nformat to the underlying Datomic-style config data.

\n

Because Arachne's configuration is so much broader, and defines so\nmuch more of an application than a typical application config file,\nit is questionable if standard nested EDN data would be a good fit\nfor representing it.

\n

Option: Code-based configuration

\n

Another option would be to go in the direction of some other\nframeworks, such as Ruby on Rails, and have the user-facing\nconfiguration be code rather than data.

\n

It should be noted that the primary motivation for having a\ndata-oriented configuration language, that it makes it easier to\ninteract with programmatically, doesn't really apply in Arachne's\ncase. Since applications are always free to interact richly with\nArachne's full configuration database, the ability to programmatically\nmanipulate the precursor data is moot. As such, one major argument\nagainst a code-based configuration strategy does not apply.

\n

Decision

\n

Developers will have the option of writing configuration using either\nnative Datomic-style, data, or code-based configuration\nscripts. Configuration scripts are Clojure files which, when\nevaluated, update a configuration stored in an atom currently in\ncontext (using a dynamically bound var.)

\n

Configuration scripts are Clojure source files in a distinct directory\nthat by convention is outside the application's classpath:\nconfiguration code is conceptually and physically separate from\napplication code. Conceptually, loading the configuration scripts\ncould take place in an entirely different process from the primary\napplication, serializing the resulting config before handing it to the\nruntime application.

\n

To further emphasize the difference between configuration scripts and\nruntime code, and because they are not on the classpath, configuration\nscripts will not have namespaces and will instead include each other\nvia Clojure's load function.

\n

Arachne will provide code supporting the ability of module authors to\nwrite &quot;configuration DSLs&quot; for users to invoke from their\nconfiguration scripts. These DSLs will emphasize making it easy to\ncreate appropriate entities in the configuration. In general, DSL\nforms will have an imperative style: they will convert their arguments\nto configuration data and immediately transact it to the context\nconfiguration.

\n

As a trivial example, instead of writing the verbose configuration data:

\n
{:arachne/id :my.app/server\n :arachne.http.server/port 8080\n :arachne.http.server/debug true}\n
\n

You could write the corresponding DSL:

\n
(server :id :my.app/server, :port 8080, :debug true)\n
\n

Note that this is an illustrative example and does not represent the\nactual DSL or config for the HTTP module.

\n

DSLs should make heavy use of Spec to make errors as comprehensible as possible.

\n

Status

\n

Proposed

\n

Consequences

\n
    \n
  • It will be possible for end users to define their configuration\nwithout writing config data by hand.
  • \n
  • Users will have access to the full power of the Clojure programming\nlanguage when configuring their application. This grants a great deal\nof power and flexibility, but also the risk of users doing inadvisable\nthings in their config scripts (e.g, non-repeatable side effects.)
  • \n
  • Module authors will bear the responsibility of providing\nan appropriate, user-friendly DSL interface to their configuration data.
  • \n
  • DSLs can compose; any module can reference and re-use the DSL\ndefinitions included in modules upon which it depends.
  • \n
\n

Architecture Decision Record: Core Runtime

\n

Context

\n

At some point, every Arachne application needs to start; to bootstrap\nitself from a static project or deployment artifact, initialize what\nneeds initializing, and begin servicing requests, connecting to\ndatabases, processing data, etc.

\n

There are several logically inherent subtasks to this bootstrapping process, which can be broken down as follows.

\n
    \n
  • Starting the JVM\n
      \n
    • Assembling the project's dependencies
    • \n
    • Building a JVM classpath
    • \n
    • Starting a JVM
    • \n
  • \n
  • Arachne Specific\n
      \n
    • Reading the initial user-supplied configuration (i.e, the configuration scripts from ADR-005)
    • \n
    • Initializing the Arachne configuration given a project's set of modules (described in ADR-002 and ADR-004)
    • \n
  • \n
  • Application Specific\n
      \n
    • Instantiate user and module-defined objects that needs to exist at runtime.
    • \n
    • Start and stop user and module-defined services
    • \n
  • \n
\n

As discussed in ADR-004, tasks in the &quot;starting the JVM&quot; category are not in-scope for Arachne; rather, they are offloaded to whatever build/dependency tool the project is using (usually either boot or leiningen.)

\n

This leaves the Arachne and application-specific startup tasks. Arachne should provide an orderly, structured startup (and shutdown) procedure, and make it possible for modules and application authors to hook into it to ensure that their own code initializes, starts and stops as desired.

\n

Additionally, it must be possible for different system components to have dependencies on eachother, such that when starting, services start after the services upon which they depend. Stopping should occur in reverse-dependency order, such that a service is never in a state where it is running but one of its dependencies is stopped.

\n

Decision

\n

Components

\n

Arachne uses the Component library to manage system components. Instead of requiring users to define a component system map manually, however, Arachne itself builds one based upon the Arachne config via Configuration Entities that appear in the configuration.

\n

Component entities may be added to the config directly by end users (via a initialization script as per ADR-005), or by modules in their configure function (ADR-004.)

\n

Component entities have attributes which indicates which other components they depend upon. Circular dependencies are not allowed; the component dependency structure must form a Directed Acyclic Graph (DAG.) The dependency attributes also specify the key that Component will use to assoc dependencies.

\n

Component entities also have an attribute that specifies a component constructor function (via a fully qualified name.) Component constructor functions must take two arguments: the configuration, and the entity ID of the component that is to be constructed. When invoked, a component constructor must return a runtime component object, to be used by the Component library. This may be any object that implements clojure.lang.Associative, and may also optionally satisfy Component's Lifecycle protocol.

\n

Arachne Runtime

\n

The top-level entity in an Arachne system is a reified Arachne Runtime object. This object contains both the Component system object, and the configuration value upon which the runtime is based. It satisfies the Lifecycle protocol itself; when it is started or stopped, all of the component objects it contains are started or stopped in the appropriate order.

\n

The constructor function for a Runtime takes a configuration value and some number of &quot;roots&quot;; entity IDs or lookup refs of Component entities in the config. Only these root components and their transitive dependencies will be instantiated or added to the Component system. In other words, only component entities that are actually used will be instantiated; unused component entities defined in the config will be ignored.

\n

A lookup function will be provided to find the runtime object instance of a component, given its entity ID or lookup ref in the configuraiton.

\n

Startup Procedure

\n

Arachne will rely upon an external build tool (such as boot or leiningen.) to handle downloading dependencies, assembling a classpath, and starting a JVM.

\n

Once JVM with the correct classpath is running, the following steps are required to yield a running Arachne runtime:

\n
    \n
  1. Determine a set of modules to use (the &quot;active modules&quot;)
  2. \n
  3. Build a configuration schema by querying each active module using its schema function (ADR-004)
  4. \n
  5. Update the config with initial configuration data from user init scripts (ADR-005)
  6. \n
  7. In module dependency order, give each module a chance to query and update the configuration using its configure function (ADR-004)
  8. \n
  9. Create a new Arachne runtime, given the configuration and a set of root components.
  10. \n
  11. Call the runtime's start method.
  12. \n
\n

The Arachne codebase will provide entry points to automatically perform these steps for common development and production scenarios. Alternatively, they can always be be executed individually in a REPL, or composed in custom startup functions.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • It is possible to fully define the system components and their dependencies in an application's configuration. This is how Arachne achieves dependency injection and inversion of control.
  • \n
  • It is possible to explicitly create, start and stop Arachne runtimes.
  • \n
  • Multiple Arachne runtimes may co-exist in the same JVM (although they may conflict and fail to start if they both attempt to use a global resource such as a HTTP port)
  • \n
  • By specifying different root components when constructing a runtime, it is possible to run different types of Arachne applications based on the same Arachne configuration value.
  • \n
\n

Architecture Decision Record: Configuration Updates

\n

Context

\n

A core part of the process of developing an application is making changes to its configuration. With its emphasis on configuration, this is even more true of Arachne than with most other web frameworks.

\n

In a development context, developers will want to see these changes reflected in their running application as quickly as possible. Keeping the test/modify cycle short is an important goal.

\n

However, accommodating change is a source of complexity. Extra code would be required to handle &quot;update&quot; scenarios. Components are initialized with a particular configuration in hand. While it would be possible to require that every component support an update operation to receive an arbitrary new config, implementing this is non-trivial and would likely need to involve conditional logic to determine the ways in which the new configuration is different from the old. If any mistakes where made in the implementation of update, for any component, such that the result was not identical to a clean restart, it would be possible to put the system in an inconsistent, unreproducible state.

\n

The &quot;simplest&quot; approach is to avoid the issue and completely discard and rebuild the Arachne runtime (ADR-006) every time the configuration is updated. Every modification to the config would be applied via a clean start, guaranteeing reproducibility and a single code path.

\n

However, this simple baseline approach has two major drawbacks:

\n
    \n
  1. The shutdown, initialization, and startup times of the entire set of components will be incurred every time the configuration is updated.
  2. \n
  3. The developer will lose any application state stored in the components whenever the config is modified.
  4. \n
\n

The startup and shutdown time issues are potentially problematic because of the general increase to cycle time. However, it might not be too bad depending on exactly how long it takes sub-components to start. Most commonly-used components take only a few milliseconds to rebuild and restart. This is a cost that most Component workflows absorb without too much trouble.

\n

The second issue is more problematic. Not only is losing state a drain on overall cycle speed, it is a direct source of frustration, causing developers to repeat the same tasks over and over. It will mean that touching the configuration has a real cost, and will cause developers to be hesitant to do so.

\n

Prior Art

\n

There is a library designed to solve the startup/shutdown problem, in conjunction with Component: Suspendable. It is not an ideal fit for Arachne, since it focuses on suspending and resuming the same Component instances rather than rebuilding, but its approach may be instructive.

\n

Decision

\n

Whenever the configuration changes, we will use the simple approach of stopping and discarding the entire old Arachne runtime (and all its components), and starting a new one.

\n

To mitigate the issue of lost state, Arachne will provide a new protocol called Preservable (name subject to change, pending a better one.) Components may optionally implement Preservable; it is not required. Preservable defines a single method, preserve.

\n

Whenever the configuration changes, the following procedure will be used:

\n
    \n
  1. Call stop on the old runtime.
  2. \n
  3. Instantiate the new runtime.
  4. \n
  5. For all components in the new runtime which implement Preservable, invoke the preserve function, passing it the corresponding component from the old runtime (if there is one).
  6. \n
  7. The preserve function will selectively copy state out of the old, stopped component into the new, not-yet-started component. It should be careful not to copy any state that would be invalidated by a configuration change.
  8. \n
  9. Call start on the new runtime.
  10. \n
\n

Arachne will not provide a mitigation for avoiding the cost of stopping and starting individual components. If this becomes a pain point, we can explore solutions such as that offered by Suspendable.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • The basic model for handling changes to the config will be easy to implement and reason about.
  • \n
  • It will be possible to develop with stateful components without losing state after a configuration change.
  • \n
  • Only components which need preservable state need to worry about it.
  • \n
  • The default behavior will prioritize correctness.
  • \n
  • It is possible to write a bad preserve method which copies elements of the old configuration.
  • \n
  • However, because all copies are explicit, it should be easy to avoid writing bad preserve methods.
  • \n
\n

Architecture Decision Record: Abstract Modules

\n

Context

\n

One design goal of Arachne is to have modules be relatively easily swappable. Users should not be permanently committed to particular technical choices, but instead should have some flexibility in choosing their preferred tech, as long as it exists in the form of an Arachne module.

\n

Some examples of the alternative implementations that people might wish to use for various parts of their application:

\n
    \n
  • HTTP Server: Pedestal or Ring
  • \n
  • Database: Datomic, an RDBMS or one of many NoSQL options.
  • \n
  • HTML Templating: Hiccup, Enlive, StringTemplate, etc.
  • \n
  • Client-side code: ClojureScript, CoffeeScript, Elm, etc.
  • \n
  • Authentication: Password-based, OpenID, Facebook, Google, etc.
  • \n
  • Emailing: SMTP, one of many third-party services.
  • \n
\n

This is only a representative sample; the actual list is unbounded.

\n

The need for this kind of flexibility raises some design concerns:

\n

Capability. Users should always be able to leverage the full power of their chosen technology. That is, they should not have to code to the &quot;least common denominator&quot; of capability. If they use Datomic Pro, for example, they should be able to write Datalog and fully utilize the in-process Peer model, not be restricted to an anemic &quot;ORM&quot; that is also compatible with RDBMSs.

\n

Uniformity. At tension with capability is the desire for uniformity; where the feature set of two alternatives is not particularly distinct, it is desirable to use a common API, so that implementations can be swapped out with little or no effort. For example, the user-facing API for sending a single email should (probably) not care whether it is ultimately sent via a local Sendmail server or a third-party service.

\n

Composition. Modules should also compose as much as possible, and they should be as general as possible in their dependencies to maximize the number of compatible modules. In this situation, it is actually desirable to have a &quot;least common denominator&quot; that modules can have a dependency on, rather than depending on specific implementations. For example, many modules will need to persist data and ultimately will need to work in projects that use Datomic or SQL. Rather than providing multiple versions, one for Datomic users and another for SQL, it would be ideal if they could code against a common persistence abstraction, and therefore be usable in any project with a persistence layer.

\n

What does it mean to use a module?

\n

The following list enumerates the ways in which it is possible to &quot;use&quot; a module, either from a user application or from another module. (See ADR-004).

\n
    \n
  1. You can call code that the module provides (the same as any Clojure library.)
  2. \n
  3. You can extend a protocol that the module provides (the same as any Clojure library.)
  4. \n
  5. You can read the attributes defined in the module from the configuration.
  6. \n
  7. You can write configuration data using the attributes defined in the module.
  8. \n
\n

These tools allow the definition of modules with many different kinds of relationships to each other. Speaking loosely, these relationships can correspond to other well-known patterns in software development including composition, mixins, interface/implementation, inheritance, etc.

\n

Decision

\n

In order to simultaneously meet the needs for capability, uniformity and composition, Arachne's core modules will (as appropriate) use the pattern of abstract modules.

\n

Abstract modules define certain attributes (and possibly also corresponding init script DSLs) that describe entities in a particular domain, without providing any runtime implementation which uses them. Then, other modules can &quot;implement&quot; the abstract module, reading the abstract entities and doing something concrete with them at runtime, as well as defining their own more specific attributes.

\n

In this way, user applications and dependent modules can rely either on the common, abstract module or the specific, concrete module as appropriate. Coding against the abstract module will yield a more generic &quot;least common denominator&quot; experience, while coding against a specific implementor will give more access to the unique distinguishing features of that particular technology, at the cost of generality.

\n

Similar relationships should hold in the library code which modules expose (if any.) An abstract module, for example, would be free to define a protocol, intended to be implemented concretely by code in an implementing module.

\n

This pattern is fully extensible; it isn't limited to a single level of abstraction. An abstract module could itself be a narrowing or refinement of another, even more general abstract module.

\n

Concrete Example

\n

As mentioned above, Arachne would like to support both Ring and Pedestal as HTTP servers. Both systems have a number of things in common:

\n
    \n
  • The concept of a &quot;server&quot; running on a port.
  • \n
  • The concept of a URL path/route
  • \n
  • The concept of a terminal &quot;handler&quot; function which receives a request and returns a response.
  • \n
\n

They also have some key differences:

\n
    \n
  • Ring composes &quot;middleware&quot; functions, whereas Pedestal uses &quot;interceptor&quot; objects
  • \n
  • Asynchronous responses are handled differently
  • \n
\n

Therefore, it makes sense to define an abstract HTTP module which defines the basic domain concepts; servers, routes, handlers, etc. Many dependent modules and applications will be able to make real use of this subset.

\n

Then, there will be the two modules which provide concrete implementations; one for Pedestal, one for Ring. These will contain the code that actually reads the configuration, and at runtime builds appropriate routing tables, starts server instances, etc. Applications which wish to make direct use of a specific feature like Pedestal interceptors may freely do so, using attributes defined by the Pedestal module.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • If modules or users want to program against a &quot;lowest common denominator&quot; abstraction, they may do so, at the cost of the ability to use the full feature set of a library.
  • \n
  • If modules or users want to use the full feature set of a library, they may do so, at the cost of being able to transparently replace it with something else.
  • \n
  • There will be a larger number of different Arachne modules available, and their relationships will be more complex.
  • \n
  • Careful thought and architecture will need to go into the factoring of modules, to determine what the correct general elements are.
  • \n
\n

Architecture Decision Record: Configuration Ontology

\n

Context

\n

In ADR-003 it was decided to use a Datomic-based configuration, the alternative being something more semantically or ontologically descriptive such as RDF+OWL.

\n

Although we elected to use Datomic, Datomic does not itself offer much ontological modeling capacity. It has no built-in notion of types/classes, and its attribute specifications are limited to what is necessary for efficient storage and indexing, rather than expressive or validative power.

\n

Ideally, we want modules to be able to communicate additional information about the structure and intent of their domain model, including:

\n
    \n
  • Types of entities which can exist
  • \n
  • Relationships between those types
  • \n
  • Logical constraints on the values of attributes:\n
      \n
    • more fine grained cardinality; optional/required attributes
    • \n
    • valid value ranges
    • \n
    • target entity type (for ref attributes)
    • \n
  • \n
\n

This additional data could serve three purposes:

\n
    \n
  • Documentation about the intended purpose and structure of the configuration defined by a module.
  • \n
  • Deeper, more specific validation of user-supplied configuration values
  • \n
  • Machine-readable integration point for tools which consume and produce Arachne configurations.
  • \n
\n

Decision

\n
    \n
  • We will add meta-attributes to the schema of every configuration, expressing basic ontological relationships.
  • \n
  • These attributes will be semantically compatible with OWL (such that we could conceivably in the future generate an OWL ontology from a config schema)
  • \n
  • The initial set of these attributes will be minimal, and targeted towards the information necessary to generate rich schema diagrams\n
      \n
    • classes and superclass
    • \n
    • attribute domain
    • \n
    • attribute range (for ref attributes)
    • \n
    • min and max cardinality
    • \n
  • \n
  • Arachne core will provide some (optional) utility functions for schema generation, to make writing module schemas less verbose.
  • \n
\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Arachne schemas will reify the concept of entity type and the possible relationships between entities of various types.
  • \n
  • We will have an approach for adding additional semantic attributes in the future, as it makes sense to do so.
  • \n
  • We will not be obligated to define an entire ontology up front
  • \n
  • Modules usage of the defined ontology is not technically enforced. Some, (such as entity type relationships) will be the strong convention and possibly required for tool support; others (such as min and max cardinality) will be optional.
  • \n
  • We will preserve the possibility for interop with OWL in the future.
  • \n
\n

Architecture Decision Record: Persistent Configuration

\n

Context

\n

While many Arachne applications will use a transient config which is rebuilt from its initialization scripts every time an instance is started, some users might wish instead to store their config persistently in a full Datomic instance.

\n

There are a number of possible benefits to this approach:

\n
    \n
  • Deployments from the same configuration are highly reproducible
  • \n
  • Organizations can maintain an immutable persistent log of configuration changes over time.
  • \n
  • External tooling can be used to persistently build and define configurations, up to and including full &quot;drag and drop&quot; architecture or application design.
  • \n
\n

Doing this introduces a number of additional challenges:

\n
    \n
  • Initialization Scripts: Having a persistent configuration introduces the question of what role initialization scripts play in the setup. Merely having a persistent config does not make it easier to modify by hand - quite the opposite. While an init script could be used to create the configuration, it's not clear how they would be updated from that point (absent a full config editor UI.)

    \n

    Re-running a modified configuration script on an existing configuration poses challenges as well; it would require that all scripts be idempotent, so as not to create spurious objects on subsequent runs. Also, scripts would then need to support some concept of retraction.

  • \n
  • Scope &amp; Naming: It is extremely convenient to use :db.unique/identity attributes to identify particular entities in a configuration and configuration init scripts. This is not only convenient, but required if init scripts are to be idempotent, since this is the only mechanism by which Datomic can determine that a new entity is &quot;the same&quot; as an older entity in the system.

    \n

    However, if there are multiple different configurations in the same database, there is the risk that some of these unique values might be unintentionally the same and &quot;collide&quot;, causing inadvertent linkages between what ought to be logically distinct configurations.

    \n

    While this can be mitigated in the simple case by ensuring that every config uses its own unique namespace, it is still something to keep in mind.

  • \n
  • Configuration Copying &amp; Versioning Although Datomic supports a full history, that history is linear. Datomic does not currently support &quot;forking&quot; or maintaining multiple concurrent versions of the same logical data set.

    \n

    This does introduce complexities when thinking about &quot;modifying&quot; a configuration, while still keeping the old one. This kind of &quot;fork&quot; would require a deep clone of all the entities in the config, as well as renaming all of the :db.unique/identity attrs.

    \n

    Renaming identity attributes compounds the complexity, since it implies that either idents cannot be hardcoded in initialization scripts, or the same init script cannot be used to generate or update two different configurations.

  • \n
  • Environment-specific Configuration: Some applications need slightly different configurations for different instances of the &quot;same&quot; application. For instance, some software needs to be told what its own IP address is. While it makes sense to put this data in the configuration, this means that there would no longer be a single configuration, but N distinct (yet 99% identical) configurations.

    \n

    One solution would be to not store this data in the configuration (instead picking it up at runtime from an environment variable or secondary config file), but multiplying the sources of configuration runs counter to Arachne's overriding philosophy of putting everything in the configuration to start with.

  • \n
  • Relationship with module load process: Would the stored configuration represent only the &quot;initial&quot; configuration, before being updated by the active modules? Or would it represent the complete configuration, after all the modules have completed their updates?

    \n

    Both alternatives present issues.

    \n

    If only the user-supplied, initial config is stored, then the usefulness of the stored config is diminished, since it does not provide a comprehensive, complete view of the configuration.

    \n

    On the other hand, if the complete, post-module config is persisted, it raises more questions. What happens if the user edits the configuration in ways that would cause modules to do something different with the config? Is it possible to run the module update process multiple times on the same config? If so, how would &quot;old&quot; or stale module-generated values be removed?

  • \n
\n

Goals

\n

We need a technical approach with good answers to the challenges described above, that enables a clean user workflow. As such, it is useful to enumerate the specific activities that it would be useful for a persistent config implementation to support:

\n
    \n
  • Define a new configuration from an init script.
  • \n
  • Run an init script on an existing configuration, updating it.
  • \n
  • Edit an existing configuration using the REPL.
  • \n
  • Edit an existing configuration using a UI.
  • \n
  • Clone a configuration
  • \n
  • Deploy based on a specific configuration
  • \n
\n

At the same time, we need to be careful not to overly complicate things for the common case; most applications will still use the pattern of generating a configuration from an init script immediately before running an application using it.

\n

Decision

\n

We will not attempt to implement a concrete strategy for config persistence at this time; it runs the risk of becoming a quagmire that will halt forward momentum.

\n

Instead, we will make a minimal set of choices and observations that will enable forward progress while preserving the ability to revisit the issue of persistent configuration at some point in the future.

\n
    \n
  1. The configuration schema itself should be compatible with having several configurations present in the same persistent database. Specifically:
  2. \n
\n
    \n
  • Each logical configuration should have its own namespace, which will be used as the namespace of all :db.unique/identity values, ensuring their global uniqueness.
  • \n
  • There is a 'configuration' entity that reifies a config, its possible root components, how it was constructed, etc.
  • \n
  • The entities in a configuration must form a connected graph. That is, every entity in a configuration must be reachable from the base 'config' entity. This is required to have any ability to identify the config as a whole within for any purpose.
  • \n
\n
    \n
  1. The current initial tooling for building configurations (including the init scripts) will focus on building configurations from scratch. Tooling capable of &quot;editing&quot; an existing configuration is sufficiently different, with a different set of requirements and constraints, that it needs its own design process.

  2. \n
  3. Any future tooling for storing, viewing and editing configurations will need to explicitly determine whether it wants to work with the configuration before or after processing by the modules, since there is a distinct set of tradeoffs.

  4. \n
\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  1. We can continue making forward progress on the &quot;local&quot; configuration case.
  2. \n
  3. Storing persistent configurations remains possible.
  4. \n
  5. It is immediately possible to save configurations for repeatability and debugging purposes.\n
      \n
    • The editing of persistent configs is what will be more difficult.
    • \n
  6. \n
  7. When we want to edit persistent configurations, we will need to analyze the specific use cases to determine the best way to do so, and develop tools specific to those tasks.
  8. \n
\n

Architecture Decision Record: Asset Pipeline

\n

Context

\n

In addition to handling arbitrary HTTP requests, we would like for Arachne to make it easy to serve up certain types of well-known resources, such as static HTML, images, CSS, and JavaScript.

\n

These &quot;static assets&quot; can generally be served to users as files directly, without processing at the time they are served. However, it is extremely useful to provide pre-processing, to convert assets in one format to another format prior to serving them. Examples of such transformations include:

\n
    \n
  • SCSS/LESS to CSS
  • \n
  • CoffeeScript to JavaScript
  • \n
  • ClojureScript to JavaScript
  • \n
  • Full-size images to thumbnails
  • \n
  • Compress files using gzip
  • \n
\n

Additionally, in some cases, several such transformations might be required, on the same resource. For example, a file might need to be converted from CoffeeScript to JavaScript, then minified, then gzipped.

\n

In this case, asset transformations form a logical pipeline, applying a set of transformations in a known order to resources that meet certain criteria.

\n

Arachne needs a module that defines a way to specify what assets are, and what transformations ought to apply and in what order. Like everything else, this system needs to be open to extension by other modules, to provide custom processing steps.

\n

Development vs Production

\n

Regardless of how the asset pipeline is implemented, it must provide a good development experience such that the developer can see their changes immediately. When the user modifies an asset file, it should be automatically reflected in the running application in near realtime. This keeps development cycle times low, and provides a fluid, low-friction development experience that allows developers to focus on their application.

\n

Production usage, however, has a different set of priorities. Being able to reflect changes is less important; instead, minimizing processing cost and response time is paramount. In production, systems will generally want to do as much processing as they can ahead of time (during or before deployment), and then cache aggressively.

\n

Deployment &amp; Distribution

\n

For development and simple deployments, Arachne should be capable of serving assets itself. However, whatever technique it uses to implement the asset pipeline, it should also be capable of sending the final assets to a separate cache or CDN such that they can be served statically with optimal efficiency. This may be implemented as a separate module from the core asset pipeline, however.

\n

Entirely Static Sites

\n

There is a large class of websites which actually do not require any dynamic behavior at all; they can be built entirely from static assets (and associated pre-processing.) Examples of frameworks that cater specifically to this type of &quot;static site generation&quot; include Jekyll, Middleman, Brunch, and many more.

\n

By including the asset pipeline module, and not the HTTP or Pedestal modules, Arachne also ought to be able to function as a capable and extensible static site generator.

\n

Decision

\n

Arachne will use Boot to provide an abstract asset pipeline. Boot has built-in support for immutable Filesets, temp directory management, and file watchers.

\n

As with everything in Arachne, the pipeline will be specified as pure data in the configuration, specifying inputs, outputs, and transformations explicitly.

\n

Modules that participate in the asset pipeline will develop against a well-defined API built around Boot Filesets.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • The asset pipeline will be fully specified as data in the Arachne configuration.
  • \n
  • Adding Arachne support for an asset transformation will involve writing a relatively straightforward wrapper adapting the library to work on boot Filesets.
  • \n
  • We will need to program against some of Boot's internal APIs, although Alan and Micha have suggested they would be willing to factor out the Fileset support to a separate library.
  • \n
\n

Architecture Decision Record: Enhanced Validation

\n

Context

\n

As much as possible, an Arachne application should be defined by its configuration. If something is wrong with the configuration, there is no way that an application can be expected to work correctly.

\n

Therefore, it is desirable to validate that a configuration is correct to the greatest extent possible, at the earliest possible moment. This is important for two distinct reasons:

\n
    \n
  • Ease of use and developer friendliness. Config validation can return helpful errors that point out exactly what's wrong instead of deep failures with lengthy debug sessions.
  • \n
  • Program correctness. Some types of errors in configs might not be discovered at all during testing or development, and aggressively failing on invalid configs will prevent those issues from affecting end users in production.
  • \n
\n

There are two &quot;kinds&quot; of config validation.

\n

The first is ensuring that a configuration as data is structurally correct; that it adheres to its own schema. This includes validating types and cardinalities as expressed by the Arachne's core ontology system.

\n

The second is ensuring that the Arachne Runtime constructed from a given configuration is correct; that the runtime component instances returned by component constructors are of the correct type and likely to work.

\n

Decision

\n

Arachne will perform both kinds of validation. To disambiguate them (since they are logically distinct), we will term the structural/schema validation &quot;configuration validation&quot;, while the validation of the runtime objects will be &quot;runtime validation.&quot;

\n

Both styles of validation should be extensible by modules, so modules can specify additional validations, where necessary.

\n

Configuration Validation

\n

Configuration validation is ensuring that an Arachne configuration object is consistent with itself and with its schema.

\n

Because this is ultimately validating a set of Datomic style eavt tuples, the natural form for checking tuple data is Datalog queries and query rules, to search for and locate data that is &quot;incorrect.&quot;

\n

Each logical validation will have its own &quot;validator&quot;, a function which takes a config, queries it, and either returns or throws an exception. To validate a config, it is passed through every validator as the final step of building a module.

\n

The set of validators is open, and defined in the configuration itself. To add new validators, a module can transact entities for them during its configuration building phase.

\n

Runtime Validation

\n

Runtime validation occurs after a runtime is instantiated, but before it is started. Validation happens on the component level; each component may be subject to validation.

\n

Unlike Configuration validation, Runtime validation uses Spec. What specs should be applied to each component are defined in the configuration using a keyword-valued attribute. Specs may be defined on individual component entities, or to the type of a component entity. When a component is validated, it is validated using all the specs defined for it or any of its supertypes.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Validations have the opportunity to find errors and return clean error messages
  • \n
  • Both the structure of the config and the runtime instances can be validated
  • \n
  • The configuration itself describes how it will be validated
  • \n
  • Modules have complete flexibility to add new validations
  • \n
  • Users can write custom validations
  • \n
\n

Architecture Decision Record: Error Reporting

\n

Context

\n

Historically, error handling has not been Clojure's strong suit. For the most part, errors take the form of a JVM exception, with a long stack trace that includes a lot of Clojure's implementation as well as stack frames that pertain directly to user code.

\n

Additionally, prior to the advent of clojure.spec, Clojure errors were often &quot;deep&quot;: a very generic error (like a NullPointerException) would be thrown from far within a branch, rather than eagerly validating inputs.

\n

There are Clojure libraries which make an attempt to improve the situation, but they typically do it by overriding Clojure's default exception printing functions across the board, and are sometimes &quot;lossy&quot;, dropping information that could be desirable to a developer.

\n

Spec provides an opportunity to improve the situation across the board, and with Arachne we want to be on the leading edge of providing helpful error messages that point straight to the problem, minimize time spent trying to figure out what's going on, and let developers get straight back to working on what matters to them.

\n

Ideally, Arachne's error handling should exhibit the following qualities:

\n
    \n
  • Never hide possibly relevant information.
  • \n
  • Allow module developers to be as helpful as possible to people using their tools.
  • \n
  • Provide rich, colorful, multi-line detailed explanations of what went wrong (when applicable.)
  • \n
  • Be compatible with existing Clojure error-handling practices for errors thrown from libraries that Arachne doesn't control.
  • \n
  • Not violate expectations of experienced Clojure programmers.
  • \n
  • Be robust enough not to cause additional problems.
  • \n
  • Not break existing logging tools for production use.
  • \n
\n

Decision

\n

We will separate the problems of creating rich exceptions, and catching them and displaying them to the user.

\n

Creating Errors

\n

Whenever a well-behaved Arachne module needs to report an error, it should throw an info-bearing exception. This exception should be formed such that it is handled gracefully by any JVM tooling; the message should be terse but communicative, containing key information with no newlines.

\n

However, in the ex-data, the exception will also contain much more detailed information, that can be used (in the correct context) to provide much more detailed or verbose errors. Specifically, it may contain the following keys:

\n
    \n
  • :arachne.error/message - The short-form error message (the same as the Exception message.)
  • \n
  • :arachne.error/explanation - a long-form error message, complete with newlines and formatting.
  • \n
  • :arachne.error/suggestions - Zero or more suggestions on how the error might be fixed.
  • \n
  • :arachne.error/type - a namespaced keyword that uniquely identifies the type of error.
  • \n
  • :arachne.error/spec - The spec that failed (if applicable)
  • \n
  • :arachne.error/failed-data - The data that failed to match the spec (if applicable)
  • \n
  • :arachne.error/explain-data - An explain-data for the spec that failed (if applicable).
  • \n
  • :arachne.error/env - A map of the locals in the env at the time the error was thrown.
  • \n
\n

Exceptions may, of course, contain additional data; these are the common keys that tools can use to more effectively render errors.

\n

There will be a suite of tools, provided with Arachne's core, for conveniently generating errors that match this pattern.

\n

Displaying Errors

\n

We will use a pluggable &quot;error handling system&quot;, where users can explicitly install an exception handler other than the default.

\n

If the user does not install any exception handlers, errors will be handled the same way as they are by default (usually, dumped with the message and stack trace to System/err.) This will not change.

\n

However, Arachne will also provide a function that a user can invoke in their main process, prior to doing anything else. Invoking this function will install a set of default exception handlers that will handle errors in a richer, more Arachne-specific way. This includes printing out the long-form error, or even (eventually) popping open a graphical data browser/debugger (if applicable.)

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Error handling will follow well-known JVM patterns.
  • \n
  • If users want, they can get much richer errors than baseline exception handling.
  • \n
  • The &quot;enhanced&quot; exception handling is optional and will not be present in production.
  • \n
\n

Architecture Decision Record: Project Templates

\n

Context

\n

When starting a new project, it isn't practical to start completely from scratch, every time. We would like to have a varity of &quot;starting point&quot; projects, for different purposes.

\n

Lein templates

\n

In the Clojure space, Leiningen Templates fill this purpose. These are sets of special string-interpolated files that are &quot;rendered&quot; into a working project using special tooling.

\n

However, they have two major drawbacks:

\n
    \n
  • They only work when using Leiningen as a build tool.
  • \n
  • The template files are are not actually valid source files, which makes them difficult to maintain. Changes need to be manually copied over to the templates.
  • \n
\n

Rails templates

\n

Rails also provides a complete project templating solution. In Rails, the project template is a template.rb file which contains DSL forms that specify operations to perform on a fresh project. These operations include creating files, modifying a projects dependencies, adding Rake tasks, and running specific generators.

\n

Generators are particularly interesting, because the idea is that they can generate or modify stubs for files pertaining to a specific part of the application (e.g, a new model or a new controller), and they can be invoked at any point, not just initial project creation.

\n

Decision

\n

To start with, Arachne templates will be standard git repositories containing an Arachne project. They will use no special syntax, and will be valid, runnable projects out of the box.

\n

In order to allow users to create their own projects, these template projects will include a rename script. The rename script will recursively rename an entire project directory to something that the user chooses, and will delete .git and re-run git init,

\n

Therefore, the process to start a new Arachne project will be:

\n
    \n
  1. Choose an appropriate project template.
  2. \n
  3. Clone its git repository from Github
  4. \n
  5. Run the rename script to rename the project to whatever you wish
  6. \n
  7. Start a repl, and begin editing.
  8. \n
\n

Maven Distribution

\n

There are certain development environments where there is not full access to the open internet (particularly in certain governmental applications.) Therefore, accessing GitHub can prove difficult. However, in order to support developers, these organizations often run their own Maven mirrors.

\n

As a convenience to users in these situations, when it is necessary, we can build a wrapper that can compress and install a project directory as a Maven artifact. Then, using standard Maven command line tooling, it will be possible to download and decompress the artifact into a local filesystem directory, and proceed as normal.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • It will take only a few moments for users to create new Arachne projects.
  • \n
  • It will be straightforward to build, curate, test and maintain multiple different types of template projects.
  • \n
  • The only code we will need to write to support templates is the &quot;rename&quot; script.
  • \n
  • The rename script will need to be capable of renaming all the code and files in the template, with awareness of the naming requirements and conventions for Clojure namespaces and code.
  • \n
  • Template projects themselves can be built continuously using CI
  • \n
\n

Contrast with Rails

\n

One way that this approach is inferior to Rails templates is that this approach is &quot;atomic&quot;; templating happens once, and it happens for the whole project. Rails templates can be composed of many different generators, and generators can be invoked at any point over a project's lifecycle to quickly stub out new functionality.

\n

This also has implications for maintenance; because Rails generators are updated along with each Rails release, the template itself is more stable, wheras Arachne templates would need to be updated every single time Arachne itself changes. This imposes a maintenance burden on templates maintained by the core team, and risks poor user experience for users who find and try to use an out-of-date third-party template.

\n

However, there is is mitigating difference between Arachne and Rails, which relates directly to the philosophy and approach of the two projects.

\n

In Rails, the project is the source files, and the project directory layout. If you ask &quot;where is a controller?&quot;, you can answer by pointing to the relevant *.rb file in the app/controllers directory. So in Rails, the task &quot;create a new controller&quot; is equivalent to creating some number of new files in the appropriate places, containing the appropriate code. Hence the importance of generators.

\n

In Arachne, by contrast, the project is not ultimately defined by its source files and directory structure; it is defined by the config. Of course there are source files and a directory structure, and there will be some conventions about how to organize them, but they are not the very definition of a project. Instead, a project's Configuration is the canonical definition of what a project is and what it does. If you ask &quot;where is a controller?&quot; in Arachne, the only meaningful answer is to point to data in the configuration. And the task &quot;create a controller&quot; means inserting the appropriate data into the config (usually via the config DSL.)

\n

As a consequence, Arachne can focus less on code generation, and more on generating config data. Instead of providing a code generator which writes source files to the project structure, Arachne can provide config generators which users can invoke (with comparable effort) in their config scripts.

\n

As such, Arachne templates will typically be very small. In Arachne, code generation is an antipattern. Instead of making it easy to generate code, Arachne focuses on building abstractions that let users specify their intent directly, in a terse manner.

\n

Architecture Decision Record: Data Abstraction Model

\n

Context

\n

Most applications need to store and manipulate data. In the current state of the art in Clojure, this is usually done in a straightforward, ad-hoc way. Users write schema, interact with their database, and parse data from user input into a persistence format using explicit code.

\n

This is acceptable, if you're writing a custom, concrete application from scratch. But it will not work for Arachne. Arachne's modules need to be able to read and write domain data, while also being compatible with multiple backend storage modules.

\n

For example a user/password based authentication module needs to be able to read and write user records to the application database, and it should work whether a user is using a Datomic, SQL or NoSQL database.

\n

In other words, Arachne cannot function well in a world in which every module is required to interoperate directly against one of several alternative modules. Instead, there needs to be a way for modules to &quot;speak a common language&quot; for data manipulation and persistence.

\n

Other use cases

\n

Data persistence isn't the only concern. There are many other situations where having a common, abstract data model is highly useful. These include:

\n
    \n
  • quickly defining API endpoints based on a data model
  • \n
  • HTML &amp; mobile form generation
  • \n
  • generalized data validation tools
  • \n
  • unified administration &amp; metrics tools
  • \n
\n

Modeling &amp; Manipulation

\n

There are actually two distinct concepts at play; data modeling and data manipulation.

\n

Modeling is the activity of defining the abstract shape of the data; essentially, it is writing schema, but in a way that is not specific to any concrete implementation. Modules can then use the data model to generate concrete schema, generate API endpoints, forms, validate data, etc.

\n

Manipulation is the activity of using the model to create, read update or delete actual data. For an abstract data manipulation layer, this generally means a polymorphic API that supports some common set of implementations, which can be extended to concrete CRUD operations

\n

Existing solutions: ORMs

\n

Most frameworks have some answer to this problem. Rails has ActiveRecord, Elixir has Ecto, old-school Java has Hibernate, etc. In every case, they try to paper over what it looks like to access the actual database, and provide an idiomatic API in the language to read and persist data. This language-level API is uniformly designed to make the database &quot;easy&quot; to use, but also has the effect of providing a common abstraction point for extensions.

\n

Unfortunately, ORMs also exhibit a common set of problems. By their very nature, they are an extra level of indirection. They provide abstraction, but given how complex databases are the abstraction is always &quot;leaky&quot; in significant ways. Using them effectively requires a thorough understanding not only of the ORM's APIs, but also the underlying database implementation, and what the ORM is doing to map the data from one format to another.

\n

ORMs are also tied more or less tightly to the relational model. Attempts to extend ActiveRecord (for example) to non-relational data stores have had varying levels of success.

\n

Database &quot;migrations&quot;

\n

One other function is to make sure that the concrete database schema matches the abstract data model that the application is using. Most ORMs implement this using some form of &quot;database migrations&quot;, which serve as a repeatable series of all changes made to a database. Ideally, these are not redundant with the abstract data model, to avoid repeating the same information twice and also to ensure consistency.

\n

Decision

\n

Arachne will provide a lightweight model for data abstraction and persistence, oriented around the Entity/Attribute mode. To avoid word salad and acronyms loaded with baggage and false expectations, we will give it a semantically clean name. We will be free to define this name, and set expectations around what it is and how it is to be used. I suggest &quot;Chimera&quot;, as it is in keeping with the Greek mythology theme and has several relevant connotations.

\n

Chimera consists of two parts:

\n
    \n
  • An entity model, to allow application authors to easily specify the shape of their domain data in their Arachne configuration.
  • \n
  • A set of persistence operations, oriented around plain Clojure data (maps, sets and vectors) that can be implemented meaningfully against multiple types of adapters. Individual operations are granular and can be both consumed and provided á la carte; adapters that don't support certain behaviors can omit them (at the cost of compatibility with modules that need them.)
  • \n
\n

Although support for any arbitrary database cannot be guaranteed, the persistence operations are designed to support a majority of commonly used systems, including relational SQL databases, document stores, tuple stores, Datomic, or other &quot;NoSQL&quot; type systems.

\n

At the data model level, Chimera should be a powerful, easy to use way to specify the structure of your data, as data. Modules can then read this data and expose new functionality driven by the application domain model. It needs to be flexible enough that it can be &quot;projected&quot; as schema into diverse types of adapters, and customizable enough that it can be configured to adapt to existing database installations.

\n

Adapters

\n

Chimera Adapters are Arachne modules which take the abstract data structures and operations defined by Chimera, and extend them to specific databases or database APIs such as JDBC, Datomic, MongoDB, etc.

\n

When applicable, there can also be &quot;abstract adapters&quot; that do the bulk of the work of adapting Chimera to some particular genre of database. For example, most key/value stores have similar semantics and core operations: there will likely be a &quot;Key/Value Adapter&quot; that does the bulk of the work for adapting Chimera's operations to key/value storage, and then several thin concrete adapters that implement the actual get/put commands for Cassandra, DynamoDB, Redis, etc.

\n

Limitations and Drawbacks

\n

Chimera is designed to make a limited set of common operations possible to write generically. It is not and cannot ever be a complete interface to every database. Application developers can and should understand and use the native APIs of their selected database, or use a dedicated wrapper module that exposes the full power of their selected technology. Chimera represents only a single dimension of functionality; the entity/attribute model. By definition, it cannot provide access to the unique and powerful features that different databases provide and which their users ought to leverage.

\n

It is also important to recognize that there are problems (even problems that modules might want to tackle) for which Chimera's basic entity/attribute model is simply not a good fit. If the entity model isn't a good fit, &lt;u&gt;do not use&lt;/u&gt; Chimera. Instead, find (or write) an Arachne module that defines a data modeling abstraction better suited for the task at hand.

\n

Examples of applications that might not be a good fit for Chimera include:

\n
    \n
  • Extremely sparse or &quot;wide&quot; data
  • \n
  • Dynamic data which cannot have pre-defined attributes or structure
  • \n
  • Unstructured heterogeneous data (such as large binary or sampling data)
  • \n
  • Data that cannot be indexed and requires distributed or streaming data processing to handle effectively
  • \n
\n

Modeling

\n

The data model for an Arachne application is, like everything else, data in the Configuration. Chimera defines a set of DSL forms that application authors can use to define data models programmatically, and of course modules can also read, write and modify these definitions as part of their normal configuration process.

\n

Note: The configuration schema, including the schema for the data model, is itself defined using Chimera. This requires some special bootstrapping in the core module. It also implies that Arachne core has a dependency on Chimera. This does not mean that modules are required to use Chimera or that Chimera has some special status relative to other conceivable data models; it just means that it is a good fit for modeling the kind of data that needs to be stored in the configuration.

\n

Modeling: Entity Types

\n

Entity types are entities that define the structure and content for a domain entity. Entity types specify a set of optional and required attributes that entities of that type must have.

\n

Entity types may have one or more supertypes. Semantically, supertypes imply that any entity which is an instance of the subtype is also an instance of the supertype. Therefore, the set of attributes that are valid or required for an entity are the attributes of its types and all ancestor types.

\n

Entity types define only data structures. They are not objects or classes; they do not define methods or behaviors.

\n

In addition to defining the structure of entities themselves, entity types can have additional config attributes that serve as implementation-specific hints. For example, an entity type could have an attribute to override the name of the SQL table used for persistence. This config attribute would be defined and used by the SQL module, not by Chimera itself.

\n

The basic attributes of the entity type, as defined by Chimera, are:

\n
    \n
  • The name of the type (as a namespace-qualified keyword)
  • \n
  • Any supertypes it may have
  • \n
  • What attributes can be applied to entities of this type
  • \n
\n

Attribute Definitions

\n

Attribute Definition entities define what types of values can be associated with an entity. They specify:

\n
    \n
  1. The name of the attribute (as a namespace-qualified keyword)
  2. \n
  3. The min and max cardinality of an attribute (thereby specifying whether it is required or optional)
  4. \n
  5. The type of allowed values (see the section on Value Types below)
  6. \n
  7. Whether the attribute is a key. The values of a key attribute are expected to be globally unique, guaranteed to be present, and serve as a way to find specific entities, no matter what the underlying storage mechanism.
  8. \n
  9. Whether the attribute is indexed. This is primarily a hint to the underlying database implementation.
  10. \n
\n

Like entity types, attribute definitions may have any number of additional attributes, to modify behavior in an implementation-specific way.

\n
Value Types
\n

The value of an attribute may be one of three types:

\n
    \n
  1. A reference is a value that is itself an entity. The attribute must specify the entity type of the target entity.

  2. \n
  3. A component is a reference, with the added semantic implication that the value entity is a logical &quot;part&quot; of the parent entity. It will be retrieved automatically, along with the parent, and will also be deleted/retracted along with the parent entity.

  4. \n
  5. A primitive is a simple, atomic value. Primitives may be one of several defined types, which map more or less directly to primitive types on the JVM:

    \n
      \n
    • Boolean (JVM java.lang.Boolean)
    • \n
    • String (JVM java.lang.String)
    • \n
    • Keyword (Clojure clojure.lang.Keyword)
    • \n
    • 64 bit integer (JVM java.lang.Long)
    • \n
    • 64 bit floating point decimal (JVM java.lang.Double)
    • \n
    • Arbitrary precision integer (JVM java.math.BigInteger)
    • \n
    • Arbitrary precision decimal (JVM java.math.BigDecimal)
    • \n
    • Instant (absolute time with millisecond resolution) (JVM java.util.Date)
    • \n
    • UUID (JVM java.util.UUID)
    • \n
    • Bytes (JVM byte array). Since not all storages support binary data, and might need to serialize it with base64, this should be fairly small.
    • \n
    \n

    This set of primitives represent a reasonable common denominator that is supportable on most target databases. Note that the set is not closed: modules can specify new primitive types that are logically &quot;subtypes&quot; of the generic primitives. Entirely new types can also be defined (with the caveat that they will only work with adapters for which an implementation has been defined.)

  6. \n
\n

Validation

\n

All attribute names are namespace-qualified keywords. If there are specs registered using those keywords, they can be used to validate the corresponding values.

\n

Clojure requires that a namespace be loaded before the specs defined in it are globally registered. To ensure that all relevant specs are loaded before an application runs, Chimera provides config attributes that specify namespaces containing specs. Arachne will ensure that these namespaces are loaded first, so module authors can ensure that their specs are loaded before they are needed.

\n

Chimera also provides a generate-spec operation which programmatically builds a spec for a given entity type, that can validate a full entity map of that type.

\n

Schema &amp; Migration Operations

\n

In order for data persistence to actually work, the schema of a particular database instance (at least, for those that have schema) needs to be compatible with the application's data model, as defined by Chimera's entity types and attributes.

\n

See ADR-16 for an in-depth discussion of database migrations work, and the ramifications for how a Chimera data model is declared in the configuration.

\n

Entity Manipulation

\n

The previous section discussed the data model, and how to define the general shape and structure of entities in an application. Entity manipulation refers to how the operations available to create, read, update, delete specific instances of those entities.

\n

Data Representation

\n

Domain entities are represented, in application code, as simple Clojure maps. In their function as Chimera entities, they are pure data; not objects. They are not required to support any additional protocols.

\n

Entity keys are restricted to being namespace-qualified keywords, which correspond with the attribute names defined in configuration (see Attribute Definitions above). Other keys will be ignored in Chimera's operations. Values may be any Clojure value, subject to spec validation before certain operations.

\n

Cardinality-many attributes must use a Clojure sequence, even if there is only one value.

\n

Reference values are represented in one of two ways; as a nested map, or as a lookup reference.

\n

Nested maps are straightforward. For example:

\n
{:myapp.person/id 123\n :myapp.person/name &quot;Bill&quot;\n :myapp.person/friends [{:myapp.person/id 42\n                          :myapp.person/name &quot;Joe&quot;}]}\n
\n

Lookup references are special values that identify an attribute (which must be a key) and value to indicate the target reference. Chimera provides a tagged literal specifially for lookup references.

\n
{:myapp.person/id 123\n :myapp.person/name &quot;Bill&quot;\n :myapp.person/friends [#chimera.key[:myapp.person/id 42]]}\n
\n

All Chimera operations that return data should use one of these representations.

\n

Both representations are largely equivalent, but there is an important note about passing nested maps to persistence operations: the intended semantics for any nested maps must be the same as the parent map. For example, you cannot call create and expect the top-level entity to be created while the nested entity is updated.

\n

Entities do not need to explicitly declare their entity type. Types may be derived from inspecting the set of keys and comparing it to the Entity Types defined in the configuration.

\n

Persistence Operations

\n

The following basic operations are defined:

\n
    \n
  • get - Given an attribute name and value, return a set of matching entity maps from the database. Results are not guaranteed to be found unless the attribute is indexed. Results may be truncated if there are more than can be efficiently returned.
  • \n
  • create - Given a full entity map, transactionally store it in the database. Adapters may throw an error if an entity with the same key attribute and value already exists.
  • \n
  • update - Given a map of attributes and values update each of the attributes provided attributes to have new values. The map must contain at least one key attribute. Also takes a set of attribute names which will be deleted/retracted from the entity. Adapters may throw an error if no entity exists for the given key.
  • \n
  • delete - Given a key attribute and a value, remove the entity and all its attributes and components.
  • \n
\n

All these operations should be transactional if possible. Adapters which cannot provide transactional behavior for these operations should note this fact clearly in their documentation, so their users do not make false assumptions about the integrity of their systems.

\n

Each of these operations has its own protocol which may be required by modules, or satisfied by adapters à la carte. Thus, a module that does not require the full set of operations can still work with an adapter, as long as it satisfies the operations that it does need.

\n

This set of operations is not exhaustive; other modules and adapters are free to extend Chimera and define additional operations, with different or stricter semantics. These operations are those that it is possible to implement consistently, in a reasonably performant way, against a &quot;broad enough&quot; set of very different types of databases.

\n

To make it possible for them to be composed more flexibly, operations are expressed as data, not as direct methods.

\n

Capability Model

\n

Adapters must specify a list of what operations they support. Modules should validate this list at runtime, to ensure the adapter works with the operations that they require.

\n

In addition to specifying whether an operation is supported or not, adapters must specify whether they support the operation idempotently and/or transactionally.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Users and modules can define the shape and structure of their domain data in a way that is independent of any particular database or type of database.
  • \n
  • Modules can perform basic data persistence tasks in a database-agnostic way.
  • \n
  • Modules will be restricted to a severely limited subset of data persistence functionality, relative to using any database natively.
  • \n
  • The common data persistence layer is optional, and can be easily bypassed when it is not a good fit.
  • \n
  • The set of data persistence operations is open for extension.
  • \n
  • Because spec-able namespaced keywords are used pervasively, it will be straightforward to leverage Spec heavily for validation, testing, and seed data generation.
  • \n
\n

Architecture Decision Record: Database Migrations

\n

Context

\n

In general, Arachne's philosophy embraces the concepts of immutability and reproducibility; rather than changing something, replace it with something new. Usually, this simplifies the mental model and reduces the number of variables, reducing the ways in which things can go wrong.

\n

But there is one area where this approach just can't work: administering changes to a production database. Databases must have a stable existence across time. You can't throw away all your data every time you want to make a change.

\n

And yet, some changes in the database do need to happen. Data models change. New fields are added. Entity relationships are refactored.

\n

The challenge is to provide a way to provide measured, safe, reproducible change across time which is also compatible with Arachne's target of defining and describing all relevant parts of an application (including it's data model (and therefore schema)) in a configuration.

\n

Compounding the challenge is the need to build a system that can define concrete schema for different types of databases, based on a common data model (such as Chimera's, as described in ADR-15.)

\n

Prior Art

\n

Several systems to do this already exist. The best known is probably Rails' Active Record Migrations, which is oriented around making schema changes to a relational database.

\n

Another solution of interest is Liquibase, a system which reifies database changes as data and explicitly applies them to a relation database.

\n

Scenarios

\n

There are a variety of &quot;user stories&quot; to accomodate. Some examples include:

\n
    \n
  1. You are a new developer on a project, and want to create a local database that will work with the current HEAD of the codebase, for local development.
  2. \n
  3. You are responsible for the production deployment of your project, and your team has a new software version ready to go, but it requires some new fields to be added to the database before the new code will run.
  4. \n
  5. You want to set up a staging environment that is an exact mirror of your current production system.
  6. \n
  7. You and a fellow developer are merging your branches for different features. You both made different changes to the data model, and you need to be sure they are compatible after the merge.
  8. \n
  9. You recognize that you made a mistake earlier in development, and stored a currency value as a floating point number. You need to create a new column in the database which uses a fixed-point type, and copy over all the existing values, using rounding logic that you've agreed on with domain experts.
  10. \n
\n

Decision

\n

Chimera will explicitly define the concept of a migration, and reify migrations as entities in the configuration.

\n

A migration represents an atomic set of changes to the schema of a database. For any given database instance, either a migration has logically been applied, or it hasn't. Migrations have unique IDs, expressed as namespace-qualified keywords.

\n

Every migration has one or more &quot;parent&quot; migrations (except for a single, special &quot;initial&quot; migration, which has no parent). A migration may not be applied to a database unless all of its parents have already been applied.

\n

Migrations are also have a signature. The signature is an MD5 checksum of the actual content of the migration as it is applied to the database (whether that be txdata for Datomic, a string for SQL DDL, a JSON string, etc.) This is used to ensure that a migration is not &quot;changed&quot; after it has already been applied to some persistent database.

\n

Adapters are responsible for exposing an implementation of migrations (and accompanying config DSL) that is appropriate for the database type.

\n

Chimera Adapters must additionally satisfy two runtime operations:

\n
    \n
  • has-migration? - takes ID and signature of a particular migration, and returns true if the migration has been successfully applied to the database. This implies that databases must be &quot;migration aware&quot; and store the IDs/signatures of migrations that have already been applied.
  • \n
  • migrate - given a specific migration, run the migration and record that the migration has been applied.
  • \n
\n

Migration Types

\n

There are four basic types of migrations.

\n
    \n
  1. Native migrations. These are instances of the migration type directly implemented by a database adapter, and are specific to the type of DB being used. For example, a native migration against a SQL database would be implemented (primarily) via a SQL string. A native migration can only be used by adapters of the appropriate type.
  2. \n
  3. Chimera migrations. These define migrations using Chimera's entity/attribute data model. They are abstract, and should work against multiple different types of adapters. Chimera migrations should be supported by all Chimera adapters.
  4. \n
  5. Sentinel migrations. These are used to coordinate manual changes to an existing database with the code that requires them. They will always fail to automatically apply to an existing database: the database admin must add the migration record explicitly after they perform the manual migration task. (Note, actually implementing these can be deferred until if or when they are needed).
  6. \n
\n

Structure &amp; Usage

\n

Because migrations may have one or more parents, migrations form a directed acyclic graph.

\n

This is appropriate, and combines well with Arachne's composability model. A module may define a sequence of migrations that build up a data model, and extending modules can branch from any point to build their own data model that shares structure with it. Modules may also depend upon a chain of migrations specified in two dependent modules, to indicate that it requires both of them.

\n

In the configuration, a Chimera database component may depend on any number of migration components. These migrations, and all their ancestors, form a &quot;database definition&quot;, and represent the complete schema of a concrete database instance (as far as Chimera is concerned.)

\n

When a database component is started and connects to the underlying data store, it verifies that all the specifies migrations have been applied. If they have not, it fails to start. This guarantees the safety of an Arachne system; a given application simply will not start if it is not compatible with the specified database.

\n
Parallel Migrations
\n

This does create an opportunity for problems: if two migrations which have no dependency relatinship (&quot;parallel migrations&quot;) have operations that are incompatible, or would yield different results depending on the order in which they are applied, then these operations &quot;conflict&quot; and applying them to a database could result in errors or non-deterministic behavior.

\n

If the parallel migrations are both Chimera migrations, then Arachne is aware of their internal structure and can detect the conflict and refuse to start or run the migrations, before it actually touches the database.

\n

Unfortunately, Arachne cannot detect conflicting parallel migrations for other migration types. It is the responsibility of application developers to ensure that parallel migrations are logically isolate and can coexist in the same database without conflict.

\n

Therefore, it is advisable in general for public modules to only use Chimera migrations. In addition to making them as broadly compatible as possible, and will also make it more tractable for application authors to avoid conflicting parallel migrations, since they only have to worry about those that they themselves create.

\n

Chimera Migrations &amp; Entity Types

\n

One drawback of using Chimera migrations is that you cannot see a full entity type defined in one place, just from reading a config DSL script. This cannot be avoided: in a real, living application, entities are defined over time, in many different migrations as the application grows, not all at once. Each Chimera migration contains only a fragment of the full data model.

\n

However, this poses a usability problem; both for developers, and for machine consumption. There are many reasons for developers or modules to view or query the entity type model as a &quot;point in time&quot; snapshot, rather than just a series of incremental changes.

\n

To support this use case, the Chimera module creates a flat entity type model for each database by &quot;rolling up&quot; the individual Chimera entity definition forms into a single, full data structure graph. This &quot;canonical entity model&quot; can then be used to render schema diagrams for users, or be queried by other modules.

\n

Applying Migrations

\n

When and how to invoke an Adapter's migrate function is not defined, since different teams will wish to do it in different ways.

\n

Some possibilities include:

\n
    \n
  1. The application calls &quot;migrate&quot; every time it is started (this is only advisable if the database has excellent support for transactional and atomic migrations.) In this scenario, developers only need to worry about deploying the code.
  2. \n
  3. The devops team can manually invoke the &quot;migrate&quot; function for each new configuration, prior to deployment.
  4. \n
  5. In a continuous-deployment setup, a CI server could run a battery of tests against a clone of the production database and invoke &quot;migrate&quot; automatically if they pass.
  6. \n
  7. The development team can inspect the set of migrations and generate a set of native SQL or txdata statements for handoff to a dedicated DBA team for review and commit prior to deployment.
  8. \n
\n

Databases without migrations

\n

Not every application wants to use Chimera's migration system. Some situations where migrations may not be a good fit include:

\n
    \n
  • You prefer to manage your own database schema.
  • \n
  • You are working with an existing database that predates Arachne.
  • \n
  • You need to work with a database administered by a separate team.
  • \n
\n

However, you still may wish to utilize Chimera's entity model, and leverage modules that define Chimera migrations.

\n

To support this, Chimera allows you to (in the configuration) designate a database component as &quot;assert-only&quot;. Assert-only databases never have migrations applied, and they do not require the database to track any concept of migrations. Instead, they inspect the Chimera entity model (after rolling up all declared migrations) and assert that the database already has compatible schema installed. If it does, everything starts up as normal; if it does not, the component fails to start.

\n

Of course, the schema that Chimera expects most likely will not be an exact match for what is present in the database. To accomodate this, Chimera adapters defines a set of override configuration entities (and accompanying DSL). Users can apply these overrides to change the behavior of the mappings that Chimera uses to query and store data.

\n

Note that Chimera Overrides are incompatible with actually running migrations: they can be used only on an &quot;assert-only&quot; database.

\n

Migration Rollback

\n

Generalized rollback of migrations is intractable, given the variety of databases Chimera intends to support. Use one of the following strategies instead:

\n
    \n
  • For development and testing, be constantly creating and throwing away new databases.
  • \n
  • Back up your database before running a migration
  • \n
  • If you can't afford the downtime or data loss associated with restoring a backup, manually revert the changes from the unwanted migration.
  • \n
\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Users can define a data model in their configuration
  • \n
  • The data model can be automatically reflected in the database
  • \n
  • Data model changes are explicitly modeled across time
  • \n
  • All migrations, entity types and schema elements are represented in an Arachne app's configuration
  • \n
  • Given the same configuration, a database built using migrations can be reliably reproduced.
  • \n
  • A configuration using migrations will contain an entire, perfectly reproducible history of the database.
  • \n
  • Migrations are optional, and Chimera's data model can be used against existing databases
  • \n
\n

Architecture Decision Record: Simplification of Chimera Model

\n

Note: this ADR supersedes some aspects of ADR-15 and ADR-16.

\n

Context

\n

The Chimera data model (as described in ADR-15 and ADR-16) includes the concepts of entity types in the domain data model: a defined entity type may have supertypes, and inherits all the attributes of a given supertype

\n

This is quite expressive, and is a good fit for certain types of data stores (such as Datomic, graph databases, and some object stores.) It makes it possible to compose types, and re-use attributes effectively.

\n

However, it leads to a number of conceptual problems, as well as implementation complexities. These issues include but are not limited to:

\n
    \n
  • There is a desire for some types to be &quot;abstract&quot;, in that they exist purely to be extended and are not intented to be reified in the target database (e.g, as a table.) In the current model it is ambiguous whether this is the case or not.
  • \n
  • A singe extend-type migration operation may need to create multiple columns in multiple tables, which some databases do not support transactionally.
  • \n
  • When doing a lookup by attribute that exists in multiple types, it is ambiguous which type is intended.
  • \n
  • In a SQL database, how to best model an extended type becomes ambiguous: copying the column leads to &quot;denormalization&quot;, which might not be desired. On the other hand, creating a separate table for the shared columns leads to more complex queries with more joins.
  • \n
\n

All of these issues can be resolved or worked around. But they add a variable amount of complexity cost to every Chimera adapter, and create a domain with large amounts of ambigous behavior that must be resolved (and which might not be discovered until writing a particular adapter.)

\n

Decision

\n

The concept of type extension and attribute inheritance does not provide benefits proportional to the cost.

\n

We will remove all concept of supertypes, subtypes and attribute inheritance from Chimera's data model.

\n

Chimera's data model will remain &quot;flat&quot;. In order to achieve attribute reuse for data stores for which that is idiomatic (such as Datomic), multiple Chimera attributes can be mapped to a single DB-level attribute in the adapter mapping metadata.

\n

Status

\n

PROPOSED

\n

Consequences

\n
    \n
  • Adapters will be significantly easier to implement.
  • \n
  • An attribute will need to be repeated if it is present on different domain entity types, even if it is semantically similar.
  • \n
  • Users may need to explicitly map multiple Chimera attributes back to the same underlying DB attr/column if they want to maintain an idiomatic data model for their database.
  • \n
\n\n
\n
\n\n\n\n\n<|start_filename|>examples/export-2.html<|end_filename|>\n\n\n\n \n \n \n ADR Documents\n\n \n\n\n
\n
\n ADR\n \n
\n
\n
\n
\n \n\n
\n
\n

1. Record architecture decisions

\n

Date: 30/03/2017

\n

Status

\n

Accepted

\n

Context

\n

We need to record the architectural decisions made on this project.

\n

Decision

\n

We will use Architecture Decision Records, as described by in this article: http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions

\n

Architecture Decisions, what are they ?: http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html

\n

Architecture Decisions: Demystifying Architecture: https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf

\n

We will use adr-tools, as this file generated by https://github.com/npryce/adr-tools

\n

Consequences

\n

See 's article, linked above.

\n

2. 团队中的密码管理

\n

Date: 30/03/2017

\n

Status

\n

Accepted

\n

Context

\n

\"\"

\n

视频链接:http://v.youku.com/v_show/id_XMjk5ODQ3NzA3Mg==.html

\n

我们工作中使用的密码有 100 + 左右,其中包括\n服务器,数据库,测试账号,第三方服务(阿里云,Dnspod,邮箱,等)

\n

我们所有的密码都是分散的管理着,每个人都自行对这 20 到 100 个密码进行管理,并且方式各种各样。

\n

当前存在以下问题:

\n
    \n
  1. 使用容易记但很不安全的密码,例如,123456
  2. \n
  3. 在每一个服务上使用相同的非安全密码;
  4. \n
  5. 当团队成员有变动时,密码没有改变;
  6. \n
  7. 无加密的将密码存在本地文件或是云笔记中;
  8. \n
  9. 通过邮箱或是微信进行密码分享。
  10. \n
\n

我们需要一个工具管理我们的密码,包括如下功能:

\n
    \n
  1. 生成复杂密码;
  2. \n
  3. 密码被加密后保存;
  4. \n
  5. 分发方式安全;
  6. \n
  7. 使用起来简单方便;
  8. \n
  9. 支持团队分组管理。
  10. \n
\n

Refs:

\n

How to Manage Passwords in a Team: https://medium.com/altcademy/how-to-manage-passwords-in-a-team-3ed010bc3ccf

\n

Decision

\n

LastPass(功能繁杂,使用人数最多,费用 1450 USD / 50 users)\nPassPack(功能简单,小众,不支持附件,费用 144 USD / 80 users)\n1Password(功能简单,使用方式友好,费用 7200 USD / 50 users)

\n

Consequences

\n
    \n
  1. 需要考虑兼容性,Win/Mac/Linux;
  2. \n
  3. 费用需要考虑;
  4. \n
  5. 需要可存储附件(比如,ssh 公私钥)。
  6. \n
\n

3. 使用 ssh key 替换用户名密码方式登录

\n

Date: 30/03/2017

\n

Status

\n

Accepted

\n

Context

\n

当前我们使用的是用户名、密码方式进行服务器登录,存在以下问题

\n
    \n
  1. 安全性问题,密码面临被破解的风险;
  2. \n
  3. 易用性问题,无法使用 config 记录密码,可以使用第三方软件解决,如,SecureCRT,ZOC7;
  4. \n
  5. 无法充分使用 local terminal,如 iTerm2;
  6. \n
\n

Refs:

\n\n

Decision

\n

禁用用户名、密码登录,使用 ssh key 进行登录

\n

\"\"

\n

Consequences

\n
    \n
  1. 团队成员使用新方式需要适应;
  2. \n
  3. key 的管理需要统一(需要引入堡垒机)。
  4. \n
\n

4. Ubuntu vs CentOS

\n

Date: 30/03/2017

\n

Status

\n

Accepted

\n

Context

\n

我们的服务器用的都是阿里云的 ECS,历史原因多数操作系统是 centos(6.5),内部得到的信息是稳定,当然目前阿里云已不提供此版本镜像。

\n

从个人使用经历看,自 10 年那会起,我所经历的公司选用的都是 ubuntu,当然我们应该知其所以然,而不是盲目的接受。

\n
    \n
  1. centos 系统初始化,软件安装基本都走的是手动编译,效率低,但这点往往被大家作为稳定性的佐证;
  2. \n
  3. centos 系统之上的所有软件都过于老旧,想装第三方软件的最新稳定版,很困难(难道一定要手动编译才好);
  4. \n
  5. 从开始使用 ubuntu,就看重他的简单易用,当然当时业界的看法是,不专业,不稳定;
  6. \n
  7. ubuntu 的社区比 centos 更活跃,网上的资料也比 centos 多;
  8. \n
  9. ubuntu 相关的问题很容易在网上找到解决方案,但 centos 不是。
  10. \n
\n

这些都是自己的使用体验

\n

从主机市场分析数据(https://www.digitalocean.com/community/questions/whats-is-better-and-why-linux-centos-or-ubuntu?answer=30514)看,Simple Hosting, VPS, Dedicated &amp; Clouds 这三个领域,centos 占有率均低于 ubuntu。尤其在云市场,centos 只有 ubuntu 的 1/20(http://thecloudmarket.com/stats#/by_platform_definition)。

\n

\"\"

\n

更多的对比信息请查看:

\n\n

Decision

\n

逐步将系统从 centos 切换至 ubuntu,保证系统的一致,为后期的运维自动化做准备。

\n

Consequences

\n
    \n
  • 手动的编译软件改为 apt-get 安装;
  • \n
  • 如果没有对旧系统,旧软件的某些特性有依赖,最好升级为各个软件的最新稳定版,这对性能和安全都大有好处。
  • \n
\n

5. 使用 Slack 替代微信、邮件和短信

\n

Date: 31/03/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 当前使用微信、邮件作为工作中的沟通工具,工作与生活混合;
  2. \n
  3. 各种告警信息需分别查看邮件、短信或是监控平台;
  4. \n
  5. 随着任务管理平台、Bug 管理平台、wiki、文档分享网站、聊天工具的流行,邮件的使用场景越来越小,并且邮件信息并不及时;
  6. \n
  7. 通过微信进行沟通,新人无法了解历史信息,经常需要把发过的内容重复发送。
  8. \n
\n

Decision

\n

Slack 支持的功能

\n
    \n
  1. 公开与私有的频道,频道可随时加入或退出;\n
      \n
    1. 按项目,project-crm, project-sms, 等;
    2. \n
    3. 按技术话题,tech-restful-api, tech-queue 等;
    4. \n
    5. 可以邀请相关人,任何人也可随意加入。
    6. \n
  2. \n
  3. 消息支持表情快速回复;\n
      \n
    1. 表情是附加在消息上的,上下文内聚很高。
    2. \n
  4. \n
  5. 消息支持收藏;\n
      \n
    1. 一些不错的重要信息,可以收藏起来随时查看。
    2. \n
  6. \n
  7. 支持各种文件的分享;\n
      \n
    1. pdf 等文件均可预览。
    2. \n
  8. \n
  9. 分享的链接支持预览;\n
      \n
    1. 分享的链接,不用点开也知道大体内容。
    2. \n
  10. \n
  11. 搜索功能强大,可通过快捷方式,搜索同事,消息记录,文件等;
  12. \n
  13. 多种程序代码支持高亮;\n
      \n
    1. 代码高亮预览,自动折叠,不影响整体效果。
    2. \n
  14. \n
  15. 强大的第三方集成,将所有消息、通知汇聚在一处,例如,Trello,Github,NewRelic, Sentry,Jenkins 等;
  16. \n
  17. 新加入者可查看群组历史信息。\n
      \n
    1. 信息再也不用重复发了。
    2. \n
  18. \n
  19. 开放性非常好\n
      \n
    1. 任何人都可以方便申请开发者 KEY,建立自己的机器人。
    2. \n
  20. \n
\n

研发部频道设计

\n
    \n
  1. CI/CD - 用于接收测试、部署结果,测试覆盖率,PR 等信息,也用于发起测试、部署等;
  2. \n
  3. NewRelic - 用于接收应用性能报警等信息;
  4. \n
  5. Sentry - 线上实时错误信息,可根据项目单独拆出来;
  6. \n
  7. Team-X - 用于组内沟通,一个 Scrum 组,包括研发,产品及测试;
  8. \n
  9. Knowledge - 用于所有研发人员进行沟通与分享;
  10. \n
  11. Product - 用于跨 Team 的产品进行沟通与分享;
  12. \n
  13. Backend - 用于所有后端人员进行问题咨询及分享;
  14. \n
  15. Leads(私密) - 用于所有 leader 进行沟通、安排周会等;
  16. \n
  17. Frontend, UI, Mobile, Devops, QA etc
  18. \n
\n

我们用了如下第三方软件

\n
    \n
  • Sentry
  • \n
  • NewRelic
  • \n
  • RedMine
  • \n
  • Teambition
  • \n
  • Confluence
  • \n
  • Github
  • \n
  • Bugly
  • \n
  • FIR.im
  • \n
  • Jenkins
  • \n
  • etc
  • \n
\n

Slack vs BearyChat

\n
    \n
  • Slack 优缺点:\n
      \n
    • 鼻祖
    • \n
    • 几乎所有常用软件(国外)都有集成
    • \n
    • 功能完善健壮,公司可信
    • \n
    • 网络不稳定
    • \n
    • 国内应用集成很少
    • \n
  • \n
  • BearChat 优缺点:\n
      \n
    • 基本有 Slack 的核心功能
    • \n
    • 数据的隐私无法保证
    • \n
    • 服务的可用性无法保证
    • \n
    • 第三方集成太少(must-read, Simple Poll, etc 都没有),倒是集成了国内的 Teambiton, 监控宝等
    • \n
  • \n
\n

最终,我们给国产软件(服务)一个机会。

\n

经过两周的 BearyChat 试用,目前已准备转用 Slack - 2017-08-03

\n
    \n
  1. BearyChat 的 Teambition 集成失败,沟通后说是 TB 的接口调整;
  2. \n
  3. 集成数的限制,都是 10 个,但同一个第三方多次集成,Slack 算一个,BearyChat 算多个,比如 Github, Sentry;
  4. \n
  5. 经过对各个国内公司的了解,发现使用中 Slack 的国内稳定性还好。
  6. \n
\n

Consequences

\n
    \n
  • 大家已习惯使用 Wechat,引入一个新的沟通平台有学习成本。
  • \n
\n

6. 使用 Git 替换 SVN

\n

Date: 06/04/2017

\n

Status

\n

Accepted

\n

Context

\n

当前我们用的是 SVN 做代码、产品文档、UI 设计图的管理\n我们在此只说其中的代码管理

\n
    \n
  1. 代码仓库过大,新分支,新Tag 代码都是一份完整的拷贝;
  2. \n
  3. 必须联网提交;
  4. \n
  5. SVN 代码合并方式低效,目前使用 Beyond Compare 做代码合并,分支使用方式落后;
  6. \n
  7. 无法很好的做 code review(只能 patch 或第三方工具);
  8. \n
  9. 面试者看到是这么落后,以此类别其他技术栈,综合理解就是,我能学到啥。
  10. \n
\n

Decision

\n

使用全球最流行的分布式管理工具 Git 及平台 Github\n分布式,目录结构简单,代码无冗余,可 review with PR。

\n

Refs:

\n

https://help.github.com/articles/what-are-the-differences-between-subversion-and-git/\nhttp://stackoverflow.com/questions/871/why-is-git-better-than-subversion

\n

Consequences

\n

方式一:

\n

git svn clone svn project url -T trunk\n将 SVN 项目的 trunk 转为 git 项目的 master,仅保留了 trunk 分支的提交记录,此方式适用于所有代码都规整到了一个分支,并且不需要其他分支的提交记录。

\n

方式二:

\n

使用命令 https://github.com/nirvdrum/svn2git ,它可以保留所有branch, tags,以及所有分支的提交历史。\nsvn2git http://svn.example.com/path/to/repo --trunk trunk --tags tag --branches branch\ngit push --all origin\ngit push --tags

\n

use --revision number to reduce the commit history.

\n

目前生产环境使用的 centos 版本过低,导致 git 也无法升级的处理方法:\nyum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm\nyum update git

\n

Refs:\nhttps://www.atlassian.com/git/tutorials/migrating-overview\nhttps://www.atlassian.com/git/tutorials/svn-to-git-prepping-your-team-migration\nhttps://www.git-tower.com/learn/git/ebook/cn/command-line/appendix/from-subversion-to-git\nhttps://tecadmin.net/how-to-upgrade-git-version-1-7-10-on-centos-6/

\n

7. 使用 PassPack 进行密码管理

\n

Date: 07/04/2017

\n

Status

\n

Accepted

\n

Context

\n

step zero:\n管理员以 company-name 注册付费管理员账号

\n

step one:\n公司成员在 https://www.passpack.com/ 使用公司邮箱注册免费账号,用户名统一:company-name-username

\n

step two:\n点击 People tab 激活自己的账号,使用相同的用户名

\n

step three:\n邀请管理员账号

\n

step four:\n创建或导入自己管理的所有用户名密码,批量 transfer 给 company-name(个人密码也可以用它管理,就无需 transfer 给管理员了)

\n

PassPack 使用介绍:https://www.passpack.com/getting-started/PasspackGettingStarted_Admin_EN.pdf

\n

Decision

\n

鉴于管理员一人处理非常琐碎,下放权限至 group owner 可编辑相应密码

\n

用户名命名规范:公司名简称-姓名\nName 命名规范:简单描述所用的服务,用于搜索,层级间使用冒号:隔开,例如,aliyun:oss:contract-doc:ak

\n

Consequences

\n
    \n
  1. 推动各个 team leader 使用并管理;
  2. \n
  3. 向 team member 分发密码走这个渠道;
  4. \n
  5. 列入新人入职注册项。
  6. \n
\n

8. 使用堡垒机加强服务器安全

\n

Date: 08/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 旧文写了为了禁止外网暴力破解,我们将用户名、密码登录方式改为了 ssh key 登录;
  2. \n
  3. 为了管理方便,当时只区分了生产 key 和测试 key,内部大家共用 key, 并且有 sudo 权限,导致存在内部风险,而针对每个人手动生成 ssh key 又会有管理上的问题;
  4. \n
  5. 每个人需要对所有机器配置 ssh config,使用不方便;
  6. \n
  7. 当前成员行为无法区分,有成员在系统上执行了 vim 大文件操作导致系统负载急剧升高,也有成员将系统配置改动导致其他项目运行出现问题,当然也存在数据安全上的问题。
  8. \n
\n

未使用堡垒机时:

\n

\"\"

\n

Decision

\n

目标:简化并统一管理线上服务器的登录并审计操作日志

\n

结构图:

\n

\"\"

\n

Refs:

\n\n

经过多个堡垒机项目的调研,我们最终选择了 https://github.com/jumpserver/jumpserver,源于使用人数多,并且项目活跃度高。

\n

Jumpserver v0.4.0 新版本预览 https://github.com/jumpserver/jumpserver/issues/350

\n

Consequences

\n
    \n
  • 0.3 版本的一些弊端导致我们激进的选择了 0.4 版本,此版本处于开发中,存在很多未知问题,并且我们已在之上做二次开发
  • \n
  • 文件下载不方便
  • \n
  • 内网之间文件同步不方便
  • \n
\n

9. 结构化 Django 项目

\n

Date: 10/04/2017

\n

Status

\n

Accepted

\n

Context

\n

We have 20+ projects which based on Django, but we don’t have the same structure which make our project hard to read.

\n

We need handle those things:

\n
    \n
  1. store all apps in one place;
  2. \n
  3. support different environments;
  4. \n
  5. store project related configs.
  6. \n
\n

Decision

\n

make a skeleton for django: https://github.com/huifenqi/django-project-skeleton

\n

Consequences

\n
    \n
  1. make all new projects with this skeleton;
  2. \n
  3. apply this structure to the old projects when refactoring.
  4. \n
\n

10. Git 基础及风格指南

\n

Date: 11/04/2017

\n

Status

\n

Accepted

\n

Context

\n

We use git and GitHub in different ways, it’s emergency to teach team members with the git basics and style guide we will use.

\n

Decision

\n

git basics

\n
    \n
  1. setup ssh keys (https://github.com/settings/keys) or GUI;
  2. \n
  3. clone repo into local system: git clone :huifenqi/django-project-skeleton.git;
  4. \n
  5. files store in three stages:\n\"\"\n
      \n
    1. Working Directory: holds the actual files;
    2. \n
    3. Index: staging area which store your changed files;
    4. \n
    5. HEAD: points to the last commit you've made.
    6. \n
  6. \n
  7. Working Directory -&gt; Index: git add &lt;filename&gt; or git add *;
  8. \n
  9. Index -&gt; HEAD: git commit -m &quot;Commit message&quot;;
  10. \n
  11. push updates to Github: git push origin master;
  12. \n
  13. create branch: git checkout -b feature/x\n\"\"
  14. \n
  15. push branch to Github and others can see: git push origin &lt;branch_name&gt;;
  16. \n
  17. sync local with Github: git pull;
  18. \n
  19. make a new tag: git tag &lt;tag_name&gt;;
  20. \n
  21. show history: git log;
  22. \n
  23. show changes: git diff &lt;previous_commit_hash&gt;;
  24. \n
  25. others: git status, git branch, git tag, etc.
  26. \n
\n

git style guide

\n

Branches

\n\n

Commits

\n
    \n
  • Each commit should be a single logical change. Don't make several logical changes in one commit;
  • \n
\n

Messages

\n
    \n
  • when writing a commit message, think about what you would need to know if you run across the commit in a year from now.
  • \n
\n

Refs

\n\n

Consequences

\n

Make sure everyone follow the guide, check the Github feeds often.

\n

11. Apply Github workflow to our team

\n

Date: 11/04/2017

\n

Status

\n

Accepted

\n

Context

\n

Context here...

\n

Decision

\n

Github workflow

\n

There are various workflows and each one has its strengths and weaknesses. Whether a workflow fits your case, depends on the team, the project and your development procedures.

\n

TBD

\n

Consequences

\n

TBD

\n

12. Think about micro service

\n

Date: 13/04/2017

\n

Status

\n

Proposed

\n

Context

\n
    \n
  1. 已拆分为各种服务(1. 接口不统一、无监控、无统一日志管理);
  2. \n
  3. API 文档管理不够;
  4. \n
  5. 服务的部署纯手动;
  6. \n
\n

Decision

\n

Decision here...

\n

Consequences

\n
    \n
  1. 跨语言;
  2. \n
  3. 提供 server 和 client 端;
  4. \n
  5. 统一上线过程:独立部署、运行、升级;
  6. \n
  7. 统一日志记录与审计:第三方日志服务;
  8. \n
  9. 统一风格:REST API or RPC;
  10. \n
  11. 统一认证和鉴权:权限管理、安全策略;
  12. \n
  13. 统一服务测试:调度方式、访问入口;
  14. \n
  15. 资源管理(虚拟机、物理机、网络);
  16. \n
  17. 负载均衡:客户端 or 服务端;
  18. \n
  19. 注册发现:中心话注册 or hardcode;
  20. \n
  21. 监控告警;
  22. \n
\n

Refs

\n

Why

\n\n

How

\n\n

服务注册

\n\n

REST API vs RPC

\n\n

13. The sense of Done

\n

Date: 14/04/2017

\n

Status

\n

Proposed

\n

Context

\n

We face this situation very often?

\n
    \n
  1. I’m already fixed this, it’s in testing;
  2. \n
  3. I’m already add this monitoring plugin in the repo, it’s deployed on staging, let’s watch for a few days, then deploy on production;
  4. \n
  5. I’m already move this service to new machine, I will clean the old machine later.
  6. \n
\n

Sounds familiar? Yes, very often.

\n

Is that all done? No, it doesn’t.

\n

Decision

\n
    \n
  1. talk this all the time, let team member have this sense;
  2. \n
  3. make specifications for each domain.
  4. \n
\n

Consequences

\n

Create specifications from our experience.

\n

An Done-Done example with User Story:

\n
    \n
  1. stories and AC reviewed (DEV);
  2. \n
  3. All AC implemented (DEV);
  4. \n
  5. Code reviewed (Dev);
  6. \n
  7. Tests passed (Dev+QA+CI);
  8. \n
  9. No bugs left (QA);
  10. \n
  11. Deployed to production (Dev);
  12. \n
  13. Accepted (PM).
  14. \n
\n

Refs:

\n\n

14. How to restart a server

\n

Date: 19/04/2017

\n

Status

\n

Accepted

\n

Context

\n

Context here...

\n

Decision

\n

Decision here...

\n

Consequences

\n

Consequences here...

\n

15. Case: How to find the root reason of high load

\n

Date: 20/04/2017

\n

Status

\n

Accepted

\n

Context

\n

Context here...

\n

Decision

\n

Decision here...

\n

Consequences

\n

Consequences here...

\n

16. 故障记录报告

\n

Date: 20/04/2017

\n

Status

\n

Accepted

\n

Context

\n

事故频发,处理速度慢,流程不清晰,并且一直未做记录,导致同样的问题会再次复现。

\n

Decision

\n

定义故障报告模板:

\n
    \n
  1. 对故障进行描述,以便查询并对我们的系统稳定性做评估;
  2. \n
  3. 对故障做分析,便于未来可快速处理同样问题;
  4. \n
  5. 加监控,以便问题出现前就做处理;
  6. \n
  7. 解决并升级方案,完全避免此类问题。
  8. \n
\n

Consequences

\n

故障报告模板

\n

问题描述

\n
    \n
  • 简单的故障描述(三句话即可)
  • \n
  • 故障出现及恢复时间
  • \n
  • 影响范围
  • \n
  • 根本原因
  • \n
\n

时间线

\n
    \n
  • 故障通知时间
  • \n
  • 各种为了恢复服务的操作时间(注意顺序)
  • \n
\n

原因分析

\n
    \n
  • 详细的故障描述
  • \n
  • 客观,不要添加粉饰性的内容
  • \n
\n

做错的事情

\n

做对的事情

\n

将来如何避免此类事情再次发生

\n
    \n
  • 监控
  • \n
  • 规范
  • \n
  • 预估
  • \n
\n

Refs:\nOutage Post-Mortem – June 14 https://www.pagerduty.com/blog/outage-post-mortem-june-14/\nHow to write an Incident Report / Postmortem https://sysadmincasts.com/episodes/20-how-to-write-an-incident-report-postmortem

\n

17. Incident classify and recovery

\n

Date: 20/04/2017

\n

Status

\n

Proposed

\n

Context

\n

对服务的可用等级不清晰,处理问题的优先级不足,临时分析现象及寻找解决方案,耗时过长

\n

Decision

\n

划分服务等级,做好预案

\n

Consequences

\n

故障分类和预案

\n

自然灾害

\n
    \n
  1. 灾备,常见的有,两地三中心;
  2. \n
\n

服务运营商

\n

DNS 解析问题

\n
    \n
  1. 联系 DNS 提供商,确定故障恢复的时间;
  2. \n
  3. 所需恢复时间大于 TTL,实施切换 DNS 运营商的预案(DnsPod to Aliyun etc)。
  4. \n
\n

Aliyun 内部问题

\n

CDN 运营商

\n

外部人为

\n

人为攻击

\n
    \n
  • DDOS
  • \n
  • CC
  • \n
  • SQL 注入
  • \n
  • XSS
  • \n
\n

正常请求

\n
    \n
  • 流量
  • \n
\n

架构内部

\n

数据库级故障

\n

内部网络级别

\n
    \n
  • Aliyun 内部
  • \n
  • 网络、防火配置
  • \n
\n

系统级别故障

\n
    \n
  • 单系统内部
  • \n
  • 系统间通信
  • \n
\n

系统服务级别故障

\n

应用服务级别故障

\n

应用虚拟环境级别故障

\n

应用代码级别故障

\n

18. iOS 持续发布

\n

Date: 20/04/2017

\n

Status

\n

Accepted

\n

Context

\n

目前使用测试同学的工作电脑做 iOS 的打包与分发,对测试同学有一定的影响。

\n

Decision

\n

\"\"

\n

基本流程不变,将打包工作交由第三方服务 buddybuild 处理并分发。\nbuddybuild 本可以直接分发,但由于其分发网络在国内比较慢,所以继续使用 fir.im 进行分发

\n

Consequences

\n

免费版单次打包过程限制在 20 分钟内,无限次打包但会优先打包付费用的的应用,未来长期的高频次使用需要购买付费版。

\n

Refs:

\n

Custom Build Steps: http://docs.buddybuild.com/docs/custom-prebuild-and-postbuild-steps

\n

19. 服务器申请与升级 - 容量评估

\n

Date: 21/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 部分机器的 CPU,内存,硬盘,使用率均在 90% 左右,另一些机器各项指标使用率在 1% 左右;
  2. \n
  3. 部分机器的 CPU,内存,硬盘搭配不合理,CPU 使用率 1%,但内存使用率在 90% 左右;
  4. \n
  5. 一些对磁盘读写要求高的服务,使用的是普通云盘,比如,数据库,SVN等;
  6. \n
  7. 申请机器时,无法提出配置要求,基本靠拍脑门决定;
  8. \n
  9. 对服务的发展没有思考,配置要了 12 个月后才能使用到的配置。
  10. \n
\n

Decision

\n
    \n
  1. 压力测试;
  2. \n
  3. 分析业务各个指标的使用情况,CPU 密集型,内存密集型还是有其他的特点;
  4. \n
  5. 鉴于 Aliyun ECS 随时可以扩展,可以先用低配机器,根据使用情况,进行单指标垂直升级;
  6. \n
  7. 水平扩展,即提升了服务的处理能力又做了高可用;
  8. \n
  9. 对于不合理的内存使用,要分析自己程序中是否有内存泄漏或大数据加载。
  10. \n
\n

Consequences

\n

Refs:

\n\n

20. 日志管理

\n

Date: 24/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 记录位置混乱,有系统默认路径,有自定义路径;
  2. \n
  3. 日志未切割,日志一直记录在一个文件中,导致文件巨大;
  4. \n
  5. 记录方式有问题,一个请求量不大的服务,每日存在 1G 的日志数据,发现存在将整个 html 写入日志的问题;
  6. \n
  7. 日志记录格式不统一,涉及日志规范有 nginx, python 和 java;
  8. \n
  9. 不容易访问,需要给开发者提供对应机器的登录与日志查看权限;
  10. \n
  11. 使用 grep 等查询方式,上下文使用不方便,查询效率低;
  12. \n
  13. 临时的统计需要写一次性的脚本;
  14. \n
  15. 无法对异常日志做监控与报警;
  16. \n
  17. 归档日志太多,需要定时清理。
  18. \n
\n

附加需求:

\n
    \n
  1. 日志根据项目区分查看权限;
  2. \n
  3. 可报警;
  4. \n
  5. 可产生图表。
  6. \n
\n

Decision

\n
    \n
  1. 日志记录统一至 /data/logs 目录下,针对每个服务创建日志目录(包括系统服务),如 nginx;
  2. \n
  3. 所有需要文件切割的地方,我们使用系统的 /etc/logrotate.d, copy /etc/logrotate.d/nginx 的设置进行改动即可。(系统的默认切割时间各个系统不一致,所以我们删除 /etc/cron.daily/logrotate,改为在 /etc/crontab 加入 59 23 * * * root /usr/sbin/logrotate /etc/logrotate.conf(使用日志服务后无需此步));
  4. \n
  5. 针对大日志文件进行调研,查看日志内容的必要性;
  6. \n
  7. 规范化日志记录格式及内容,格式可以参考 Aliyun 采集方式及常见配置示例 https://help.aliyun.com/document_detail/28981.html
  8. \n
  9. 使用日志管理服务可用解决如上 5 - 9 的问题。
  10. \n
\n

可选的日志服务:

\n
    \n
  1. Aliyun 日志服务 (功能强大(复杂),价格计算复杂,阿里云体系内速度应该快些,服务提供没多久,可用性待验证,展示效果很一般,价格适中);
  2. \n
  3. sumologic (查询功能强大,上下文展示方便,费用高);
  4. \n
  5. logentries (使用很方便,展示效果很棒,上下文展示一般,费用高);
  6. \n
\n

综合考虑后,选用 Aliyun 日志服务

\n

整体功能强大

\n

\"\"

\n

查询功能够用,虽然界面一般

\n

\"\"

\n

Consequences

\n

创建一个项目,然后创建各自服务的日志库,如下

\n
    \n
  • nginx: nginx-access, nginx-error
  • \n
  • service1: service1-access, service1-log
  • \n
\n

未来需处理好 Aliyun 子账号与日志的权限关系

\n

Refs:

\n\n

21. Redis 使用按业务分离并上云

\n

Date: 26/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. redis server 部署在业务机上,业务与数据存储耦合;
  2. \n
  3. 所有业务的数据存在一个 db 0 中,业务之间很容易产生 key 冲突,业务扩展时需顾虑其他业务数据;
  4. \n
  5. 单点,业务中存有流程数据,风险比较大;
  6. \n
  7. 如果切到独立的机器,资源利用率不高。
  8. \n
\n

Decision

\n
    \n
  1. 将自建 redis server 迁移至 aliyun redis 中;
  2. \n
  3. 理清业务对 redis 的使用情况,按业务划分指定 redis db index 或 独立 redis 实例;
  4. \n
  5. aliyun redis 做了高可用;
  6. \n
  7. aliyun 目前可选的范围很多,最小实例是 256M,价格也合理。
  8. \n
\n

使用 aliyun redis 后,额外得到一个数据管理与监控功能功能,如图

\n

\"\"

\n

Consequences

\n
    \n
  1. 针对缓存数据:

    \n

    我们无需做数据迁移,直接指定预分配的 aliyun redis db index 即可;

  2. \n
  3. 对于存在需要迁移的数据:

    \n

    测试 -&gt; 更新连接配置 -&gt; 暂停业务服务 -&gt; 导入数据(AOF) -&gt; 启动业务服务

    \n

    redis-cli -h xxx.redis.rds.aliyuncs.com -p 6379 -a xx--pipe &lt; appendonly.aof

    \n
      \n
    1. 确保 AOF 已打开(未打开的话,需更新配置及使用 bgrewriteaof 手动触发);
    2. \n
    3. 当前使用的版本(3.0.4)不支持单 db 导入及 db swap,所以只能将整个 instance 数据导入(对于按 db index 区分的业务,需要注意数据不被搞乱)。
    4. \n
  4. \n
\n

Refs:

\n\n

22. 防 DDOS 攻击

\n

Date: 28/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. DDOS 导致业务全线中断,购买高防 IP ,仍然需要重启机器进行 IP 更换(nginx 和业务系统在同一台机器上);
  2. \n
  3. 入口过多,针对 DDOS,需要多线解决;
  4. \n
  5. 机器出问题,业务中断,单点;
  6. \n
  7. 新功能部署,业务中断,没有对多实例进行管理,每次都是杀掉所有,然后重新启动。
  8. \n
\n

Decision

\n
    \n
  • 入口收敛,保证对外只有一个域名;
  • \n
  • 做业务服务的高可用;
  • \n
  • 使用 slb + nginx 做高可用,并且在遭遇 DDOS 攻击时,可以通过切换 slb 低成本的解决 DDOS;
  • \n
  • 使用 supervisor 进行任务管理,可逐步进行服务实例的重启。
  • \n
\n

Consequences

\n

需要保证所有业务机器都是无状态的,即无数据库(mysql, redis, mongodb 等服务在此机器运行),没有用这台机器存储业务用的文件等。

\n

Refs:

\n\n

23. 应用性能监控

\n

Date: 28/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 服务 A,用户访问搜索页面时,请求了 10 分钟,还没返回内容;
  2. \n
  3. 服务 B,这个页面请求怎么有 1000 次数据库查询;
  4. \n
  5. 服务 C,这条数据库查询怎么耗时 5 分钟。
  6. \n
  7. 我们的这个项目做了半年,使用效果如何呀,哦,页面平均响应时间是 5 秒,啊!;
  8. \n
  9. 用户反馈平均需要需要 1 天以上的时间;
  10. \n
  11. 测试很难将所有边界场景测试到。
  12. \n
\n

Decision

\n

使用 Newrelic 对我们线上主要业务做性能监控,包括响应时长、吞吐量、错误率,慢查询,查询分析等,他可以做到实时定位和通知,并指出具体的代码行及 SQL 语句。

\n

Consequences

\n

Refs:

\n\n

24. 实时错误跟踪

\n

Date: 28/04/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 用户 A 使用功能 B,咦,出错了,怎么办呢,再试,还是不行,算了,不用了;又或者我报告一下吧,写邮件?;
  2. \n
  3. 项目 A 昨晚上线后出现了很多问题,怎么办呢,回滚还是赶快去解决呢?
  4. \n
  5. 用户发邮件说使用我们应用时出现错误了,错误描述不清晰,我们和用户沟通下吧,1小时过去了,还是重现不了,那我们去看看日志吧,翻出很久之前的日志,使用二分法慢慢查询,3 个小时过去了,终于定位出错误行啦,但是没有上下文及当时的环境变量等信息;
  6. \n
  7. 异常使用不规范。
  8. \n
\n

Decision

\n

使用 Sentry 对我们线上主要业务做异常监控。

\n

\"\"

\n
    \n
  • 实时通知(sms, email, chat),推荐使用 slack;

  • \n
  • 可定位具体的代码,包括错误栈信息;

  • \n
  • 包含异常的环境变量信息。

  • \n
  • 可主动上报信息;

  • \n
  • 异常信息会聚合,了解当前异常优先级,避免被异常信息淹没;

  • \n
  • 支持所有主流语言及对应的框架;

    \n

    \"\"

  • \n
  • 配置非常简单,如,Django 集成

  • \n
  • 价格合理,并且有每月1万条的免费限额。

  • \n
\n

规范化异常

\n

使用异常的优势

\n
    \n
  1. 隔离错误处理代码和常规代码;
  2. \n
  3. 在调用栈中向上传播错误;
  4. \n
  5. 归类和区分错误类型。
  6. \n
\n

异常处理实践原则

\n
    \n
  1. 使用异常,而不使用返回码;
  2. \n
  3. 利用运行时异常设定方法使用规则;
  4. \n
  5. 消除运行时异常;
  6. \n
  7. 正确处理检查异常;
  8. \n
  9. 使主流程代码保持整洁;
  10. \n
  11. 尽量处理最具体的异常,不能处理的异常请抛出来;
  12. \n
  13. 无法处理的异常却不能抛出时,通过日志记录详细异常栈,并返回给调用方友好的错误信息。
  14. \n
\n

Consequences

\n

Refs:

\n\n

25. 按 RESTful 风格设计更新服务接口

\n

Date: 04/05/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 当前 URL 定义类似这样,add_message, report_exception, check_pwd 等,函数式定义,导致接口数量增长过快,管理麻烦;
  2. \n
  3. 所有的请求都走 POST 方法;
  4. \n
  5. 所有请求返回状态都是 200,使用晦涩难懂的自定义状态码;
  6. \n
  7. 函数式编程,代码重用度不高;
  8. \n
  9. 自定义接口文档,无法及时更新;
  10. \n
  11. 返回结构差异化大,过滤,排序和分页各式各样,无统一的规范;
  12. \n
  13. 无 API 控制台可供测试;
  14. \n
  15. 更多。
  16. \n
\n

Decision

\n
    \n
  1. URL的设计应使用资源集合的概念;\n
      \n
    • 每种资源有两类网址(接口):\n
        \n
      • 资源集合(例如,/orders);
      • \n
      • 集合中的单个资源(例如,/orders/{orderId})。
      • \n
    • \n
    • 使用复数形式 (使用 ‘orders’ 而不是 ‘order’);
    • \n
    • 资源名称和 ID 组合可以作为一个网址的节点(例如,/orders/{orderId}/items/{itemId});
    • \n
    • 尽可能的让网址越短越好,单个网址最好不超过三个节点。
    • \n
  2. \n
  3. 使用名词作为资源名称 (例如,不要在网址中使用动词);
  4. \n
  5. 使用有意义的资源描述;\n
      \n
    • “禁止单纯的使用 ID!” 响应信息中不应该存在单纯的 ID,应使用链接或是引用的对象;
    • \n
    • 设计资源的描述信息,而不是简简单单的做数据库表的映射;
    • \n
    • 合并描述信息,不要通过两个 ID 直接表示两个表的关系;
    • \n
  6. \n
  7. 资源的集合应支持过滤,排序和分页;
  8. \n
  9. 支持通过链接扩展关系,允许客户端通过添加链接扩展响应中的数据;
  10. \n
  11. 支持资源的字段裁剪,运行客户端减少响应中返回的字段数量;
  12. \n
  13. 使用 HTTP 方法名来表示对应的行为:\n
      \n
    • POST - 创建资源,非幂等性操作;
    • \n
    • PUT - 更新资源(替换);
    • \n
    • PATCH - 更新资源(部分更新);
    • \n
    • GET - 获取单个资源或资源集合;
    • \n
    • DELETE - 删除单个资源或资源集合;
    • \n
  14. \n
  15. 合理使用 HTTP 状态码;\n
      \n
    • 200 - 成功;
    • \n
    • 201 - 创建成功,成功创建一个新资源时返回。 返回信息中将包含一个 'Location' 报头,他通过一个链接指向新创建的资源地址;
    • \n
    • 400 - 错误的请求,数据问题,如不正确的 JSON 等;
    • \n
    • 404 - 未找到,通过 GET 请求未找到对应的资源;
    • \n
    • 409 - 冲突,将出现重复的数据或是无效的数据状态。
    • \n
  16. \n
  17. 使用 ISO 8601 时间戳格式来表示日期;
  18. \n
  19. 确保你的 GET,PUT,DELETE 请求是幂等的,这些请求多次操作不应该有副作用。
  20. \n
  21. PUT、POST、PATCH 请求参数通过 application/json 传递;
  22. \n
  23. 正确返回格式:\n
      \n
    • 单个资源:{field1: value1, …}
    • \n
    • 资源集合:[{field1: value1, …}]
    • \n
    • 资源集合(带分页):
    • \n
  24. \n
\n
{\n &quot;count&quot;: 0,\n &quot;next&quot;: null,\n &quot;previous&quot;: null,\n &quot;results&quot;: [{&quot;field1&quot;: &quot;value1&quot;, …}]\n}\n
\n
    \n
  1. 错误返回格式:\n
      \n
    • 非特定字段错误
    • \n
  2. \n
\n
{\n &quot;non_field_errors&quot;: [\n  &quot;该手机号码未注册!&quot;\n ]\n}\n
\n
    \n
  • 特定字段错误
  • \n
\n
{\n &quot;phone_number&quot;: [\n  &quot;该字段不能为空。&quot;\n ],\n &quot;address&quot;: [\n  &quot;该字段不能为空。&quot;\n ]\n}\n
\n
    \n
  1. 使用 swagger 做 API 展示 与调试。\n\"\"
  2. \n
\n

Consequences

\n

Refs:

\n\n

26. 文件服务与业务服务隔离

\n

Date: 06/05/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 当前存储方案有 3 种(FastDFS, nginx static, OSS),各自分别维护,人力成本高,都是单点,资源有效性无法保障;
  2. \n
  3. 文件存储和业务服务共享服务器资源(CPU, 内存,带宽,磁盘 IO),服务器资源使用不合理,文件服务会占用大量内存和磁盘 IO 及网络 IO,影响业务,并且业务服务无法做高可用,遇到 DDOS 只能傻眼;
  4. \n
  5. 面向用户的资源无法做加速;
  6. \n
  7. 所有文件都是公开可访问,存在严重的安全问题(用户身份证照片、合同及报表数据的泄露)。
  8. \n
  9. 所有敏感信息可被任何人全网下载;
  10. \n
\n

Decision

\n
    \n
  1. 将所有文件存储和业务机器分离,将 FastDFS 配置单独机器提供服务;
  2. \n
  3. 所有静态文件集中上云,录音,电子合同等静态文件上云;
  4. \n
  5. 文件分权限访问,分配临时 token 去获取文件;
  6. \n
  7. css/js/images 等上云并配置 CDN,加速用户端访问。
  8. \n
\n

Consequences

\n

综合考虑了 Aliyun OSS 及七牛云,最终选择 OSS 是因为我们的服务都是基于 Aliyun ECS 的,使用 OSS 内网数据同步速度会快很多,并且内网通讯不收费。

\n
    \n
  1. 本地文件迁移至 Aliyun OSS (使用 ossimport2)注意事项:\n
      \n
    • 宿主机内存消耗量大,磁盘读 IO 很高;
    • \n
    • 需要写脚本进行文件比对,确认所有文件都同步成功。
    • \n
  2. \n
  3. FastDFS 迁移注意事项:\n
      \n
    • 同过配置多节点来进行新机器得同步;
    • \n
    • 新机器需要 IO 优化的磁盘,否则整个数据同步瓶颈将在写磁盘操作上。
    • \n
  4. \n
\n

Refs:

\n\n

27. 消息队列

\n

Date: 10/05/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 我们的很多业务都有这个需要,当前的一些定时任务已导致机器的产生瓶颈,很多业务之间的耦合性也很高;
  2. \n
  3. 当前只有少量的业务在使用消息队列服务(activeMQ);
  4. \n
  5. activeMQ 对非 java 语言的支持并不友好;
  6. \n
  7. 自己需要维护队列服务,做监控,高可用等。
  8. \n
\n

Decision

\n

我们急需一个多语言支持且可靠的服务可以解决如上问题,即

\n
    \n
  • 异步解耦
  • \n
  • 削峰填谷
  • \n
\n

Aliyun 的 MNS 和 ONS 功能的重合导致选择起来很困难,最终选择 MNS 源于以下几点。

\n
    \n
  1. 支持消息优先级;
  2. \n
  3. 可靠性更高;
  4. \n
  5. 文档更完善;
  6. \n
  7. 服务更成熟;
  8. \n
  9. 使用起来简单方便,定时消息不支持这点比较遗憾;
  10. \n
  11. ONS 使用起来有些复杂,监控方面的功能确实强大许多,但多数在开发与公测中;
  12. \n
  13. 不好的点是各自都加了一些私活,MNS 加了自家的短信服务,ONS 加入了 MQTT 物联网套件,让 Q 看起来不单纯。
  14. \n
\n

Consequences

\n

使用 MNS 时需要确认以下几点:

\n
    \n
  • 确认队列模型(支持一对一发送和接收消息)还是主题模型(支持一对多发布和订阅消息,并且支持多种消息推送方式)

    \n

    \"\"

    \n

    \"\"

  • \n
  • 队列模型,需关注

    \n
      \n
    1. 消息接收长轮询等待时间(0-30s);
    2. \n
    3. 消息最大长度(1K-64K);
    4. \n
    5. 消息存活时间(1min-15day);
    6. \n
    7. 消息延时(0-7day);
    8. \n
    9. 取出消息隐藏时长(1s-12hour);
    10. \n
  • \n
  • 主题模型,需关注

    \n
      \n
    1. 消息最大长度(1K-64K);
    2. \n
    3. 消息可以加过滤标签;
    4. \n
  • \n
\n

Refs:

\n\n

28. What should we do when we setup a new server

\n

Date: 11/05/2017

\n

Status

\n

Accepted

\n

Context

\n

Context here...

\n

Decision

\n

Decision here...

\n

Consequences

\n

Refs:

\n\n

29. 本地 hosts 管理

\n

Date: 18/05/2017

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 我们有多个测试环境(开发、测试、预发布及线上);
  2. \n
  3. 我们的客户端为了避免针对不同环境做多次打包,使用了和线上一致的域名,所以当我们的 QA 需要测试不同环境时,需要手动更新每个 QA 的本地 hosts 文件;
  4. \n
  5. 由于服务器及对应服务的调整,无法实时做到 hosts 的及时更新,也没法保证每个测试人员都做了更新(当前无通知,出问题后主要依靠问其他 QA 成员或咨询 Dev);
  6. \n
  7. 部分线上服务未配置外网域名,比如 Boss 系统、Wiki 等,需要包括运营人员在内的所有人各自去配置本地 hosts。
  8. \n
\n

Decision

\n
    \n
  1. 方案一:使用 SwitchHosts(Chosen)\n
      \n
    • 可快速切换 hosts;
    • \n
    • 支持集中式的 hosts 管理(在线);
    • \n
    • 支持多 hosts 合并;
    • \n
    • 支持多客户端。
    • \n
  2. \n
\n

主界面如下,默认会将旧的 hosts 文件保存为 backup

\n

\"\"

\n

可以新建 hosts,比如测试环境一

\n

\"\"

\n

可以使用远程集中式管理的 hosts

\n

\"\"

\n

最重要的是这些 hosts 可以通过同时打开各自开关将其合并使用。

\n
    \n
  1. 方案二:使用路由器\n
      \n
    • 只需切换不同的路由器即可进行不同环境的测试;
    • \n
    • 配置办公网络路由器,需要 IT 人员来维护(暂无);
    • \n
    • 只能办公室内进行访问。
    • \n
  2. \n
\n

Consequences

\n

软件基于 Electron 开发,跨平台,Windows/Mac/Linus 客户端下载地址: https://pan.baidu.com/share/link?shareid=150951&amp;uk=3607385901#list/path=%2Fshare%2FSwitchHosts!&amp;parentPath=%2Fshare

\n

Refs:

\n

SwitchHosts Github: https://github.com/oldj/SwitchHosts

\n

30. 容量评估 - 存储

\n

Date: 2017-05-25

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 一些需要高 IOPS 的服务,磁盘使用的是普通云盘,如,数据库,备份服务,图片服务等。
  2. \n
\n

Decision

\n
    \n
  1. 明确存储的使用场景;
  2. \n
  3. 关注吞吐量,IOPS和数据首次获取时间。
  4. \n
\n

我们的存储都是基于 Aliyun 的,他有以下类别及特点:

\n
    \n
  • nas(文件存储)\n
      \n
    • 使用场景\n
        \n
      • 负载均衡共享存储和高可用
      • \n
      • 企业办公文件共享(不支持本地挂载)
      • \n
      • 数据备份
      • \n
      • 服务器日志共享
      • \n
    • \n
    • 价格及吞吐能力\n
        \n
      • 2/G/M SSD性能型 60M/s
      • \n
      • 0.65/G/M 容量型 30M/s
      • \n
    • \n
  • \n
  • disk(块存储、云盘)\n
      \n
    • 使用场景\n
        \n
      • 普通云盘\n
          \n
        • 不被经常访问或者低 I/O 负载的应用场景
        • \n
      • \n
      • 高效云盘\n
          \n
        • 中小型数据库
        • \n
        • 大型开发测试
        • \n
        • Web 服务器日志
        • \n
      • \n
      • SSD 云盘\n
          \n
        • I/O 密集型应用
        • \n
        • 中大型关系型数据库
        • \n
        • NoSQL 数据库
        • \n
      • \n
    • \n
    • 价格\n
        \n
      • 普通云盘 0.3/G/M
      • \n
      • 高效云盘 0.35/G/M
      • \n
      • SSD 云盘 1/G/M
      • \n
    • \n
    • 吞吐量\n
        \n
      • 普通云盘 30MBps
      • \n
      • 高效云盘 80MBps
      • \n
      • SSD 云盘 256MBps
      • \n
    • \n
    • IOPS\n
        \n
      • 普通云盘 数百
      • \n
      • 高效云盘 3000
      • \n
      • SSD 云盘 20000
      • \n
    • \n
    • 访问延迟\n
        \n
      • 普通云盘 5 - 10 ms
      • \n
      • 高效云盘 1 - 3 ms
      • \n
      • SSD 云盘 0.5 - 2 ms
      • \n
    • \n
  • \n
  • oss(对象存储)\n
      \n
    • 使用场景\n
        \n
      • 图片和音视频等应用的海量存储
      • \n
      • 网页或者移动应用的静态和动态资源分离
      • \n
      • 云端数据处理
      • \n
    • \n
    • 价格及吞吐能力\n
        \n
      • 0.148/G/M 标准型 吞吐量大,热点文件、需要频繁访问的业务场景 大概 50M/s,类似高效云盘
      • \n
      • 0.08/G/M 低频访问型 数据访问实时,读取频率较低的业务场景 Object 存储最低 30 天
      • \n
      • 0.06/G/M 归档型 数据恢复有等待时间,数据有存储时长要求 Object 存储最低 30 天
      • \n
    • \n
  • \n
  • oas(归档存储)\n
      \n
    • 使用场景\n
        \n
      • 低成本备份
      • \n
      • 数据归档
      • \n
      • 取代磁带
      • \n
    • \n
    • 价格及吞吐能力\n
        \n
      • 0.07/G/M 用户提取数据时能够容忍0-4小时的时间延迟
      • \n
    • \n
  • \n
\n

Consequences

\n
    \n
  1. 加粗的信息可以重点查看下,同类别里比较推荐;
  2. \n
  3. 我们选择时还要考虑价格及存储时长要求。
  4. \n
\n

Refs:

\n\n

31. 容量评估 - 内存

\n

Date: 2017-05-25

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 机器内存太小了,需要升级一下;
  2. \n
  3. 我们之前公司服务需要用多少多少;
  4. \n
  5. Java 程序最大最小堆的指定无标准。
  6. \n
\n

Decision

\n
    \n
  • 分析业务场景,明确我们到底需要多少内存,合理的预留1-2倍内存都没有问题;
  • \n
  • 我们的业务目前分别由两种语言实现 Python 及 Java,Java 程序对内存的使用量非常大且监控不直观,为了合理分配内存,我们采取了以下分析方法。\n
      \n
    • 分配的最大内存用完后,GC 频率高且特定时间内无法做到垃圾回收,将会导致 java.lang.OutOfMemoryError
    • \n
    • OOF,GC 频率及 GC 时间是确定 heap 参数的一个指标;
    • \n
    • 线上不可能等到 OOF 时,才做升级,这样直接影响了系统的可用性,所以针对 Java 程序,一定要做好压力测试或对 JVM 做好监控(通过 Java VisualVM or JConsole),鉴于我们已用 Newrelic 栈,将有其通知我们服务的状况,Memory Analyzer 可以做更详细的变量级别内存使用查看;
    • \n
  • \n
  • 内存的不合理使用有:将大文件完整加载至内存,将整个表的数据读取至内存;
  • \n
  • 内存泄漏:微观的有对象的引用问题,宏观的有连接未释放等;
  • \n
  • Xmx 设置后,对系统来说是已使用的,所以我们需要同时关注系统级别和 JVM 级别的内存使用情况。
  • \n
\n

\"\"

\n

Consequences

\n

这篇文章的缘起是因为我们的一个同事发现自己使用的测试环境内存不够用,导致其他服务无法启动,并要求升级机器配置。当时的测试环境配置是:2核4G。出现问题前的操作是将 Xmx 由 1G 调整为 2G,通过分析发现是程序中加载了一个 7万条数据的大表导致,调整批量加载数据将以原先一半的内存解决此问题。

\n

Refs:

\n\n

32. TCP 长连接高可用

\n

Date: 2017-05-25

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 我们的一些智能设备,通过 TCP 和后端进行通信,上报数据及接收指令;
  2. \n
  3. 智能设备由第三方提供,我们实现后端服务,当前支持域名和 IP 请求;
  4. \n
  5. 随着未来设备数量的增长,我们的单台服务预计将无法满足;
  6. \n
  7. 原方案是针对不同批次的智能设备,我们绑定不同的域名,已做客户的负载;
  8. \n
  9. 存在设备使用的不可控引起服务端的使用率会存在问题;
  10. \n
  11. 服务器出问题后服务的恢复时间受限于 DNS 更新的时间(切换新机器)。
  12. \n
\n

Decision

\n

\"\"

\n

Consequences

\n

Refs:

\n\n

33. 容量评估 - MySQL

\n

Date: 2017-05-25

\n

Status

\n

Accepted

\n

Context

\n

QPS: 每秒钟查询量。如果每秒钟能处理 100 条查询 SQL 语句,那么 QPS 就约等于 100\nTPS: 每秒钟事务处理的数量

\n

Decision

\n

和 MySQL 性能相关的几个指标

\n
    \n
  • CPU\n
      \n
    • 对于 CPU 密集型的应用,我们需要加快 SQL 语句的处理速度。由于MySQL 的 SQL 语句处理是单线程的,因此我们需要更好的 CPU,而不是更多的cpu
    • \n
    • 一个 CPU 同时只能处理一条 SQL 语句。所以高并发量的情况下,就需要更多的 CPU 而不是更快的 CPU。
    • \n
  • \n
  • 内存\n
      \n
    • 把数据缓存到内存中读取,可以大大提高性能。常用的 MySQL 引擎中,MyISAM 把索引缓存到内存,数据不缓存。而InnoDB 同时缓存数据和索引
    • \n
  • \n
  • 磁盘\n
      \n
    • MySQL 对磁盘 IO 的要求比较高,推荐高性能磁盘设备,比如,Aliyun 就推荐使用其 SSD,而不是普通云盘和高效云盘,当然 SSD 这个介质的可靠性,我们也需要考虑
    • \n
    • MySQL 实例应该独享,尤其不能和其他磁盘 IO 密集型任务放在一起
    • \n
  • \n
  • 网络\n
      \n
    • 一般数据库服务都部署在内网,带宽影响不大,避免使用外网连接数据库
    • \n
    • 外网查询,尤其避免使用 select * 进行查询
    • \n
    • 从库如果跨地域,走外网,则尽量减少从库数量。
    • \n
  • \n
\n

影响数据库性能的因素及应对方式

\n
    \n
  • 高并发\n
      \n
    • 数据库连接数被占满
    • \n
    • 对于数据库而言,所能建立的连接数是有限的,MySQL 中max_connections 参数默认值是 100
    • \n
  • \n
  • 大表\n
      \n
    • 记录行数巨大,单表超过千万行
    • \n
    • 表数据文件巨大,表数据文件超过10G
    • \n
    • 影响\n
        \n
      • 慢查询:很难在一定的时间内过滤出所需要的数据
      • \n
      • DDL 操作、建立索引需要很长的时间:MySQL 版本 &lt;5.5 建立索引会锁表,&gt;=5.5 虽然不会锁表但会引起主从延迟
      • \n
      • 修改表结构需要很长时间锁表:会造成长时间的主从延迟;影响正常的数据操作
      • \n
    • \n
    • 处理\n
        \n
      • 分库分表
      • \n
      • 历史数据归档
      • \n
    • \n
  • \n
  • 大事务\n
      \n
    • 运行时间比较长,操作数据比较多的事务
    • \n
    • 影响\n
        \n
      • 锁定太多数据,造成大量的阻塞和锁超时
      • \n
      • 回滚时需要的时间比较长
      • \n
      • 执行时间长,容易造成主从延迟
      • \n
    • \n
    • 处理\n
        \n
      • 避免一次处理太多的数据
      • \n
      • 移出不必要在事务中的select操作
      • \n
    • \n
  • \n
\n

Consequences

\n

鉴于我们使用了 Aliyun MySQL,他有完善的监控项,CPU、内存、磁盘、连接数及网络流量,关注各个指标并针对其做好报警策略即可

\n

Refs:

\n\n

34. DNS 笔记

\n

Date: 2017-06-03

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 网站被 DDOS 需要考虑切换 DNS 解析;
  2. \n
  3. 负载均衡服务切换服务器,需要更新 DNS 解析;
  4. \n
  5. 新加子域名,需要配置 DNS 解析。
  6. \n
\n

Decision

\n

DNS 解析的同步需要时间,涉及以下几点:

\n
    \n
  1. DNSPod 生效时间,一般在 30s 以内;
  2. \n
  3. 各个 ISP DNS 服务器刷新时间;
  4. \n
  5. 域名 TTL (用户本地缓存时间)。
  6. \n
\n

针对全球性业务,保险起见,我们等待一天以上。DNSPod 给出的说法是,域名解析通常需 24 小时至 72 小时才能全球完全同步。大多数业务正常情况以 TTL 为依据即可。

\n

Consequences

\n

一种域名解析更新策略是,现将旧的域名解析 TTL 设为最小值,等待一天,确保解析都已完全同步,这个完全不影响现有业务。将 DNS 解析更新到新的记录,这个时候 DNS 服务器将以最快的速度进行同步更新;确认都更新完毕后,我们将 TTL 设为较长时间,确保 DNS 解析的稳定性。

\n

Refs:

\n\n

35. 关于灾难恢复

\n

Date: 2017-06-05

\n

Status

\n

Proposed

\n

Context

\n

当前我们使用的是华北2可用区A机房(即北京昌平区的一个机房)部署了所有服务,存在以下几个问题,出现概率逐级减少:

\n
    \n
  1. 服务本身部署在单台机器,单机的故障会导致服务的不可用,这个我们的业务服务频频出现;
  2. \n
  3. 所有服务部署于一个机房,机房电力,网络出现故障,将导致服务完全不可用,这个 2016 年中旬我们使用的 Aliyun 机房网络设备出现过一次问题,导致服务停服 1 小时左右(官方),实际对我们的影响在 12 个小时左右;
  4. \n
  5. 北京发生各种灾害,殃及所有机房,导致服务不可用。
  6. \n
\n

基础概念

\n

灾难恢复(Disaster recovery,也称灾备),指自然或人为灾害后,重新启用信息系统的数据、硬件及软体设备,恢复正常商业运作的过程。灾难恢复规划是涵盖面更广的业务连续规划的一部分,其核心即对企业或机构的灾难性风险做出评估、防范,特别是对关键性业务数据、流程予以及时记录、备份、保护。

\n

地域,即城市,不同的地域可以做到自然灾害级别的灾备,之间延迟较高

\n

可用区,即机房,不同的可用区可以做到电力和网络设备互相独立,之间有少量延迟

\n

两地三中心,业界目前最可靠的解决方案,即在两个城市共三个机房中部署服务

\n

灾备的两项指标

\n

RTO - Recovery Time Objective,它是指灾难发生后,从 IT 系统宕机导致业务停顿之时开始,到 IT 系统恢复至可以支持各部门运作、恢复运营之时,此两点之间的时间段称为 RTO

\n

RPO - Recovery Point Objective,是指从系统和应用数据而言,要实现能够恢复至可以支持各部门业务运作,系统及生产数据应恢复到怎样的更新程度,这种更新程度可以是上一周的备份数据,也可以是上一次交易的实时数据

\n

两地三中心

\n

\"\"

\n
    \n
  • 主系统\n
      \n
    • 即当前对外提供服务的机房
    • \n
    • 首先要做到自身的高可用,所有服务不因单机故障导致服务不可用
    • \n
    • 无资源浪费,多一些部署和维护成本
    • \n
  • \n
  • 同城灾备\n
      \n
    • 单个城市多个机房,解决单机房电力或网络故障导致的服务不可用
    • \n
    • 主备的方式会有一半的资源浪费,双活的方式对服务有一定的延迟
    • \n
    • 有一定的部署和维护成本
    • \n
  • \n
  • 异地灾备\n
      \n
    • 即跨城市部署服务,解决自然灾害等引起的服务不可用
    • \n
    • 由于延迟的原因,这部分资源属于备用服务,仅在发生灾害是激活
    • \n
    • 平时资源都是浪费,并且有较高的部署和维护成本
    • \n
  • \n
\n

Decision

\n
    \n
  1. 同机房的服务高可用(进行中),这个是目前最高优先级;
  2. \n
  3. 同城双活(提议中),可以解决大部分我们遇到的机房问题;
  4. \n
  5. 异地灾备(暂不考虑),针对支付业务,当涉及合规性时,我们得考虑下;
  6. \n
  7. 明确我们各个服务的重要程度,分服务针对性的做高可用及灾备策略。
  8. \n
\n

Consequences

\n

Refs:

\n\n

36. 关于 MySQL 高可用

\n

Date: 2017-06-06

\n

Status

\n

Proposed

\n

Context

\n
    \n
  1. 数据库版本 5.1,太旧,性能,安全,主从复制都存在问题;
  2. \n
  3. 数据库部署在 ECS 上,但磁盘使用的是普通云盘,IOPS 已到阈值(优先级最高);
  4. \n
  5. 数据库一主两从,但无高可用;
  6. \n
  7. 业务端使用 IP 连接主数据库。
  8. \n
\n

Decision

\n
    \n
  1. 提交 Aliyun 工单,尝试是否能申请下 5.1 版本的 MySQL,迁移数据至 RDS,解决 2,3,4 问题(沟通后,5.1 版本已不再提供,PASS);
  2. \n
  3. 将部分数据库迁移出,缓解当前 MySQL 服务器压力,维护多个数据库实例(并未解决实际问题,PASS,当前压力最终确认是慢查询原因);
  4. \n
  5. ECS 上自建 HA,并启用新的实例磁盘为 SSD,切换新实例为 Master,停掉旧实例(根本问题未解决,技术债一直存在,自行维护仍然存在风险点);
  6. \n
  7. 调研 5.5 和 5.1 的差异,直接迁移自建数据库至 Aliyun RDS MySQL 5.5。
  8. \n
\n

鉴于查看文档后, 5.1 到 5.5 的差异性影响不大,Aliyun 官方也支持直接 5.1 到 5.5 的迁移,所以计划直接迁移至 RDS 的 5.5 版本。

\n

为了杜绝风险:

\n
    \n
  1. 按业务分数据库分别迁移;
  2. \n
  3. 所有迁移先走测试数据库,由 QA 做完整的测试。
  4. \n
\n

ECS self built MySQL 5.1 to RDS 5.5 with DTS 迁移流程:

\n
    \n
  1. 在 RDS 中创建原 MySQL 数据库对应的账号(各个项目账号独立);
  2. \n
  3. 更新白名单:添加项目所部署的服务器;
  4. \n
  5. 明确数据规模,对同步时间做个预期;
  6. \n
  7. 同步(全量 or 增量),明确无延迟状态;
  8. \n
  9. 更新数据库连接配置文件;
  10. \n
  11. 明确无延迟状态,停服;
  12. \n
  13. 确定数据量一致(由预先写好的脚本判断)(1min);
  14. \n
  15. 关闭迁移服务(10s);
  16. \n
  17. 重启服务器(10s)。
  18. \n
\n

6 至 9 步决定我们的停服时间。

\n

鉴于我们使用从库作为迁移的数据源,需更新如下配置:

\n
    \n
  • log-slave-updates=1
  • \n
  • binlog-format=row
  • \n
\n

Consequences

\n

同步过程中出现如下问题,请周知:

\n
    \n
  1. 判断脚本出问题,未准备好脚本命令;
  2. \n
  3. 终端出问题,更改命令麻烦;
  4. \n
  5. 配置信息直接在生产环境更改,应走 github 提交;
  6. \n
  7. 停服那步影响其他业务;
  8. \n
  9. 从库使用者是否受影响,如数据组。
  10. \n
\n

Refs:

\n\n

37. 通过代理解决白名单问题

\n

Date: 2017-06-07

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 我们的支付及财务业务,需要向第三方金融机构发起请求,第三方机构出于安全性考虑,需要将我们的服务器 IP 地址进行报备;
  2. \n
  3. 第三方机构较多,针对服务器扩容,更换,报备一次比较麻烦;
  4. \n
  5. 第三方机构审核时间不定,1 天到多天不定,关键时刻影响业务。
  6. \n
\n

Decision

\n

正向代理是一个位于客户端和目标服务器之间的代理服务器(中间服务器)。为了从原始服务器取得内容,客户端向代理服务器发送一个请求,并且指定目标服务器,之后代理向目标服务器转交并且将获得的内容返回给客户端。正向代理的情况下客户端必须要进行一些特别的设置才能使用。

\n

常见场景:

\n

\"\"

\n

反向代理正好相反。对于客户端来说,反向代理就好像目标服务器。并且客户端不需要进行任何设置。客户端向反向代理发送请求,接着反向代理判断请求走向何处,并将请求转交给客户端,使得这些内容就好似他自己一样,一次客户端并不会感知到反向代理后面的服务,也因此不需要客户端做任何设置,只需要把反向代理服务器当成真正的服务器就好了。

\n

常见场景:

\n

\"\"

\n

方案:

\n
    \n
  1. 使用正向代理;\n
      \n
    • 这个场景最容易想到的方案,使用起来直观,易懂;
    • \n
    • 需要每个客户端进行配置,或是在应用中对单个请求做代理配置;
    • \n
    • 需要维护一个高可用的代理服务,并备案此代理服务器。
    • \n
  2. \n
  3. 使用反向代理。\n
      \n
    • 在我们的服务器上做对方服务的反向代理(听起来有点绕,不直观)
    • \n
    • 维护简单,就像是我们用 nginx/slb 为对方做了个负载均衡,但配置稍有不同;
    • \n
  4. \n
\n
server {\n\n     server_name {{ proxy_info.server_name }};\n     listen {{ proxy_info.ssl_listen }};\n\n     location / {\n         proxy_pass_header Server;\n         proxy_pass {{ proxy_info.proxy_url }};\n         proxy_redirect off;\n         proxy_set_header X-Real-IP $remote_addr;\n         proxy_set_header X-Scheme $scheme;\n         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n     }\n}\n
\n
    \n
  • 使用简单,使用方配置本机 hosts 即可,为对方域名和代理 IP 映射。
  • \n
\n
    \n
  1. iptables\n
      \n
    • 类似局域网共享上网;
    • \n
    • 对 iptables 配置有要求;
    • \n
    • 目标域名对应的 ip 地址改变,需要更新配置。
    • \n
  2. \n
\n

最终我们通过 aliyun slb 的4层负载接两台部署了 ss5 的机器提供高可用的代理服务

\n
    \n
  • 4层(TCP协议)服务中,当前不支持添加进后端云服务器池的ECS既作为Real Server,又作为客户端向所在的负载均衡实例发送请求。
  • \n
  • ss5 启动于内网地址即可
  • \n
  • ss5 配置需关注 AUTHENTICATION 和 AUTHORIZATION
  • \n
\n

Consequences

\n

Refs:

\n
    \n
  1. 云服务器 ECS Linux 系统通过 Squid 配置实现代理上网 https://help.aliyun.com/knowledge_detail/41342.html
  2. \n
  3. 正向代理与反向代理的区别 http://www.jianshu.com/p/208c02c9dd1d
  4. \n
  5. 设置 iptables 使用linux做代理服务器 https://www.l68.net/493.html
  6. \n
  7. SS5 http://ss5.sourceforge.net/project.htm
  8. \n
\n

38. 数据脱敏

\n

Date: 2017-06-13

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 数据目前交由服务后台或前端进行敏感信息处理,原始数据存在多种风险(外部脱裤,内部人员非必要性的查看等);
  2. \n
  3. 各个 Team 数据加密策略不一致(有 MD5, AES etc);
  4. \n
  5. 数据掩码方式也不统一。
  6. \n
\n

Decision

\n

使用四个策略的结合:

\n
    \n
  1. 掩码 - 业务系统需要查看部分内容,已核对信息,日志中为了便于定位;
  2. \n
  3. 替换 - 字段实际不被使用,但保留字段,并将数据替换为空内容;
  4. \n
  5. 可逆加密 - AES(ECB/PKCS5Padding - 128)
  6. \n
  7. 不可逆加密 - SHA1
  8. \n
\n

策略的使用需考虑,使用场景(生产、测试等环境),成本(对人员、服务器的需求),是否易用(影响开发效率),维度(目前就分两种:机密和公开)

\n

掩码规则:

\n
    \n
  • 姓名 - *斌 - 保留最后一个字,其余部分统一为一个星号
  • \n
  • 电话 - 131****0039 - 中间4~7位每个字符替换为一个星号
  • \n
  • 身份证号 - **************1234 - 保留后四位,其余部分每个字符替换为一个星号
  • \n
  • 银行卡号 - 3111111******1234 - 保留前六、后四位,其余部分每个字符替换为一个星号
  • \n
  • 地址 - ``
  • \n
  • 邮箱 - ``
  • \n
  • 密码 - ``
  • \n
  • 交易金额 - ``
  • \n
  • 充值码 - ``
  • \n
\n

两个原则:

\n
    \n
  1. remain meaningful for application logic(尽可能的为脱敏后的应用,保留脱敏前的有意义信息)
  2. \n
  3. sufficiently treated to avoid reverse engineer(最大程度上防止黑客进行破解)
  4. \n
\n

Consequences

\n

Refs:

\n\n

39. 秘钥管理

\n

Date: 2017-06-14

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 目前有相当多的账户、密码等信息存储在项目配置文件中;
  2. \n
  3. 部分项目将敏感信息和项目分离,但所部署的服务器还是能被所有人登录查看;
  4. \n
  5. 将服务器登录权限限制在运维手中,需要运维人员维护所有敏感信息的存储与管理,数量线性增长,尤其是支付组涉及的敏感信息更多,每一个新项目都需要运维人员的参与和维护。
  6. \n
\n

Decision

\n
    \n
  1. 将服务器登录权限限制在个别人的手中;
  2. \n
  3. 使用密码管理服务,确保运维人员只需维护一个秘钥;
  4. \n
  5. 使用 Aliyun KMS 而不是自己搭建,节约运维成本。
  6. \n
\n

直接使用KMS加密、解密

\n

\"\"

\n

结合我们的需求,我们选用这种方式,使用方式如下

\n
import json\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkkms.request.v20160120 import EncryptRequest, DecryptRequest\n\nOLD = 'password'\nNEW = '\n\nclient = AcsClient('id', 'secret', 'cn-beijing')\n\n\ndef en():\n    request = EncryptRequest.EncryptRequest()\n    request.set_KeyId('')\n    request.set_Plaintext(OLD)\n    response = client.do_action_with_exception(request)\n    print json.loads(response)['CiphertextBlob']\n\n\ndef de():\n    request = DecryptRequest.DecryptRequest()\n    request.set_CiphertextBlob(NEW)\n    response = client.do_action_with_exception(request)\n    print json.loads(response)['Plaintext'] == OLD\n\n\nif __name__ == '__main__':\n    de()\n
\n

使用信封加密在本地加密、解密

\n

\"\"

\n

\"\"

\n

Consequences

\n
    \n
  1. 直接使用KMS加密、解密会影响启动速度;
  2. \n
  3. 一个明文多次加密,产生的密文不同,但所有密文都可以解密为明文。
  4. \n
\n

Refs:

\n\n

40. Agile - Daily standup meeting

\n

Date: 2017-06-16

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. Team devops set up recently, we need some change to improve the performance;
  2. \n
  3. No communication in the team, always person to person;
  4. \n
  5. Tasks not organized well which spread among different projects;
  6. \n
  7. Some teams require daily reports for their management, but lose the communication between team members.
  8. \n
\n

Decision

\n

We're going to have 10 minutes daily standup meetings with each team so that We're on the same page about what everyone in the team is working on and we can strategize on how to approach the work items on the board for the day to come.

\n

Effective standups are all about communication and commitment, not about status updates. So before every scrum take 5 minutes to actually think and note down what you were planning to accomplish yesterday, did you actually accomplish what you've committed to, if not why?

\n

Take some time to plan your day and decide what you're going to accomplish today, commit to it and state it to the team (not the management), so the team members will keep each other accountable for the commitments they make to make the whole team improve together and make sure to remove impediments that prevent team members to accomplish what they plan.

\n

Scrum master should pay more attention to the status of each card, encourage team members to deploy in time.

\n

We change scrum master every two week to make sure all team members understand the details as an owner.

\n

Keynotes

\n
    \n
  • Safe time - make sure everyone free that time;
  • \n
  • Everyone should standup;
  • \n
  • Focus - Every should watching the board;
  • \n
  • Less than 10 minutes for the whole meeting;
  • \n
  • One minute per person, no more than two minutes;
  • \n
  • Remove impediments;
  • \n
  • What done yesterday;
  • \n
  • What will do today.
  • \n
\n

Consequences

\n

Everyone in the team will know each other better.

\n

Refs:

\n\n

41. MySQL 迁移 RDS 总结

\n

Date: 2017-07-17

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. 当前数据库为 Master, Slave 模式;
  2. \n
  3. Master 实例上创建了 16 个数据库,全部需要迁移;
  4. \n
  5. 部分业务存在跨库查询;
  6. \n
  7. 有一个数据库被近 10 个业务进行查询等数据库操作;
  8. \n
  9. 当前数据库为 MySQL 5.1,存在主从同步性能问题;
  10. \n
  11. RDS 仅支持 MySQL 5.5, 5.6, 5.7 版本;
  12. \n
\n

Decision

\n
    \n
  1. 调研 MySQL 5.1 与 5.5 之间的差异,并周知各个项目组成员;
  2. \n
  3. 将数据库与业务之间的引用关系用二维表列举出来;
  4. \n
  5. 选出被业务单独或少量引用的数据库,先通过将对应测试数据库进行迁移,并交由测试人员进行测试;
  6. \n
  7. 测试完成后对正式环境直接进行迁移;
  8. \n
  9. 针对被10多个业务引用的数据库迁移,我们不止要做测试环境的迁移,还要做线上环境的测试\n
      \n
    1. 为了保证线上测试可回滚,我们需限定只有测试人员进行操作;\n
        \n
      1. 限制我们的服务器安全组,外网只能通过办公网络访问;
      2. \n
      3. 限制我们的入口 slb,只能通过办公网络访问。
      4. \n
    2. \n
    3. 我们的服务之间存在调用关系,部分业务走的外网域名;\n
        \n
      1. 准备我们所有外网业务的域名及其内网 ip 映射,通过 ansible 分发并追加其至所有的线上机器 hosts
      2. \n
    4. \n
    5. 所有业务准备好分支 feature/db-config-update-to-rds,此分支与 master 分支差异只有数据库配置改动,冻结 master 新代码合入,如此确保随时可上线,随时可回滚;
    6. \n
    7. 创建数据库迁移任务: 结构迁移+整体数据+增量数据迁移;
    8. \n
    9. 停止并备份任务计划调度(/etc/crontab,cron.d,/var/spool/cron);
    10. \n
    11. 停止所有业务服务;
    12. \n
    13. 停止所有 nginx;
    14. \n
    15. 脚本验证所有机器上的服务和任务计划,确保无运行中相关程序;
    16. \n
    17. 验证无数据库连接;
    18. \n
    19. 锁定原数据库写操作(验证确认确实不可写)
    20. \n
    21. 网络隔离;
    22. \n
    23. 检查源数据库与目的数据库 数据一致性;
    24. \n
    25. 停止数据迁移任务;
    26. \n
    27. 停止主db数据库服务;
    28. \n
    29. 启动RDS到从库的数据同步任务;
    30. \n
    31. 重启所有服务;
    32. \n
    33. 重启 nginx;
    34. \n
    35. 测试团队开始全面验证;
    36. \n
    37. 网络隔离解除;
    38. \n
    39. 恢复任务计划;
    40. \n
    41. 重新执行停服期间计划任务。
    42. \n
  10. \n
\n

Consequences

\n
    \n
  1. RDS 磁盘预留过低,导致同步中途停止,无法进行写操作;
  2. \n
  3. 一些业务需要回调,测试不完整;
  4. \n
  5. 如果有完整的预发布环境,可保证服务零停机时间;
  6. \n
\n

42. Agile - Retrospective meeting

\n

Date: 2017-07-31

\n

Status

\n

Accepted

\n

Context

\n
    \n
  1. Team members know little about last iteration and don’t know which part is good, bad or need improve;
  2. \n
  3. New team members know nothing about the team’s history and don’t know the best practices for this team;
  4. \n
  5. We need learn from what we done.
  6. \n
\n

Decision

\n

Description

\n

After each iteration we'll spend one hour discussing relevant topics we add during the iteration in our retrospective board.

\n

The idea is to spend quality time and get the most value out of this meeting, therefore each team member is encouraged to bring discussion topics as well as suggestion for improvement.

\n

Preparation

\n
    \n
  • The SM marks the current iteration as finished, moving all the unfinished tasks to the new iteration;
  • \n
  • Check the dashboard and analyze our metrics for the last finished iteration. Find out all problematic tasks with low Flow Efficiency or low Quality Score;
  • \n
  • Safety check;
  • \n
  • The SM remind team members in team channel at least 10 minutes before starting the meeting;\n
      \n
    • Everyone is available;
    • \n
    • Everyone is encouraged to prepared the Good,Bad and Need improve cards;\n
        \n
      • Something that went well or wrong;
      • \n
      • Any type of improvement suggestion you might think of. Regarding the process, the code base, the collaboration etc.
      • \n
    • \n
    • Add description/comments to existing ones;
    • \n
    • Votes(optional);
    • \n
  • \n
\n

Process

\n
    \n
  • Discuss problematic tasks that have bad metrics, in order to understand how we can improve;\n
      \n
    • Identify the root cause of the problem;
    • \n
    • Come up with ideas about how we could have done it better, so that we can learn from our mistakes;
    • \n
  • \n
  • The SM prioritizes the topics, based on team member's votes (optional);
  • \n
  • Follow up on the previous iteration's discussion (optional);
  • \n
  • Follow up on existing action items;
  • \n
  • During the meeting the SM records the outcomes and action items in our retrospective board;
  • \n
  • At the end of the meeting we should save 10 min for a brief overview of the past iteration(recently completed features, features in progress, planed features, velocity graphs and user story vs bugs graphs)
  • \n
\n

Notice

\n
    \n
  • Starts on time and all the team members must participate;
  • \n
  • Discuss the accumulated cards in our Backlog, 5 minutes/card;
  • \n
  • Each topic is time-boxed. However after the 5min timer expires, if everyone agrees we need further discussion, we restart the timer one more time.
  • \n
  • Anybody can stop the current discussion if it's clear we're going nowhere;
  • \n
  • We keep the retrospective meetings within 1 hour.
  • \n
\n

Consequences

\n

Everyone will learn from history, and not make same error twice.

\n

43. 支持过滤的消息队列

\n

Date: 2017-08-18

\n

Status

\n

Accepted

\n

Context

\n

最近需要优化这样的场景,我们的合同状态有多种(待完善,待审核,审核通过,审核不通过等),每种状态的改变来自多个地方(中介后台,运营后台,风控系统等),每种状态的处理也来自多个地方(SAAS系统,中介后台,运营系统等),且处理者需要处理的状态不相同;

\n

当前实现方案是:

\n
    \n
  1. 定时任务,各个系统定时处理状态为 X 的合同(处理不及时);
  2. \n
  3. 使用回调,状态更新时回调至处理者处(扩展不方便);
  4. \n
\n

Decision

\n
    \n
  1. 消息服务(MNS) 主题模型

    \n

    \"\"

    \n
      \n
    • 可订阅,并且可以通过 Tag 进行消息过滤;
    • \n
    • 只支持推送模式,每个消费者需要创建回调接口;
    • \n
    • 只支持外网地址推送,对内部服务来说,网络耗时太高。
    • \n
  2. \n
  3. 消息服务(MNS) 队列模型

    \n

    \"\"

    \n
      \n
    • 根据消费者创建队列,几个消费者就创建几个队列;
    • \n
    • 生产者根据消费者所需向其队列发送消息,即生产者需要发送相同消息至多个队列;
    • \n
    • 每增加一个消费者,都需更新所有对应生产者的代码,维护性太低。
    • \n
  4. \n
  5. 消息服务(MNS) 主题+队列模型

    \n

    \"\"

    \n
      \n
    • 根据消费者创建队列,几个消费者就创建几个队列;
    • \n
    • 生产着只需向主题队列发送消息,&lt;del&gt;消费者队列订阅所有主题队列的消息&lt;/del&gt;;
    • \n
    • &lt;del&gt;消费者需要接收所有消息,并在业务逻辑中过滤出自己需要处理的消息&lt;/del&gt;;
    • \n
    • 消费者队列可以按 tag 进行过滤;
    • \n
    • 消费者完整消费自己的队列即可。
    • \n
  6. \n
  7. 消息队列(ONS) MQ

    \n

    \"\"

    \n
      \n
    • 总共只需一个 topic 队列,各个消费者通过 Tag 进行过滤;
    • \n
    • 完美支持我们的使用场景;
    • \n
    • 不提供 Python SDK。
    • \n
  8. \n
\n

Consequences

\n
    \n
  • 方案 1,2 不用考虑;
  • \n
  • 使用方案 3,所有消费者需要处理所有的消息;
  • \n
  • 使用方案 4,需先实现其 SDK。
  • \n
\n

\"\"

\n

官方不建议用方案 4,我们尝试调试也不顺畅,所以决定使用方案 3。

\n

Refs:

\n\n

44. 泛域名解析

\n

Date: 2017-08-25

\n

Status

\n

Accepted

\n

Context

\n

随着会找房平台第三方公寓的入驻,我们需要手动添加大量的公寓二级域名于 DNS 中,如,ayk.huizhaofang.com, jingyu.huizhaofang.com 等。

\n
    \n
  1. 整个流程依赖域名管理者;
  2. \n
  3. DNS 管理控制台维护这些记录很麻烦,并将原有专用域名淹没在大量记录中;
  4. \n
  5. 网站做了前后端分离,起始页永远返回状态为 200 的页面。
  6. \n
\n

Decision

\n
    \n
  1. DNS 记录添加泛解析;
  2. \n
  3. Nginx server name 添加泛解析;
  4. \n
  5. 不受约束的泛解析,会使所有子域名返回状态为 200 的页面,导致搜索引擎降权;
  6. \n
  7. 使用 include /path/to/server_names; 可以通过独立的文件解决此问题,并可对新添加的子域名做 code review;
  8. \n
  9. 上面的方案需要每次更改后做 nginx reload;有个想法是通过 lua 从 redis 中获取支持的子域名,进行判断并过滤;
  10. \n
\n

Consequences

\n
    \n
  1. include 方案:当前最简单,且有审核机制,但运维参与较重,需经常重启 nginx;
  2. \n
  3. lua + redis 方案:\n
      \n
    • 每次请求需查询 redis;
    • \n
    • 需做一个对应的管理系统进行子域名的管理。
    • \n
  4. \n
\n

Refs:

\n\n\n
\n
\n\n\n\n\n<|start_filename|>examples/export-3.html<|end_filename|>\n\n\n\n \n \n \n ADR Documents\n\n \n\n\n
\n
\n ADR\n \n
\n
\n
\n \n
\n

1. Record architecture decisions

\n

Date: 12/02/2016

\n

Status

\n

Accepted

\n

Context

\n

We need to record the architectural decisions made on this project.

\n

Decision

\n

We will use Architecture Decision Records, as described by in this article: http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions

\n

Consequences

\n

See 's article, linked above.

\n

2. Implement as shell scripts

\n

Date: 12/02/2016

\n

Status

\n

Accepted

\n

Context

\n

ADRs are plain text files stored in a subdirectory of the project.

\n

The tool needs to create new files and apply small edits to\nthe Status section of existing files.

\n

Decision

\n

The tool is implemented as shell scripts that use standard Unix\ntools -- grep, sed, awk, etc.

\n

Consequences

\n

The tool won't support Windows. Being plain text files, ADRs can\nbe created by hand and edited in any text editor. This tool just\nmakes the process more convenient.

\n

Development will have to cope with differences between Unix\nvariants, particularly Linux and MacOS X.

\n

3. Single command with subcommands

\n

Date: 12/02/2016

\n

Status

\n

Accepted

\n

Context

\n

The tool provides a number of related commands to create\nand manipulate architecture decision records.

\n

How can the user find out about the commands that are available?

\n

Decision

\n

The tool defines a single command, called adr.

\n

The first argument to adr (the subcommand) specifies the\naction to perform. Further arguments are interpreted by the\nsubcommand.

\n

Running adr without any arguments lists the available\nsubcommands.

\n

Subcommands are implemented as scripts in the same\ndirectory as the adr script. E.g. the subcommand new is\nimplemented as the script adr-new, the subcommand help\nas the script adr-help and so on.

\n

Helper scripts that are part of the implementation but not\nsubcommands follow a different naming convention, so that\nsubcommands can be listed by filtering and transforming script\nfile names.

\n

Consequences

\n

Users can more easily explore the capabilities of the tool.

\n

Users are already used to this style of command-line tool. For\nexample, Git works this way.

\n

Each subcommand can be implemented in the most appropriate\nlanguage.

\n

4. Markdown format

\n

Date: 12/02/2016

\n

Status

\n

Accepted

\n

Context

\n

The decision records must be stored in a plain text format:

\n
    \n
  • This works well with version control systems.

  • \n
  • It allows the tool to modify the status of records and insert\nhyperlinks when one decision supercedes another.

  • \n
  • Decisions can be read in the terminal, IDE, version control\nbrowser, etc.

  • \n
\n

People will want to use some formatting: lists, code examples,\nand so on.

\n

People will want to view the decision records in a more readable\nformat than plain text, and maybe print them out.

\n

Decision

\n

Record architecture decisions in Markdown format.

\n

Consequences

\n

Decisions can be read in the terminal.

\n

Decisions will be formatted nicely and hyperlinked by the\nbrowsers of project hosting sites like GitHub and Bitbucket.

\n

Tools like Pandoc can be used to convert\nthe decision records into HTML or PDF.

\n

5. Help comments

\n

Date: 13/02/2016

\n

Status

\n

Accepted

\n

Context

\n

The tool will have a help subcommand to provide documentation\nfor users.

\n

It's nice to have usage documentation in the script files\nthemselves, in comments. When reading the code, that's the first\nplace to look for information about how to run a script.

\n

Decision

\n

Write usage documentation in comments in the source file.

\n

Distinguish between documentation comments and normal comments.\nDocumentation comments have two hash characters at the start of\nthe line.

\n

The adr help command can parse comments out from the script\nusing the standard Unix tools grep and cut.

\n

Consequences

\n

No need to maintain help text in a separate file.

\n

Help text can easily be kept up to date as the script is edited.

\n

There's no automated check that the help text is up to date. The\ntests do not work well as documentation for users, and the help\ntext is not easily cross-checked against the code.

\n

This won't work if any subcommands are not implemented as scripts\nthat use '#' as a comment character.

\n

6. Packaging and distribution in other version control repositories

\n

Date: 16/02/2016

\n

Status

\n

Accepted

\n

Context

\n

Users want to install adr-tools with their preferred package\nmanager. For example, Ubuntu users use apt, RedHat users use\nyum and Mac OS X users use Homebrew.

\n

The developers of adr-tools don't know how, nor have permissions,\nto use all these packaging and distribution systems. Therefore packaging\nand distribution must be done by &quot;downstream&quot; parties.

\n

The developers of the tool should not favour any one particular\npackaging and distribution solution.

\n

Decision

\n

The adr-tools project will not contain any packaging or\ndistribution scripts and config.

\n

Packaging and distribution will be managed by other projects in\nseparate version control repositories.

\n

Consequences

\n

The git repo of this project will be simpler.

\n

Eventually, users will not have to use Git to get the software.

\n

We will have to tag releases in the adr-tools repository so that\npackaging projects know what can be published and how it should be\nidentified.

\n

We will document how users can install the software in this\nproject's README file.

\n

7. Invoke adr-config executable to get configuration

\n

Date: 17/12/2016

\n

Status

\n

Accepted

\n

Context

\n

Packagers (e.g. Homebrew developers) want to configure adr-tools to match the conventions of their installation.

\n

Currently, this is done by sourcing a file config.sh, which should sit beside the adr executable.

\n

This name is too common.

\n

The config.sh file is not executable, and so doesn't belong in a bin directory.

\n

Decision

\n

Replace config.sh with an executable, named adr-config that outputs configuration.

\n

Each script in ADR Tools will eval the output of adr-config to configure itself.

\n

Consequences

\n

Configuration within ADR Tools is a little more complicated.

\n

Packagers can write their own implementation of adr-config that outputs configuration that matches the platform's installation conventions, and deploy it next to the adr script.

\n

To make development easier, the implementation of adr-config in the project's src/ directory will output configuration that lets the tool to run from the src/ directory without any installation step. (Packagers should not include this script in a deployable package.)

\n

8. Use ISO 8601 Format for Dates

\n

Date: 21/02/2017

\n

Status

\n

Accepted

\n

Context

\n

adr-tools seeks to communicate the history of architectural decisions of a\nproject. An important component of the history is the time at which a decision\nwas made.

\n

To communicate effectively, adr-tools should present information as\nunambiguously as possible. That means that culture-neutral data formats should\nbe preferred over culture-specific formats.

\n

Existing adr-tools deployments format dates as dd/mm/yyyy by default. That\nformatting is common formatting in the United Kingdom (where the adr-tools\nproject was originally written), but is easily confused with the mm/dd/yyyy\nformat preferred in the United States.

\n

The default date format may be overridden by setting ADR_DATE in config.sh.

\n

Decision

\n

adr-tools will use the ISO 8601 format for dates: yyyy-mm-dd

\n

Consequences

\n

Dates are displayed in a standard, culture-neutral format.

\n

The UK-style and ISO 8601 formats can be distinguished by their separator\ncharacter. The UK-style dates used a slash (/), while the ISO dates use a\nhyphen (-).

\n

Prior to this decision, adr-tools was deployed using the UK format for dates.\nAfter adopting the ISO 8601 format, existing deployments of adr-tools must do\none of the following:

\n
    \n
  • Accept mixed formatting of dates within their documentation library.
  • \n
  • Update existing documents to use ISO 8601 dates by running adr upgrade-repository
  • \n
\n\n
\n
\n\n\n"},"max_stars_repo_name":{"kind":"string","value":"iT-Boyer/adr"}}},{"rowIdx":242,"cells":{"content":{"kind":"string","value":"<|start_filename|>src/com/wuyr/dmifier/utils/ReflectUtil.kt<|end_filename|>\n@file:Suppress(\"UNCHECKED_CAST\", \"KDocMissingDocumentation\", \"PublicApiImplicitType\", \"unused\")\n\npackage com.wuyr.dmifier.utils\n\nimport com.jetbrains.rd.util.string.println\nimport java.io.PrintWriter\nimport java.io.StringWriter\nimport java.lang.reflect.Field\nimport java.lang.reflect.Method\nimport java.lang.reflect.Modifier\nimport kotlin.reflect.KClass\n\n/**\n * @author wuyr\n * @github https://github.com/wuyr/HookwormForAndroid\n * @since 2020-09-10 上午11:32\n */\nconst val TAG = \"ReflectUtil\"\n\n/**\n * 发生异常是否抛出(默认不抛出,只打印堆栈信息)\n */\nvar throwReflectException: Boolean = true\n\n/**\n * 给对象成员变量设置新的值(可以修改final属性,静态的基本类型除外)\n *\n * @param target 目标对象\n * @param fieldName 目标变量名\n * @param value 新的值\n *\n * @return true为成功\n */\nfun Class<*>.set(target: Any?, fieldName: String, value: Any?) = try {\n findField(fieldName).apply {\n isAccessible = true\n if (isLocked()) unlock()\n set(target, value)\n }\n true\n} catch (e: Exception) {\n if (throwReflectException) throw e else false\n}\n\nprivate fun Field.isLocked() = modifiers and Modifier.FINAL != 0\n\nprivate fun Field.unlock() = let { target ->\n try {\n Field::class.java.getDeclaredField(\"modifiers\")\n } catch (e: Exception) {\n Field::class.java.getDeclaredField(\"accessFlags\")\n }.run {\n isAccessible = true\n setInt(target, target.modifiers and Modifier.FINAL.inv())\n }\n}\n\n/**\n * 获取目标对象的变量值\n *\n * @param target 目标对象\n * @param fieldName 目标变量名\n *\n * @return 目标变量值(获取失败则返回null)\n */\nfun Class<*>.get(target: Any?, fieldName: String) = try {\n findField(fieldName).run {\n isAccessible = true\n get(target) as? T?\n }\n} catch (e: Exception) {\n if (throwReflectException) throw e else e.stackTraceString.println()\n null\n}\n\n/**\n * 调用目标对象的方法\n *\n * @param target 目标对象\n * @param methodName 目标方法名\n * @param paramsPairs 参数类型和参数值的键值对。示例:\n *
\n *  val view = LayoutInflater::class.invoke(layoutInflater, \"tryInflatePrecompiled\",\n *      Int::class to R.layout.view_test,\n *      Resource::class to context.resource,\n *      ViewGroup::class to rootView,\n *      Boolean::class to false\n *  )\n * 
\n *\n * @return 方法返回值\n */\nfun Class<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) = try {\n findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {\n isAccessible = true\n invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T?\n }\n} catch (e: Exception) {\n if (throwReflectException) throw e else e.stackTraceString.println()\n null\n}\n\n/**\n * 同上,此乃调用void方法,即无返回值\n */\nfun Class<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) {\n try {\n findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {\n isAccessible = true\n invoke(target, *paramsPairs.map { it.second }.toTypedArray())\n }\n } catch (e: Exception) {\n if (throwReflectException) throw e else e.stackTraceString.println()\n }\n}\n\n/**\n * 创建目标类对象\n *\n * @param paramsPairs 参数类型和参数值的键值对。示例:\n *
\n *  val context = ContextImpl::class.newInstance(\n *      ActivityThread::class to ...,\n *      LoadedApk::class to ...,\n *      String::class to ...,\n *      IBinder::class to ...,\n *  )\n *\n *  @return 目标对象新实例\n */\nfun  Class<*>.newInstance(vararg paramsPairs: Pair, Any?> = emptyArray()) = try {\n    getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run {\n        isAccessible = true\n        newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T?\n    }\n} catch (e: Exception) {\n    if (throwReflectException) throw e else e.stackTraceString.println()\n    null\n}\n\nfun Class<*>.findField(fieldName: String): Field {\n    declaredFields.forEach {\n        if (it.name == fieldName) {\n            return it\n        }\n    }\n    if (this == Any::class.java) {\n        throw NoSuchFieldException(fieldName)\n    } else {\n        if (isInterface) {\n            interfaces.forEach {\n                runCatching { it.findField(fieldName) }.getOrNull()?.run { return this }\n            }\n            throw NoSuchFieldException(fieldName)\n        } else return superclass.findField(fieldName)\n    }\n}\n\nfun Class<*>.findMethod(methodName: String, parameterTypes: Array> = emptyArray()): Method {\n    declaredMethods.forEach {\n        if (it.name == methodName && parameterTypes.contentEquals(it.parameterTypes)) {\n            return it\n        }\n    }\n    if (this == Any::class.java) {\n        throw NoSuchMethodException(parameterTypes.joinToString(prefix = \"$methodName(\", postfix = \")\") { it.name })\n    } else {\n        if (isInterface) {\n            interfaces.forEach {\n                runCatching { it.findMethod(methodName, parameterTypes) }.getOrNull()?.run { return this }\n            }\n            throw NoSuchMethodException(parameterTypes.joinToString(prefix = \"$methodName(\", postfix = \")\") { it.name })\n        } else return superclass.findMethod(methodName, parameterTypes)\n    }\n}\n\nfun  KClass<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) = try {\n    java.run {\n        findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {\n            isAccessible = true\n            invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T?\n        }\n    }\n} catch (e: Exception) {\n    if (throwReflectException) throw e else e.println()\n    null\n}\n\nfun KClass<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?> = emptyArray()) {\n    try {\n        java.run {\n            findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run {\n                isAccessible = true\n                invoke(target, *paramsPairs.map { it.second }.toTypedArray())\n            }\n        }\n    } catch (e: Exception) {\n        if (throwReflectException) throw e else e.stackTraceString.println()\n    }\n}\n\nfun  KClass<*>.newInstance(vararg paramsPairs: Pair, Any?> = emptyArray()) = try {\n    java.run {\n        getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run {\n            isAccessible = true\n            newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T?\n        }\n    }\n} catch (e: Exception) {\n    if (throwReflectException) throw e else e.stackTraceString.println()\n    null\n}\n\nfun String.set(target: Any?, fieldName: String, value: Any?) =\n    Class.forName(this).set(target, fieldName, value)\n\nfun  String.get(target: Any?, fieldName: String) =\n    Class.forName(this).get(target, fieldName)\n\nfun  String.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?>) =\n    Class.forName(this).invoke(target, methodName, *paramsPairs)\n\nfun String.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair, Any?>) =\n    Class.forName(this).invokeVoid(target, methodName, *paramsPairs)\n\nfun  String.newInstance(vararg paramsPairs: Pair, Any?>) =\n    Class.forName(this).newInstance(*paramsPairs)\n\nfun KClass<*>.set(target: Any?, fieldName: String, value: Any?) = java.set(target, fieldName, value)\n\nfun  KClass<*>.get(target: Any?, fieldName: String) = java.get(target, fieldName)\n\nval Throwable.stackTraceString: String\n    get() = StringWriter().use { sw ->\n        PrintWriter(sw).use { pw ->\n            printStackTrace(pw)\n            pw.flush()\n        }\n        sw.flush()\n    }.toString()\n\nfun Any?.println() = println(toString())\n\n<|start_filename|>src/com/wuyr/dmifier/actions/ViewCodeAction.kt<|end_filename|>\npackage com.wuyr.dmifier.actions\n\nimport com.intellij.openapi.actionSystem.AnAction\nimport com.intellij.openapi.actionSystem.AnActionEvent\nimport com.intellij.openapi.actionSystem.LangDataKeys\nimport com.intellij.openapi.actionSystem.PlatformDataKeys\nimport com.intellij.openapi.module.Module\nimport com.intellij.openapi.project.Project\nimport com.intellij.openapi.roots.*\nimport com.intellij.openapi.ui.Messages\nimport com.intellij.openapi.vfs.VirtualFile\nimport com.intellij.openapi.vfs.VirtualFileManager\nimport com.intellij.psi.PsiManager\nimport com.intellij.task.ProjectTaskManager\nimport com.intellij.util.io.URLUtil\nimport com.wuyr.dmifier.core.DMifier\nimport com.wuyr.dmifier.utils.invoke\nimport org.objectweb.asm.ClassReader\nimport org.objectweb.asm.util.TraceClassVisitor\nimport java.io.File\nimport java.io.FileInputStream\nimport java.io.PrintWriter\nimport java.io.StringWriter\nimport java.nio.file.Paths\n\nclass ViewCodeAction : AnAction() {\n\n    override fun update(e: AnActionEvent) {\n        e.presentation.isEnabled = e.project?.let { project ->\n            e.getData(PlatformDataKeys.VIRTUAL_FILE)?.let { file ->\n                PsiManager.getInstance(project).findFile(file)?.fileType?.name == \"JAVA\"\n            }\n        } ?: false\n    }\n\n    override fun actionPerformed(e: AnActionEvent) {\n        e.project?.compileAndShow(e.getData(LangDataKeys.PSI_FILE)?.virtualFile ?: return)\n    }\n\n    private fun Project.compileAndShow(target: VirtualFile) {\n        ProjectTaskManager.getInstance(this).compile(target).onSuccess { result ->\n            if (!result.hasErrors()) {\n                val file = PsiManager.getInstance(this).findFile(target) ?: return@onSuccess\n                val packageName = file::class.invoke(file, \"getPackageName\")!!\n                this.findClassFromOutputDirectories(target, packageName)?.let { outputFile ->\n                    Messages.showMessageDialog(outputFile.convertToDexMakerCode(), \"DexMaker\", null)\n                }\n            }\n        }\n    }\n\n    private fun VirtualFile.convertToDexMakerCode() = StringWriter(2048).use { sw ->\n        runCatching {\n            ClassReader(FileInputStream(path)).accept(TraceClassVisitor(null, DMifier(), PrintWriter(sw)), 0)\n        }.getOrElse {\n            it.printStackTrace(PrintWriter(sw))\n        }\n        sw.toString()\n    }\n\n    private fun Project.findClassFromOutputDirectories(target: VirtualFile, packageName: String): VirtualFile? {\n        ProjectRootManager.getInstance(this).fileIndex.getModuleForFile(target)?.let { module ->\n            module.getOutputDirectories(module.getModuleScope(false).contains(target)).forEach { outputDir ->\n                outputDir?.let { dir ->\n                    VirtualFileManager.getInstance().getFileSystem(URLUtil.FILE_PROTOCOL).refreshAndFindFileByPath(\n                            Paths.get(dir, packageName, \"${target.nameWithoutExtension}.class\").toString()\n                    )?.also { outputFile ->\n                        outputFile.refresh(false, false)\n                        return outputFile\n                    }\n                }\n            }\n        }\n        return null\n    }\n\n    private fun Module.getOutputDirectories(isRelease: Boolean) = ArrayList().also { result ->\n        CompilerModuleExtension.getInstance(this)?.let { moduleExtension ->\n            CompilerProjectExtension.getInstance(project)?.let { projectExtension ->\n                (if (isRelease) moduleExtension.compilerOutputPath else moduleExtension.compilerOutputPathForTests)\n                        ?.let { result.add(it.path) } ?: projectExtension.compilerOutput?.let { result.add(it.path) }\n                OrderEnumerationHandler.EP_NAME.extensions.forEach { factory ->\n                    if (factory.isApplicable(this)) {\n                        ArrayList().also { urls ->\n                            @Suppress(\"OverrideOnly\")\n                            factory.createHandler(this).addCustomModuleRoots(\n                                    OrderRootType.CLASSES, ModuleRootManager.getInstance(this), urls, isRelease, !isRelease\n                            )\n                        }.forEach { url ->\n                            result.add(VirtualFileManager.extractPath(url).replace('/', File.separatorChar))\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n<|start_filename|>src/com/wuyr/dmifier/core/DMifier.kt<|end_filename|>\npackage com.wuyr.dmifier.core\n\nimport org.objectweb.asm.*\nimport org.objectweb.asm.util.Printer\nimport java.lang.reflect.Modifier\nimport java.util.*\n\nclass DMifier : Printer(589824) {\n\n    private fun StringBuilder.newLine() = append(\"\\n\")\n\n    private var superTypeId = \"\"\n\n    override fun visit(\n            version: Int, access: Int, name: String?, signature: String?, superName: String, interfaces: Array\n    ) {\n        appendCodeBlockAndAdd {\n            append(\"TypeId classId = \")\n            append(name?.typeId)\n            append(\";\")\n            newLine()\n            append(\"String fileName = \\\"\")\n            val simpleName = name?.run {\n                val lastSlashIndex = lastIndexOf('/')\n                if (lastSlashIndex == -1) name\n                else substring(lastSlashIndex + 1).replace(\"[-()]\".toRegex(), \"_\")\n            } ?: \"DexMakerClass\"\n            append(simpleName)\n            append(\".generated\\\";\")\n            newLine()\n            append(\"DexMaker dexMaker = new DexMaker();\")\n            newLine()\n            append(\"TypeId[] interfacesTypes = new TypeId[\")\n            append(interfaces.size)\n            append(\"];\")\n            newLine()\n            interfaces.forEachIndexed { index, content ->\n                append(\"interfacesTypes[\")\n                append(index)\n                append(\"] = \")\n                append(content.typeId)\n                append(\";\")\n                newLine()\n            }\n            append(\"dexMaker.declare(classId, fileName, \")\n            append((access or ACCESS_CLASS).accessFlag)\n            append(\", \")\n            superTypeId = superName.typeId\n            append(superTypeId)\n            append(\", interfacesTypes);\")\n            newLine()\n        }\n    }\n\n    override fun visit(name: String?, value: Any?) {\n        appendCodeBlockAndAdd {\n            append(\"TypeId classId = \")\n            append(name?.typeId)\n            append(\";\")\n            newLine()\n            append(\"String fileName = \\\"\")\n            val simpleName = name?.run {\n                val lastSlashIndex = lastIndexOf('/')\n                if (lastSlashIndex == -1) name\n                else substring(lastSlashIndex + 1).replace(\"[-()]\".toRegex(), \"_\")\n            } ?: \"DexMakerClass\"\n            append(simpleName)\n            append(\".generated\\\";\")\n            newLine()\n            append(\"DexMaker dexMaker = new DexMaker();\")\n            newLine()\n            append(\"dexMaker.declare(classId, fileName, \")\n            append(\"Modifier.PUBLIC\")\n            append(\");\")\n            newLine()\n        }\n    }\n\n    private val Int.accessFlag: String\n        get() = StringBuilder().also { sb ->\n            if (this == 0) {\n                sb.append(\"0\")\n            } else {\n                if ((this and Modifier.PUBLIC) != 0) sb.append(\"Modifier.PUBLIC | \")\n                if ((this and Modifier.PRIVATE) != 0) sb.append(\"Modifier.PRIVATE | \")\n                if ((this and Modifier.PROTECTED) != 0) sb.append(\"Modifier.PROTECTED | \")\n                if ((this and Modifier.STATIC) != 0) sb.append(\"Modifier.STATIC | \")\n                if ((this and Modifier.FINAL) != 0) sb.append(\"Modifier.FINAL | \")\n                if ((this and Modifier.SYNCHRONIZED) != 0 && this and ACCESS_CLASS == 0) sb.append(\"Modifier.SYNCHRONIZED | \")\n                if ((this and Modifier.VOLATILE) != 0) sb.append(\"Modifier.VOLATILE | \")\n                if ((this and Modifier.TRANSIENT) != 0 && this and ACCESS_FIELD != 0) sb.append(\"Modifier.TRANSIENT | \")\n                if ((this and Modifier.NATIVE) != 0 && this and (ACCESS_CLASS or ACCESS_FIELD) == 0) sb.append(\"Modifier.NATIVE | \")\n                if ((this and Modifier.INTERFACE) != 0) sb.append(\"Modifier.INTERFACE | \")\n                if ((this and Modifier.ABSTRACT) != 0) sb.append(\"Modifier.ABSTRACT | \")\n                if ((this and Modifier.STRICT) != 0) sb.append(\"Modifier.STRICT | \")\n                if (sb.isEmpty()) {\n                    sb.append(\"0\")\n                } else {\n                    sb.deleteCharAt(sb.lastIndex)\n                    sb.deleteCharAt(sb.lastIndex)\n                    sb.deleteCharAt(sb.lastIndex)\n                }\n            }\n        }.toString()\n\n    override fun visitSource(source: String?, debug: String?) {\n\n    }\n\n    override fun visitOuterClass(owner: String?, name: String?, descriptor: String?) {\n\n    }\n\n    override fun visitClassAnnotation(descriptor: String?, visible: Boolean): Printer {\n\n        return this\n    }\n\n    override fun visitClassAttribute(attribute: Attribute?) {\n\n    }\n\n    override fun visitInnerClass(name: String?, outerName: String?, innerName: String?, access: Int) {\n\n    }\n\n    override fun visitField(access: Int, name: String, descriptor: String, signature: String?, value: Any?): Printer {\n        appendCodeBlockAndAdd {\n            append(\"dexMaker.declare(classId.getField(\")\n            append(descriptor.typeId)\n            append(\", \\\"\")\n            append(name)\n            append(\"\\\"), \")\n            append((access or ACCESS_FIELD).accessFlag)\n            append(\", \")\n            append(value)\n            append(\");\")\n        }\n        return this\n    }\n\n    private var currentMethodParameters = emptyList()\n    private var currentMethodReturnType = \"\"\n    private var isStaticMethod = false\n\n    override fun visitMethod(\n            access: Int, name: String, descriptor: String, signature: String?, exceptions: Array?\n    ): Printer {\n        appendCodeBlockAndAdd {\n            newLine()\n            append(\"{\")\n            newLine()\n            val parameters = descriptor.getParameterTypes()\n            isStaticMethod = (access and Modifier.STATIC) != 0\n            currentMethodParameters = parameters\n            currentMethodReturnType = descriptor.getReturnType().typeId\n            localCount = currentMethodParameters.size + if (isStaticMethod) 0 else 1\n            append(\"MethodId methodId = classId.\")\n            when (name) {\n                \"\" -> {\n                    append(\"getConstructor(\")\n                    if (parameters.isNotEmpty()) {\n                        parameters.forEach {\n                            append(it.typeId)\n                            append(\", \")\n                        }\n                        deleteCharAt(lastIndex)\n                        deleteCharAt(lastIndex)\n                    }\n                    append(\");\")\n                }\n                \"\" -> {\n                    append(\"getStaticInitializer();\")\n                }\n                else -> {\n                    append(\"getMethod(\")\n                    append(currentMethodReturnType)\n                    append(\", \\\"\")\n                    append(name)\n                    if (parameters.isEmpty()) {\n                        append(\"\\\"\")\n                    } else {\n                        append(\"\\\", \")\n                        parameters.forEach {\n                            append(it.typeId)\n                            append(\", \")\n                        }\n                        deleteCharAt(lastIndex)\n                        deleteCharAt(lastIndex)\n                    }\n                    append(\");\")\n                }\n            }\n            newLine()\n            append(\"Code methodCodeBlock = dexMaker.declare(methodId, \")\n            append(access.accessFlag)\n            append(\");\")\n            newLine()\n        }\n        return this\n    }\n\n    private fun String.getReturnType() = substring(lastIndexOf(')') + 1)\n\n    private fun String.getParameterTypes() = substring(1, lastIndexOf(')')).run {\n        ArrayList().apply {\n            split(\";\").forEach { type ->\n                if (type.isNotEmpty()) {\n                    if (type.contains('[') && type.indexOf('[') != type.lastIndexOf('[')) {\n                        type.split(\"[\").forEach {\n                            if (it.isNotEmpty()) {\n                                addParameter(\"[$it\")\n                            }\n                        }\n                    } else {\n                        addParameter(type)\n                    }\n                }\n            }\n            removeIf { it.isEmpty() }\n        }\n    }\n\n    private fun ArrayList.addParameter(type: String) {\n        if (type.startsWith('L') || type.startsWith(\"[L\")) {\n            add(type)\n        } else {\n            val index = type.indexOf(if (type.contains('[')) '[' else 'L')\n            if (index == 0 && type.length >= 2) {\n                add(type.substring(0, 2))\n                add(type.substring(2, type.length))\n            } else if (index > -1) {\n                type.substring(0, index).forEach { c -> add(c.toString()) }\n                add(type.substring(index, type.length))\n            } else {\n                type.forEach { c -> add(c.toString()) }\n            }\n        }\n    }\n\n    private val String.typeId: String\n        get() = when (this) {\n            \"Z\" -> \"TypeId.BOOLEAN\"\n            \"C\" -> \"TypeId.CHAR\"\n            \"F\" -> \"TypeId.FLOAT\"\n            \"D\" -> \"TypeId.DOUBLE\"\n            \"B\" -> \"TypeId.BYTE\"\n            \"S\" -> \"TypeId.SHORT\"\n            \"I\" -> \"TypeId.INT\"\n            \"J\" -> \"TypeId.LONG\"\n            \"V\" -> \"TypeId.VOID\"\n            else -> StringBuilder().also { sb ->\n                sb.append(\"TypeId.get(\\\"\")\n                if ((!startsWith('L')) && !startsWith('[')) sb.append('L')\n                sb.append(this)\n                if (!endsWith(';') && length != 2) sb.append(';')\n                sb.append(\"\\\")\")\n            }.toString()\n        }\n\n    private fun String.getMethodId(name: String, returnType: String, parameterTypes: List) = appendCodeBlock {\n        append(typeId)\n        append(\".getMethod(\")\n        append(returnType.typeId)\n        append(\", \\\"\")\n        append(name)\n        if (parameterTypes.isEmpty()) {\n            append(\"\\\")\")\n        } else {\n            append(\"\\\", \")\n            append(parameterTypes.joinToString { it.typeId })\n            append(\")\")\n        }\n    }\n\n    private fun String.getFieldId(type: String, name: String) = appendCodeBlock {\n        append(typeId)\n        append(\".getField(\")\n        append(type.typeId)\n        append(\", \\\"\")\n        append(name)\n        append(\"\\\")\")\n    }\n\n    override fun visitClassEnd() {\n\n    }\n\n    override fun visitEnum(name: String?, descriptor: String?, value: String?) {\n\n    }\n\n    override fun visitAnnotation(name: String?, descriptor: String?): Printer {\n\n        return this\n    }\n\n    override fun visitArray(name: String?): Printer {\n\n        return this\n    }\n\n    override fun visitAnnotationEnd() {\n\n    }\n\n    override fun visitFieldAnnotation(descriptor: String?, visible: Boolean): Printer {\n\n        return this\n    }\n\n    override fun visitFieldAttribute(attribute: Attribute?) {\n\n    }\n\n    override fun visitFieldEnd() {\n\n    }\n\n    override fun visitAnnotationDefault(): Printer {\n\n        return this\n    }\n\n    override fun visitMethodAnnotation(descriptor: String?, visible: Boolean): Printer {\n        return this\n    }\n\n    override fun visitParameterAnnotation(parameter: Int, descriptor: String?, visible: Boolean): Printer {\n        return this\n    }\n\n    override fun visitMethodAttribute(attribute: Attribute?) {\n\n    }\n\n    override fun visitCode() {\n\n    }\n\n    override fun visitFrame(type: Int, numLocal: Int, local: Array?, numStack: Int, stack: Array?) {\n\n    }\n\n    private var operationStringBuilder = StringBuilder()\n    private var declarationStringBuilder = StringBuilder()\n\n    private fun appendDeclarationCodeBlock(block: StringBuilder.() -> Unit) {\n        declarationStringBuilder.apply {\n            block()\n            newLine()\n        }\n    }\n\n    private fun appendOperationCodeBlock(appendNewLine: Boolean = true, block: StringBuilder.() -> Unit) {\n        operationStringBuilder.apply {\n            block()\n            if (appendNewLine) {\n                newLine()\n            }\n        }\n    }\n\n    private fun flushTempCodeBlock() {\n        declarationStringBuilder.newLine()\n        text.add(declarationStringBuilder.toString())\n        text.add(operationStringBuilder.toString())\n        declarationStringBuilder.setLength(0)\n        operationStringBuilder.setLength(0)\n    }\n\n    // localName : typeId\n    private val stack = LinkedList>()\n\n    private var localCount = 0\n    private var tempLocalCount = 0\n    private val localNames = HashMap>()\n\n    private fun newLocalName(typeId: String, store: Boolean = false, conflictLocal: String? = null) =\n            if (store && conflictLocal != null) {\n                var currentConflictLocal = conflictLocal!!\n                do {\n                    currentConflictLocal = \"${currentConflictLocal}_append\"\n                } while (localNames.containsKey(currentConflictLocal))\n                localNames[currentConflictLocal] = currentConflictLocal to typeId\n                currentConflictLocal\n            } else (if (store) \"local${localCount++}\" else \"tempLocal${tempLocalCount++}\").also { name ->\n                if (store) {\n                    if (typeId == \"TypeId.LONG\" || typeId == \"TypeId.DOUBLE\") {\n                        localCount++\n                    }\n                    localNames[name] = name to typeId\n                }\n            }\n\n    private fun getLocalName(index: Int): Pair? {\n        var localName = \"local$index\"\n        while (localNames.containsKey(\"${localName}_append\")) {\n            localName = \"${localName}_append\"\n        }\n        return localNames[localName]\n    }\n\n    private fun cast(targetType: String) {\n        val typeId = targetType.typeId\n        val output = newLocalName(typeId)\n        appendDeclarationCodeBlock {\n            append(\"Local \")\n            append(output)\n            append(\" = methodCodeBlock.newLocal(\")\n            append(typeId)\n            append(\");\")\n        }\n        appendOperationCodeBlock {\n            append(\"methodCodeBlock.cast(\")\n            append(output)\n            append(\", \")\n            append(stack.pop().first)\n            append(\");\")\n        }\n        stack.push(output to typeId)\n    }\n\n    private fun loadConstant(type: String, value: Any?) {\n        val typeId = type.typeId\n        val output = newLocalName(typeId)\n        appendDeclarationCodeBlock {\n            append(\"Local \")\n            append(output)\n            append(\" = methodCodeBlock.newLocal(\")\n            append(typeId)\n            append(\");\")\n        }\n        appendOperationCodeBlock {\n            append(\"methodCodeBlock.loadConstant(\")\n            append(output)\n            append(\", \")\n            append(value)\n            append(\");\")\n        }\n        stack.push(output to typeId)\n    }\n\n    override fun visitInsn(opcode: Int) {\n        when (opcode) {\n            Opcodes.ACONST_NULL -> loadConstant(\"java/lang/Object\", null)\n            Opcodes.ICONST_M1 -> loadConstant(\"I\", -1)\n            Opcodes.ICONST_0 -> loadConstant(\"I\", 0)\n            Opcodes.ICONST_1 -> loadConstant(\"I\", 1)\n            Opcodes.ICONST_2 -> loadConstant(\"I\", 2)\n            Opcodes.ICONST_3 -> loadConstant(\"I\", 3)\n            Opcodes.ICONST_4 -> loadConstant(\"I\", 4)\n            Opcodes.ICONST_5 -> loadConstant(\"I\", 5)\n            Opcodes.LCONST_0 -> loadConstant(\"J\", 0)\n            Opcodes.LCONST_1 -> loadConstant(\"J\", 1)\n            Opcodes.FCONST_0 -> loadConstant(\"F\", 0)\n            Opcodes.FCONST_1 -> loadConstant(\"F\", 1)\n            Opcodes.FCONST_2 -> loadConstant(\"F\", 2)\n            Opcodes.DCONST_0 -> loadConstant(\"D\", 0)\n            Opcodes.DCONST_1 -> loadConstant(\"D\", 1)\n\n            Opcodes.IALOAD, Opcodes.LALOAD, Opcodes.FALOAD, Opcodes.DALOAD,\n            Opcodes.AALOAD, Opcodes.BALOAD, Opcodes.CALOAD, Opcodes.SALOAD -> {\n                val typeId = stack[1].second.replaceFirst(\"[\", \"\")\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.aget(\")\n                    append(output)\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\");\")\n                    stack.pop()\n                    stack.pop()\n                }\n                stack.push(output to typeId)\n            }\n\n            Opcodes.IASTORE, Opcodes.LASTORE, Opcodes.FASTORE, Opcodes.DASTORE,\n            Opcodes.AASTORE, Opcodes.BASTORE, Opcodes.CASTORE, Opcodes.SASTORE -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.aput(\")\n                    append(stack[2].first)\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\");\")\n                    stack.pop()\n                    stack.pop()\n                    stack.pop()\n                }\n            }\n\n            Opcodes.ARRAYLENGTH -> {\n                val typeId = \"TypeId.INT\"\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.arrayLength(\")\n                    append(output)\n                    append(\", \")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n                stack.push(output to typeId)\n            }\n\n            Opcodes.L2I, Opcodes.F2I, Opcodes.D2I -> cast(\"I\")\n            Opcodes.I2L, Opcodes.F2L, Opcodes.D2L -> cast(\"J\")\n            Opcodes.I2F, Opcodes.L2F, Opcodes.D2F -> cast(\"F\")\n            Opcodes.I2D, Opcodes.L2D, Opcodes.F2D -> cast(\"D\")\n            Opcodes.I2B -> cast(\"B\")\n            Opcodes.I2C -> cast(\"C\")\n            Opcodes.I2S -> cast(\"S\")\n\n            Opcodes.IADD -> binaryOp(\"I\", \"BinaryOp.ADD\")\n            Opcodes.LADD -> binaryOp(\"J\", \"BinaryOp.ADD\")\n            Opcodes.FADD -> binaryOp(\"F\", \"BinaryOp.ADD\")\n            Opcodes.DADD -> binaryOp(\"D\", \"BinaryOp.ADD\")\n\n            Opcodes.ISUB -> binaryOp(\"I\", \"BinaryOp.SUBTRACT\")\n            Opcodes.LSUB -> binaryOp(\"J\", \"BinaryOp.SUBTRACT\")\n            Opcodes.FSUB -> binaryOp(\"F\", \"BinaryOp.SUBTRACT\")\n            Opcodes.DSUB -> binaryOp(\"D\", \"BinaryOp.SUBTRACT\")\n\n            Opcodes.IMUL -> binaryOp(\"I\", \"BinaryOp.MULTIPLY\")\n            Opcodes.LMUL -> binaryOp(\"J\", \"BinaryOp.MULTIPLY\")\n            Opcodes.FMUL -> binaryOp(\"F\", \"BinaryOp.MULTIPLY\")\n            Opcodes.DMUL -> binaryOp(\"D\", \"BinaryOp.MULTIPLY\")\n\n            Opcodes.IDIV -> binaryOp(\"I\", \"BinaryOp.DIVIDE\")\n            Opcodes.LDIV -> binaryOp(\"J\", \"BinaryOp.DIVIDE\")\n            Opcodes.FDIV -> binaryOp(\"F\", \"BinaryOp.DIVIDE\")\n            Opcodes.DDIV -> binaryOp(\"D\", \"BinaryOp.DIVIDE\")\n\n            Opcodes.IREM -> binaryOp(\"I\", \"BinaryOp.REMAINDER\")\n            Opcodes.LREM -> binaryOp(\"J\", \"BinaryOp.REMAINDER\")\n            Opcodes.FREM -> binaryOp(\"F\", \"BinaryOp.REMAINDER\")\n            Opcodes.DREM -> binaryOp(\"D\", \"BinaryOp.REMAINDER\")\n\n            Opcodes.INEG -> binaryOp(\"I\", \"BinaryOp.NEGATE\")\n            Opcodes.LNEG -> binaryOp(\"J\", \"BinaryOp.NEGATE\")\n            Opcodes.FNEG -> binaryOp(\"F\", \"BinaryOp.NEGATE\")\n            Opcodes.DNEG -> binaryOp(\"D\", \"BinaryOp.NEGATE\")\n\n            Opcodes.ISHL -> binaryOp(\"I\", \"BinaryOp.SHIFT_LEFT\")\n            Opcodes.LSHL -> binaryOp(\"J\", \"BinaryOp.SHIFT_LEFT\")\n\n            Opcodes.ISHR -> binaryOp(\"I\", \"BinaryOp.SHIFT_RIGHT\")\n            Opcodes.LSHR -> binaryOp(\"J\", \"BinaryOp.SHIFT_RIGHT\")\n\n            Opcodes.IUSHR -> binaryOp(\"I\", \"BinaryOp.UNSIGNED_SHIFT_RIGHT\")\n            Opcodes.LUSHR -> binaryOp(\"J\", \"BinaryOp.UNSIGNED_SHIFT_RIGHT\")\n\n            Opcodes.IAND -> binaryOp(\"I\", \"BinaryOp.AND\")\n            Opcodes.LAND -> binaryOp(\"J\", \"BinaryOp.AND\")\n\n            Opcodes.IOR -> binaryOp(\"I\", \"BinaryOp.OR\")\n            Opcodes.LOR -> binaryOp(\"J\", \"BinaryOp.OR\")\n\n            Opcodes.IXOR -> binaryOp(\"I\", \"BinaryOp.XOR\")\n            Opcodes.LXOR -> binaryOp(\"J\", \"BinaryOp.XOR\")\n\n            Opcodes.LCMP -> {\n                val typeId = \"TypeId.INT\"\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(TypeId.INT);\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.compareLongs(\")\n                    append(output)\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\");\")\n                    stack.pop()\n                    stack.pop()\n                }\n                stack.push(output to typeId)\n            }\n\n            Opcodes.FCMPL, Opcodes.FCMPG, Opcodes.DCMPL, Opcodes.DCMPG -> {\n                val typeId = \"TypeId.INT\"\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(TypeId.INT);\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.compareFloatingPoint(\")\n                    append(output)\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\", \")\n                    append(if (opcode == Opcodes.FCMPG || opcode == Opcodes.DCMPG) 1 else -1)\n                    append(\");\")\n                    stack.pop()\n                    stack.pop()\n                }\n                stack.push(output to typeId)\n            }\n\n            Opcodes.IRETURN, Opcodes.LRETURN, Opcodes.FRETURN, Opcodes.DRETURN, Opcodes.ARETURN -> {\n                appendOperationCodeBlock {\n                    if (stack.peek().second != currentMethodReturnType) {\n                        stack.push(store(currentMethodReturnType) to currentMethodReturnType)\n                    }\n                    append(\"methodCodeBlock.returnValue(\")\n                    append(stack.pop().first)\n                    append(\");\")\n                    stack.clear()\n                }\n            }\n\n            Opcodes.RETURN -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.returnVoid();\")\n                    stack.clear()\n                }\n            }\n            Opcodes.POP -> {\n                stack.pop()\n            }\n            Opcodes.DUP -> {\n                if (!pendingNewInstance) {\n                    stack.push(stack.peek())\n                }\n            }\n            Opcodes.MONITORENTER -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.monitorEnter(\")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n            }\n            Opcodes.MONITOREXIT -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.monitorExit(\")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n            }\n            Opcodes.ATHROW -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.throwValue(\")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n            }\n        }\n\n    }\n\n    private fun binaryOp(type: String, op: String) {\n        val typeId = type.typeId\n        val output = newLocalName(typeId)\n        appendDeclarationCodeBlock {\n            append(\"Local \")\n            append(output)\n            append(\" = methodCodeBlock.newLocal(\")\n            append(typeId)\n            append(\");\")\n        }\n        appendOperationCodeBlock {\n            append(\"methodCodeBlock.op(\")\n            append(op)\n            append(\", \")\n            append(output)\n            append(\", \")\n            append(stack[1].first)\n            append(\", \")\n            append(stack[0].first)\n            append(\");\")\n            stack.pop()\n            stack.pop()\n        }\n        stack.push(output to typeId)\n    }\n\n    override fun visitIntInsn(opcode: Int, operand: Int) {\n        when (opcode) {\n            Opcodes.BIPUSH -> loadConstant(\"B\", operand)\n            Opcodes.SIPUSH -> loadConstant(\"S\", operand)\n            Opcodes.NEWARRAY -> visitTypeInsn(\n                Opcodes.ANEWARRAY, when (operand) {\n                    4 -> \"Z\"\n                    5 -> \"C\"\n                    6 -> \"F\"\n                    7 -> \"D\"\n                    8 -> \"B\"\n                    9 -> \"S\"\n                    10 -> \"I\"\n                    11 -> \"J\"\n                    else -> return\n                }\n            )\n\n        }\n    }\n\n    override fun visitVarInsn(opcode: Int, index: Int) {\n        when (opcode) {\n            Opcodes.ILOAD, Opcodes.LLOAD, Opcodes.FLOAD, Opcodes.DLOAD, Opcodes.ALOAD -> {\n                val originLocalCount = currentMethodParameters.size + if (isStaticMethod) 0 else 1\n                if (index < originLocalCount) {\n                    if (index == 0 && !isStaticMethod) {\n                        stack.push(\"methodCodeBlock.getThis(classId)\" to \"classId\")\n                    } else {\n                        val realIndex = if (isStaticMethod) index else index - 1\n                        val typeId = currentMethodParameters[realIndex].typeId\n                        stack.push(\"methodCodeBlock.getParameter($realIndex, $typeId)\" to typeId)\n                    }\n                } else {\n                    stack.push(getLocalName(index))\n                }\n            }\n            Opcodes.ISTORE, Opcodes.LSTORE, Opcodes.FSTORE, Opcodes.DSTORE, Opcodes.ASTORE -> {\n                val currentTypeId = stack.peek().second\n                getLocalName(index)?.let { (targetLocal, targetTypeId) ->\n                    if (currentTypeId == targetTypeId) {\n                        store(currentTypeId, targetLocal)\n                    } else {\n                        store(currentTypeId, newLocalName(currentTypeId, true, targetLocal).also {\n                            appendDeclarationCodeBlock {\n                                append(\"Local \")\n                                append(it)\n                                append(\" = methodCodeBlock.newLocal(\")\n                                append(currentTypeId)\n                                append(\");\")\n                            }\n                        })\n                    }\n                } ?: store(currentTypeId)\n            }\n        }\n\n    }\n\n    private fun store(typeId: String, target: String? = null): String {\n        val output = target ?: run {\n            newLocalName(typeId, true).also {\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(it)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n            }\n        }\n        appendOperationCodeBlock {\n            append(\"methodCodeBlock.move(\")\n            append(output)\n            append(\", \")\n            append(stack.pop().first)\n            append(\");\")\n        }\n        return output\n    }\n\n    private var pendingNewInstance = false\n\n    override fun visitTypeInsn(opcode: Int, type: String) {\n        when (opcode) {\n            Opcodes.NEW -> {\n                pendingNewInstance = true\n            }\n            Opcodes.ANEWARRAY -> {\n                val ownerTypeId = (if (type.length == 1) \"[$type\" else \"[L$type\").typeId\n                val output = newLocalName(ownerTypeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(ownerTypeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.newArray(\")\n                    append(output)\n                    append(\", \")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n                stack.push(output to ownerTypeId)\n            }\n            Opcodes.CHECKCAST -> {\n                cast(type)\n            }\n            Opcodes.INSTANCEOF -> {\n                val typeId = type.typeId\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.instanceOfType(\")\n                    append(output)\n                    append(\", \")\n                    append(stack.pop().first)\n                    append(\", \")\n                    append(typeId)\n                    append(\");\")\n                }\n                stack.push(output to typeId)\n            }\n        }\n    }\n\n    override fun visitFieldInsn(opcode: Int, owner: String, name: String, descriptor: String) {\n        when (opcode) {\n            Opcodes.GETSTATIC -> {\n                val typeId = descriptor.typeId\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.sget(\")\n                    append(owner.getFieldId(descriptor, name))\n                    append(\", \")\n                    append(output)\n                    append(\");\")\n                }\n                stack.push(output to typeId)\n            }\n            Opcodes.PUTSTATIC -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.sput(\")\n                    append(owner.getFieldId(descriptor, name))\n                    append(\", \")\n                    append(stack.peek().first)\n                    append(\");\")\n                    if (popAfterPut) {\n                        popAfterPut = false\n                        stack.pop()\n                    }\n                }\n            }\n            Opcodes.GETFIELD -> {\n                val typeId = descriptor.typeId\n                val output = newLocalName(typeId)\n                appendDeclarationCodeBlock {\n                    append(\"Local \")\n                    append(output)\n                    append(\" = methodCodeBlock.newLocal(\")\n                    append(typeId)\n                    append(\");\")\n                }\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.iget(\")\n                    append(owner.getFieldId(descriptor, name))\n                    append(\", \")\n                    append(output)\n                    append(\", \")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n                stack.push(output to typeId)\n            }\n            Opcodes.PUTFIELD -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.iput(\")\n                    append(owner.getFieldId(descriptor, name))\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\");\")\n                    stack.pop()\n                    if (popAfterPut) {\n                        popAfterPut = false\n                        stack.pop()\n                    }\n                }\n            }\n        }\n    }\n\n    override fun visitInvokeDynamicInsn(\n            name: String?, descriptor: String?, bootstrapMethodHandle: Handle?, vararg bootstrapMethodArguments: Any?\n    ) {\n        //FIXME: 不支持INVOKE DYNAMIC\n    }\n\n    override fun visitJumpInsn(opcode: Int, label: Label) {\n        when (opcode) {\n            Opcodes.IFEQ, Opcodes.IFNE, Opcodes.IFLT, Opcodes.IFGE, Opcodes.IFGT, Opcodes.IFLE -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.compareZ(\")\n                    append(\n                            when (opcode) {\n                                Opcodes.IFEQ -> \"Comparison.EQ\"\n                                Opcodes.IFNE -> \"Comparison.NE\"\n                                Opcodes.IFLT -> \"Comparison.LT\"\n                                Opcodes.IFGE -> \"Comparison.GE\"\n                                Opcodes.IFGT -> \"Comparison.GT\"\n                                Opcodes.IFLE -> \"Comparison.LE\"\n                                else -> \"\"\n                            }\n                    )\n                    append(\", \")\n                    append(label)\n                    append(\", \")\n                    append(stack.pop().first)\n                    append(\");\")\n                }\n            }\n            Opcodes.IF_ICMPEQ, Opcodes.IF_ICMPNE, Opcodes.IF_ICMPLT, Opcodes.IF_ICMPGE,\n            Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE, Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.compare(\")\n                    append(\n                            when (opcode) {\n                                Opcodes.IF_ICMPEQ, Opcodes.IF_ACMPEQ -> \"Comparison.EQ\"\n                                Opcodes.IF_ICMPNE, Opcodes.IF_ACMPNE -> \"Comparison.NE\"\n                                Opcodes.IF_ICMPLT -> \"Comparison.LT\"\n                                Opcodes.IF_ICMPGE -> \"Comparison.GE\"\n                                Opcodes.IF_ICMPGT -> \"Comparison.GT\"\n                                Opcodes.IF_ICMPLE -> \"Comparison.LE\"\n                                else -> \"\"\n                            }\n                    )\n                    append(\", \")\n                    append(label)\n                    append(\", \")\n                    append(stack[1].first)\n                    append(\", \")\n                    append(stack[0].first)\n                    append(\");\")\n                    stack.pop()\n                    stack.pop()\n                }\n            }\n            Opcodes.IFNULL -> {\n                visitInsn(Opcodes.ACONST_NULL)\n                visitJumpInsn(Opcodes.IF_ACMPEQ, label)\n            }\n            Opcodes.IFNONNULL -> {\n                visitInsn(Opcodes.ACONST_NULL)\n                visitJumpInsn(Opcodes.IF_ACMPNE, label)\n            }\n            Opcodes.GOTO -> {\n                appendOperationCodeBlock {\n                    append(\"methodCodeBlock.jump(\")\n                    append(label)\n                    append(\");\")\n                }\n            }\n        }\n    }\n\n    private val labelMapping = HashSet