├── src ├── cache.js ├── debug.js ├── index.js ├── db.js ├── telegram-notion-saver.dbml ├── notion.js ├── migrating.sql ├── generateDb.sql ├── onBoarding.js └── bot.js ├── package.json ├── .gitignore ├── README.md ├── LICENSE └── yarn.lock /src/cache.js: -------------------------------------------------------------------------------- 1 | import NodeCache from 'node-cache' 2 | 3 | const cache = new NodeCache(); 4 | 5 | export default cache -------------------------------------------------------------------------------- /src/debug.js: -------------------------------------------------------------------------------- 1 | function debugLog (...args) { 2 | if (process.env.DEBUG) 3 | console.log(...args) 4 | } 5 | 6 | export default debugLog -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "telegram-notion-saver", 3 | "version": "0.1", 4 | "description": "Telegram bot to save content to notion database", 5 | "main": "src/index.js", 6 | "repository": "https://github.com/LuigiMasini/telegram-notion-saver.git", 7 | "author": "Luigi Masini ", 8 | "license": "MIT", 9 | "private": false, 10 | "type": "module", 11 | "scripts": { 12 | "start": "NODE_ENV=development; nodemon ./node_modules/.bin/nodenv -- --env .env.$NODE_ENV src/index.js", 13 | "start-production": "pm2 --env production start ecosystem.config.cjs" 14 | }, 15 | "dependencies": { 16 | "@notionhq/client": "^0.3.2", 17 | "html-metadata-parser": "^2.0.4", 18 | "http-terminator": "^3.0.3", 19 | "mysql2": "^2.3.0", 20 | "node-cache": "^5.1.2", 21 | "node-env-run": "^4.0.2", 22 | "telegraf": "^4.4.2" 23 | }, 24 | "devDependencies": {} 25 | } 26 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import bot from './bot.js' 2 | import db from './db.js' 3 | import onBoardingServer from './onBoarding.js' 4 | import debugLog from './debug.js' 5 | 6 | function start(){ 7 | 8 | debugLog("starting service") 9 | 10 | /*Start order: 11 | * mysql client 12 | * https server 13 | * bot 14 | */ 15 | 16 | if (db){ 17 | 18 | //dumb query to initialize connection to db 19 | //pointless to start everithing if then it crashes at the first query) 20 | db.promiseExecute('SELECT max(id) FROM `TelegramChats`').then( 21 | ({error}) => { 22 | 23 | if (error) 24 | throw error 25 | 26 | debugLog('db connected') 27 | 28 | //launch server 29 | onBoardingServer.start(err=>{ 30 | 31 | //check server 32 | if (err) 33 | throw new Error ("Https server cn't start: "+err) 34 | 35 | debugLog('https server started') 36 | 37 | //start bot 38 | bot.launch().then(()=>debugLog('telegram bot launched\n')) 39 | 40 | 41 | }) 42 | }) 43 | } 44 | else{ 45 | throw new Error ("mysql database is "+typeof db) 46 | } 47 | } 48 | 49 | start() 50 | 51 | function stop(sig){ 52 | 53 | debugLog("\n\nStopping service"+(!!sig ? " due to "+sig : "")+"\nBye!") 54 | 55 | /*Stop order (opposite of start order) 56 | * bot 57 | * https server 58 | * mysql client 59 | */ 60 | 61 | bot.stop(sig) 62 | 63 | onBoardingServer.stop().then(()=>{ 64 | 65 | //callback argument 66 | db.end() 67 | }) 68 | 69 | } 70 | 71 | // Enable graceful stop 72 | process.once('SIGINT', () => stop('SIGINT')) 73 | process.once('SIGTERM', () => stop('SIGTERM')) 74 | -------------------------------------------------------------------------------- /src/db.js: -------------------------------------------------------------------------------- 1 | import mysql from 'mysql2' 2 | 3 | import debugLog from './debug.js' 4 | 5 | const db = mysql.createPool({ 6 | host: process.env.dbHost, 7 | user: process.env.dbUser, 8 | password: process.env.dbPassword, 9 | database: process.env.dbName, 10 | port:process.env.dbPort, 11 | namedPlaceholders:true, 12 | charset:'utf8mb4_general_ci', 13 | }) 14 | 15 | function handleError(error, reject, state){ 16 | !!error && error.code != 'ER_DUP_ENTRY' && debugLog(error) 17 | 18 | if (error && error.fatal) 19 | reject({error, state}) 20 | } 21 | 22 | const promisify = (object=db, method="execute") => (query, params, state) => new Promise((resolve, reject) => 23 | object[method](query, params, (error, result, fields)=>{ 24 | handleError(error, reject, state) 25 | resolve({error, result, fields, state}) 26 | }) 27 | ) 28 | 29 | const commitPromise = (connection)=>new Promise((resolve, reject)=> 30 | connection.commit(error=>{ 31 | handleError(error, reject) 32 | 33 | connection.release() 34 | 35 | resolve(error) 36 | }) 37 | ) 38 | 39 | const rollbackPromise = (connection) => new Promise((resolve, reject)=> 40 | connection.rollback(error=>{ 41 | handleError(error, reject) 42 | 43 | connection.release() 44 | 45 | resolve(error) 46 | }) 47 | ) 48 | 49 | const transactionPromise = ()=>new Promise((resolve, reject)=> 50 | 51 | db.getConnection((error, connection)=>{ 52 | connection.beginTransaction(error=>{ 53 | handleError(error, reject) 54 | resolve(Object.assign(connection, {promiseExecute:promisify(connection, "execute"), promiseQuery:promisify(connection, "query"), commitPromise, rollbackPromise}), error) 55 | }) 56 | }) 57 | ) 58 | 59 | export default Object.assign(db, {promiseExecute:promisify(db, "execute"), promiseQuery:promisify(db, "query"), transactionPromise}) 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.* 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | *~ 107 | tmp* 108 | cert/ 109 | *.pem 110 | 111 | ignore/ 112 | 113 | ecosystem.config.cjs 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # telegram-notion-saver 2 | Telegram bot to save content to notion database 3 | 4 | You can check it out at [t.me/NotionSaverBot](https://t.me/NotionSaverBot) 5 | 6 | > **Still a Work In Progress** 7 | 8 | ## Showcase 9 | 10 | 11 | https://user-images.githubusercontent.com/51889753/160253052-4a29213e-a019-47f4-9e7d-ddf7af2eeade.mp4 12 | 13 | 14 | ## Yet Another? 15 | 16 | Yes, but this bot is both very flexible and powerful: from a single message it can fill 17 | properties and content of a new database page, so that you no longer have to come back 18 | later to notion and adjust the saved content. Just set the rules once. 19 | 20 | > **IMPORTANT** 21 | > currently only has supports for adding pages to a database or subpages to a page. 22 | > 23 | > if you find it not suitable for you send a pull request or switch to another telegram to notion bot 24 | 25 | ## How it works 26 | 27 | First you ```/start``` the bot. 28 | You will have to authorize the bot as a public integration in Notion, grant access to your workspace and select as many pages as you want. 29 | 30 | 31 | https://user-images.githubusercontent.com/51889753/160253172-7f5d7c44-986b-4e13-a210-f7760fe5ae3e.mp4 32 | 33 | 34 | Then you will have to ```/config``` a template: it is just a collection of rules on how the bot will read and split the information in the messages you send to it, 35 | and where to put these informations, like properties, content or even icon or cover for images. You can also configure the extraction of metatata from one or more urls. 36 | You can even configure default values for properties or content. 37 | 38 | 39 | https://user-images.githubusercontent.com/51889753/160253257-c9b30666-12d3-4926-9400-7ad37bf0e792.mp4 40 | 41 | 42 | You can also configure more than one templates (set of rules) to be able to switch quickly between pages, databases and rules. 43 | You can switch between templates with chat buttons or with ```/use n``` where n is template number. 44 | 45 | ## Future improvements 46 | 47 | - documentation & guides 48 | - Workspaces & templates can be shared between users 49 | - support for images, files, audio, stikers, video, etc 50 | - support for url buttons in forwarded messages 51 | - multiple templates active at the same time, automatically determine which one to use looking at formats, link domains, forwarded from, is / contains file 52 | - a template can modify multiple pages (save same content to more than one location with more than one rule) 53 | - in TemplateRule have different order for parsing and writing (may be useful when writing blocks) 54 | - add possibility to add a sub page block with certain title and content 55 | - regex support for text splitting (instead of endsWith) and text filtering, like having ABC and you want AC in a prop 56 | - more freedom in content 57 | 58 | > **Still a Work In Progress** 59 | -------------------------------------------------------------------------------- /src/telegram-notion-saver.dbml: -------------------------------------------------------------------------------- 1 | Enum "TelegramChats_chatType_enum" { 2 | "private" 3 | "group" 4 | "supergroup" 5 | "channel" 6 | } 7 | 8 | Enum "NotionPages_pageType_enum" { 9 | "db" 10 | "pg" 11 | } 12 | 13 | Table "TelegramChats" { 14 | "id" INT [pk, not null, increment] 15 | "telegramChatId" CHAR(10) [unique, not null] 16 | "currentTemplateId" INT [ref: - Templates.id] 17 | "chatType" TelegramChats_chatType_enum 18 | Note: 'Table containing chats info (not users cuz the bot can be added to a grout chat)' 19 | } 20 | 21 | Table "NotionWorkspaces" { 22 | "id" INT [pk, not null, increment] 23 | "creatorChatId" INT [not null, ref: > TelegramChats.id] 24 | "workspaceId" CHAR(36) [unique, not null] 25 | "name" CHAR(255) 26 | "icon" CHAR(255) 27 | } 28 | 29 | Table "NotionWorkspacesCredentials" { 30 | "chatId" INT [not null, ref: > TelegramChats.id] 31 | "workspaceId" INT [not null, ref: > NotionWorkspaces.id] 32 | "botId" CHAR(36) [not null] 33 | "accessToken" CHAR(255) [unique] 34 | } 35 | 36 | Table "NotionPages" { 37 | "id" INT [pk, not null, increment] 38 | "notionPageId" CHAR(36) [not null] 39 | "workspaceId" INT [not null, ref: > NotionWorkspaces.id] 40 | "pageType" NotionPages_pageType_enum 41 | "icon" CHAR(255) 42 | "title" CHAR(255) 43 | "chatId" INT [not null, ref: > TelegramChats.id] 44 | } 45 | 46 | Table "NotionPagesProps" { 47 | "id" INT [pk, not null, increment] 48 | "notionPropId" CHAR(255) //if null not a prop but page content 49 | "pageId" INT [not null, ref: > NotionPages.id] 50 | "propName" CHAR(255) 51 | "propTypeId" INT [ref: > NotionPropTypes.id] 52 | } 53 | 54 | Table "NotionPropTypes" { 55 | "id" INT [pk, not null, increment] 56 | "type" CHAR(16) [unique, not null] 57 | } 58 | 59 | Table "Templates" { 60 | "id" INT [pk, not null, increment] 61 | "pageId" INT [ref: > NotionPages.id] 62 | "userTemplateNumber" TINYINT [not null] 63 | "chatId" INT [not null, ref: > TelegramChats.id] 64 | "imageDestination" TINYINT [ref: > ImageDestinations.id] 65 | } 66 | 67 | Table "ImageDestinations" { 68 | "id" TINYINT [pk, not null, increment] 69 | "destinations" CHAR(10) [not null] 70 | Note: 'Table containing possible destinations for an extracted image' 71 | } 72 | 73 | Table "TemplateRules" { 74 | "propId" INT [ref: > NotionPagesProps.id] 75 | "templateId" INT [not null, ref: > Templates.id] 76 | "orderNumber" TINYINT 77 | "defaultValue" CHAR(255) 78 | "endsWith" CHAR(255) //termination string for extraction, if NULL use defaultValue instead of extracting, if \n to avoid breaking output use replace(endsWith, '\n', '\\n') as endsWith 79 | "urlMetaTemplateRule" INT [ref: - UrlMetaTemplateRules.id] 80 | } 81 | 82 | 83 | Table "UrlMetaTemplateRules" { 84 | "id" INT [pk, not null, increment] 85 | "imageDestination" TINYINT [ref: > ImageDestinations.id] 86 | "title" INT [ref: > NotionPagesProps.id] 87 | "description" INT [ref: > NotionPagesProps.id] 88 | "author" INT [ref: > NotionPagesProps.id] 89 | "siteName" INT [ref: > NotionPagesProps.id] 90 | "type" INT [ref: > NotionPagesProps.id] 91 | Note: 'Table containing rules for URL meta extraction, in what propId to put the extracted content (if NULL discard)' 92 | } 93 | -------------------------------------------------------------------------------- /src/notion.js: -------------------------------------------------------------------------------- 1 | import { Client as NotionClient } from "@notionhq/client" 2 | 3 | import db from './db.js' 4 | import debugLog from './debug.js' 5 | 6 | // https://stackoverflow.com/a/7033662 7 | const chunkString = (str, length) => str.match(new RegExp(`(.|[\r\n]){1,${length}}`, 'g')) || ['\n']; 8 | 9 | //creating a single NotionClient for every user 10 | //do not set a global token but pass it as parameter to every endpoint method 11 | //2021-09-21 it is an undocumented method parameter, could break ¯\_(ツ)_/¯ 12 | 13 | const notion = new NotionClient() 14 | 15 | function getAccessToken (telegramChatId, workspaceId){ 16 | return db.promiseExecute('SELECT accessToken FROM `NotionWorkspacesCredentials` as n JOIN `TelegramChats` as t on n.chatId = t.id WHERE workspaceId=? AND telegramChatId=?', [telegramChatId, workspaceId]) 17 | } 18 | 19 | function mapValueToPropObj (inputValue, propType){ 20 | 21 | let value = {} 22 | 23 | switch (propType){ 24 | case 'title': 25 | value=[{ 26 | type:'text', 27 | text:{ 28 | content:inputValue 29 | } 30 | }] 31 | break; 32 | case 'rich_text': 33 | value=[{ 34 | type:"text", 35 | //plain_text:inputValue 36 | text: { 37 | content:inputValue 38 | } 39 | }] 40 | break; 41 | case 'number': 42 | value=parseFloat(inputValue) 43 | break; 44 | case 'select': 45 | value={ 46 | name:inputValue.replaceAll(',', '-') //commas not alloweds 47 | } 48 | break; 49 | case 'multi_select': 50 | value=inputValue.split(',').map(str=>({name:str.trim()})) 51 | break; 52 | case 'date': 53 | const arr = inputValue.split(',').map(str=>{ 54 | const millis = Date.parse(str) 55 | if (isNaN(millis)) 56 | throw new Error ("Cannot parse date "+str+"\nPlease use a different format") 57 | return new Date(millis).toISOString() 58 | }) 59 | value={ 60 | start:arr[1], 61 | end:arr[2] 62 | } 63 | break; 64 | case 'checkbox': 65 | value= !!inputValue 66 | break; 67 | case 'url': 68 | case 'email': 69 | case 'phone_number': 70 | value=inputValue 71 | break; 72 | } 73 | 74 | return value 75 | } 76 | 77 | 78 | function mapValueToBlockObjs (inputValue, blockType){ 79 | 80 | let value = {} 81 | 82 | switch (blockType){ 83 | case 'text': 84 | 85 | 86 | const textBlocks = inputValue 87 | .split('\n') 88 | .map(string => chunkString(string, 2000)) 89 | .flat() 90 | .map(str => ({ 91 | type: "text", 92 | text: { 93 | content: str, 94 | }, 95 | })) 96 | 97 | const paragraphs = [] 98 | const chunkSize = 100 99 | 100 | //https://stackoverflow.com/a/8495740 101 | for (let i=0; iObject.entries(properties).filter( ([key, value]) => value.type === 'title')[0][1].title[0].plain_text), //NOTE works only for pages 137 | propTypes:["title","rich_text","number","select","multi_select","date","people","files","checkbox","url","email","phone_number","formula","relation","rollup","created_time","created_by","last_edited_time","last_edited_by"], 138 | supportedTypes:[0, 1, 2, 3, 4, 5, 8, 9, 10, 11, null], 139 | mapValueToPropObj, 140 | mapValueToBlockObjs, 141 | } 142 | 143 | export default exportObj 144 | -------------------------------------------------------------------------------- /src/migrating.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE `TemplateRules` ADD COLUMN `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT; 2 | ALTER TABLE `UrlMetaTemplateRules` ADD COLUMN `ruleId` INT; 3 | 4 | UPDATE `UrlMetaTemplateRules` AS u, ( SELECT t.`id`, t.urlMetaTemplateRule FROM TemplateRules AS t JOIN UrlMetaTemplateRules as U ON t.urlMetaTemplateRule = U.`id` ) AS d SET u.ruleId = d.`id` WHERE d.urlMetaTemplateRule = u.`id`; 5 | DELETE FROM `UrlMetaTemplateRules` WHERE ruleId IS NULL; 6 | 7 | ALTER TABLE `TemplateRules` DROP FOREIGN KEY TemplateRules_ibfk_3, DROP COLUMN urlMetaTemplateRule; 8 | ALTER TABLE `UrlMetaTemplateRules` DROP PRIMARY KEY, DROP COLUMN `id`; 9 | ALTER TABLE `UrlMetaTemplateRules` MODIFY COLUMN `ruleId` INT PRIMARY KEY NOT NULL; 10 | 11 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`ruleId`) REFERENCES `TemplateRules` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 12 | 13 | ALTER TABLE `TelegramChats` DROP FOREIGN KEY TelegramChats_ibfk_1; 14 | ALTER TABLE `TelegramChats` ADD FOREIGN KEY (`currentTemplateId`) REFERENCES `Templates` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 15 | 16 | ALTER TABLE `NotionWorkspaces` DROP FOREIGN KEY NotionWorkspaces_ibfk_1; 17 | ALTER TABLE `NotionWorkspaces` CHANGE COLUMN `creatorChatId` `creatorChatId` INT; 18 | ALTER TABLE `NotionWorkspaces` ADD FOREIGN KEY (`creatorChatId`) REFERENCES `TelegramChats` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 19 | 20 | ALTER TABLE `NotionWorkspacesCredentials` DROP FOREIGN KEY NotionWorkspacesCredentials_ibfk_1; 21 | ALTER TABLE `NotionWorkspacesCredentials` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 22 | ALTER TABLE `NotionWorkspacesCredentials` DROP FOREIGN KEY NotionWorkspacesCredentials_ibfk_2; 23 | ALTER TABLE `NotionWorkspacesCredentials` ADD FOREIGN KEY (`workspaceId`) REFERENCES `NotionWorkspaces` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 24 | 25 | ALTER TABLE `NotionWorkspacesCredentials` ADD PRIMARY KEY (`botId`); 26 | ALTER TABLE `NotionWorkspacesCredentials` DROP INDEX `accessToken`; 27 | 28 | ALTER TABLE `NotionPages` DROP FOREIGN KEY NotionPages_ibfk_1; 29 | ALTER TABLE `NotionPages` ADD FOREIGN KEY (`workspaceId`) REFERENCES `NotionWorkspaces` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 30 | ALTER TABLE `NotionPages` DROP FOREIGN KEY NotionPages_ibfk_2; 31 | ALTER TABLE `NotionPages` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 32 | 33 | ALTER TABLE `NotionPagesProps` DROP FOREIGN KEY NotionPagesProps_ibfk_1; 34 | ALTER TABLE `NotionPagesProps` ADD FOREIGN KEY (`pageId`) REFERENCES `NotionPages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 35 | ALTER TABLE `NotionPagesProps` DROP FOREIGN KEY NotionPagesProps_ibfk_2; 36 | ALTER TABLE `NotionPagesProps` ADD FOREIGN KEY (`propTypeId`) REFERENCES `NotionPropTypes` (`id`) ON UPDATE CASCADE; 37 | 38 | ALTER TABLE `Templates` DROP FOREIGN KEY Templates_ibfk_1; 39 | ALTER TABLE `Templates` ADD FOREIGN KEY (`pageId`) REFERENCES `NotionPages` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 40 | ALTER TABLE `Templates` DROP FOREIGN KEY Templates_ibfk_2; 41 | ALTER TABLE `Templates` ADD FOREIGN KEY (`imageDestination`) REFERENCES `ImageDestinations` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 42 | ALTER TABLE `Templates` DROP FOREIGN KEY Templates_ibfk_3; 43 | ALTER TABLE `Templates` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 44 | 45 | ALTER TABLE `TemplateRules` DROP FOREIGN KEY TemplateRules_ibfk_1; 46 | ALTER TABLE `TemplateRules` ADD FOREIGN KEY (`propId`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 47 | ALTER TABLE `TemplateRules` DROP FOREIGN KEY TemplateRules_ibfk_2; 48 | ALTER TABLE `TemplateRules` ADD FOREIGN KEY (`templateId`) REFERENCES `Templates` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 49 | 50 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_1; 51 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`imageDestination`) REFERENCES `ImageDestinations` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 52 | 53 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_2; 54 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`title`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 55 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_3; 56 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`description`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 57 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_4; 58 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`author`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 59 | 60 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_5; 61 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`siteName`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 62 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_6; 63 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`type`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 64 | ALTER TABLE `UrlMetaTemplateRules` DROP FOREIGN KEY UrlMetaTemplateRules_ibfk_7; 65 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`url`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 66 | -------------------------------------------------------------------------------- /src/generateDb.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `telegram-notion-saver` CHARACTER SET utf8mb4; 2 | use `telegram-notion-saver`; 3 | 4 | CREATE TABLE IF NOT EXISTS `TelegramChats` ( 5 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 6 | `telegramChatId` CHAR(10) UNIQUE NOT NULL, 7 | `currentTemplateId` INT, 8 | `chatType` ENUM ('private', 'group', 'supergroup', 'channel') 9 | ); 10 | 11 | CREATE TABLE IF NOT EXISTS `NotionWorkspaces` ( 12 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 13 | `creatorChatId` INT NOT NULL, 14 | `workspaceId` CHAR(36) UNIQUE NOT NULL, 15 | `name` CHAR(255), 16 | `icon` CHAR(255) 17 | ); 18 | 19 | CREATE TABLE IF NOT EXISTS `NotionWorkspacesCredentials` ( 20 | `chatId` INT NOT NULL, 21 | `workspaceId` INT NOT NULL, 22 | `botId` CHAR(36) PRIMARY KEY NOT NULL, 23 | `accessToken` CHAR(255) 24 | ); 25 | 26 | CREATE TABLE IF NOT EXISTS `NotionPages` ( 27 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 28 | `notionPageId` CHAR(36) NOT NULL, 29 | `workspaceId` INT NOT NULL, 30 | `pageType` ENUM ('db', 'pg'), 31 | `icon` CHAR(255), 32 | `title` CHAR(255), 33 | `chatId` INT 34 | ); 35 | 36 | CREATE TABLE IF NOT EXISTS `NotionPagesProps` ( 37 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 38 | `notionPropId` CHAR(255), 39 | `pageId` INT NOT NULL, 40 | `propName` CHAR(255), 41 | `propTypeId` INT 42 | ); 43 | 44 | DROP TABLE IF EXISTS NotionPropTypes; 45 | 46 | CREATE TABLE IF NOT EXISTS `NotionPropTypes` ( 47 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 48 | `type` CHAR(16) UNIQUE NOT NULL 49 | ); 50 | 51 | CREATE TABLE IF NOT EXISTS `Templates` ( 52 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 53 | `pageId` INT, 54 | `userTemplateNumber` TINYINT NOT NULL, 55 | `chatId` INT NOT NULL, 56 | `imageDestination` INT 57 | ); 58 | 59 | DROP TABLE IF EXISTS ImageDestinations; 60 | 61 | CREATE TABLE IF NOT EXISTS `ImageDestinations` ( 62 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 63 | `destinations` CHAR(10) NOT NULL 64 | ); 65 | 66 | CREATE TABLE IF NOT EXISTS `TemplateRules` ( 67 | `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, 68 | `propId` INT, 69 | `templateId` INT NOT NULL, 70 | `orderNumber` TINYINT, 71 | `defaultValue` CHAR(255), 72 | `endsWith` CHAR(255) 73 | ); 74 | 75 | CREATE TABLE IF NOT EXISTS `UrlMetaTemplateRules` ( 76 | `ruleId` INT PRIMARY KEY NOT NULL, 77 | `url` INT, 78 | `imageDestination` INT, 79 | `title` INT, 80 | `description` INT, 81 | `author` INT, 82 | `siteName` INT, 83 | `type` INT 84 | ); 85 | 86 | ALTER TABLE `TelegramChats` ADD FOREIGN KEY (`currentTemplateId`) REFERENCES `Templates` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 87 | 88 | ALTER TABLE `NotionWorkspaces` ADD FOREIGN KEY (`creatorChatId`) REFERENCES `TelegramChats` (`id`) ON UPDATE CASCADE; 89 | 90 | ALTER TABLE `NotionWorkspacesCredentials` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 91 | 92 | ALTER TABLE `NotionWorkspacesCredentials` ADD FOREIGN KEY (`workspaceId`) REFERENCES `NotionWorkspaces` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 93 | 94 | ALTER TABLE `NotionPages` ADD FOREIGN KEY (`workspaceId`) REFERENCES `NotionWorkspaces` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 95 | 96 | ALTER TABLE `NotionPages` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 97 | 98 | ALTER TABLE `NotionPagesProps` ADD FOREIGN KEY (`pageId`) REFERENCES `NotionPages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 99 | 100 | ALTER TABLE `NotionPagesProps` ADD FOREIGN KEY (`propTypeId`) REFERENCES `NotionPropTypes` (`id`) ON UPDATE CASCADE; 101 | 102 | ALTER TABLE `Templates` ADD FOREIGN KEY (`pageId`) REFERENCES `NotionPages` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 103 | 104 | ALTER TABLE `Templates` ADD FOREIGN KEY (`imageDestination`) REFERENCES `ImageDestinations` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 105 | 106 | ALTER TABLE `Templates` ADD FOREIGN KEY (`chatId`) REFERENCES `TelegramChats` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 107 | 108 | ALTER TABLE `TemplateRules` ADD FOREIGN KEY (`propId`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 109 | 110 | ALTER TABLE `TemplateRules` ADD FOREIGN KEY (`templateId`) REFERENCES `Templates` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 111 | 112 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`ruleId`) REFERENCES `TemplateRules` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 113 | 114 | 115 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`imageDestination`) REFERENCES `ImageDestinations` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 116 | 117 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`title`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 118 | 119 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`description`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 120 | 121 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`author`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 122 | 123 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`siteName`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 124 | 125 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`type`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 126 | 127 | ALTER TABLE `UrlMetaTemplateRules` ADD FOREIGN KEY (`url`) REFERENCES `NotionPagesProps` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; 128 | 129 | ALTER TABLE `TelegramChats` COMMENT = "Table containing chats info (not users cuz the bot can be added to a grout chat)"; 130 | 131 | ALTER TABLE `ImageDestinations` COMMENT = "Table containing possible destinations for an extracted image"; 132 | 133 | ALTER TABLE `UrlMetaTemplateRules` COMMENT = "Table containing rules for URL meta extraction, in what propId to put the extracted content (if NULL discard)"; 134 | 135 | 136 | SET sql_mode='NO_AUTO_VALUE_ON_ZERO'; 137 | 138 | INSERT INTO ImageDestinations VALUES (0, 'content'), (1, 'cover'), (2, 'icon'); 139 | INSERT INTO NotionPropTypes VALUES (0, 'title'), (1, 'rich_text'), (2, 'number'), (3, 'select'), (4, 'multi_select'), (5, 'date'), (6, 'people'), (7, 'files'), (8, 'checkbox'), (9, 'url'), (10, 'email'), (11, 'phone_number'), (12, 'formula'), (13, 'relation'), (14, 'rollup'), (15, 'created_time'), (16, 'created_by'), (17, 'last_edited_time'), (18, 'last_edited_by'); 140 | -------------------------------------------------------------------------------- /src/onBoarding.js: -------------------------------------------------------------------------------- 1 | import url from 'url' 2 | import https from 'https' 3 | import fs from 'fs' 4 | import fetch from 'node-fetch' 5 | 6 | import httpTerminator from 'http-terminator' 7 | 8 | import bot, {Markup} from './bot.js' 9 | import db from './db.js' 10 | import debugLog from './debug.js' 11 | 12 | const options = { 13 | key: fs.readFileSync(process.env.sslKeyFile), 14 | cert: fs.readFileSync(process.env.sslCertFile), 15 | passphrase: process.env.sslKeyPassphrase, 16 | }; 17 | 18 | const redirect_uri = process.env.notionRedirectUri 19 | 20 | 21 | function rfc6749ErrorMessageComposer(obj){ 22 | //https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.2.1 23 | //https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 24 | 25 | var additionalInfo = "" 26 | if (typeof obj.error === "string" && obj.error.length) 27 | additionalInfo="\n\nInfo from Noiton: \nError: "+obj.error 28 | if (typeof obj.error_description === "string" && obj.error_description.length) 29 | additionalInfo+="\nError description: "+obj.error_description 30 | if (typeof obj.error_uri === "string" && obj.error_uri.length) 31 | additionalInfo+="\nMore info: "+obj.error_uri 32 | return additionalInfo 33 | } 34 | 35 | var server = https.createServer(options, function(req, res) { 36 | 37 | function redirect(){ 38 | //redirect user from browser to telegram chat with the bot 39 | res.writeHead(302, {'Location': 'https://t.me/NotionSaverBot'}); 40 | res.end('Ciao'); 41 | } 42 | 43 | try{ 44 | const t = Date.now() 45 | 46 | const queryObject = url.parse(req.url,true).query; 47 | 48 | debugLog("Recived query from Notion authorization: ",queryObject) 49 | 50 | //if received state param from notion 51 | if ( typeof queryObject === "object" && typeof queryObject.state === "string" && queryObject.state.length && typeof parseInt(queryObject.state.slice(1 ,-1)) === "number" ){ 52 | 53 | const telegramChatId = parseInt(queryObject.state.slice(1 ,-1)) 54 | 55 | //if received temporary authorization code 56 | if (typeof queryObject.code === "string" && queryObject.code.length){ 57 | 58 | //get access token 59 | fetch("https://api.notion.com/v1/oauth/token", { 60 | method:'POST', 61 | headers: { 62 | 'Authorization': 'Basic '+Buffer.from(process.env.notionOAuthClientId+':'+process.env.notionOAuthSecret).toString('base64'), 63 | 'Accept': 'application/json', 64 | 'Content-Type' : 'application/json', 65 | }, 66 | body: JSON.stringify({ 67 | grant_type:"authorization_code", 68 | redirect_uri: redirect_uri, 69 | code:queryObject.code, 70 | }), 71 | }) 72 | .then(response=>{ 73 | if (response.statusCode >= 400 ) 74 | throw new Error("can't get access token from notion server: "+rfc6749ErrorMessageComposer(response.json())) 75 | return response 76 | }) 77 | .then(response=>response.json()) 78 | .then(response=>{ 79 | debugLog("Notion token response: ",response) 80 | 81 | 82 | //start sql transaction 83 | db.transactionPromise() 84 | .then((connection, transactionError)=>{ 85 | 86 | //get TelegramChats.id 87 | return connection.promiseExecute( 88 | 'SELECT id FROM `TelegramChats` WHERE telegramChatId = ? ', 89 | [telegramChatId], 90 | {connection, transactionError} //state 91 | ) 92 | }) 93 | .then(({error, result, state})=>{ 94 | 95 | if (!result || !result.length) 96 | throw new Error("Can't find saved user information") 97 | 98 | const chatId = result[0].id 99 | 100 | //register workspace, 101 | return state.connection.promiseExecute( 102 | 'INSERT INTO `NotionWorkspaces` (`workspaceId`, `creatorChatId`, `name`, `icon`) VALUES (?, ?, ?, ?)', 103 | [response.workspace_id, chatId, response.workspace_name, response.workspace_icon], 104 | {chatId, ...state} 105 | ) 106 | }) 107 | .then(({error, state})=>{ 108 | 109 | /*Ignore ER_DUP_ENTRY: the workspace could be already registered by another user: 110 | * https://developers.notion.com/changelog/space-level-integrations-will-be-deprecated-soon-migrate-your-oauth-flows 111 | */ 112 | if (error && error.code !== 'ER_DUP_ENTRY') 113 | throw new Error("Error registering workspace: "+error.code+" - "+error.sqlMessage) 114 | 115 | //get NotionWorkspaces.id of authorized workspace 116 | return state.connection.promiseExecute( 117 | 'SELECT id FROM `NotionWorkspaces` WHERE workspaceId = ?', 118 | [response.workspace_id], 119 | state 120 | ) 121 | }) 122 | .then(({error, result, state})=>{ 123 | //register access token for authorized workspace 124 | return state.connection.promiseExecute( 125 | 'INSERT INTO `NotionWorkspacesCredentials` (`chatId`, `workspaceId`, `botId`, `accessToken`) VALUES (?, ?, ?, ?)', 126 | [state.chatId, result[0].id, response.bot_id, response.access_token], 127 | {...state, workspaceId:result[0].id} 128 | ) 129 | }) 130 | .then(({error, state})=>{ 131 | 132 | if (error && error.code !== 'ER_DUP_ENTRY') 133 | throw new Error("Error registering workspace credentials: "+error.code+" - "+error.sqlMessage) 134 | 135 | if (error.code === 'ER_DUP_ENTRY') 136 | return state.connection.promiseExecute( 137 | 'UPDATE `NotionWorkspacesCredentials` SET `accessToken`=? WHERE `chatId`=? AND `workspaceId`=?', 138 | [response.access_token, state.chatId, state.workspaceId], 139 | {...state} 140 | ) 141 | .then(({error, state})=>{ 142 | 143 | if (error && error.code !== 'ER_DUP_ENTRY') 144 | throw new Error("Error updating workspace credentials: "+error.code+" - "+error.sqlMessage) 145 | 146 | return state.connection.commitPromise(state.connection) 147 | }) 148 | 149 | return state.connection.commitPromise(state.connection) 150 | }) 151 | .then(errC=>{ 152 | 153 | if (errC) 154 | throw new Error("Error committing changes: "+errC.code+" - "+errC.sqlMessage) 155 | 156 | //TODO: if user already have templates send different message 157 | bot.telegram.sendMessage(telegramChatId, "Good!\n\nNow you can set up a template with /config") 158 | 159 | debugLog("time elapsed: ", Date.now()-t) 160 | }) 161 | }) 162 | .catch(err => { 163 | console.warn(err) 164 | bot.telegram.sendMessage(telegramChatId, "Error setting up your account: "+err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 165 | }) 166 | } 167 | else{ 168 | 169 | console.warn("No tmp token from notion: "+rfc6749ErrorMessageComposer(queryObject)) 170 | 171 | bot.telegram.sendMessage(chatId, "Did not receive temporary authorization code from Notion"+additionalInfo+"\n\nYou can try again later, search the error or report the incident on Github.") 172 | } 173 | 174 | 175 | redirect() 176 | return 177 | } 178 | }catch(err){ 179 | console.warn (err) 180 | redirect() 181 | return 182 | } 183 | 184 | res.writeHead(400); 185 | res.end("Did not receive \'state\' query parameter from Notion\n\n"+ 186 | "Is it your fault, fellow human?\n\n"+ 187 | "You can try logging in again but I do not guarantee success:\n"+ 188 | "Get back to https://t.me/NotionSaverBot"); 189 | }); 190 | 191 | /*NOTE if server will take more than 5s to complete any request, 192 | * add gracefulTerminationTimeout property to config object in createHttpTerminator 193 | * with the time taken by the server to complete requests in millis 194 | */ 195 | const serverTerminator = httpTerminator.createHttpTerminator({server}) 196 | 197 | const onBoardingServer = { 198 | start:((func)=>server.listen(process.env.port, func)), 199 | stop:(()=>serverTerminator.terminate()),//promise 200 | redirect_uri:redirect_uri, 201 | } 202 | 203 | 204 | export default onBoardingServer 205 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | "@notionhq/client@^0.3.2": 6 | version "0.3.2" 7 | resolved "https://registry.yarnpkg.com/@notionhq/client/-/client-0.3.2.tgz#16e2a5abbcab32c836b2fa08188217dacf6002f4" 8 | integrity sha512-CSYk88/+gwRff9ftz8G+7EKHgE8/3TWDdQVmIoesXhHZp+FmV8L82Y+dn2dRuWrDf1XZiVYv0A0DPLwlh94fzw== 9 | dependencies: 10 | "@types/node-fetch" "^2.5.10" 11 | node-fetch "^2.6.1" 12 | 13 | "@types/common-tags@^1.4.0": 14 | version "1.8.1" 15 | resolved "https://registry.yarnpkg.com/@types/common-tags/-/common-tags-1.8.1.tgz#a5a49ca5ebbb58e0f8947f3ec98950c8970a68a9" 16 | integrity sha512-20R/mDpKSPWdJs5TOpz3e7zqbeCNuMCPhV7Yndk9KU2Rbij2r5W4RzwDPkzC+2lzUqXYu9rFzTktCBnDjHuNQg== 17 | 18 | "@types/debug@^4.1.5": 19 | version "4.1.7" 20 | resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" 21 | integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg== 22 | dependencies: 23 | "@types/ms" "*" 24 | 25 | "@types/ms@*": 26 | version "0.7.31" 27 | resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197" 28 | integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA== 29 | 30 | "@types/node-fetch@^2.5.10": 31 | version "2.5.12" 32 | resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.5.12.tgz#8a6f779b1d4e60b7a57fb6fd48d84fb545b9cc66" 33 | integrity sha512-MKgC4dlq4kKNa/mYrwpKfzQMB5X3ee5U6fSprkKpToBqBmX4nFZL9cW5jl6sWn+xpRJ7ypWh2yyqqr8UUCstSw== 34 | dependencies: 35 | "@types/node" "*" 36 | form-data "^3.0.0" 37 | 38 | "@types/node@*": 39 | version "16.9.4" 40 | resolved "https://registry.yarnpkg.com/@types/node/-/node-16.9.4.tgz#a12f0ee7847cf17a97f6fdf1093cb7a9af23cca4" 41 | integrity sha512-KDazLNYAGIuJugdbULwFZULF9qQ13yNWEBFnfVpqlpgAAo6H/qnM9RjBgh0A0kmHf3XxAKLdN5mTIng9iUvVLA== 42 | 43 | "@types/node@^10.17.28": 44 | version "10.17.60" 45 | resolved "https://registry.yarnpkg.com/@types/node/-/node-10.17.60.tgz#35f3d6213daed95da7f0f73e75bcc6980e90597b" 46 | integrity sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw== 47 | 48 | "@types/yargs-parser@*": 49 | version "21.0.0" 50 | resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.0.tgz#0c60e537fa790f5f9472ed2776c2b71ec117351b" 51 | integrity sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA== 52 | 53 | "@types/yargs@^15.0.5": 54 | version "15.0.14" 55 | resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-15.0.14.tgz#26d821ddb89e70492160b66d10a0eb6df8f6fb06" 56 | integrity sha512-yEJzHoxf6SyQGhBhIYGXQDSCkJjB6HohDShto7m8vaKg9Yp0Yn8+71J9eakh2bnPg6BfsH9PRMhiRTZnd4eXGQ== 57 | dependencies: 58 | "@types/yargs-parser" "*" 59 | 60 | abort-controller@^3.0.0: 61 | version "3.0.0" 62 | resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" 63 | integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== 64 | dependencies: 65 | event-target-shim "^5.0.0" 66 | 67 | ajv@^6.11.0: 68 | version "6.12.6" 69 | resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" 70 | integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== 71 | dependencies: 72 | fast-deep-equal "^3.1.1" 73 | fast-json-stable-stringify "^2.0.0" 74 | json-schema-traverse "^0.4.1" 75 | uri-js "^4.2.2" 76 | 77 | ansi-regex@^5.0.1: 78 | version "5.0.1" 79 | resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" 80 | integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== 81 | 82 | ansi-styles@^4.0.0: 83 | version "4.3.0" 84 | resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" 85 | integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== 86 | dependencies: 87 | color-convert "^2.0.1" 88 | 89 | asynckit@^0.4.0: 90 | version "0.4.0" 91 | resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" 92 | integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= 93 | 94 | axios@^0.24.0: 95 | version "0.24.0" 96 | resolved "https://registry.yarnpkg.com/axios/-/axios-0.24.0.tgz#804e6fa1e4b9c5288501dd9dff56a7a0940d20d6" 97 | integrity sha512-Q6cWsys88HoPgAaFAVUb0WpPk0O8iTeisR9IMqy9G8AbO4NlpVknrnQS03zzF9PGAWgO3cgletO3VjV/P7VztA== 98 | dependencies: 99 | follow-redirects "^1.14.4" 100 | 101 | boolbase@^1.0.0: 102 | version "1.0.0" 103 | resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" 104 | integrity sha1-aN/1++YMUes3cl6p4+0xDcwed24= 105 | 106 | boolean@^3.1.4: 107 | version "3.1.4" 108 | resolved "https://registry.yarnpkg.com/boolean/-/boolean-3.1.4.tgz#f51a2fb5838a99e06f9b6ec1edb674de67026435" 109 | integrity sha512-3hx0kwU3uzG6ReQ3pnaFQPSktpBw6RHN3/ivDKEuU8g1XSfafowyvDnadjv1xp8IZqhtSukxlwv9bF6FhX8m0w== 110 | 111 | buffer-alloc-unsafe@^1.1.0: 112 | version "1.1.0" 113 | resolved "https://registry.yarnpkg.com/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz#bd7dc26ae2972d0eda253be061dba992349c19f0" 114 | integrity sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg== 115 | 116 | buffer-alloc@^1.2.0: 117 | version "1.2.0" 118 | resolved "https://registry.yarnpkg.com/buffer-alloc/-/buffer-alloc-1.2.0.tgz#890dd90d923a873e08e10e5fd51a57e5b7cce0ec" 119 | integrity sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow== 120 | dependencies: 121 | buffer-alloc-unsafe "^1.1.0" 122 | buffer-fill "^1.0.0" 123 | 124 | buffer-fill@^1.0.0: 125 | version "1.0.0" 126 | resolved "https://registry.yarnpkg.com/buffer-fill/-/buffer-fill-1.0.0.tgz#f8f78b76789888ef39f205cd637f68e702122b2c" 127 | integrity sha1-+PeLdniYiO858gXNY39o5wISKyw= 128 | 129 | camelcase@^5.0.0: 130 | version "5.3.1" 131 | resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" 132 | integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== 133 | 134 | cliui@^6.0.0: 135 | version "6.0.0" 136 | resolved "https://registry.yarnpkg.com/cliui/-/cliui-6.0.0.tgz#511d702c0c4e41ca156d7d0e96021f23e13225b1" 137 | integrity sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ== 138 | dependencies: 139 | string-width "^4.2.0" 140 | strip-ansi "^6.0.0" 141 | wrap-ansi "^6.2.0" 142 | 143 | clone@2.x: 144 | version "2.1.2" 145 | resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f" 146 | integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= 147 | 148 | color-convert@^2.0.1: 149 | version "2.0.1" 150 | resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" 151 | integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== 152 | dependencies: 153 | color-name "~1.1.4" 154 | 155 | color-name@~1.1.4: 156 | version "1.1.4" 157 | resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" 158 | integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== 159 | 160 | combined-stream@^1.0.8: 161 | version "1.0.8" 162 | resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" 163 | integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== 164 | dependencies: 165 | delayed-stream "~1.0.0" 166 | 167 | common-tags@^1.7.2: 168 | version "1.8.2" 169 | resolved "https://registry.yarnpkg.com/common-tags/-/common-tags-1.8.2.tgz#94ebb3c076d26032745fd54face7f688ef5ac9c6" 170 | integrity sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA== 171 | 172 | cross-spawn@^7.0.3: 173 | version "7.0.3" 174 | resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" 175 | integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== 176 | dependencies: 177 | path-key "^3.1.0" 178 | shebang-command "^2.0.0" 179 | which "^2.0.1" 180 | 181 | css-select@^4.2.1: 182 | version "4.2.1" 183 | resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.2.1.tgz#9e665d6ae4c7f9d65dbe69d0316e3221fb274cdd" 184 | integrity sha512-/aUslKhzkTNCQUB2qTX84lVmfia9NyjP3WpDGtj/WxhwBzWBYUV3DgUpurHTme8UTPcPlAD1DJ+b0nN/t50zDQ== 185 | dependencies: 186 | boolbase "^1.0.0" 187 | css-what "^5.1.0" 188 | domhandler "^4.3.0" 189 | domutils "^2.8.0" 190 | nth-check "^2.0.1" 191 | 192 | css-what@^5.1.0: 193 | version "5.1.0" 194 | resolved "https://registry.yarnpkg.com/css-what/-/css-what-5.1.0.tgz#3f7b707aadf633baf62c2ceb8579b545bb40f7fe" 195 | integrity sha512-arSMRWIIFY0hV8pIxZMEfmMI47Wj3R/aWpZDDxWYCPEiOMv6tfOrnpDtgxBYPEQD4V0Y/958+1TdC3iWTFcUPw== 196 | 197 | debug@^4.1.1: 198 | version "4.3.4" 199 | resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" 200 | integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== 201 | dependencies: 202 | ms "2.1.2" 203 | 204 | debug@^4.3.1: 205 | version "4.3.2" 206 | resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" 207 | integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== 208 | dependencies: 209 | ms "2.1.2" 210 | 211 | decamelize@^1.2.0: 212 | version "1.2.0" 213 | resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" 214 | integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= 215 | 216 | deepmerge@^4.2.2: 217 | version "4.2.2" 218 | resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" 219 | integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== 220 | 221 | define-properties@^1.1.3: 222 | version "1.1.3" 223 | resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" 224 | integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== 225 | dependencies: 226 | object-keys "^1.0.12" 227 | 228 | delay@^5.0.0: 229 | version "5.0.0" 230 | resolved "https://registry.yarnpkg.com/delay/-/delay-5.0.0.tgz#137045ef1b96e5071060dd5be60bf9334436bd1d" 231 | integrity sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw== 232 | 233 | delayed-stream@~1.0.0: 234 | version "1.0.0" 235 | resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" 236 | integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= 237 | 238 | denque@^1.4.1: 239 | version "1.5.1" 240 | resolved "https://registry.yarnpkg.com/denque/-/denque-1.5.1.tgz#07f670e29c9a78f8faecb2566a1e2c11929c5cbf" 241 | integrity sha512-XwE+iZ4D6ZUB7mfYRMb5wByE8L74HCn30FBN7sWnXksWc1LO1bPDl67pBR9o/kC4z/xSNAwkMYcGgqDV3BE3Hw== 242 | 243 | detect-node@^2.1.0: 244 | version "2.1.0" 245 | resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" 246 | integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== 247 | 248 | dom-serializer@^1.0.1: 249 | version "1.3.2" 250 | resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-1.3.2.tgz#6206437d32ceefaec7161803230c7a20bc1b4d91" 251 | integrity sha512-5c54Bk5Dw4qAxNOI1pFEizPSjVsx5+bpJKmL2kPn8JhBUq2q09tTCa3mjijun2NfK78NMouDYNMBkOrPZiS+ig== 252 | dependencies: 253 | domelementtype "^2.0.1" 254 | domhandler "^4.2.0" 255 | entities "^2.0.0" 256 | 257 | domelementtype@^2.0.1, domelementtype@^2.2.0: 258 | version "2.2.0" 259 | resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-2.2.0.tgz#9a0b6c2782ed6a1c7323d42267183df9bd8b1d57" 260 | integrity sha512-DtBMo82pv1dFtUmHyr48beiuq792Sxohr+8Hm9zoxklYPfa6n0Z3Byjj2IV7bmr2IyqClnqEQhfgHJJ5QF0R5A== 261 | 262 | domhandler@^4.2.0: 263 | version "4.2.2" 264 | resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-4.2.2.tgz#e825d721d19a86b8c201a35264e226c678ee755f" 265 | integrity sha512-PzE9aBMsdZO8TK4BnuJwH0QT41wgMbRzuZrHUcpYncEjmQazq8QEaBWgLG7ZyC/DAZKEgglpIA6j4Qn/HmxS3w== 266 | dependencies: 267 | domelementtype "^2.2.0" 268 | 269 | domhandler@^4.3.0: 270 | version "4.3.0" 271 | resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-4.3.0.tgz#16c658c626cf966967e306f966b431f77d4a5626" 272 | integrity sha512-fC0aXNQXqKSFTr2wDNZDhsEYjCiYsDWl3D01kwt25hm1YIPyDGHvvi3rw+PLqHAl/m71MaiF7d5zvBr0p5UB2g== 273 | dependencies: 274 | domelementtype "^2.2.0" 275 | 276 | domutils@^2.8.0: 277 | version "2.8.0" 278 | resolved "https://registry.yarnpkg.com/domutils/-/domutils-2.8.0.tgz#4437def5db6e2d1f5d6ee859bd95ca7d02048135" 279 | integrity sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A== 280 | dependencies: 281 | dom-serializer "^1.0.1" 282 | domelementtype "^2.2.0" 283 | domhandler "^4.2.0" 284 | 285 | dotenv@^8.2.0: 286 | version "8.6.0" 287 | resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.6.0.tgz#061af664d19f7f4d8fc6e4ff9b584ce237adcb8b" 288 | integrity sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g== 289 | 290 | emoji-regex@^8.0.0: 291 | version "8.0.0" 292 | resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" 293 | integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== 294 | 295 | entities@^2.0.0: 296 | version "2.2.0" 297 | resolved "https://registry.yarnpkg.com/entities/-/entities-2.2.0.tgz#098dc90ebb83d8dffa089d55256b351d34c4da55" 298 | integrity sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A== 299 | 300 | event-target-shim@^5.0.0: 301 | version "5.0.1" 302 | resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" 303 | integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== 304 | 305 | fast-deep-equal@^3.1.1: 306 | version "3.1.3" 307 | resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" 308 | integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== 309 | 310 | fast-json-stable-stringify@^2.0.0: 311 | version "2.1.0" 312 | resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" 313 | integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== 314 | 315 | fast-json-stringify@^2.7.9: 316 | version "2.7.10" 317 | resolved "https://registry.yarnpkg.com/fast-json-stringify/-/fast-json-stringify-2.7.10.tgz#7afcdf2e8bfeee9d361b38781deadae8e154e8b0" 318 | integrity sha512-MPuVXMMueV8e3TRVLOpxxicJnSdu5mwbHrsO9IZU15zqfay6k19OqIv7N2DCeNPDOCNOmZwjvMUTwvblZsUmFw== 319 | dependencies: 320 | ajv "^6.11.0" 321 | deepmerge "^4.2.2" 322 | rfdc "^1.2.0" 323 | string-similarity "^4.0.1" 324 | 325 | fast-printf@^1.6.9: 326 | version "1.6.9" 327 | resolved "https://registry.yarnpkg.com/fast-printf/-/fast-printf-1.6.9.tgz#212f56570d2dc8ccdd057ee93d50dd414d07d676" 328 | integrity sha512-FChq8hbz65WMj4rstcQsFB0O7Cy++nmbNfLYnD9cYv2cRn8EG6k/MGn9kO/tjO66t09DLDugj3yL+V2o6Qftrg== 329 | dependencies: 330 | boolean "^3.1.4" 331 | 332 | find-up@^4.1.0: 333 | version "4.1.0" 334 | resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" 335 | integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== 336 | dependencies: 337 | locate-path "^5.0.0" 338 | path-exists "^4.0.0" 339 | 340 | follow-redirects@^1.14.4: 341 | version "1.14.9" 342 | resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.9.tgz#dd4ea157de7bfaf9ea9b3fbd85aa16951f78d8d7" 343 | integrity sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w== 344 | 345 | form-data@^3.0.0: 346 | version "3.0.1" 347 | resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" 348 | integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== 349 | dependencies: 350 | asynckit "^0.4.0" 351 | combined-stream "^1.0.8" 352 | mime-types "^2.1.12" 353 | 354 | generate-function@^2.3.1: 355 | version "2.3.1" 356 | resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.3.1.tgz#f069617690c10c868e73b8465746764f97c3479f" 357 | integrity sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ== 358 | dependencies: 359 | is-property "^1.0.2" 360 | 361 | get-caller-file@^2.0.1: 362 | version "2.0.5" 363 | resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" 364 | integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== 365 | 366 | globalthis@^1.0.2: 367 | version "1.0.2" 368 | resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.2.tgz#2a235d34f4d8036219f7e34929b5de9e18166b8b" 369 | integrity sha512-ZQnSFO1la8P7auIOQECnm0sSuoMeaSq0EEdXMBFF2QJO4uNcwbyhSgG3MruWNbFTqCLmxVwGOl7LZ9kASvHdeQ== 370 | dependencies: 371 | define-properties "^1.1.3" 372 | 373 | he@1.2.0: 374 | version "1.2.0" 375 | resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" 376 | integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== 377 | 378 | html-metadata-parser@^2.0.4: 379 | version "2.0.4" 380 | resolved "https://registry.yarnpkg.com/html-metadata-parser/-/html-metadata-parser-2.0.4.tgz#74d74f4361631d2d9f4e2221219371e0db5d343d" 381 | integrity sha512-pBjST/bbe3nuy/fNmvyY4G+ypukQ/QHiGc+YnS4up2OVnT4vI0CZA4x2J0Ri77sQkQGH2IMAAug0fE78FfDrLw== 382 | dependencies: 383 | axios "^0.24.0" 384 | node-html-parser "^5.2.0" 385 | 386 | http-terminator@^3.0.3: 387 | version "3.0.3" 388 | resolved "https://registry.yarnpkg.com/http-terminator/-/http-terminator-3.0.3.tgz#2638c82b0223c13b483f0da8ea2eb73364b9bf6e" 389 | integrity sha512-rYvizQCjA9h4Lzh334/F7QJx71TOsyvHDxFzPA1+Sh520Wkgz8+C3KmYFwUAzy16pQrhFGg3BhJc5ZlcgixEag== 390 | dependencies: 391 | delay "^5.0.0" 392 | p-wait-for "^3.2.0" 393 | roarr "^7.0.4" 394 | type-fest "^2.3.3" 395 | 396 | iconv-lite@^0.6.2: 397 | version "0.6.3" 398 | resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501" 399 | integrity sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw== 400 | dependencies: 401 | safer-buffer ">= 2.1.2 < 3.0.0" 402 | 403 | is-circular@^1.0.2: 404 | version "1.0.2" 405 | resolved "https://registry.yarnpkg.com/is-circular/-/is-circular-1.0.2.tgz#2e0ab4e9835f4c6b0ea2b9855a84acd501b8366c" 406 | integrity sha512-YttjnrswnUYRVJvxCvu8z+PGMUSzC2JttP0OEXezlAEdp3EXzhf7IZ3j0gRAybJBQupedIZFhY61Tga6E0qASA== 407 | 408 | is-fullwidth-code-point@^3.0.0: 409 | version "3.0.0" 410 | resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" 411 | integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== 412 | 413 | is-property@^1.0.2: 414 | version "1.0.2" 415 | resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" 416 | integrity sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ= 417 | 418 | isexe@^2.0.0: 419 | version "2.0.0" 420 | resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" 421 | integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= 422 | 423 | json-schema-traverse@^0.4.1: 424 | version "0.4.1" 425 | resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" 426 | integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== 427 | 428 | json-stringify-safe@^5.0.1: 429 | version "5.0.1" 430 | resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" 431 | integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus= 432 | 433 | locate-path@^5.0.0: 434 | version "5.0.0" 435 | resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" 436 | integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== 437 | dependencies: 438 | p-locate "^4.1.0" 439 | 440 | long@^4.0.0: 441 | version "4.0.0" 442 | resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28" 443 | integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA== 444 | 445 | lru-cache@^4.1.3: 446 | version "4.1.5" 447 | resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.5.tgz#8bbe50ea85bed59bc9e33dcab8235ee9bcf443cd" 448 | integrity sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g== 449 | dependencies: 450 | pseudomap "^1.0.2" 451 | yallist "^2.1.2" 452 | 453 | lru-cache@^6.0.0: 454 | version "6.0.0" 455 | resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" 456 | integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== 457 | dependencies: 458 | yallist "^4.0.0" 459 | 460 | mime-db@1.49.0: 461 | version "1.49.0" 462 | resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.49.0.tgz#f3dfde60c99e9cf3bc9701d687778f537001cbed" 463 | integrity sha512-CIc8j9URtOVApSFCQIF+VBkX1RwXp/oMMOrqdyXSBXq5RWNEsRfyj1kiRnQgmNXmHxPoFIxOroKA3zcU9P+nAA== 464 | 465 | mime-types@^2.1.12: 466 | version "2.1.32" 467 | resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.32.tgz#1d00e89e7de7fe02008db61001d9e02852670fd5" 468 | integrity sha512-hJGaVS4G4c9TSMYh2n6SQAGrC4RnfU+daP8G7cSCmaqNjiOoUY0VHCMS42pxnQmVF1GWwFhbHWn3RIxCqTmZ9A== 469 | dependencies: 470 | mime-db "1.49.0" 471 | 472 | minimist@^1.2.5: 473 | version "1.2.5" 474 | resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" 475 | integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== 476 | 477 | module-alias@^2.2.2: 478 | version "2.2.2" 479 | resolved "https://registry.yarnpkg.com/module-alias/-/module-alias-2.2.2.tgz#151cdcecc24e25739ff0aa6e51e1c5716974c0e0" 480 | integrity sha512-A/78XjoX2EmNvppVWEhM2oGk3x4lLxnkEA4jTbaK97QKSDjkIoOsKQlfylt/d3kKKi596Qy3NP5XrXJ6fZIC9Q== 481 | 482 | ms@2.1.2: 483 | version "2.1.2" 484 | resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" 485 | integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== 486 | 487 | mysql2@^2.3.0: 488 | version "2.3.0" 489 | resolved "https://registry.yarnpkg.com/mysql2/-/mysql2-2.3.0.tgz#600f5cc27e397dfb77b59eac93666434f88e8079" 490 | integrity sha512-0t5Ivps5Tdy5YHk5NdKwQhe/4Qyn2pload+S+UooDBvsqngtzujG1BaTWBihQLfeKO3t3122/GtusBtmHEHqww== 491 | dependencies: 492 | denque "^1.4.1" 493 | generate-function "^2.3.1" 494 | iconv-lite "^0.6.2" 495 | long "^4.0.0" 496 | lru-cache "^6.0.0" 497 | named-placeholders "^1.1.2" 498 | seq-queue "^0.0.5" 499 | sqlstring "^2.3.2" 500 | 501 | named-placeholders@^1.1.2: 502 | version "1.1.2" 503 | resolved "https://registry.yarnpkg.com/named-placeholders/-/named-placeholders-1.1.2.tgz#ceb1fbff50b6b33492b5cf214ccf5e39cef3d0e8" 504 | integrity sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA== 505 | dependencies: 506 | lru-cache "^4.1.3" 507 | 508 | node-cache@^5.1.2: 509 | version "5.1.2" 510 | resolved "https://registry.yarnpkg.com/node-cache/-/node-cache-5.1.2.tgz#f264dc2ccad0a780e76253a694e9fd0ed19c398d" 511 | integrity sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg== 512 | dependencies: 513 | clone "2.x" 514 | 515 | node-env-run@^4.0.2: 516 | version "4.0.2" 517 | resolved "https://registry.yarnpkg.com/node-env-run/-/node-env-run-4.0.2.tgz#41c07cc6d6eef73300e30411af42b8be27578d83" 518 | integrity sha512-qAGmXrM32xUGdaCBmkQG8RIgm+8Oj22rURkAoX9HuKDQiM0Vm66QebkWEnU5nozYgPbO/PFPrPmerI6ZEPp8UQ== 519 | dependencies: 520 | "@types/common-tags" "^1.4.0" 521 | "@types/debug" "^4.1.5" 522 | "@types/node" "^10.17.28" 523 | "@types/yargs" "^15.0.5" 524 | common-tags "^1.7.2" 525 | cross-spawn "^7.0.3" 526 | debug "^4.1.1" 527 | dotenv "^8.2.0" 528 | pkginfo "^0.4.1" 529 | upath "^1.2.0" 530 | yargs "^15.4.1" 531 | 532 | node-fetch@^2.6.1: 533 | version "2.6.2" 534 | resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.2.tgz#986996818b73785e47b1965cc34eb093a1d464d0" 535 | integrity sha512-aLoxToI6RfZ+0NOjmWAgn9+LEd30YCkJKFSyWacNZdEKTit/ZMcKjGkTRo8uWEsnIb/hfKecNPEbln02PdWbcA== 536 | 537 | node-html-parser@^5.2.0: 538 | version "5.3.3" 539 | resolved "https://registry.yarnpkg.com/node-html-parser/-/node-html-parser-5.3.3.tgz#2845704f3a7331a610e0e551bf5fa02b266341b6" 540 | integrity sha512-ncg1033CaX9UexbyA7e1N0aAoAYRDiV8jkTvzEnfd1GDvzFdrsXLzR4p4ik8mwLgnaKP/jyUFWDy9q3jvRT2Jw== 541 | dependencies: 542 | css-select "^4.2.1" 543 | he "1.2.0" 544 | 545 | nth-check@^2.0.1: 546 | version "2.0.1" 547 | resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-2.0.1.tgz#2efe162f5c3da06a28959fbd3db75dbeea9f0fc2" 548 | integrity sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w== 549 | dependencies: 550 | boolbase "^1.0.0" 551 | 552 | object-keys@^1.0.12: 553 | version "1.1.1" 554 | resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" 555 | integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== 556 | 557 | p-finally@^1.0.0: 558 | version "1.0.0" 559 | resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae" 560 | integrity sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4= 561 | 562 | p-limit@^2.2.0: 563 | version "2.3.0" 564 | resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" 565 | integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== 566 | dependencies: 567 | p-try "^2.0.0" 568 | 569 | p-locate@^4.1.0: 570 | version "4.1.0" 571 | resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" 572 | integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== 573 | dependencies: 574 | p-limit "^2.2.0" 575 | 576 | p-timeout@^3.0.0: 577 | version "3.2.0" 578 | resolved "https://registry.yarnpkg.com/p-timeout/-/p-timeout-3.2.0.tgz#c7e17abc971d2a7962ef83626b35d635acf23dfe" 579 | integrity sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg== 580 | dependencies: 581 | p-finally "^1.0.0" 582 | 583 | p-timeout@^4.1.0: 584 | version "4.1.0" 585 | resolved "https://registry.yarnpkg.com/p-timeout/-/p-timeout-4.1.0.tgz#788253c0452ab0ffecf18a62dff94ff1bd09ca0a" 586 | integrity sha512-+/wmHtzJuWii1sXn3HCuH/FTwGhrp4tmJTxSKJbfS+vkipci6osxXM5mY0jUiRzWKMTgUT8l7HFbeSwZAynqHw== 587 | 588 | p-try@^2.0.0: 589 | version "2.2.0" 590 | resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" 591 | integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== 592 | 593 | p-wait-for@^3.2.0: 594 | version "3.2.0" 595 | resolved "https://registry.yarnpkg.com/p-wait-for/-/p-wait-for-3.2.0.tgz#640429bcabf3b0dd9f492c31539c5718cb6a3f1f" 596 | integrity sha512-wpgERjNkLrBiFmkMEjuZJEWKKDrNfHCKA1OhyN1wg1FrLkULbviEy6py1AyJUgZ72YWFbZ38FIpnqvVqAlDUwA== 597 | dependencies: 598 | p-timeout "^3.0.0" 599 | 600 | path-exists@^4.0.0: 601 | version "4.0.0" 602 | resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" 603 | integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== 604 | 605 | path-key@^3.1.0: 606 | version "3.1.1" 607 | resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" 608 | integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== 609 | 610 | pkginfo@^0.4.1: 611 | version "0.4.1" 612 | resolved "https://registry.yarnpkg.com/pkginfo/-/pkginfo-0.4.1.tgz#b5418ef0439de5425fc4995042dced14fb2a84ff" 613 | integrity sha1-tUGO8EOd5UJfxJlQQtztFPsqhP8= 614 | 615 | pseudomap@^1.0.2: 616 | version "1.0.2" 617 | resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" 618 | integrity sha1-8FKijacOYYkX7wqKw0wa5aaChrM= 619 | 620 | punycode@^2.1.0: 621 | version "2.1.1" 622 | resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" 623 | integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== 624 | 625 | require-directory@^2.1.1: 626 | version "2.1.1" 627 | resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" 628 | integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= 629 | 630 | require-main-filename@^2.0.0: 631 | version "2.0.0" 632 | resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" 633 | integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== 634 | 635 | rfdc@^1.2.0: 636 | version "1.3.0" 637 | resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.3.0.tgz#d0b7c441ab2720d05dc4cf26e01c89631d9da08b" 638 | integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA== 639 | 640 | roarr@^7.0.4: 641 | version "7.0.4" 642 | resolved "https://registry.yarnpkg.com/roarr/-/roarr-7.0.4.tgz#45b99eeb994281ffa42857037831a529e77a01f2" 643 | integrity sha512-o03Iq3Ne/Y8cVJ1+95ohOSST73j8PZmyjjxSp+XDdhIvpuG5shFB4zWOUPQUqfTI3GOm5Tc7ngJSxLaIqcOOKA== 644 | dependencies: 645 | boolean "^3.1.4" 646 | detect-node "^2.1.0" 647 | fast-json-stringify "^2.7.9" 648 | fast-printf "^1.6.9" 649 | globalthis "^1.0.2" 650 | is-circular "^1.0.2" 651 | json-stringify-safe "^5.0.1" 652 | semver-compare "^1.0.0" 653 | 654 | safe-compare@^1.1.4: 655 | version "1.1.4" 656 | resolved "https://registry.yarnpkg.com/safe-compare/-/safe-compare-1.1.4.tgz#5e0128538a82820e2e9250cd78e45da6786ba593" 657 | integrity sha512-b9wZ986HHCo/HbKrRpBJb2kqXMK9CEWIE1egeEvZsYn69ay3kdfl9nG3RyOcR+jInTDf7a86WQ1d4VJX7goSSQ== 658 | dependencies: 659 | buffer-alloc "^1.2.0" 660 | 661 | "safer-buffer@>= 2.1.2 < 3.0.0": 662 | version "2.1.2" 663 | resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" 664 | integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== 665 | 666 | sandwich-stream@^2.0.2: 667 | version "2.0.2" 668 | resolved "https://registry.yarnpkg.com/sandwich-stream/-/sandwich-stream-2.0.2.tgz#6d1feb6cf7e9fe9fadb41513459a72c2e84000fa" 669 | integrity sha512-jLYV0DORrzY3xaz/S9ydJL6Iz7essZeAfnAavsJ+zsJGZ1MOnsS52yRjU3uF3pJa/lla7+wisp//fxOwOH8SKQ== 670 | 671 | semver-compare@^1.0.0: 672 | version "1.0.0" 673 | resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" 674 | integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= 675 | 676 | seq-queue@^0.0.5: 677 | version "0.0.5" 678 | resolved "https://registry.yarnpkg.com/seq-queue/-/seq-queue-0.0.5.tgz#d56812e1c017a6e4e7c3e3a37a1da6d78dd3c93e" 679 | integrity sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4= 680 | 681 | set-blocking@^2.0.0: 682 | version "2.0.0" 683 | resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" 684 | integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= 685 | 686 | shebang-command@^2.0.0: 687 | version "2.0.0" 688 | resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" 689 | integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== 690 | dependencies: 691 | shebang-regex "^3.0.0" 692 | 693 | shebang-regex@^3.0.0: 694 | version "3.0.0" 695 | resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" 696 | integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== 697 | 698 | sqlstring@^2.3.2: 699 | version "2.3.2" 700 | resolved "https://registry.yarnpkg.com/sqlstring/-/sqlstring-2.3.2.tgz#cdae7169389a1375b18e885f2e60b3e460809514" 701 | integrity sha512-vF4ZbYdKS8OnoJAWBmMxCQDkiEBkGQYU7UZPtL8flbDRSNkhaXvRJ279ZtI6M+zDaQovVU4tuRgzK5fVhvFAhg== 702 | 703 | string-similarity@^4.0.1: 704 | version "4.0.4" 705 | resolved "https://registry.yarnpkg.com/string-similarity/-/string-similarity-4.0.4.tgz#42d01ab0b34660ea8a018da8f56a3309bb8b2a5b" 706 | integrity sha512-/q/8Q4Bl4ZKAPjj8WerIBJWALKkaPRfrvhfF8k/B23i4nzrlRj2/go1m90In7nG/3XDSbOo0+pu6RvCTM9RGMQ== 707 | 708 | string-width@^4.1.0, string-width@^4.2.0: 709 | version "4.2.3" 710 | resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" 711 | integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== 712 | dependencies: 713 | emoji-regex "^8.0.0" 714 | is-fullwidth-code-point "^3.0.0" 715 | strip-ansi "^6.0.1" 716 | 717 | strip-ansi@^6.0.0, strip-ansi@^6.0.1: 718 | version "6.0.1" 719 | resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" 720 | integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== 721 | dependencies: 722 | ansi-regex "^5.0.1" 723 | 724 | telegraf@^4.4.2: 725 | version "4.4.2" 726 | resolved "https://registry.yarnpkg.com/telegraf/-/telegraf-4.4.2.tgz#dd1b99a50593de303c8f47bbe98201a93a125f31" 727 | integrity sha512-OGt9w1LbxYUOsRk3htAavBnL9hqWycmJNiOmS74oARzxKFnYS/MdwW8b5CX9VLCJt537AXkm8/eBNiEYD8E7lQ== 728 | dependencies: 729 | abort-controller "^3.0.0" 730 | debug "^4.3.1" 731 | minimist "^1.2.5" 732 | module-alias "^2.2.2" 733 | node-fetch "^2.6.1" 734 | p-timeout "^4.1.0" 735 | safe-compare "^1.1.4" 736 | sandwich-stream "^2.0.2" 737 | typegram "^3.4.2" 738 | 739 | type-fest@^2.3.3: 740 | version "2.3.4" 741 | resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.3.4.tgz#59bd28c5715a7ea39f8fb0d7e424355ae231a24e" 742 | integrity sha512-2UdQc7cx8F4Ky81Xj7NYQKPhZVtDFbtorrkairIW66rW7xQj5msAhioXa04HqEdP4MD4K2G6QAF7Zyiw/Hju1Q== 743 | 744 | typegram@^3.4.2: 745 | version "3.4.3" 746 | resolved "https://registry.yarnpkg.com/typegram/-/typegram-3.4.3.tgz#a1e212beaf6b43079a3774457b40d6eab1a93acf" 747 | integrity sha512-pH0TQJzCWM2+7y6yiBoQVNt7PO9ZvAu/lQukVx4sm68FIBBZEBWI+2MzuMcdbwrD5mD5NrEMAyml9N6DupUZag== 748 | 749 | upath@^1.2.0: 750 | version "1.2.0" 751 | resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz#8f66dbcd55a883acdae4408af8b035a5044c1894" 752 | integrity sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg== 753 | 754 | uri-js@^4.2.2: 755 | version "4.4.1" 756 | resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" 757 | integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== 758 | dependencies: 759 | punycode "^2.1.0" 760 | 761 | which-module@^2.0.0: 762 | version "2.0.0" 763 | resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" 764 | integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= 765 | 766 | which@^2.0.1: 767 | version "2.0.2" 768 | resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" 769 | integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== 770 | dependencies: 771 | isexe "^2.0.0" 772 | 773 | wrap-ansi@^6.2.0: 774 | version "6.2.0" 775 | resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" 776 | integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== 777 | dependencies: 778 | ansi-styles "^4.0.0" 779 | string-width "^4.1.0" 780 | strip-ansi "^6.0.0" 781 | 782 | y18n@^4.0.0: 783 | version "4.0.3" 784 | resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.3.tgz#b5f259c82cd6e336921efd7bfd8bf560de9eeedf" 785 | integrity sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ== 786 | 787 | yallist@^2.1.2: 788 | version "2.1.2" 789 | resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" 790 | integrity sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI= 791 | 792 | yallist@^4.0.0: 793 | version "4.0.0" 794 | resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" 795 | integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== 796 | 797 | yargs-parser@^18.1.2: 798 | version "18.1.3" 799 | resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0" 800 | integrity sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ== 801 | dependencies: 802 | camelcase "^5.0.0" 803 | decamelize "^1.2.0" 804 | 805 | yargs@^15.4.1: 806 | version "15.4.1" 807 | resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.4.1.tgz#0d87a16de01aee9d8bec2bfbf74f67851730f4f8" 808 | integrity sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A== 809 | dependencies: 810 | cliui "^6.0.0" 811 | decamelize "^1.2.0" 812 | find-up "^4.1.0" 813 | get-caller-file "^2.0.1" 814 | require-directory "^2.1.1" 815 | require-main-filename "^2.0.0" 816 | set-blocking "^2.0.0" 817 | string-width "^4.2.0" 818 | which-module "^2.0.0" 819 | y18n "^4.0.0" 820 | yargs-parser "^18.1.2" 821 | -------------------------------------------------------------------------------- /src/bot.js: -------------------------------------------------------------------------------- 1 | import { Telegraf, Markup } from 'telegraf' 2 | import parser from 'html-metadata-parser' 3 | 4 | import db from './db.js' 5 | import onBoardingServer from './onBoarding.js' 6 | import debugLog from './debug.js' 7 | import notion from './notion.js' 8 | import cache from './cache.js' 9 | 10 | const bot = new Telegraf(process.env.telegramBotToken) 11 | 12 | //TODO refactor entire file using scenes, composers, stages, sessions 13 | //look https://blog.logrocket.com/how-to-build-a-telegram-ocr-bot/ 14 | //and https://telegraf.js.org/classes/MemorySessionStore.html 15 | 16 | //TODO accorpare codice duplicato in funzioni 17 | 18 | //TODO dare nomi meaningful a funzioni 19 | 20 | //TODO if parent is a page (not db) how to distinguish between create subpage or block 21 | 22 | function cancel (ctx) { 23 | cache.del( ctx.chat.id.toString() ) 24 | return ctx.reply('Current operation cancelled') 25 | } 26 | 27 | bot.command('cancel', cancel) 28 | 29 | bot.action('stopOperation', ctx=> 30 | ctx.answerCbQuery() 31 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 32 | .then(()=>cancel(ctx)) 33 | ) 34 | 35 | //BEGIN bot onBoarding 36 | 37 | function authorizeInNotion (ctx, again=false){ 38 | 39 | const notionAuthorizationUrl = new URL ("https://api.notion.com/v1/oauth/authorize") 40 | 41 | notionAuthorizationUrl.searchParams.append("client_id", process.env.notionOAuthClientId) 42 | notionAuthorizationUrl.searchParams.append("redirect_uri", onBoardingServer.redirect_uri) 43 | notionAuthorizationUrl.searchParams.append("response_type", "code") 44 | notionAuthorizationUrl.searchParams.append("state", '"'+ctx.chat.id+'"') 45 | notionAuthorizationUrl.searchParams.append("owner", "user") 46 | 47 | return ctx.reply( (again ? "A" : "Fisrt thing, a")+"uthorize the integration in Notion and select which pages to make available to this bot", 48 | Markup.inlineKeyboard([ 49 | Markup.button.url("Authorize in Notion", notionAuthorizationUrl), 50 | ]) 51 | ) 52 | } 53 | 54 | 55 | bot.action('continueReauthorization', ctx=> 56 | ctx.answerCbQuery() 57 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 58 | .then(()=>authorizeInNotion(ctx, true)) 59 | ) 60 | 61 | bot.start(ctx=> 62 | db.promiseExecute('INSERT INTO `TelegramChats` (`telegramChatId`,`chatType`) VALUES (?, ?)', [ctx.chat.id, ctx.chat.type]) 63 | .then(({error, result})=>{ 64 | 65 | if (error && error.code === 'ER_DUP_ENTRY') 66 | return ctx.reply( 67 | "You are alredy registered, do you wish to autorize again?", 68 | Markup.inlineKeyboard([ 69 | Markup.button.callback("Yes", "continueReauthorization"), 70 | Markup.button.callback("No", "stopOperation"), 71 | ]) 72 | ) 73 | 74 | //NOTE probably there are other errors that should be handled, but 10911 sql errors to read in documentation is a bit too much https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html 75 | //finger crossed 76 | if (!!error) 77 | throw new Error("Error registering telegram chat: "+err.code+" - "+err.sqlMessage) 78 | 79 | return ctx.reply( 80 | "Hey There!\n"+ 81 | "This is the most advanced (at the moment) Telegram to Notion bot.\n"+ 82 | "It takes few steps to get it up and running.\n"+ 83 | "Let's get started!" 84 | ) 85 | .then(()=>authorizeInNotion(ctx)) 86 | 87 | }) 88 | .catch(err=>{ 89 | console.warn(err) 90 | return ctx.reply(err) 91 | }) 92 | 93 | ) 94 | 95 | //END bot onBoarding 96 | 97 | 98 | /*TODO 99 | instead of 100 | - message 1: Selected template : n 101 | - message 2: Changing Page 102 | - message 3: Selected Workspace : n 103 | etc 104 | 105 | have message 1 with all that information, store its message_id in cache & modify it every time, add new information & needed buttons 106 | */ 107 | //TODO disposizioni e paginazione di pulsanti 108 | //TODO cancellare cache a fine operazioni 109 | //TODO add catch & error handling in every function 110 | //### maybe add back button here and there in keyboards 111 | //NOTE in cache.set all expansions in 'value' argument should go first, or they will overwrite changes, resulting in no change at all 112 | 113 | //regex stole @ https://stackoverflow.com/a/41603920 114 | const removeDoubleQuotes = /"(.*)"/ 115 | 116 | //BEGIN config 117 | 118 | const setTextRules = (ctx) => { 119 | const data = cache.get(ctx.chat.id.toString()) 120 | 121 | if (!data || ( !!data.templateData && !data.templateData.pageId && !data.pageData.id) ) 122 | return ctx.editMessageText("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 123 | 124 | 125 | //### maybe in future will have rules in a notion db the user share with the bot 126 | 127 | return db.promiseExecute( 128 | 'SELECT * FROM `NotionPagesProps` WHERE pageId=?', 129 | [data.templateData.pageId|| data.pageData.id] //if op:edit from template, if adding template from page 130 | ) 131 | .then(({result}) => db.promiseExecute( 132 | 'SELECT tr.orderNumber, pp.propName, tr.endsWith, tr.defaultValue, u.ruleId, u.title, u.imageDestination, u.siteName, u.description, u.type, u.author, u.url FROM `TemplateRules` AS tr LEFT OUTER JOIN `NotionPagesProps` AS pp ON pp.id = tr.propId LEFT OUTER JOIN `UrlMetaTemplateRules` AS u ON u.ruleId = tr.id WHERE tr.templateId=? ORDER BY tr.orderNumber', 133 | [data.templateData.id], 134 | {props:result} 135 | ) 136 | ) 137 | .then(({result, state}) => ctx.replyWithMarkdown( 138 | ( ( !result|| !result.length ) ? 139 | "There are no rules yet for this template" : 140 | "The rules for this template are:\n\n"+result.map(rule => { 141 | const {orderNumber, propName, endsWith, defaultValue, title, description, author, type, siteName, imageDestination, url} = rule 142 | 143 | const propIdToName = (propId) => propId === null ? '' : state.props.filter(prop=>prop.id === propId)[0].propName 144 | 145 | const stdRules = [propName, endsWith, defaultValue] 146 | const urlRules = [title, siteName, description, url, type, author].map(propIdToName) 147 | 148 | return orderNumber+" - "+stdRules.join(', ')+( typeof rule.ruleId !== 'number' ? '' : ("\\[ "+imageDestination+', '+urlRules.join(', ')+" \]") ) //dunno y but first one wants \\ 149 | }).join('\n') 150 | )+ 151 | "\n\nTo change the rules reply to this message with the new set of rules that will replace the old ones (if any). Use the same format:\n\n"+ 152 | "`number - property name, string end with, property default value`\n\n"+ 153 | "Property names for pages are only Title and Content."+ 154 | "You can leave blank between commas. If `string ends with` is blank, `default value` will be saved in `property name`.\n\n"+ 155 | "If you need to have commas or escaped characters in a field, wrap it with \" \", note that *if `ends with` is wrapped in \" \" it will be used as a regex*\n"+ 156 | "Numbers must be progressive.\n\n"+ 157 | "If it is a url that you want to parse add\n\n"+ 158 | "`\[ image, title, site name, description, url, type, author \]`\n\n"+ 159 | "after _`property default value`_ where values between \[\]:\n"+ 160 | "- image: 0 to save url cover to content, 1 to cover, 2 to icon\n"+ 161 | "- all other are properties names of the selected database where that information extracted from the url will be saved.\n\n"+ 162 | "Property names are: "+state.props.map(prop=>prop.propName).join(', '), 163 | Markup.forceReply() 164 | ) 165 | .then(({message_id}) => { 166 | cache.set(ctx.chat.id.toString(), { 167 | ...data, 168 | replyFor:'editRule', 169 | props:state.props, 170 | message_id 171 | }) 172 | }) 173 | ) 174 | .catch(err => { 175 | console.warn(err) 176 | ctx.reply("Error getting teplate rules: "+err+"\n\nYou can try again later or report the incident on GitHub.") 177 | }) 178 | } 179 | 180 | bot.action('editTextRules', ctx => ctx.answerCbQuery() 181 | .then(() => ctx.editMessageText("Editing text rules")) 182 | .then(() => setTextRules(ctx)) 183 | ) 184 | 185 | bot.action(/setImageDestination(\d+)/i, ctx=> 186 | ctx.answerCbQuery() 187 | .then(() => ctx.editMessageText(ctx.callbackQuery.message.text)) 188 | .then(() => { 189 | const data = cache.get(ctx.chat.id.toString()) 190 | 191 | if (!data) 192 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 193 | 194 | debugLog(ctx.match[1] === '3' ? null : ctx.match[1]) 195 | 196 | return db.promiseExecute('UPDATE `Templates` SET `ImageDestination`=? WHERE id=?', [(ctx.match[1] === '3' ? null : ctx.match[1]), data.templateData.id], {data}) 197 | }) 198 | .then(({error, state}) => { 199 | if (!!error) 200 | throw new Error(error.code+" - "+error.sqlMessage) 201 | 202 | const msg = ctx.match[1] === '3' ? " is ignoring images" : " is saving images to "+["content", "cover", "icon"][ctx.match[1]] 203 | 204 | return ctx.reply("Done: now template "+state.data.templateData.userTemplateNumber+msg) 205 | .then(()=>state.data) 206 | }) 207 | .then(data => { 208 | 209 | if(data.op==='edit') 210 | return selectTemplate(data.templateData.id, ctx) 211 | 212 | return setTextRules(ctx) 213 | }) 214 | .catch(err => { 215 | console.warn(err) 216 | debugLog(ctx.message) 217 | ctx.reply("Error updating image destination: "+err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 218 | }) 219 | ) 220 | 221 | 222 | const editImageDestination = ctx => ctx.reply( 223 | "In which section of the page do you want me to save images you send me?", 224 | Markup.inlineKeyboard([ 225 | Markup.button.callback("Content", 'setImageDestination0'), 226 | Markup.button.callback("Cover", 'setImageDestination1'), 227 | Markup.button.callback("Icon", 'setImageDestination2'), 228 | Markup.button.callback("Do not save",'setImageDestination3'), 229 | //TODO add cancel button 230 | ]) 231 | ) 232 | 233 | bot.action('editImageDestination', ctx => 234 | ctx.answerCbQuery() 235 | .then(() => ctx.editMessageText(ctx.callbackQuery.message.text)) 236 | .then(() => editImageDestination(ctx)) 237 | ) 238 | 239 | const selectPage = (pageId, ctx) => { 240 | 241 | const data = cache.get(ctx.chat.id.toString()) 242 | 243 | if (!data) 244 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 245 | 246 | const {pages, templateData, workspaceData, op, ...userData} = data 247 | 248 | const page = pages.filter( ({id}) => id === pageId)[0] 249 | 250 | //can always call editMessageText because selectPage is always called from bot.action 251 | return ctx.editMessageText("Selected page: "+page.title) 252 | .then(() => db.promiseExecute('UPDATE `Templates` SET pageId=? WHERE id=?', [page.id, templateData.id])) 253 | .then(({error}) => { 254 | 255 | if(!!error) 256 | throw new Error(error.code+" - "+error.sqlMessage) 257 | 258 | cache.set(ctx.chat.id.toString(), {...userData, templateData, workspaceData, op, pageData:page}) 259 | 260 | if (!!op && op === 'edit') 261 | return ctx.reply("All good: page for template "+templateData.userTemplateNumber+" set to "+page.title+" in workspace named "+workspaceData.name) 262 | .then(()=>selectTemplate(templateData.id, ctx)) 263 | 264 | return editImageDestination(ctx) 265 | }) 266 | } 267 | 268 | bot.action(/selectPG(\d+)/i, ctx=> 269 | ctx.answerCbQuery() 270 | .then(()=>selectPage(parseInt(ctx.match[1]), ctx)) 271 | ) 272 | 273 | bot.action(/registerPG(\d+)/i, ctx=>{ 274 | 275 | const data = cache.get(ctx.chat.id.toString()) 276 | 277 | if (!data) 278 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience 😅") 279 | 280 | 281 | const {notionPages, pages, ...userData} = data 282 | 283 | var {id, icon, properties, object, title} = notionPages[parseInt(ctx.match[1])] 284 | 285 | const pageTitle = object === 'database' ? title[0].plain_text : notion.titleFromProps(properties) 286 | 287 | icon = !!icon ? (icon.type === 'emoji' ? icon.emoji : icon.url) : null; 288 | 289 | debugLog([object === "database" ? "db" : "pg", data.workspaceData.workspaceId, id, icon, pageTitle, data.templateData.chatId]) 290 | 291 | return db.promiseExecute( 292 | 'INSERT INTO `NotionPages` (`pageType`, `workspaceId`, `notionPageId`, `icon`, `title`, `chatId`) VALUES (?, ?, ?, ?, ?, ?)', 293 | [object === "database" ? "db" : "pg", data.workspaceData.workspaceId, id, icon, pageTitle, data.templateData.chatId] 294 | ) 295 | .then(({error}) => { 296 | 297 | if (!!error) 298 | throw new Error("Cannot register new page: "+error.code+" - "+error.sqlMessage) 299 | 300 | return db.promiseExecute('SELECT MAX(id) AS id, pageType, icon, title FROM NotionPages WHERE chatId=?', [data.templateData.chatId]) 301 | }) 302 | .then( ({result}) => { 303 | 304 | const props = Object.entries(properties).map( ([key, value]) => ([value.id, result[0].id, key, notion.propTypes.indexOf(value.type)])) 305 | props.push([null, result[0].id, "Content", null]) 306 | 307 | //cannot use db.promise ( === db.execute) cuz cannot bulk import with prepared statements, using db.promiseQuery ( === db.query ) 308 | return db.promiseQuery( 309 | 'INSERT INTO `NotionPagesProps` (`notionPropId`, `pageId`, `propName`, `propTypeId`) VALUES ?', 310 | [props], 311 | result 312 | ) 313 | }) 314 | .then(({error, state})=>{ 315 | 316 | if (!!error) 317 | throw new Error("Cannot register props: "+error.code+" - "+error.sqlMessage) 318 | 319 | 320 | cache.set(ctx.chat.id.toString(), {...userData, pages:state}) 321 | 322 | return selectPage(state[0].id, ctx) 323 | }) 324 | .catch(err => { 325 | console.warn(err) 326 | ctx.reply("Error saving new page: "+err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 327 | }) 328 | 329 | }) 330 | 331 | bot.on(['text', 'edited_message'], (ctx, next)=>{ 332 | 333 | const data = cache.get(ctx.chat.id.toString()) 334 | 335 | if (!!data && 336 | ( 337 | ( data.message_id && ctx.message?.reply_to_message?.message_id === data.message_id ) || 338 | ( data.ed_message_id && ctx.update?.edited_message?.reply_to_message?.message_id === data.ed_message_id ) 339 | ) 340 | ) { 341 | 342 | switch(data.replyFor){ 343 | case 'editRule': 344 | 345 | const retry = err => 346 | ctx.reply(err+"\nYou can try again or /cancel\n\nThis page properties are: "+data.props.map(p=>p.propName).join(', '), Markup.forceReply()) 347 | .then(({message_id})=>cache.set(ctx.chat.id.toString(), {...data, message_id, ed_message_id: ctx.updateType === 'edited_message' ? data.ed_message_id : data.message_id})) //only allow edit on users last message 348 | 349 | 350 | try { 351 | /*exampe for https://t.me/ebookfreehouse: 352 | 353 | 0 - , "📚 ", 354 | 1 - Titolo, "📚\n\n✍🏻 Autore:", 355 | 2 - Autore, "\n📤 Formato: ", 356 | 3 - , "\n🇮🇹 Lingua: ", 357 | 4 - , "\n📆 Anno: ", 358 | 5 - Anno, "\n📖 Genere: ", 359 | 6 - Genere, "\n📝 Fonte: ", 360 | 7 - Link, "\n—", [ , , , , , ] 361 | 8 - , "𝘐𝘯𝘤𝘪𝘱𝘪𝘵: ", 362 | 9 - Content, @, 363 | 364 | */ 365 | 366 | const text = !!ctx.message ? ctx.message.text : ctx.update.edited_message.text 367 | 368 | const rows = text.split(/\n?(\d+) *- *//* match like '5 - '*/).filter(item => item.length > 1) //remove order number from capture group (\d+), will use that in future to have different parse and write order 369 | // debugLog(rows) 370 | debugLog("\n") 371 | 372 | const rules = rows.map(rule => { 373 | const a = rule.split(/ *\[(.*)\] */) 374 | 375 | if (a[a.length-1] === '') 376 | a.pop() 377 | 378 | //regex proudly stole @ https://stackoverflow.com/a/25544437 379 | const [one, two] = a.map(item=>item.split(/ *,(?=(?:[^"]*"[^"]*")*[^"]*$) */g).map(str => str.length ? str.trim() : null)) 380 | 381 | if (!!two) 382 | one.push(two) 383 | 384 | //prepare data for import 385 | return one.map((item, key) => { 386 | 387 | const propNameToId = propName => { 388 | 389 | if (!propName) 390 | return null 391 | 392 | const prop = data.props.filter(prop => prop.propName.toLowerCase() === propName.toLowerCase()) 393 | 394 | if (!prop.length) 395 | throw new Error("Couldnt find property `"+propName+"` in the selected page.") 396 | 397 | return prop[0].id 398 | } 399 | 400 | switch (key){ 401 | case 0: //prop name 402 | 403 | //prop name to prop id 404 | return !!item ? propNameToId(item.replace(removeDoubleQuotes, '$1')) : null 405 | 406 | case 1: //ends with 407 | 408 | if (!!item && item.length > 255) 409 | throw new Error("Maximum length for `ends with` is 255 characters") 410 | 411 | return item 412 | 413 | case 2: //default value 414 | 415 | if (!!item && item.length > 255) 416 | throw new Error("Maximum length for `default value` is 255 characters") 417 | 418 | return item 419 | 420 | case 3: //url rule 421 | 422 | //prop names to prop id s 423 | 424 | var [urlImageDestination, ...urlRules] = item 425 | 426 | urlRules = urlRules.map(propNameToId) 427 | 428 | urlRules = Array(6).fill(null).map((el, key) => !!urlRules[key] ? urlRules[key] : null) 429 | 430 | return [urlImageDestination, ...urlRules] 431 | 432 | } 433 | }) 434 | }) 435 | 436 | debugLog("Parsed rules: ", rules) 437 | 438 | const urlRules = rules.filter(rule=>rule.length === 4).map(rule=>rule[3]) 439 | 440 | debugLog("Parsed url rules: ", urlRules) 441 | 442 | return db.transactionPromise() 443 | .then((connection, transactionError) => { 444 | 445 | if (!!transactionError) 446 | throw new Error("Cannot begin transaction: "+transactionError.code+" - "+transactionError.sqlMessage) 447 | 448 | return connection.promiseExecute( 449 | 'DELETE TemplateRules.*, UrlMetaTemplateRules.* FROM TemplateRules LEFT OUTER JOIN UrlMetaTemplateRules ON UrlMetaTemplateRules.ruleId = TemplateRules.id WHERE TemplateRules.templateId=?', 450 | [data.templateData.id] 451 | ) 452 | .then(({error}) => { 453 | 454 | if (!!error) 455 | throw new Error("Cannot delete old rules: "+error.code+" - "+error.sqlMessage) 456 | 457 | debugLog("Deleted old rules") 458 | 459 | const a = rules.map((rule, key) => [ data.templateData.id, key, ...rule.slice(0,3) ]) 460 | 461 | debugLog(a) 462 | 463 | return connection.promiseQuery( 464 | 'INSERT INTO `TemplateRules` (templateId, orderNumber, propId, endsWith, defaultValue) VALUES ?', 465 | [a] 466 | ) 467 | }) 468 | .then(({error}) => { 469 | 470 | if (!!error){ 471 | 472 | if (error.code === 'ER_WRONG_VALUE_COUNT_ON_ROW') 473 | throw new Error("Cannot parse rules: missing a comma?") 474 | throw new Error("Cannot save rules: "+error.code+" - "+error.sqlMessage) 475 | } 476 | 477 | debugLog("Inserted new rules") 478 | 479 | return connection.promiseExecute('SELECT MAX(id) AS id from `TemplateRules`', []) 480 | }) 481 | .then(({result}) =>{ 482 | 483 | if (!urlRules|| !urlRules.length) 484 | return {} 485 | 486 | const firstRuleWithUrlId = result[0].id + 1 - rules.length 487 | const ruleWithUrlIds = [] 488 | 489 | let i=0; 490 | while (i < rules.length) { 491 | rules[i].length === 4 && ruleWithUrlIds.push(firstRuleWithUrlId + i); 492 | i++; 493 | } 494 | 495 | const a = urlRules.map((rule, key) => [ ruleWithUrlIds[key] , ...rule]) 496 | 497 | 498 | debugLog(a) 499 | 500 | return connection.promiseQuery( 501 | 'INSERT INTO `UrlMetaTemplateRules` (ruleId, imageDestination, title, siteName, description, url, type, author) VALUES ?', 502 | [a] 503 | ) 504 | }) 505 | .then(({error}) => { 506 | 507 | if (!!error) 508 | throw new Error("Cannot save url rules: "+error.code+" - "+error.sqlMessage) 509 | 510 | debugLog("Inserted new url rules") 511 | 512 | return connection.commitPromise(connection) 513 | }) 514 | .then((error) =>{ 515 | 516 | if (!!error) 517 | throw new Error("Cannot commit rules: "+error.code+" - "+error.sqlMessage) 518 | 519 | // const {replyFor, message_id, props, ed_message_id, ...databis} = data 520 | // cache.set(ctx.chat.id.toString(), databis) 521 | cache.del(ctx.chat.id.toString()) 522 | 523 | return ctx.reply("All good, understood new rules and updated.") 524 | }) 525 | .catch(error=>{ 526 | console.warn(error) 527 | connection.rollbackPromise(connection) 528 | // return ctx.reply("Failed setting rules: \n"+error+"\n\nYou can try again later, search the error or report the incident on GitHub.") 529 | return retry(error) 530 | }) 531 | }) 532 | } 533 | catch (err){ 534 | debugLog(err) 535 | 536 | return retry(err) 537 | } 538 | 539 | break; 540 | default: 541 | case 'addPage' : 542 | return notion.client.search({ 543 | auth:data.workspaceData.accessToken, 544 | query:ctx.message.text, 545 | }).then(res=>{ 546 | 547 | if (!res.results.length) 548 | return ctx.reply('no results, search again or /cancel', Markup.forceReply()) 549 | .then(({message_id})=>cache.set(ctx.chat.id.toString(), {...data, message_id, ed_message_id: ctx.updateType === 'edited_message' ? data.ed_message_id : data.message_id})) //only allow edit on users last message 550 | else{ 551 | 552 | const {replyFor, message_id, ed_message_id, ...databis} = data 553 | cache.set(ctx.chat.id.toString(), {...databis, notionPages:res.results}) 554 | 555 | return ctx.reply( 556 | "Select a page:", 557 | Markup.inlineKeyboard(res.results.map(({id, object, title, properties}, key)=>{ 558 | 559 | //TODO display pg.icon if emoji in button text 560 | //TODO display emoji if page or database (pg.pageType) 561 | 562 | const buttonTitle = object === 'database' ? title[0].plain_text : notion.titleFromProps(properties) 563 | 564 | return Markup.button.callback((key+1)+" - "+buttonTitle, "registerPG"+key) 565 | })) 566 | ) 567 | } 568 | }) 569 | .catch(err => { 570 | console.warn(err) 571 | debugLog(ctx.message) 572 | ctx.reply("Error adding page: "+err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 573 | }) 574 | break; 575 | } 576 | } 577 | else 578 | return next() 579 | }) 580 | 581 | const addPage = ctx =>{ 582 | 583 | const data = cache.get(ctx.chat.id.toString()) 584 | 585 | if (!data) 586 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 587 | 588 | return ctx.reply( 589 | "Reply to this message with the title of the page or database you would like to use in your template.\n\nNote: the page or database must exist and be shared with this integration.", 590 | Markup.forceReply() 591 | ) 592 | .then(({message_id})=>cache.set(ctx.chat.id.toString(), {...data, message_id, replyFor:'addPage'})) 593 | } 594 | 595 | bot.action('addPage', ctx=> 596 | ctx.answerCbQuery() 597 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 598 | .then(()=>addPage(ctx)) 599 | ) 600 | 601 | const selectWorkspace = (workspaceId, ctx) => { 602 | 603 | const data = cache.get(ctx.chat.id.toString()) 604 | 605 | if (!data) 606 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 607 | 608 | const {workspaces, ...userData} = data 609 | 610 | const workspaceData = workspaces.filter(workspace =>workspace.workspaceId === workspaceId)[0] 611 | 612 | ctx.callbackQuery && ctx.callbackQuery.message.from.username === 'NotionSaverBot' && ctx.editMessageText("Selected Workspace : "+workspaceData.name) 613 | 614 | //check if user has any page 615 | return db.promiseExecute('SELECT id, pageType, icon, title FROM NotionPages WHERE chatId=?', [userData.templateData.chatId]) 616 | .then(({result})=>{ 617 | 618 | //keep just selected workspace & save pages 619 | cache.set(ctx.chat.id.toString(), {...userData, workspaceData, pages:result}) 620 | 621 | if (!result.length) 622 | return addPage(ctx) 623 | else 624 | //TODO display pg.icon if emoji in button text 625 | //TODO display emoji if page or database (pg.pageType) 626 | return ctx.reply( 627 | "Select a page:", 628 | Markup.inlineKeyboard([ 629 | ...result.map(({id, title}, key)=>Markup.button.callback((key+1)+" - "+title, "selectPG"+id)), 630 | Markup.button.callback('+', 'addPage'), 631 | ]) 632 | ) 633 | 634 | }) 635 | } 636 | 637 | bot.action(/selectWK(\d+)/i, ctx=> 638 | ctx.answerCbQuery() 639 | .then(()=>selectWorkspace(parseInt(ctx.match[1]), ctx)) 640 | ) 641 | 642 | //cant define addWorkspace function as authorizeInNotion.then etc bc there is onBoarding before 643 | //TODO pass templateId to authorizeInNotion, that saves it in state, then read it in onBoarding and after everything done call selectWorkspace to resume operation 644 | 645 | bot.action('addWorkspace', ctx=> 646 | ctx.answerCbQuery() 647 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 648 | .then(()=>authorizeInNotion(ctx)) 649 | ) 650 | 651 | const preSelectWorkspace = ctx => { 652 | 653 | const data = cache.get(ctx.chat.id.toString()) 654 | 655 | if (!data) 656 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 657 | 658 | const {templateData, ...userData} = data 659 | 660 | //check if user has any workspace 661 | return db.promiseExecute('SELECT wc.accessToken, wc.workspaceId, nw.name, nw.icon FROM NotionWorkspacesCredentials AS wc LEFT OUTER JOIN NotionWorkspaces AS nw ON nw.id=wc.workspaceId WHERE wc.chatId=?', [templateData.chatId]) 662 | .then(({result})=>{ 663 | 664 | //keep just the selected template & save workspaces 665 | cache.set(ctx.chat.id.toString(), {...data, workspaces:result}) 666 | 667 | //if no workspaces authorized 668 | if (!result|| !result.length) 669 | return ctx.reply("No workspace found. Add one then try again:") 670 | //TODO see preceding TODO 671 | .then(()=>authorizeInNotion(ctx)) 672 | 673 | //select a workspace 674 | else 675 | //TODO display nw.icon if emoji in button text 676 | return ctx.reply( 677 | "Select a workspace:", 678 | Markup.inlineKeyboard([ 679 | ...result.map(({workspaceId, name}, key)=>Markup.button.callback((key+1)+" - "+name, "selectWK"+workspaceId)), 680 | Markup.button.callback('+', 'addWorkspace'), 681 | //TODO add cancel button 682 | ]) 683 | ) 684 | }) 685 | } 686 | 687 | bot.action('changePage', ctx => 688 | ctx.answerCbQuery() 689 | .then(()=>ctx.editMessageText("Changing template's page")) 690 | .then(()=>preSelectWorkspace(ctx)) 691 | ) 692 | 693 | bot.action('changeRule', ctx => 694 | ctx.answerCbQuery() 695 | .then(()=>ctx.editMessageText("Editing rules")) 696 | .then(()=>ctx.reply( 697 | "Do you want to edit what to do with image or text?", 698 | Markup.inlineKeyboard([ 699 | Markup.button.callback('Image', 'editImageDestination'), 700 | Markup.button.callback('Text', 'editTextRules'), 701 | //NOTE will add audio & files 702 | //TODO add cancel button 703 | ]) 704 | )) 705 | ) 706 | 707 | bot.action('deleteTemplateConfirmed', ctx => 708 | ctx.answerCbQuery() 709 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 710 | .then(()=>{ 711 | const data = cache.get(ctx.chat.id.toString()) 712 | 713 | if (!data) 714 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 715 | 716 | //delete a template and its rules (via sql foreign key ON DELETE CASCADE) 717 | return db.promiseExecute('DELETE FROM Templates WHERE id=?', [data.templateData.id], data.templateData) 718 | }) 719 | .then(({error, state})=>{ 720 | 721 | if (error) 722 | throw new Error (`Cannot delete template '${state.userTemplateNumber}': ${error.code} - ${error.sqlMessage}`) 723 | 724 | return ctx.editMessageText(`Template '${state.userTemplateNumber}' deleted`) 725 | }) 726 | .catch(err => { 727 | console.warn(err) 728 | ctx.editMessageText(err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 729 | }) 730 | ) 731 | 732 | bot.action('deleteTemplate', ctx => 733 | ctx.answerCbQuery() 734 | .then(()=>ctx.editMessageText( 735 | "Do you really want to delete this template?", 736 | Markup.inlineKeyboard([ 737 | Markup.button.callback("Yes", 'deleteTemplateConfirmed'), 738 | Markup.button.callback("No", 'stopOperation'), 739 | ]))) 740 | ) 741 | 742 | const selectTemplate = (templateId, ctx) => { 743 | 744 | const data = cache.get(ctx.chat.id.toString()) 745 | 746 | if (!data) 747 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 748 | 749 | //get array of templates 750 | const {templates, ...userData} = data 751 | 752 | if (!!templates){ 753 | const templateData = templates.filter(({id})=>id===templateId)[0] 754 | 755 | ctx.callbackQuery && ctx.callbackQuery.message.from.username === 'NotionSaverBot' && ctx.editMessageText("Selected Template : "+templateData.userTemplateNumber) 756 | 757 | cache.set(ctx.chat.id.toString(), {...userData, templateData}) 758 | 759 | //if the selected template has NULL pageId automatically add it 760 | if (!templateData.pageId) 761 | return preSelectWorkspace(ctx) 762 | } 763 | 764 | if (!!userData.op && userData.op === "edit") 765 | return ctx.reply( 766 | //TODO insert here current template configuration" 767 | "What do you want to do?", 768 | Markup.inlineKeyboard([ 769 | Markup.button.callback("Change page", 'changePage'), 770 | Markup.button.callback("Change rules", 'changeRule'), 771 | Markup.button.callback("Delete Template", 'deleteTemplate'), 772 | //TODO exit button ('exit') 773 | ])) 774 | 775 | return preSelectWorkspace(ctx) 776 | } 777 | 778 | bot.action(/selectTP(\d+)/i, ctx=>{ 779 | 780 | const data = cache.get(ctx.chat.id.toString()) 781 | 782 | if (!data) 783 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 784 | 785 | cache.set(ctx.chat.id.toString(), {...data, op:'edit'}) 786 | 787 | return ctx.answerCbQuery() 788 | .then(()=>ctx.editMessageText(`Editing template '${ data.templates.filter(tp => tp.id === parseInt(ctx.match[1]))[0].userTemplateNumber }'`)) //remove keyboard 789 | .then(()=>selectTemplate(parseInt(ctx.match[1]), ctx)) 790 | }) 791 | 792 | const addTemplate = ctx =>{ 793 | 794 | const data = cache.get(ctx.chat.id.toString()) 795 | 796 | if (!data) 797 | return ctx.reply("We lost your cached data, please start the operation again.\n\nSorry for the incovenience") 798 | 799 | const {templates} = data 800 | 801 | const userTemplateNumber = !templates.length ? 0 : templates[templates.length-1].userTemplateNumber+1 802 | 803 | return db.promiseExecute('SELECT id FROM TelegramChats WHERE telegramChatId=?', [ctx.chat.id]) 804 | .then(({result})=>db.promiseExecute('INSERT INTO Templates (`userTemplateNumber`, `chatId`) VALUES (?, ?)', [userTemplateNumber, result[0].id], {id:result[0].id})) 805 | .then(({state})=>db.promiseExecute('SELECT MAX(id) AS id, userTemplateNumber, chatId FROM Templates WHERE chatId=?', [state.id], state)) 806 | .then(({result, state}) => { 807 | 808 | //if first template added by 0user, set as default 809 | if ( !templates.length ) 810 | return db.promiseExecute('UPDATE TelegramChats SET currentTemplateId = ? WHERE id = ?', [ result[0].id, state.id ], result); 811 | 812 | return {state:result} 813 | }) 814 | .then(({state : result})=>{ 815 | 816 | //set array of templates, just one 817 | cache.set(ctx.chat.id.toString(), {templates:result}) //NOTE result is already an array thanks to MAX 818 | 819 | return selectTemplate(result[0].id, ctx) 820 | }) 821 | } 822 | 823 | bot.action('addTemplate', ctx=> 824 | ctx.answerCbQuery() 825 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 826 | .then(()=>{ 827 | cache.set(ctx.chat.id.toString(), {templates:[]}) 828 | return addTemplate(ctx) 829 | }) 830 | ) 831 | 832 | bot.command('config', ctx=> 833 | //get user templates 834 | // db.promiseExecute('SELECT t.id, t.userTemplateNumber, p.pageType, p.icon, tc.id AS chatId FROM Templates AS t LEFT OUTER JOIN NotionPages AS p ON p.id=t.pageId LEFT OUTER JOIN TelegramChats AS tc ON tc.id = p.chatId WHERE tc.telegramChatId=? ORDER BY t.userTemplateNumber',[ctx.chat.id]) 835 | //WARNING tmp to not create a new template every time the operation will not conclude 836 | db.promiseExecute('SELECT t.id, t.userTemplateNumber, t.pageId, tc.id AS chatId, t.pageId FROM Templates AS t LEFT OUTER JOIN TelegramChats AS tc ON tc.id = t.chatId WHERE tc.telegramChatId=? ORDER BY t.userTemplateNumber',[ctx.chat.id]) 837 | .then(({result})=>{ 838 | 839 | //set array of templates 840 | cache.set(ctx.chat.id.toString(), {templates:result}) 841 | 842 | //if no templates add one: 843 | if (!result.length) 844 | return ctx.reply("No existing template found, adding a new one") 845 | .then(()=>addTemplate(ctx)) 846 | 847 | //choose between existing templates & add button 848 | else 849 | //TODO display p.icon if emoji in button text 850 | //TODO display emoji if page or database (p.pageType) 851 | return ctx.reply( 852 | "Select a template to edit", 853 | Markup.inlineKeyboard([ 854 | ...result.map(({id, userTemplateNumber}, key)=>Markup.button.callback(userTemplateNumber, "selectTP"+id)), 855 | Markup.button.callback('+', 'addTemplate'), 856 | //TODO add cancel button 857 | ]) 858 | ) 859 | }) 860 | ) 861 | 862 | //END config 863 | 864 | //BEGIN use 865 | const activateTemplate = (userTemplateNumber, ctx) => 866 | db.promiseExecute('SELECT t.id FROM Templates AS t JOIN TelegramChats as tc ON tc.id = t.chatId WHERE tc.telegramChatId=? AND t.userTemplateNumber=?', [ctx.chat.id, userTemplateNumber]) 867 | .then(({error, result})=> { 868 | if (!!error) 869 | throw new Error ("Cannot get template id: "+error.code+" - "+error.sqlMessage) 870 | 871 | return db.promiseExecute('UPDATE TelegramChats SET currentTemplateId=? WHERE TelegramChats.telegramChatId=? ', [result[0].id, ctx.chat.id]) 872 | }) 873 | .then(({error}) => { 874 | if (!!error) 875 | throw new Error ("Cannot set active template"+error.code+" - "+error.sqlMessage) 876 | 877 | return ctx.reply("Using template "+userTemplateNumber) 878 | }) 879 | .catch(err => { 880 | console.warn(err) 881 | ctx.reply("Cannot use template "+userTemplateNumber+" : "+err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 882 | }) 883 | 884 | bot.action(/activateTemplate(\d+)/i, ctx => 885 | ctx.answerCbQuery() 886 | .then(()=>ctx.editMessageText(ctx.callbackQuery.message.text)) //remove keyboard 887 | .then(()=>activateTemplate(ctx.match[1], ctx)) 888 | ) 889 | 890 | bot.command("use", ctx => { 891 | 892 | const userTemplateNumber = ctx.message.text.split('/use ')[1] 893 | 894 | return db.promiseExecute('SELECT t.userTemplateNumber, np.title FROM Templates as t JOIN TelegramChats as tc ON tc.id = t.chatId JOIN NotionPages as np on np.id = t.pageId WHERE tc.telegramChatId=?', [ctx.chat.id]) 895 | .then(({error, result}) => { 896 | if (!!error) 897 | throw new Error ("Cannot get your templates: "+error.code+" - "+error.sqlMessage) 898 | if (!result.length) 899 | return ctx.reply("No template found, adding a new one (use /cancel to abort)") 900 | .then(() => { 901 | 902 | cache.set(ctx.chat.id.toString(), {templates:[]}) 903 | 904 | return addTemplate(ctx) 905 | }) 906 | .then(() => activateTemplate(0, ctx)) 907 | 908 | //if a valid template number specified, select it directly 909 | if (typeof userTemplateNumber === "string" && result.map(({userTemplateNumber}) => userTemplateNumber+"").includes(userTemplateNumber)) 910 | return activateTemplate(userTemplateNumber, ctx) 911 | 912 | //else ask wich one to use 913 | return ctx.reply( 914 | "Choose wich template to use (if you dont remember them you can use /list):", 915 | Markup.inlineKeyboard([ 916 | ...result.map(({userTemplateNumber, title})=>Markup.button.callback(`${userTemplateNumber} - ${title}`, "activateTemplate"+userTemplateNumber)), 917 | Markup.button.callback('+', 'addTemplate'), 918 | //TODO add cancel button 919 | ]) 920 | ) 921 | }) 922 | .catch(err => { 923 | console.warn(err) 924 | ctx.reply(err+"\n\nYou can try again later, search the error or report the incident on GitHub.") 925 | }) 926 | }) 927 | 928 | //END use 929 | 930 | 931 | //BEGIN core 932 | 933 | bot.on( 934 | ['message', 'edited_message'], 935 | (ctx, next) => { 936 | 937 | 938 | if (ctx.update[ctx.updateType].reply_to_message) 939 | next() 940 | 941 | debugLog(ctx.updateType) 942 | debugLog(ctx.update[ctx.updateType]) 943 | 944 | const extraReplyOptions = {reply_to_message_id : ctx.message.message_id} 945 | 946 | db.promiseExecute('SELECT te.id, te.userTemplateNumber, te.imageDestination, te.pageId, np.pageType, np.notionPageId FROM Templates AS te JOIN TelegramChats AS tc ON te.id=tc.currentTemplateId JOIN NotionPages AS np ON np.id=te.pageId WHERE tc.telegramChatId=?', [ctx.chat.id]) 947 | .then(({error, result}) => { 948 | 949 | if(!!error) 950 | throw new Error("Cannot get template settings: "+error.code+" - "+error.sqlMessage) 951 | 952 | if (!result.length) 953 | throw new Error("Couldnt find active template. Set one with /use") 954 | 955 | return db.promiseExecute( 956 | 'SELECT tr.orderNumber, tr.propId, pp.propName, pp.notionPropId, pp.propTypeId, pt.type AS propTypeName, tr.endsWith, tr.defaultValue, u.title as urlTitle, u.imageDestination as urlImageDestination, u.siteName as urlSitename, u.description as urlDescription, u.type as urlType, u.author as urlAuthor, u.url as urlDestination FROM `TemplateRules` AS tr LEFT OUTER JOIN `NotionPagesProps` AS pp ON pp.id = tr.propId LEFT OUTER JOIN `UrlMetaTemplateRules` AS u ON u.ruleId = tr.id LEFT OUTER JOIN NotionPropTypes AS pt ON pt.id = pp.propTypeId WHERE tr.templateId=? ORDER BY tr.orderNumber', 957 | [result[0].id], 958 | {template:result[0]} 959 | ) 960 | }) 961 | .then(({error, result, state}) => { 962 | 963 | if(!!error) 964 | throw new Error("Cannot get template settings: "+error.code+" - "+error.sqlMessage) 965 | 966 | if (!result.length) 967 | throw new Error("No rules for the active template `"+state.template.userTemplateNumber+"`.") 968 | 969 | 970 | return db.promiseExecute( 971 | 'SELECT wc.accessToken FROM NotionWorkspacesCredentials AS wc JOIN TelegramChats AS tc ON tc.id=wc.chatId JOIN NotionPages AS np ON np.workspaceId=wc.workspaceId JOIN Templates AS t ON t.pageId = np.id WHERE tc.telegramChatId=? AND t.id=?', 972 | [ctx.chat.id, state.template.id], 973 | {...state, props:result} 974 | ) 975 | }) 976 | .then(({error, result, state}) => { 977 | 978 | if (!!error) 979 | throw new Error("Cannot get your access token: "+error.code+" - "+error.sqlMessage) 980 | 981 | if(result.length !== 1) 982 | throw new Error("Cannot get your access token") 983 | 984 | //https://core.telegram.org/bots/api#message 985 | const { 986 | text, 987 | caption, 988 | entities, 989 | caption_entities, 990 | 991 | photo, 992 | /*not yet handled: 993 | 994 | //all same 995 | sticker, 996 | animation (gif), 997 | audio, 998 | document, 999 | video, 1000 | video_note, 1001 | voice, 1002 | 1003 | //all separate 1004 | reply_markup, 1005 | contact, 1006 | poll, 1007 | venue, 1008 | location, 1009 | invoice, 1010 | successful_payment, 1011 | passport_data, 1012 | */ 1013 | } = ctx.update[ctx.updateType] 1014 | 1015 | 1016 | var Cover = undefined, Icon = undefined, Content = [] 1017 | 1018 | const saveFotoUrl = (url, destination) => { 1019 | 1020 | const fileUrl = new URL(url).toString() 1021 | 1022 | switch(destination){ 1023 | case 0: 1024 | Content.push({value:fileUrl, type:'image'}) 1025 | break 1026 | case 1: 1027 | Cover = fileUrl 1028 | break 1029 | case 2: 1030 | Icon = fileUrl 1031 | break 1032 | } 1033 | } 1034 | 1035 | 1036 | if ( !!photo ){ 1037 | 1038 | //in the array are different sizes, but file_id does not change, we take the first 1039 | //NOTE it is a promise but it should have already resolved by the time we get to the end 1040 | ctx.tg.getFileLink(photo[0].file_id) 1041 | .then(fileUrl => saveurl(fileUrl, state.template.imageDestination)) 1042 | } 1043 | 1044 | var ent = [] 1045 | 1046 | if (!!entities || !!caption_entities){ 1047 | 1048 | /* 1049 | //https://core.telegram.org/bots/api#messageentity 1050 | const { 1051 | type, //one of: mention, hashtag, cashtag, bot_command, url, email, phone_number, bold, italic, , underline, strikethrough, code, pre, text_link, text_mention 1052 | offset, 1053 | length, 1054 | url, 1055 | 1056 | //not yet handled 1057 | user, 1058 | language, 1059 | } 1060 | */ 1061 | 1062 | //TODO support all following entities, and later also bold, italic ecc 1063 | //atm i think theres no need to handle email, phone_number, hashtag 1064 | const types = ["mention", "url", "text_link", "text_mention"] 1065 | 1066 | ent = (!!entities ? entities : caption_entities).filter(({type}) => types.includes(type)) 1067 | 1068 | } 1069 | 1070 | var origStr = text || caption || "" 1071 | var tmpStr = origStr 1072 | var offset = 0 //offset of tmpStr from original string 1073 | var lastUsedEnt = 0 //id of last used entity 1074 | 1075 | //map rules to the correspondig content, extracted from message 1076 | const data = state.props.map(rule => { 1077 | 1078 | var value = undefined 1079 | let valueEnt = {} 1080 | 1081 | var endsWith = rule.endsWith 1082 | 1083 | if (!endsWith) 1084 | value=rule.defaultValue.replace(removeDoubleQuotes, '$1') 1085 | else{ 1086 | 1087 | let start = origStr.indexOf(tmpStr) 1088 | let end = -1 //end of this field value is id of first occurence of endWith 1089 | 1090 | if (endsWith.match(/".*"/g) !== null) { 1091 | endsWith = endsWith.replace(removeDoubleQuotes, '$1') 1092 | end = tmpStr.search(endsWith) 1093 | } 1094 | else 1095 | end = tmpStr.indexOf(endsWith) 1096 | 1097 | if (end<0) 1098 | throw new Error("Couldnt find `"+rule.propName+"` ending with `"+rule.endsWith+"` as specified in rule "+rule.orderNumber) 1099 | 1100 | 1101 | 1102 | value = tmpStr.slice(0, end) 1103 | 1104 | 1105 | while (ent[lastUsedEnt].offset < offset && lastUsedEnt < ent.length) lastUsedEnt++; 1106 | 1107 | debugLog(lastUsedEnt, start, end) 1108 | 1109 | //NOTE currently only one ent per rule 1110 | if (lastUsedEnt < ent.length && ent[lastUsedEnt].offset + ent[lastUsedEnt].length <= start+end) 1111 | Object.assign(valueEnt, ent[lastUsedEnt]) 1112 | 1113 | debugLog(valueEnt) 1114 | 1115 | tmpStr = tmpStr.slice(end+endsWith.length-1) 1116 | offset=start+end 1117 | } 1118 | 1119 | debugLog(rule.propName, " = ", value) 1120 | 1121 | return {...rule, value, valueEnt} 1122 | }) 1123 | .filter(rule => notion.supportedTypes.includes(rule.propTypeId) ) //remove unsupported types 1124 | 1125 | //prepare promises for extracting properties 1126 | const propsPromises = data 1127 | .filter(rule=> typeof rule.propTypeId === "number" || !!rule.valueEnt.type) //keep items that will be notion props directly or indirectly (rule with entity but without property_name) 1128 | .map(current => { 1129 | 1130 | var newObj = {} 1131 | 1132 | if (current.notionPropId){ 1133 | newObj[current.notionPropId] = {} 1134 | newObj[current.notionPropId][current.propTypeName] = notion.mapValueToPropObj(current.value, current.propTypeName) 1135 | } 1136 | 1137 | if (!current.valueEnt.type) 1138 | return async ()=>newObj 1139 | 1140 | //else handle entities 1141 | return async ()=>{ 1142 | 1143 | const UrlParser = (url) => parser.parser(url) 1144 | .then(res => { 1145 | debugLog("parsed url",res) 1146 | return res 1147 | }) 1148 | .then(res => ({ 1149 | //NOTE og has precedence over meta 1150 | urlTitle : res.og.title || res.meta.title, 1151 | urlDestination : current.valueEnt.url, 1152 | urlSitename : res.og.site_name || res.meta.site_name, 1153 | urlDescription: res.og.description || res.meta.description, 1154 | urlType : res.og.type || res.meta.type, 1155 | urlImageDestination: res.og.image || res.meta.image, 1156 | })) 1157 | .then(urlMetas => { 1158 | 1159 | const dbPromises = Object.entries(urlMetas) 1160 | .filter(([key, value]) => typeof current[key] === "number" && !!value ) 1161 | .map(([key, value]) => async () => { 1162 | 1163 | if (key === "urlImageDestination") 1164 | return saveFotoUrl(value, current[key]) 1165 | 1166 | return db.promiseExecute('SELECT pp.notionPropId, pt.type as propTypeName FROM NotionPagesProps as pp JOIN NotionPropTypes as pt ON pp.propTypeId = pt.id WHERE pp.id=?', [current[key]]) 1167 | .then(({result}) => { 1168 | 1169 | //if Content instead of prop 1170 | if (!result.length || !result[0]){ 1171 | Content.push({value, type:'text'}) 1172 | return {} 1173 | } 1174 | 1175 | var urlObj = {} 1176 | urlObj[result[0].notionPropId] = {} 1177 | urlObj[result[0].notionPropId][result[0].propTypeName] = notion.mapValueToPropObj(value, result[0].propTypeName) 1178 | 1179 | return urlObj 1180 | }) 1181 | }) 1182 | 1183 | return Promise.all(dbPromises.map(it=>it())) 1184 | }) 1185 | .then(it=> it.reduce( ( completeObj, urlObj ) => Object.assign({}, completeObj, urlObj) , newObj) ) //NOTE this will override props with same notionPropId 1186 | .catch(error => { 1187 | console.warn(error) 1188 | ctx.reply(`Error parsing url: ${error}`, extraReplyOptions) 1189 | return newObj 1190 | }); 1191 | 1192 | 1193 | //NOTE currently only one entity per rule 1194 | switch (current.valueEnt.type){ 1195 | case 'url': 1196 | return await UrlParser(current.value.trim()) 1197 | case 'text_link': 1198 | return await UrlParser(current.valueEnt.url) 1199 | 1200 | break; 1201 | } 1202 | } 1203 | }) 1204 | 1205 | //extract promises 1206 | return Promise.all(propsPromises.map(item => item())) 1207 | .then(it=> it.reduce( ( allProps, singleProp ) => Object.assign({}, allProps, singleProp) , {}) ) //NOTE this will override props with same notionPropId 1208 | .then(properties => { 1209 | 1210 | const children = data 1211 | .filter(rule => typeof rule.propTypeId !== "number" && typeof rule.propId === "number") //keep content, remove props & waste 1212 | .map(({value})=> notion.mapValueToBlockObjs(value, 'text')) 1213 | .flat() 1214 | 1215 | var pageObj = { 1216 | auth:result[0].accessToken, 1217 | parent:{ 1218 | type: state.template.pageType === 'db' ? 'database_id' : 'page_id', 1219 | database_id:state.template.notionPageId, 1220 | }, 1221 | properties, 1222 | children, 1223 | } 1224 | 1225 | if (!!Icon) 1226 | pageObj.icon = { 1227 | type : "external", 1228 | external : { 1229 | url: Icon, 1230 | }, 1231 | } 1232 | 1233 | if (!!Cover) 1234 | pageObj.cover = { 1235 | type : "external", 1236 | external : { 1237 | url: Cover, 1238 | }, 1239 | } 1240 | 1241 | //WARNING temporary, maybe in future will be ordered following rule order, 1242 | //not all before the rest of the text content 1243 | if (Content.length) 1244 | pageObj.children = [ 1245 | ...pageObj.children, 1246 | ...Content 1247 | .map(({value, type}) => notion.mapValueToBlockObjs(value, type)) 1248 | .flat(), 1249 | ] 1250 | 1251 | 1252 | debugLog("\n\n--------------------------\n\n") 1253 | debugLog("properties : ", properties) 1254 | debugLog("children : ", pageObj.children) 1255 | 1256 | pageObj.children.forEach(({paragraph}) => debugLog(paragraph.text)) 1257 | 1258 | debugLog("cover : ", pageObj.cover) 1259 | debugLog("icon : ", pageObj.icon) 1260 | debugLog("\n\n--------------------------\n\n") 1261 | 1262 | 1263 | return notion.client.pages.create(pageObj) 1264 | 1265 | }) 1266 | }) 1267 | .then(res => ctx.replyWithMarkdown("Content saved!\nView in [Notion]("+res.url+")", extraReplyOptions)) 1268 | .catch(error => { 1269 | console.warn(error) 1270 | ctx.reply(`Error saving content: ${error}`, extraReplyOptions) 1271 | }) 1272 | } 1273 | ) 1274 | 1275 | //END core 1276 | 1277 | //BEGIN list 1278 | /* 1279 | bot.command('list', ctx => { 1280 | 1281 | return db.promiseExecute('SELECT * FROM ' 1282 | 1283 | }); 1284 | */ 1285 | //END list 1286 | export default bot 1287 | export {Markup} 1288 | --------------------------------------------------------------------------------