edward-io/starcoderdata-repo · Datasets at Fast360
{
// 获取包含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 *