akkun3704 commited on
Commit
5ae7e18
·
1 Parent(s): 4e173d1

Upload folder using huggingface_hub

Browse files
.editorconfig ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ indent_style = space
9
+ indent_size = 2
.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ PORT="4888"
2
+ BOT_TOKEN=""
3
+ EMOJI_DOMAIN="https://emojipedia.org/"
.eslintrc.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "es6": true,
4
+ "node": true
5
+ },
6
+ "extends": "standard",
7
+ "globals": {
8
+ "Atomics": "readonly",
9
+ "SharedArrayBuffer": "readonly"
10
+ },
11
+ "parserOptions": {
12
+ "ecmaVersion": 2018,
13
+ "sourceType": "module"
14
+ },
15
+ "rules": {
16
+ }
17
+ }
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/emoji/emoji-apple-image.json filter=lfs diff=lfs merge=lfs -text
37
+ assets/emoji/emoji-google-image.json filter=lfs diff=lfs merge=lfs -text
38
+ assets/emoji/emoji-joypixels-image.json filter=lfs diff=lfs merge=lfs -text
39
+ assets/emoji/emoji-twitter-image.json filter=lfs diff=lfs merge=lfs -text
40
+ assets/pattern_ny_old.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+
8
+ # Runtime data
9
+ pids
10
+ *.pid
11
+ *.seed
12
+ *.pid.lock
13
+
14
+ # Directory for instrumented libs generated by jscoverage/JSCover
15
+ lib-cov
16
+
17
+ # Coverage directory used by tools like istanbul
18
+ coverage
19
+
20
+ # nyc test coverage
21
+ .nyc_output
22
+
23
+ # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24
+ .grunt
25
+
26
+ # Bower dependency directory (https://bower.io/)
27
+ bower_components
28
+
29
+ # node-waf configuration
30
+ .lock-wscript
31
+
32
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
33
+ build/Release
34
+
35
+ # Dependency directories
36
+ node_modules/
37
+ jspm_packages/
38
+
39
+ # TypeScript v1 declaration files
40
+ typings/
41
+
42
+ # Optional npm cache directory
43
+ .npm
44
+
45
+ # Optional eslint cache
46
+ .eslintcache
47
+
48
+ # Optional REPL history
49
+ .node_repl_history
50
+
51
+ # Output of 'npm pack'
52
+ *.tgz
53
+
54
+ # Yarn Integrity file
55
+ .yarn-integrity
56
+
57
+ # dotenv environment variables file
58
+ .env
59
+
60
+ # next.js build output
61
+ .next
62
+
63
+ assets/fonts/*
64
+ assets/emojis/*
65
+
66
+ !.gitkeep
.vscode/launch.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "type": "node",
9
+ "runtimeVersion": "16.5.0",
10
+ "request": "launch",
11
+ "name": "Launch Program",
12
+ "skipFiles": [
13
+ "<node_internals>/**"
14
+ ],
15
+ "program": "${workspaceFolder}/index.js"
16
+ }
17
+ ]
18
+ }
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nikolaik/python-nodejs:python3.8-nodejs12 AS builder
2
+
3
+ ENV NODE_WORKDIR /app
4
+ WORKDIR $NODE_WORKDIR
5
+
6
+ ADD . $NODE_WORKDIR
7
+
8
+ RUN apt-get update && apt-get install -y build-essential gcc wget git libvips && rm -rf /var/lib/apt/lists/*
9
+
10
+
11
+ RUN npm install [email protected] && npm install # TODO: canvas crashes if installed via npm install from package.json
README.md CHANGED
@@ -1,12 +1,232 @@
1
- ---
2
- title: Quote Api
3
- emoji: 💻
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.13.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # quote-api
2
+
3
+ [![wakatime](https://wakatime.com/badge/github/LyoSU/quote-api.svg)](https://wakatime.com/badge/github/LyoSU/quote-api)
4
+
5
+ Апи для генерации Telegram цитат
6
+
7
+ ## Методы
8
+ ##### Создание цитаты
9
+ ```http
10
+ POST /generate
11
+ ```
12
+
13
+ Пример JSON запроса:
14
+ ```json
15
+ {
16
+ "type": "quote",
17
+ "format": "png",
18
+ "backgroundColor": "#1b1429",
19
+ "width": 512,
20
+ "height": 768,
21
+ "scale": 2,
22
+ "messages": [
23
+ {
24
+ "entities": [],
25
+ "chatId": 66478514,
26
+ "avatar": true,
27
+ "from": {
28
+ "id": 66478514,
29
+ "first_name": "Yuri 💜",
30
+ "last_name": "Ly",
31
+ "username": "LyoSU",
32
+ "language_code": "ru",
33
+ "title": "Yuri 💜 Ly",
34
+ "photo": {
35
+ "small_file_id": "AQADAgADCKoxG7Jh9gMACBbSEZguAAMCAAOyYfYDAATieVimvJOu7M43BQABHgQ",
36
+ "small_file_unique_id": "AQADFtIRmC4AA843BQAB",
37
+ "big_file_id": "AQADAgADCKoxG7Jh9gMACBbSEZguAAMDAAOyYfYDAATieVimvJOu7NA3BQABHgQ",
38
+ "big_file_unique_id": "AQADFtIRmC4AA9A3BQAB"
39
+ },
40
+ "type": "private",
41
+ "name": "Yuri 💜 Ly"
42
+ },
43
+ "text": "I love you 💜",
44
+ "replyMessage": {}
45
+ }
46
+ ]
47
+ }
48
+ ```
49
+
50
+ Медиа:
51
+ ```json
52
+ {
53
+ "type": "quote",
54
+ "format": "png",
55
+ "backgroundColor": "#1b1429",
56
+ "width": 512,
57
+ "height": 768,
58
+ "scale": 2,
59
+ "messages": [
60
+ {
61
+ "media": [
62
+ {
63
+ "file_id": "CAACAgIAAxkBAAIyH2AAAUcJoPJqv4uOPabtiSR3judSnQACaQEAAiI3jgQe29BUaNTqrx4E",
64
+ "file_size": 22811,
65
+ "height": 512,
66
+ "width": 512
67
+ }
68
+ ],
69
+ "mediaType": "sticker",
70
+ "chatId": 66478514,
71
+ "avatar": true,
72
+ "from": {
73
+ "id": 66478514,
74
+ "first_name": "Yuri 💜",
75
+ "last_name": "Ly",
76
+ "username": "LyoSU",
77
+ "language_code": "ru",
78
+ "title": "Yuri 💜 Ly",
79
+ "photo": {
80
+ "small_file_id": "AQADAgADCKoxG7Jh9gMACBbSEZguAAMCAAOyYfYDAATieVimvJOu7M43BQABHgQ",
81
+ "small_file_unique_id": "AQADFtIRmC4AA843BQAB",
82
+ "big_file_id": "AQADAgADCKoxG7Jh9gMACBbSEZguAAMDAAOyYfYDAATieVimvJOu7NA3BQABHgQ",
83
+ "big_file_unique_id": "AQADFtIRmC4AA9A3BQAB"
84
+ },
85
+ "type": "private",
86
+ "name": "Yuri 💜 Ly"
87
+ },
88
+ "replyMessage": {}
89
+ }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ Без Telegram
95
+ ```json
96
+ {
97
+ "type": "quote",
98
+ "format": "png",
99
+ "backgroundColor": "#1b1429",
100
+ "width": 512,
101
+ "height": 768,
102
+ "scale": 2,
103
+ "messages": [
104
+ {
105
+ "entities": [],
106
+ "media": {
107
+ "url": "https://via.placeholder.com/1000"
108
+ },
109
+ "avatar": true,
110
+ "from": {
111
+ "id": 1,
112
+ "name": "Mike",
113
+ "photo": {
114
+ "url": "https://via.placeholder.com/100"
115
+ }
116
+ },
117
+ "text": "Hey",
118
+ "replyMessage": {}
119
+ }
120
+ ]
121
+ }
122
+ ```
123
+
124
+ Параметры:
125
+ | Поле | Тип | Описание |
126
+ | :------------ | :------------ | :------------ |
127
+ | type | string | Тип выходного изображения. Может быть: quote, image, null |
128
+ | backgroundColor | string | Цвет фона цитаты. Может быть Hex, название или random для случайного цвета |
129
+ | messages | array | Массив из сообщений |
130
+ | width | number | Максимальная ширина |
131
+ | height | number | Максимальная высота |
132
+ | scale | number | Маcштаб |
133
+
134
+ Пример ответа:
135
+
136
+ ```json
137
+ {
138
+ "ok": true,
139
+ "result": {
140
+ "image": "base64 image",
141
+ "type": "quote",
142
+ "width": 512,
143
+ "height": 359
144
+ }
145
+ }
146
+
147
+ ```
148
+
149
+ ## Примеры запросов:
150
+ > JavaScript
151
+ ```js
152
+ const axios = require('axios')
153
+ const fs = require('fs')
154
+
155
+ const text = "Hello World"
156
+ const username = "Alι_Aryαɴ"
157
+ const avatar = "https://telegra.ph/file/59952c903fdfb10b752b3.jpg"
158
+
159
+ const json = {
160
+ "type": "quote",
161
+ "format": "png",
162
+ "backgroundColor": "#FFFFFF",
163
+ "width": 512,
164
+ "height": 768,
165
+ "scale": 2,
166
+ "messages": [
167
+ {
168
+ "entities": [],
169
+ "avatar": true,
170
+ "from": {
171
+ "id": 1,
172
+ "name": username,
173
+ "photo": {
174
+ "url": avatar
175
+ }
176
+ },
177
+ "text": text,
178
+ "replyMessage": {}
179
+ }
180
+ ]
181
+ };
182
+ const response = axios.post('https://bot.lyo.su/quote/generate', json, {
183
+ headers: {'Content-Type': 'application/json'}
184
+ }).then(res => {
185
+ const buffer = Buffer.from(res.data.result.image, 'base64')
186
+ fs.writeFile('Quotly.png', buffer, (err) => {
187
+ if (err) throw err;
188
+ })
189
+ });
190
+ ```
191
+
192
+ > Python
193
+ ```py
194
+ import requests
195
+ import base64
196
+
197
+ text = "Hello World"
198
+ username = "Alι_Aryαɴ"
199
+ avatar = "https://telegra.ph/file/59952c903fdfb10b752b3.jpg"
200
+
201
+ json = {
202
+ "type": "quote",
203
+ "format": "webp",
204
+ "backgroundColor": "#FFFFFF",
205
+ "width": 512,
206
+ "height": 768,
207
+ "scale": 2,
208
+ "messages": [
209
+ {
210
+ "entities": [],
211
+ "avatar": True,
212
+ "from": {
213
+ "id": 1,
214
+ "name": username,
215
+ "photo": {
216
+ "url": avatar
217
+ }
218
+ },
219
+ "text": text,
220
+ "replyMessage": {}
221
+ }
222
+ ]
223
+ }
224
+
225
+ response = requests.post('https://bot.lyo.su/quote/generate', json=json).json()
226
+ buffer = base64.b64decode(response['result']['image'].encode('utf-8'))
227
+ open('Quotly.png', 'wb').write(buffer)
228
+ print('Quotly.png')
229
+ ```
230
+ ### Response
231
+
232
+ ![Quotly.png](assets/Quotly.png)
app.js ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const logger = require('koa-logger')
2
+ const responseTime = require('koa-response-time')
3
+ const bodyParser = require('koa-bodyparser')
4
+ const ratelimit = require('koa-ratelimit')
5
+ const Router = require('koa-router')
6
+ const Koa = require('koa')
7
+
8
+ const app = new Koa()
9
+
10
+ app.use(logger())
11
+ app.use(responseTime())
12
+ app.use(bodyParser())
13
+
14
+ const ratelimitВb = new Map()
15
+
16
+ app.use(ratelimit({
17
+ driver: 'memory',
18
+ db: ratelimitВb,
19
+ duration: 1000 * 55,
20
+ errorMessage: {
21
+ ok: false,
22
+ error: {
23
+ code: 429,
24
+ message: 'Rate limit exceeded. See "Retry-After"'
25
+ }
26
+ },
27
+ id: (ctx) => ctx.ip,
28
+ headers: {
29
+ remaining: 'Rate-Limit-Remaining',
30
+ reset: 'Rate-Limit-Reset',
31
+ total: 'Rate-Limit-Total'
32
+ },
33
+ max: 20,
34
+ disableHeader: false,
35
+ whitelist: (ctx) => {
36
+ return ctx.query.botToken === process.env.BOT_TOKEN
37
+ },
38
+ blacklist: (ctx) => {
39
+ }
40
+ }))
41
+
42
+ app.use(require('./helpers').helpersApi)
43
+
44
+ const route = new Router()
45
+
46
+ const routes = require('./routes')
47
+
48
+ route.use('/*', routes.routeApi.routes())
49
+
50
+ app.use(route.routes())
51
+
52
+ const port = process.env.PORT || 3000
53
+
54
+ app.listen(port, () => {
55
+ console.log('Listening on localhost, port', port)
56
+ })
assets/Quotly.png ADDED
assets/emoji/emoji-apple-image.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f6822c2fe7de7e5af4637a812c89ffce5826ec546d0852e772ee117c50ecda
3
+ size 28524906
assets/emoji/emoji-blob-image.json ADDED
The diff for this file is too large to render. See raw diff
 
assets/emoji/emoji-google-image.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2be7165b28cb0346161e94cc0e1813af1c175fab279128851128b09fa8b29ca
3
+ size 18282533
assets/emoji/emoji-joypixels-image.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f9f1323fddae35bd891dfbe5ad218380e78d197834e4a250a073257d487faad
3
+ size 18326902
assets/emoji/emoji-twitter-image.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fec5f05b7a8735b18883eedbef089532b827fc6c970adb0071f550a60b56ea38
3
+ size 13737806
assets/fonts/.gitkeep ADDED
File without changes
assets/pattern_02.png ADDED
assets/pattern_ny.png ADDED
assets/pattern_ny_old.png ADDED

Git LFS Details

  • SHA256: 498deafb36f8ccd3c154b87f520b10f7edba8c0bc0dc266b9ed38541fef6688d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.01 MB
docker-compose.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3'
2
+
3
+ services:
4
+ api:
5
+ build:
6
+ context: .
7
+ env_file: .env
8
+ restart: always
9
+ logging:
10
+ driver: "json-file"
11
+ options:
12
+ max-size: "10m"
13
+ max-file: "3"
14
+ networks:
15
+ - quotly
16
+ command: node index.js
17
+ ports:
18
+ - 127.0.0.1:4888:4888
19
+
20
+
21
+ networks:
22
+ quotly:
23
+ external: true
ecosystem.config.js ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ apps: [{
3
+ name: 'quote-api',
4
+ script: './index.js',
5
+ max_memory_restart: '1000M',
6
+ instances: 3,
7
+ exec_mode: 'cluster',
8
+ watch: true,
9
+ ignore_watch: ['node_modules', 'assets'],
10
+ env: {
11
+ NODE_ENV: 'development'
12
+ },
13
+ env_production: {
14
+ NODE_ENV: 'production'
15
+ }
16
+ }]
17
+ }
helpers/api.js ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = async (ctx, next) => {
2
+ ctx.props = Object.assign(ctx.query || {}, ctx.request.body || {})
3
+
4
+ try {
5
+ await next()
6
+
7
+ if (!ctx.body) {
8
+ ctx.assert(ctx.result, 404, 'Not Found')
9
+
10
+ if (ctx.result.error) {
11
+ ctx.status = 400
12
+ ctx.body = {
13
+ ok: false,
14
+ error: {
15
+ code: 400,
16
+ message: ctx.result.error
17
+ }
18
+ }
19
+ } else {
20
+ if (ctx.result.ext) {
21
+ if (ctx.result.ext === 'webp') ctx.response.set('content-type', 'image/webp')
22
+ if (ctx.result.ext === 'png') ctx.response.set('content-type', 'image/png')
23
+ ctx.response.set('quote-type', ctx.result.type)
24
+ ctx.response.set('quote-width', ctx.result.width)
25
+ ctx.response.set('quote-height', ctx.result.height)
26
+ ctx.body = ctx.result.image
27
+ } else {
28
+ ctx.body = {
29
+ ok: true,
30
+ result: ctx.result
31
+ }
32
+ }
33
+ }
34
+ }
35
+ } catch (error) {
36
+ console.error(error)
37
+ ctx.status = error.statusCode || error.status || 500
38
+ ctx.body = {
39
+ ok: false,
40
+ error: {
41
+ code: ctx.status,
42
+ message: error.message,
43
+ description: error.description
44
+ }
45
+ }
46
+ }
47
+ }
helpers/index.js ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ const helpersApi = require('./api')
2
+
3
+ module.exports = {
4
+ helpersApi
5
+ }
index.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ require('dotenv').config({ path: './.env' })
2
+ require('./app')
methods/generate.js ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const {
2
+ QuoteGenerate
3
+ } = require('../utils')
4
+ const { createCanvas, loadImage } = require('canvas')
5
+ const sharp = require('sharp')
6
+
7
+ const normalizeColor = (color) => {
8
+ const canvas = createCanvas(0, 0)
9
+ const canvasCtx = canvas.getContext('2d')
10
+
11
+ canvasCtx.fillStyle = color
12
+ color = canvasCtx.fillStyle
13
+
14
+ return color
15
+ }
16
+
17
+ const colorLuminance = (hex, lum) => {
18
+ hex = String(hex).replace(/[^0-9a-f]/gi, '')
19
+ if (hex.length < 6) {
20
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
21
+ }
22
+ lum = lum || 0
23
+
24
+ // convert to decimal and change luminosity
25
+ let rgb = '#'
26
+ let c
27
+ let i
28
+ for (i = 0; i < 3; i++) {
29
+ c = parseInt(hex.substr(i * 2, 2), 16)
30
+ c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16)
31
+ rgb += ('00' + c).substr(c.length)
32
+ }
33
+
34
+ return rgb
35
+ }
36
+
37
+ const imageAlpha = (image, alpha) => {
38
+ const canvas = createCanvas(image.width, image.height)
39
+
40
+ const canvasCtx = canvas.getContext('2d')
41
+
42
+ canvasCtx.globalAlpha = alpha
43
+
44
+ canvasCtx.drawImage(image, 0, 0)
45
+
46
+ return canvas
47
+ }
48
+
49
+ module.exports = async (parm) => {
50
+ // console.log(JSON.stringify(parm, null, 2))
51
+ if (!parm) return { error: 'query_empty' }
52
+ if (!parm.messages || parm.messages.length < 1) return { error: 'messages_empty' }
53
+
54
+ let botToken = parm.botToken || process.env.BOT_TOKEN
55
+
56
+ const quoteGenerate = new QuoteGenerate(botToken)
57
+
58
+ const quoteImages = []
59
+
60
+ let backgroundColor = parm.backgroundColor || '//#292232'
61
+ let backgroundColorOne
62
+ let backgroundColorTwo
63
+
64
+ const backgroundColorSplit = backgroundColor.split('/')
65
+
66
+ if (backgroundColorSplit && backgroundColorSplit.length > 1 && backgroundColorSplit[0] !== '') {
67
+ backgroundColorOne = normalizeColor(backgroundColorSplit[0])
68
+ backgroundColorTwo = normalizeColor(backgroundColorSplit[1])
69
+ } else if (backgroundColor.startsWith('//')) {
70
+ backgroundColor = normalizeColor(backgroundColor.replace('//', ''))
71
+ backgroundColorOne = colorLuminance(backgroundColor, 0.35)
72
+ backgroundColorTwo = colorLuminance(backgroundColor, -0.15)
73
+ } else {
74
+ backgroundColor = normalizeColor(backgroundColor)
75
+ backgroundColorOne = backgroundColor
76
+ backgroundColorTwo = backgroundColor
77
+ }
78
+
79
+ for (const key in parm.messages) {
80
+ const message = parm.messages[key]
81
+
82
+ if (message) {
83
+ const canvasQuote = await quoteGenerate.generate(
84
+ backgroundColorOne,
85
+ backgroundColorTwo,
86
+ message,
87
+ parm.width,
88
+ parm.height,
89
+ parseFloat(parm.scale),
90
+ parm.emojiBrand
91
+ )
92
+
93
+ quoteImages.push(canvasQuote)
94
+ }
95
+ }
96
+
97
+ if (quoteImages.length === 0) {
98
+ return {
99
+ error: 'empty_messages'
100
+ }
101
+ }
102
+
103
+ let canvasQuote
104
+
105
+ if (quoteImages.length > 1) {
106
+ let width = 0
107
+ let height = 0
108
+
109
+ for (let index = 0; index < quoteImages.length; index++) {
110
+ if (quoteImages[index].width > width) width = quoteImages[index].width
111
+ height += quoteImages[index].height
112
+ }
113
+
114
+ const quoteMargin = 5 * parm.scale
115
+
116
+ const canvas = createCanvas(width, height + (quoteMargin * quoteImages.length))
117
+ const canvasCtx = canvas.getContext('2d')
118
+
119
+ let imageY = 0
120
+
121
+ for (let index = 0; index < quoteImages.length; index++) {
122
+ canvasCtx.drawImage(quoteImages[index], 0, imageY)
123
+ imageY += quoteImages[index].height + quoteMargin
124
+ }
125
+ canvasQuote = canvas
126
+ } else {
127
+ canvasQuote = quoteImages[0]
128
+ }
129
+
130
+ let quoteImage
131
+
132
+ let { type, format, ext } = parm
133
+
134
+ if (!type && ext) type = 'png'
135
+ if (type !== 'image' && type !== 'stories' && canvasQuote.height > 1024 * 2) type = 'png'
136
+
137
+ if (type === 'quote') {
138
+ const downPadding = 75
139
+ const maxWidth = 512
140
+ const maxHeight = 512
141
+
142
+ const imageQuoteSharp = sharp(canvasQuote.toBuffer())
143
+
144
+ if (canvasQuote.height > canvasQuote.width) imageQuoteSharp.resize({ height: maxHeight })
145
+ else imageQuoteSharp.resize({ width: maxWidth })
146
+
147
+ const canvasImage = await loadImage(await imageQuoteSharp.toBuffer())
148
+
149
+ const canvasPadding = createCanvas(canvasImage.width, canvasImage.height + downPadding)
150
+ const canvasPaddingCtx = canvasPadding.getContext('2d')
151
+
152
+ canvasPaddingCtx.drawImage(canvasImage, 0, 0)
153
+
154
+ const imageSharp = sharp(canvasPadding.toBuffer())
155
+
156
+ if (canvasPadding.height >= canvasPadding.width) imageSharp.resize({ height: maxHeight })
157
+ else imageSharp.resize({ width: maxWidth })
158
+
159
+ if (format === 'png') quoteImage = await imageSharp.png().toBuffer()
160
+ else quoteImage = await imageSharp.webp({ lossless: true, force: true }).toBuffer()
161
+ } else if (type === 'image') {
162
+ const heightPadding = 75 * parm.scale
163
+ const widthPadding = 95 * parm.scale
164
+
165
+ const canvasImage = await loadImage(canvasQuote.toBuffer())
166
+
167
+ const canvasPic = createCanvas(canvasImage.width + widthPadding, canvasImage.height + heightPadding)
168
+ const canvasPicCtx = canvasPic.getContext('2d')
169
+
170
+ // radial gradient background (top left)
171
+ const gradient = canvasPicCtx.createRadialGradient(
172
+ canvasPic.width / 2,
173
+ canvasPic.height / 2,
174
+ 0,
175
+ canvasPic.width / 2,
176
+ canvasPic.height / 2,
177
+ canvasPic.width / 2
178
+ )
179
+
180
+ const patternColorOne = colorLuminance(backgroundColorTwo, 0.15)
181
+ const patternColorTwo = colorLuminance(backgroundColorOne, 0.15)
182
+
183
+ gradient.addColorStop(0, patternColorOne)
184
+ gradient.addColorStop(1, patternColorTwo)
185
+
186
+ canvasPicCtx.fillStyle = gradient
187
+ canvasPicCtx.fillRect(0, 0, canvasPic.width, canvasPic.height)
188
+
189
+ const canvasPatternImage = await loadImage('./assets/pattern_02.png')
190
+ // const canvasPatternImage = await loadImage('./assets/pattern_ny.png');
191
+
192
+ const pattern = canvasPicCtx.createPattern(imageAlpha(canvasPatternImage, 0.3), 'repeat')
193
+
194
+ canvasPicCtx.fillStyle = pattern
195
+ canvasPicCtx.fillRect(0, 0, canvasPic.width, canvasPic.height)
196
+
197
+ // Add shadow effect to the canvas image
198
+ canvasPicCtx.shadowOffsetX = 8
199
+ canvasPicCtx.shadowOffsetY = 8
200
+ canvasPicCtx.shadowBlur = 13
201
+ canvasPicCtx.shadowColor = 'rgba(0, 0, 0, 0.5)'
202
+
203
+ // Draw the image to the canvas with padding centered
204
+ canvasPicCtx.drawImage(canvasImage, widthPadding / 2, heightPadding / 2)
205
+
206
+ canvasPicCtx.shadowOffsetX = 0
207
+ canvasPicCtx.shadowOffsetY = 0
208
+ canvasPicCtx.shadowBlur = 0
209
+ canvasPicCtx.shadowColor = 'rgba(0, 0, 0, 0)'
210
+
211
+ // write text button right
212
+ canvasPicCtx.fillStyle = `rgba(0, 0, 0, 0.3)`
213
+ canvasPicCtx.font = `${8 * parm.scale}px Noto Sans`
214
+ canvasPicCtx.textAlign = 'right'
215
+ canvasPicCtx.fillText('@QuotLyBot', canvasPic.width - 25, canvasPic.height - 25)
216
+
217
+ quoteImage = await sharp(canvasPic.toBuffer()).png({ lossless: true, force: true }).toBuffer()
218
+ } else if (type === 'stories') {
219
+ const canvasPic = createCanvas(720, 1280)
220
+ const canvasPicCtx = canvasPic.getContext('2d')
221
+
222
+ // radial gradient background (top left)
223
+ const gradient = canvasPicCtx.createRadialGradient(
224
+ canvasPic.width / 2,
225
+ canvasPic.height / 2,
226
+ 0,
227
+ canvasPic.width / 2,
228
+ canvasPic.height / 2,
229
+ canvasPic.width / 2
230
+ )
231
+
232
+ const patternColorOne = colorLuminance(backgroundColorTwo, 0.25)
233
+ const patternColorTwo = colorLuminance(backgroundColorOne, 0.15)
234
+
235
+ gradient.addColorStop(0, patternColorOne)
236
+ gradient.addColorStop(1, patternColorTwo)
237
+
238
+ canvasPicCtx.fillStyle = gradient
239
+ canvasPicCtx.fillRect(0, 0, canvasPic.width, canvasPic.height)
240
+
241
+ const canvasPatternImage = await loadImage('./assets/pattern_02.png')
242
+
243
+ const pattern = canvasPicCtx.createPattern(imageAlpha(canvasPatternImage, 0.3), 'repeat')
244
+
245
+ canvasPicCtx.fillStyle = pattern
246
+ canvasPicCtx.fillRect(0, 0, canvasPic.width, canvasPic.height)
247
+
248
+ // Add shadow effect to the canvas image
249
+ canvasPicCtx.shadowOffsetX = 8
250
+ canvasPicCtx.shadowOffsetY = 8
251
+ canvasPicCtx.shadowBlur = 13
252
+ canvasPicCtx.shadowColor = 'rgba(0, 0, 0, 0.5)'
253
+
254
+ let canvasImage = await loadImage(canvasQuote.toBuffer())
255
+
256
+ // мінімальний відступ від країв картинки
257
+ const minPadding = 110
258
+
259
+ // resize canvasImage if it is larger than canvasPic + minPadding
260
+ if (canvasImage.width > canvasPic.width - minPadding * 2 || canvasImage.height > canvasPic.height - minPadding * 2) {
261
+ canvasImage = await sharp(canvasQuote.toBuffer()).resize({
262
+ width: canvasPic.width - minPadding * 2,
263
+ height: canvasPic.height - minPadding * 2,
264
+ fit: 'contain',
265
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
266
+ }).toBuffer()
267
+
268
+ canvasImage = await loadImage(canvasImage)
269
+ }
270
+
271
+ // розмістити canvasImage в центрі по горизонталі і вертикалі
272
+ const imageX = (canvasPic.width - canvasImage.width) / 2
273
+ const imageY = (canvasPic.height - canvasImage.height) / 2
274
+
275
+ canvasPicCtx.drawImage(canvasImage, imageX, imageY)
276
+
277
+ canvasPicCtx.shadowOffsetX = 0
278
+ canvasPicCtx.shadowOffsetY = 0
279
+ canvasPicCtx.shadowBlur = 0
280
+
281
+ // write text vertical left center text
282
+ canvasPicCtx.fillStyle = `rgba(0, 0, 0, 0.4)`
283
+ canvasPicCtx.font = `${16 * parm.scale}px Noto Sans`
284
+ canvasPicCtx.textAlign = 'center'
285
+ canvasPicCtx.translate(70, canvasPic.height / 2)
286
+ canvasPicCtx.rotate(-Math.PI / 2)
287
+ canvasPicCtx.fillText('@QuotLyBot', 0, 0)
288
+
289
+ quoteImage = await sharp(canvasPic.toBuffer()).png({ lossless: true, force: true }).toBuffer()
290
+ } else {
291
+ quoteImage = canvasQuote.toBuffer()
292
+ }
293
+
294
+ const imageMetadata = await sharp(quoteImage).metadata()
295
+
296
+ const width = imageMetadata.width
297
+ const height = imageMetadata.height
298
+
299
+ let image
300
+ if (ext) image = quoteImage
301
+ else image = quoteImage.toString('base64')
302
+
303
+ return {
304
+ image,
305
+ type,
306
+ width,
307
+ height,
308
+ ext
309
+ }
310
+ }
methods/index.js ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const crypto = require('crypto')
2
+ const LRU = require('lru-cache')
3
+ const sizeof = require('object-sizeof')
4
+
5
+ const generate = require('./generate')
6
+
7
+ const methods = {
8
+ generate
9
+ }
10
+
11
+ const cache = new LRU({
12
+ max: 1000 * 1000 * 1000,
13
+ length: (n) => { return sizeof(n) },
14
+ maxAge: 1000 * 60 * 45
15
+ })
16
+
17
+ module.exports = async (method, parm) => {
18
+ if (methods[method]) {
19
+ let methodResult = {}
20
+
21
+ let cacheString = crypto.createHash('md5').update(JSON.stringify({ method, parm })).digest('hex')
22
+ const methodResultCache = cache.get(cacheString)
23
+
24
+ if (!methodResultCache) {
25
+ methodResult = await methods[method](parm)
26
+
27
+ if (!methodResult.error) cache.set(cacheString, methodResult)
28
+ } else {
29
+ methodResult = methodResultCache
30
+ }
31
+
32
+ return methodResult
33
+ } else {
34
+ return {
35
+ error: 'method not found'
36
+ }
37
+ }
38
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "quote-api",
3
+ "version": "0.14.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "start": "node index.js",
8
+ "lint": "node_modules/.bin/eslint --ext js .",
9
+ "lint:fix": "node_modules/.bin/eslint --fix --ext js ."
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/LyoSU/quote-api.git"
14
+ },
15
+ "author": "LyoSU",
16
+ "license": "MIT",
17
+ "bugs": {
18
+ "url": "https://github.com/LyoSU/quote-api/issues"
19
+ },
20
+ "homepage": "https://github.com/LyoSU/quote-api#readme",
21
+ "dependencies": {
22
+ "canvas": "2.11.0",
23
+ "dotenv": "^7.0.0",
24
+ "emoji-db": "^14.0.1",
25
+ "jimp": "^0.16.1",
26
+ "jsdom": "^16.5.3",
27
+ "koa": "^2.11.0",
28
+ "koa-bodyparser": "^4.2.1",
29
+ "koa-logger": "^3.2.1",
30
+ "koa-ratelimit": "^4.2.1",
31
+ "koa-response-time": "^2.1.0",
32
+ "koa-router": "^7.4.0",
33
+ "lottie-node": "^2.0.0",
34
+ "lottie-web": "^5.7.8",
35
+ "lru-cache": "^5.1.1",
36
+ "object-sizeof": "^1.6.0",
37
+ "runes": "^0.4.3",
38
+ "sharp": "^0.31.3",
39
+ "smartcrop-sharp": "^2.0.7",
40
+ "telegraf": "^3.38.0"
41
+ },
42
+ "devDependencies": {
43
+ "eslint": "^8.6.0",
44
+ "eslint-config-standard": "^12.0.0",
45
+ "eslint-plugin-import": "^2.17.3",
46
+ "eslint-plugin-node": "^9.1.0",
47
+ "eslint-plugin-promise": "^4.1.1",
48
+ "eslint-plugin-standard": "^4.0.0"
49
+ }
50
+ }
routes/api.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const Router = require('koa-router')
2
+ const api = new Router()
3
+
4
+ const method = require('../methods')
5
+
6
+ const apiHandle = async (ctx) => {
7
+ const methodWithExt = ctx.params[0].match(/(.*).(png|webp)/)
8
+ if (methodWithExt) ctx.props.ext = methodWithExt[2]
9
+ ctx.result = await method(methodWithExt ? methodWithExt[1] : ctx.params[0], ctx.props)
10
+ }
11
+
12
+ api.post('/', apiHandle)
13
+
14
+ module.exports = api
routes/index.js ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ const routeApi = require('./api')
2
+
3
+ module.exports = {
4
+ routeApi
5
+ }
utils/emoji-image.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const path = require('path')
2
+ const fs = require('fs')
3
+ const loadImageFromUrl = require('./image-load-url')
4
+ const EmojiDbLib = require('emoji-db')
5
+ const promiseAllStepN = require('./promise-concurrent')
6
+
7
+ const emojiDb = new EmojiDbLib({ useDefaultDb: true })
8
+
9
+ const emojiJFilesDir = '../assets/emoji/'
10
+
11
+ const brandFoledIds = {
12
+ apple: 325,
13
+ google: 313,
14
+ twitter: 322,
15
+ joypixels: 340,
16
+ blob: 56
17
+ }
18
+
19
+ const emojiJsonByBrand = {
20
+ apple: 'emoji-apple-image.json',
21
+ google: 'emoji-google-image.json',
22
+ twitter: 'emoji-twitter-image.json',
23
+ joypixels: 'emoji-joypixels-image.json',
24
+ blob: 'emoji-blob-image.json'
25
+ }
26
+
27
+ let emojiImageByBrand = {
28
+ apple: [],
29
+ google: [],
30
+ twitter: [],
31
+ joypixels: [],
32
+ blob: []
33
+ }
34
+
35
+ async function downloadEmoji (brand) {
36
+ console.log('emoji image load start')
37
+
38
+ const emojiImage = emojiImageByBrand[brand]
39
+
40
+ const emojiJsonFile = path.resolve(
41
+ __dirname,
42
+ emojiJFilesDir + emojiJsonByBrand[brand]
43
+ )
44
+
45
+ const dbData = emojiDb.dbData
46
+ const dbArray = Object.keys(dbData)
47
+ const emojiPromiseArray = []
48
+
49
+ for (const key of dbArray) {
50
+ const emoji = dbData[key]
51
+
52
+ if (!emoji.qualified && !emojiImage[key]) {
53
+ emojiPromiseArray.push(async () => {
54
+ let brandFolderName = brand
55
+ if (brand === 'blob') brandFolderName = 'google'
56
+
57
+ const fileUrl = `${process.env.EMOJI_DOMAIN}/thumbs/60/${brandFolderName}/${brandFoledIds[brand]}/${emoji.image.file_name}`
58
+
59
+ const img = await loadImageFromUrl(fileUrl, (headers) => {
60
+ return !headers['content-type'].match(/image/)
61
+ })
62
+
63
+ const base64 = img.toString('base64')
64
+
65
+ if (base64) {
66
+ return {
67
+ key,
68
+ base64
69
+ }
70
+ }
71
+ })
72
+ }
73
+ }
74
+
75
+ const donwloadResult = await promiseAllStepN(200)(emojiPromiseArray)
76
+
77
+ for (const emojiData of donwloadResult) {
78
+ if (emojiData) emojiImage[emojiData.key] = emojiData.base64
79
+ }
80
+
81
+ if (Object.keys(emojiImage).length > 0) {
82
+ const emojiJson = JSON.stringify(emojiImage, null, 2)
83
+
84
+ fs.writeFile(emojiJsonFile, emojiJson, (err) => {
85
+ if (err) return console.log(err)
86
+ })
87
+ }
88
+
89
+ console.log('emoji image load end')
90
+ }
91
+
92
+ for (const brand in emojiJsonByBrand) {
93
+ const emojiJsonFile = path.resolve(
94
+ __dirname,
95
+ emojiJFilesDir + emojiJsonByBrand[brand]
96
+ )
97
+
98
+ try {
99
+ if (fs.existsSync(emojiJsonFile)) emojiImageByBrand[brand] = require(emojiJsonFile)
100
+ } catch (error) {
101
+ console.log(error)
102
+ }
103
+ // downloadEmoji(brand)
104
+ }
105
+
106
+ module.exports = emojiImageByBrand
utils/image-load-path.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs')
2
+
3
+ module.exports = (path) => {
4
+ return new Promise((resolve, reject) => {
5
+ fs.readFile(path, (_error, data) => {
6
+ resolve(data)
7
+ })
8
+ })
9
+ }
utils/image-load-url.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const https = require('https')
2
+
3
+ module.exports = (url, filter = false) => {
4
+ return new Promise((resolve, reject) => {
5
+ https.get(url, (res) => {
6
+ if (filter && filter(res.headers)) {
7
+ resolve(Buffer.concat([]))
8
+ }
9
+
10
+ const chunks = []
11
+
12
+ res.on('error', (err) => {
13
+ reject(err)
14
+ })
15
+ res.on('data', (chunk) => {
16
+ chunks.push(chunk)
17
+ })
18
+ res.on('end', () => {
19
+ resolve(Buffer.concat(chunks))
20
+ })
21
+ })
22
+ })
23
+ }
utils/index.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ QuoteGenerate: require('./quote-generate'),
3
+ loadImageFromUrl: require('./image-load-url'),
4
+ loadImageFromPath: require('./image-load-path'),
5
+ promiseAllStepN: require('./promise-concurrent'),
6
+ userName: require('./user-name')
7
+ }
utils/promise-concurrent.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function promiseAllStepN (n, list) {
2
+ let tail = list.splice(n)
3
+ let head = list
4
+ let resolved = []
5
+ let processed = 0
6
+ return new Promise(resolve => {
7
+ head.forEach(x => {
8
+ let res = x()
9
+ resolved.push(res)
10
+ res.then(y => {
11
+ runNext()
12
+ return y
13
+ })
14
+ })
15
+ function runNext () {
16
+ if (processed == tail.length) {
17
+ resolve(Promise.all(resolved))
18
+ } else {
19
+ resolved.push(tail[processed]().then(x => {
20
+ runNext()
21
+ return x
22
+ }))
23
+ processed++
24
+ }
25
+ }
26
+ })
27
+ }
28
+
29
+ module.exports = n => list => promiseAllStepN(n, list)
utils/quote-generate.js ADDED
@@ -0,0 +1,1100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs')
2
+ const { createCanvas, registerFont } = require('canvas')
3
+ const EmojiDbLib = require('emoji-db')
4
+ const { loadImage } = require('canvas')
5
+ const loadImageFromUrl = require('./image-load-url')
6
+ const sharp = require('sharp')
7
+ const Jimp = require('jimp')
8
+ const smartcrop = require('smartcrop-sharp')
9
+ const runes = require('runes')
10
+ const lottie = require('lottie-node')
11
+ const zlib = require('zlib')
12
+ const { Telegram } = require('telegraf')
13
+
14
+ const emojiDb = new EmojiDbLib({ useDefaultDb: true })
15
+
16
+ function loadFont () {
17
+ console.log('font load start')
18
+ const fontsDir = 'assets/fonts/'
19
+
20
+ fs.readdir(fontsDir, (_err, files) => {
21
+ files.forEach((file) => {
22
+ try {
23
+ registerFont(`${fontsDir}${file}`, { family: file.replace(/\.[^/.]+$/, '') })
24
+ } catch (error) {
25
+ console.error(`${fontsDir}${file} not font file`)
26
+ }
27
+ })
28
+ })
29
+
30
+ console.log('font load end')
31
+ }
32
+
33
+ loadFont()
34
+
35
+ const emojiImageByBrand = require('./emoji-image')
36
+
37
+ const LRU = require('lru-cache')
38
+
39
+ const avatarCache = new LRU({
40
+ max: 20,
41
+ maxAge: 1000 * 60 * 5
42
+ })
43
+
44
+ // write a nodejs function that accepts 2 colors. the first is the background color and the second is the text color. as a result, the first color should come out brighter or darker depending on the contrast. for example, if the first text is dark, then make the second brighter and return it. you need to change not the background color, but the text color
45
+
46
+ // here are all the possible colors that will be passed as the second argument. the first color can be any
47
+ class ColorContrast {
48
+ constructor() {
49
+ this.brightnessThreshold = 175; // A threshold to determine when a color is considered bright or dark
50
+ }
51
+
52
+ getBrightness(color) {
53
+ // Calculates the brightness of a color using the formula from the WCAG 2.0
54
+ // See: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
55
+ const [r, g, b] = this.hexToRgb(color);
56
+ return (r * 299 + g * 587 + b * 114) / 1000;
57
+ }
58
+
59
+ hexToRgb(hex) {
60
+ // Converts a hex color string to an RGB array
61
+ const r = parseInt(hex.substring(1, 3), 16);
62
+ const g = parseInt(hex.substring(3, 5), 16);
63
+ const b = parseInt(hex.substring(5, 7), 16);
64
+ return [r, g, b];
65
+ }
66
+
67
+ rgbToHex([r, g, b]) {
68
+ // Converts an RGB array to a hex color string
69
+ return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
70
+ }
71
+
72
+ adjustBrightness(color, amount) {
73
+ // Adjusts the brightness of a color by a specified amount
74
+ const [r, g, b] = this.hexToRgb(color);
75
+ const newR = Math.max(0, Math.min(255, r + amount));
76
+ const newG = Math.max(0, Math.min(255, g + amount));
77
+ const newB = Math.max(0, Math.min(255, b + amount));
78
+ return this.rgbToHex([newR, newG, newB]);
79
+ }
80
+
81
+ getContrastRatio(background, foreground) {
82
+ // Calculates the contrast ratio between two colors using the formula from the WCAG 2.0
83
+ // See: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
84
+ const brightness1 = this.getBrightness(background);
85
+ const brightness2 = this.getBrightness(foreground);
86
+ const lightest = Math.max(brightness1, brightness2);
87
+ const darkest = Math.min(brightness1, brightness2);
88
+ return (lightest + 0.05) / (darkest + 0.05);
89
+ }
90
+
91
+ adjustContrast(background, foreground) {
92
+ // Adjusts the brightness of the foreground color to meet the minimum contrast ratio
93
+ // with the background color
94
+ const contrastRatio = this.getContrastRatio(background, foreground);
95
+ const brightnessDiff = this.getBrightness(background) - this.getBrightness(foreground);
96
+ if (contrastRatio >= 4.5) {
97
+ return foreground; // The contrast ratio is already sufficient
98
+ } else if (brightnessDiff >= 0) {
99
+ // The background is brighter than the foreground
100
+ const amount = Math.ceil((this.brightnessThreshold - this.getBrightness(foreground)) / 2);
101
+ return this.adjustBrightness(foreground, amount);
102
+ } else {
103
+ // The background is darker than the foreground
104
+ const amount = Math.ceil((this.getBrightness(foreground) - this.brightnessThreshold) / 2);
105
+ return this.adjustBrightness(foreground, -amount);
106
+ }
107
+ }
108
+ }
109
+
110
+
111
+ class QuoteGenerate {
112
+ constructor (botToken) {
113
+ this.telegram = new Telegram(botToken)
114
+ }
115
+
116
+ async avatarImageLatters (letters, color) {
117
+ const size = 500
118
+ const canvas = createCanvas(size, size)
119
+ const context = canvas.getContext('2d')
120
+
121
+ const gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height)
122
+
123
+ gradient.addColorStop(0, color[0])
124
+ gradient.addColorStop(1, color[1])
125
+
126
+ context.fillStyle = gradient
127
+ context.fillRect(0, 0, canvas.width, canvas.height)
128
+
129
+ const drawLetters = await this.drawMultilineText(
130
+ letters,
131
+ null,
132
+ size / 2,
133
+ '#FFF',
134
+ 0,
135
+ size,
136
+ size * 5,
137
+ size * 5
138
+ )
139
+
140
+ context.drawImage(drawLetters, (canvas.width - drawLetters.width) / 2, (canvas.height - drawLetters.height) / 1.5)
141
+
142
+ return canvas.toBuffer()
143
+ }
144
+
145
+ async downloadAvatarImage (user) {
146
+ let avatarImage
147
+
148
+ let nameLatters
149
+ if (user.first_name && user.last_name) nameLatters = runes(user.first_name)[0] + (runes(user.last_name || '')[0])
150
+ else {
151
+ let name = user.first_name || user.name || user.title
152
+ name = name.toUpperCase()
153
+ const nameWord = name.split(' ')
154
+
155
+ if (nameWord.length > 1) nameLatters = runes(nameWord[0])[0] + runes(nameWord.splice(-1)[0])[0]
156
+ else nameLatters = runes(nameWord[0])[0]
157
+ }
158
+
159
+ const cacheKey = user.id
160
+
161
+ const avatarImageCache = avatarCache.get(cacheKey)
162
+
163
+ const avatarColorArray = [
164
+ [ '#FF885E', '#FF516A' ], // red
165
+ [ '#FFCD6A', '#FFA85C' ], // orange
166
+ [ '#E0A2F3', '#D669ED' ], // purple
167
+ [ '#A0DE7E', '#54CB68' ], // green
168
+ [ '#53EDD6', '#28C9B7' ], // sea
169
+ [ '#72D5FD', '#2A9EF1' ], // blue
170
+ [ '#FFA8A8', '#FF719A' ] // pink
171
+ ]
172
+
173
+ const nameIndex = Math.abs(user.id) % 7
174
+
175
+ const avatarColor = avatarColorArray[nameIndex]
176
+
177
+ if (avatarImageCache) {
178
+ avatarImage = avatarImageCache
179
+ } else if (user.photo && user.photo.url) {
180
+ avatarImage = await loadImage(user.photo.url)
181
+ } else {
182
+ try {
183
+ let userPhoto, userPhotoUrl
184
+
185
+ if (user.photo && user.photo.big_file_id) userPhotoUrl = await this.telegram.getFileLink(user.photo.big_file_id).catch(console.error)
186
+
187
+ if (!userPhotoUrl) {
188
+ const getChat = await this.telegram.getChat(user.id).catch(console.error)
189
+ if (getChat && getChat.photo && getChat.photo.big_file_id) userPhoto = getChat.photo.big_file_id
190
+
191
+ if (userPhoto) userPhotoUrl = await this.telegram.getFileLink(userPhoto)
192
+ else if (user.username) userPhotoUrl = `https://telega.one/i/userpic/320/${user.username}.jpg`
193
+ else avatarImage = await loadImage(await this.avatarImageLatters(nameLatters, avatarColor))
194
+ }
195
+
196
+ if (userPhotoUrl) avatarImage = await loadImage(userPhotoUrl)
197
+
198
+ avatarCache.set(cacheKey, avatarImage)
199
+ } catch (error) {
200
+ avatarImage = await loadImage(await this.avatarImageLatters(nameLatters, avatarColor))
201
+ }
202
+ }
203
+
204
+ return avatarImage
205
+ }
206
+
207
+ ungzip (input, options) {
208
+ return new Promise((resolve, reject) => {
209
+ zlib.gunzip(input, options, (error, result) => {
210
+ if (!error) resolve(result)
211
+ else reject(Error(error))
212
+ })
213
+ })
214
+ }
215
+
216
+ async downloadMediaImage (media, mediaSize, type = 'id', crop = true) {
217
+ let mediaUrl
218
+ if (type === 'id') mediaUrl = await this.telegram.getFileLink(media).catch(console.error)
219
+ else mediaUrl = media
220
+ const load = await loadImageFromUrl(mediaUrl)
221
+ if (mediaUrl.match(/.tgs/)) {
222
+ const jsonLottie = await this.ungzip(load)
223
+ const canvas = createCanvas(512, 512)
224
+ const animation = lottie(JSON.parse(jsonLottie.toString()), canvas)
225
+ const middleFrame = Math.floor(animation.getDuration(true) / 2)
226
+ animation.goToAndStop(middleFrame, true)
227
+
228
+ return canvas
229
+ } else if (crop || mediaUrl.match(/.webp/)) {
230
+ const imageSharp = sharp(load)
231
+ const imageMetadata = await imageSharp.metadata()
232
+ const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()
233
+
234
+ let croppedImage
235
+
236
+ if (imageMetadata.format === 'webp') {
237
+ const jimpImage = await Jimp.read(sharpPng)
238
+
239
+ croppedImage = await jimpImage.autocrop(false).getBufferAsync(Jimp.MIME_PNG)
240
+ } else {
241
+ const smartcropResult = await smartcrop.crop(sharpPng, { width: mediaSize, height: imageMetadata.height })
242
+ const crop = smartcropResult.topCrop
243
+
244
+ croppedImage = imageSharp.extract({ width: crop.width, height: crop.height, left: crop.x, top: crop.y })
245
+ croppedImage = await imageSharp.png({ lossless: true, force: true }).toBuffer()
246
+ }
247
+
248
+ return loadImage(croppedImage)
249
+ } else {
250
+ return loadImage(load)
251
+ }
252
+ }
253
+
254
+ hexToRgb (hex) {
255
+ return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
256
+ , (m, r, g, b) => '#' + r + r + g + g + b + b)
257
+ .substring(1).match(/.{2}/g)
258
+ .map(x => parseInt(x, 16))
259
+ }
260
+
261
+ // https://codepen.io/andreaswik/pen/YjJqpK
262
+ lightOrDark (color) {
263
+ let r, g, b
264
+
265
+ // Check the format of the color, HEX or RGB?
266
+ if (color.match(/^rgb/)) {
267
+ // If HEX --> store the red, green, blue values in separate variables
268
+ color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/)
269
+
270
+ r = color[1]
271
+ g = color[2]
272
+ b = color[3]
273
+ } else {
274
+ // If RGB --> Convert it to HEX: http://gist.github.com/983661
275
+ color = +('0x' + color.slice(1).replace(
276
+ color.length < 5 && /./g, '$&$&'
277
+ )
278
+ )
279
+
280
+ r = color >> 16
281
+ g = color >> 8 & 255
282
+ b = color & 255
283
+ }
284
+
285
+ // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
286
+ const hsp = Math.sqrt(
287
+ 0.299 * (r * r) +
288
+ 0.587 * (g * g) +
289
+ 0.114 * (b * b)
290
+ )
291
+
292
+ // Using the HSP value, determine whether the color is light or dark
293
+ if (hsp > 127.5) {
294
+ return 'light'
295
+ } else {
296
+ return 'dark'
297
+ }
298
+ }
299
+
300
+ async drawMultilineText (text, entities, fontSize, fontColor, textX, textY, maxWidth, maxHeight, emojiBrand = 'apple') {
301
+ if (maxWidth > 10000) maxWidth = 10000
302
+ if (maxHeight > 10000) maxHeight = 10000
303
+
304
+ const emojiImageJson = emojiImageByBrand[emojiBrand]
305
+
306
+ let fallbackEmojiBrand = 'apple'
307
+ if (emojiBrand === 'blob') fallbackEmojiBrand = 'google'
308
+
309
+ const fallbackEmojiImageJson = emojiImageByBrand[fallbackEmojiBrand]
310
+
311
+ const canvas = createCanvas(maxWidth + fontSize, maxHeight + fontSize)
312
+ const canvasCtx = canvas.getContext('2d')
313
+
314
+ // text = text.slice(0, 4096)
315
+ text = text.replace(/і/g, 'i') // замена украинской буквы і на английскую, так как она отсутствует в шрифтах Noto
316
+ const chars = text.split('')
317
+
318
+ const lineHeight = 4 * (fontSize * 0.3)
319
+
320
+ const styledChar = []
321
+
322
+ const emojis = emojiDb.searchFromText({ input: text, fixCodePoints: true })
323
+
324
+ for (let charIndex = 0; charIndex < chars.length; charIndex++) {
325
+ const char = chars[charIndex]
326
+
327
+ styledChar[charIndex] = {
328
+ char,
329
+ style: []
330
+ }
331
+
332
+ if (entities && typeof entities === 'string') styledChar[charIndex].style.push(entities)
333
+ }
334
+
335
+ if (entities && typeof entities === 'object') {
336
+ for (let entityIndex = 0; entityIndex < entities.length; entityIndex++) {
337
+ const entity = entities[entityIndex]
338
+ const style = []
339
+
340
+ if (['pre', 'code'].includes(entity.type)) {
341
+ style.push('monospace')
342
+ } else if (
343
+ ['mention', 'text_mention', 'hashtag', 'email', 'phone_number', 'bot_command', 'url', 'text_link']
344
+ .includes(entity.type)
345
+ ) {
346
+ style.push('mention')
347
+ } else {
348
+ style.push(entity.type)
349
+ }
350
+
351
+ if (entity.type === 'custom_emoji') {
352
+ styledChar[entity.offset].customEmojiId = entity.custom_emoji_id
353
+ }
354
+
355
+ for (let charIndex = entity.offset; charIndex < entity.offset + entity.length; charIndex++) {
356
+ styledChar[charIndex].style = styledChar[charIndex].style.concat(style)
357
+ }
358
+ }
359
+ }
360
+
361
+ for (let emojiIndex = 0; emojiIndex < emojis.length; emojiIndex++) {
362
+ const emoji = emojis[emojiIndex]
363
+
364
+ for (let charIndex = emoji.offset; charIndex < emoji.offset + emoji.length; charIndex++) {
365
+ styledChar[charIndex].emoji = {
366
+ index: emojiIndex,
367
+ code: emoji.found
368
+ }
369
+ }
370
+ }
371
+
372
+ const styledWords = []
373
+
374
+ let stringNum = 0
375
+
376
+ const breakMatch = /<br>|\n|\r/
377
+ const spaceMatch = /[\f\n\r\t\v\u0020\u1680\u2000-\u200a\u2028\u2029\u205f\u3000]/
378
+
379
+ for (let index = 0; index < styledChar.length; index++) {
380
+ const charStyle = styledChar[index]
381
+ const lastChar = styledChar[index - 1]
382
+
383
+ if (
384
+ lastChar && (
385
+ (
386
+ (charStyle.emoji && !lastChar.emoji) ||
387
+ (!charStyle.emoji && lastChar.emoji) ||
388
+ (charStyle.emoji && lastChar.emoji && charStyle.emoji.index !== lastChar.emoji.index)
389
+ ) ||
390
+ (
391
+ (charStyle.char.match(breakMatch)) ||
392
+ (charStyle.char.match(spaceMatch) && !lastChar.char.match(spaceMatch)) ||
393
+ (lastChar.char.match(spaceMatch) && !charStyle.char.match(spaceMatch)) ||
394
+ (charStyle.style && lastChar.style && charStyle.style.toString() !== lastChar.style.toString())
395
+ )
396
+ )
397
+ ) {
398
+ stringNum++
399
+ }
400
+
401
+ if (!styledWords[stringNum]) {
402
+ styledWords[stringNum] = {
403
+ word: charStyle.char
404
+ }
405
+
406
+ if (charStyle.style) styledWords[stringNum].style = charStyle.style
407
+ if (charStyle.emoji) styledWords[stringNum].emoji = charStyle.emoji
408
+ if (charStyle.customEmojiId) styledWords[stringNum].customEmojiId = charStyle.customEmojiId
409
+ } else styledWords[stringNum].word += charStyle.char
410
+ }
411
+
412
+ let lineX = textX
413
+ let lineY = textY
414
+
415
+ let textWidth = 0
416
+
417
+ // load custom emoji
418
+ const customEmojiIds = []
419
+
420
+ for (let index = 0; index < styledWords.length; index++) {
421
+ const word = styledWords[index]
422
+
423
+ if (word.customEmojiId) {
424
+ customEmojiIds.push(word.customEmojiId)
425
+ }
426
+ }
427
+
428
+ const getCustomEmojiStickers = await this.telegram.callApi('getCustomEmojiStickers', {
429
+ custom_emoji_ids: customEmojiIds
430
+ }).catch(() => {})
431
+
432
+ const customEmojiStickers = {}
433
+
434
+ const loadCustomEmojiStickerPromises = []
435
+
436
+ if (getCustomEmojiStickers) {
437
+ for (let index = 0; index < getCustomEmojiStickers.length; index++) {
438
+ const sticker = getCustomEmojiStickers[index]
439
+
440
+ loadCustomEmojiStickerPromises.push((async () => {
441
+ const getFileLink = await this.telegram.getFileLink(sticker.thumb.file_id).catch(() => {})
442
+
443
+ if (getFileLink) {
444
+ const load = await loadImageFromUrl(getFileLink).catch(() => {})
445
+ const imageSharp = sharp(load)
446
+ const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()
447
+
448
+ customEmojiStickers[sticker.custom_emoji_id] = await loadImage(sharpPng).catch(() => {})
449
+ }
450
+ })())
451
+ }
452
+
453
+ await Promise.all(loadCustomEmojiStickerPromises).catch(() => {})
454
+ }
455
+
456
+ let breakWrite = false
457
+ for (let index = 0; index < styledWords.length; index++) {
458
+ const styledWord = styledWords[index]
459
+
460
+ let emojiImage
461
+
462
+ if (styledWord.emoji) {
463
+ if (styledWord.customEmojiId && customEmojiStickers[styledWord.customEmojiId]) {
464
+ emojiImage = customEmojiStickers[styledWord.customEmojiId]
465
+ } else {
466
+ const emojiImageBase = emojiImageJson[styledWord.emoji.code]
467
+ if (emojiImageBase) {
468
+ emojiImage = await loadImage(
469
+ Buffer.from(emojiImageBase, 'base64')
470
+ ).catch(() => {})
471
+ }
472
+ if (!emojiImage) {
473
+ emojiImage = await loadImage(
474
+ Buffer.from(fallbackEmojiImageJson[styledWord.emoji.code], 'base64')
475
+ ).catch(() => {})
476
+ }
477
+ }
478
+ }
479
+
480
+ let fontType = ''
481
+ let fontName = 'NotoSans'
482
+ let fillStyle = fontColor
483
+
484
+ if (styledWord.style.includes('bold')) {
485
+ fontType += 'bold '
486
+ }
487
+ if (styledWord.style.includes('italic')) {
488
+ fontType += 'italic '
489
+ }
490
+ if (styledWord.style.includes('monospace')) {
491
+ fontName = 'NotoSansMono'
492
+ fillStyle = '#5887a7'
493
+ }
494
+ if (styledWord.style.includes('mention')) {
495
+ fillStyle = '#6ab7ec'
496
+ }
497
+ if (styledWord.style.includes('spoiler')) {
498
+ const rbaColor = this.hexToRgb(this.normalizeColor(fontColor))
499
+ fillStyle = `rgba(${rbaColor[0]}, ${rbaColor[1]}, ${rbaColor[2]}, 0.15)`
500
+ }
501
+ // else {
502
+ // canvasCtx.font = `${fontSize}px OpenSans`
503
+ // canvasCtx.fillStyle = fontColor
504
+ // }
505
+
506
+ canvasCtx.font = `${fontType} ${fontSize}px ${fontName}`
507
+ canvasCtx.fillStyle = fillStyle
508
+
509
+ if (canvasCtx.measureText(styledWord.word).width > maxWidth - fontSize * 3) {
510
+ while (canvasCtx.measureText(styledWord.word).width > maxWidth - fontSize * 3) {
511
+ styledWord.word = styledWord.word.substr(0, styledWord.word.length - 1)
512
+ if (styledWord.word.length <= 0) break
513
+ }
514
+ styledWord.word += '…'
515
+ }
516
+
517
+ let lineWidth
518
+ const wordlWidth = canvasCtx.measureText(styledWord.word).width
519
+
520
+ if (styledWord.emoji) lineWidth = lineX + fontSize
521
+ else lineWidth = lineX + wordlWidth
522
+
523
+ if (styledWord.word.match(breakMatch) || (lineWidth > maxWidth - fontSize * 2 && wordlWidth < maxWidth)) {
524
+ if (styledWord.word.match(spaceMatch) && !styledWord.word.match(breakMatch)) styledWord.word = ''
525
+ if ((styledWord.word.match(spaceMatch) || !styledWord.word.match(breakMatch)) && lineY + lineHeight > maxHeight) {
526
+ while (lineWidth > maxWidth - fontSize * 2) {
527
+ styledWord.word = styledWord.word.substr(0, styledWord.word.length - 1)
528
+ lineWidth = lineX + canvasCtx.measureText(styledWord.word).width
529
+ if (styledWord.word.length <= 0) break
530
+ }
531
+
532
+ styledWord.word += '…'
533
+ lineWidth = lineX + canvasCtx.measureText(styledWord.word).width
534
+ breakWrite = true
535
+ } else {
536
+ if (styledWord.emoji) lineWidth = textX + fontSize + (fontSize * 0.2)
537
+ else lineWidth = textX + canvasCtx.measureText(styledWord.word).width
538
+
539
+ lineX = textX
540
+ lineY += lineHeight
541
+ }
542
+ }
543
+
544
+ if (styledWord.emoji) lineWidth += (fontSize * 0.2)
545
+
546
+ if (lineWidth > textWidth) textWidth = lineWidth
547
+ if (textWidth > maxWidth) textWidth = maxWidth
548
+
549
+ if (emojiImage) {
550
+ canvasCtx.drawImage(emojiImage, lineX, lineY - fontSize + (fontSize * 0.15), fontSize + (fontSize * 0.22), fontSize + (fontSize * 0.22))
551
+ } else {
552
+ canvasCtx.fillText(styledWord.word, lineX, lineY)
553
+
554
+ if (styledWord.style.includes('strikethrough')) canvasCtx.fillRect(lineX, lineY - fontSize / 2.8, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
555
+ if (styledWord.style.includes('underline')) canvasCtx.fillRect(lineX, lineY + 2, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
556
+ }
557
+
558
+ lineX = lineWidth
559
+
560
+ if (breakWrite) break
561
+ }
562
+
563
+ const canvasResize = createCanvas(textWidth, lineY + fontSize)
564
+ const canvasResizeCtx = canvasResize.getContext('2d')
565
+
566
+ canvasResizeCtx.drawImage(canvas, 0, 0)
567
+
568
+ return canvasResize
569
+ }
570
+
571
+ // https://stackoverflow.com/a/3368118
572
+ drawRoundRect (color, w, h, r) {
573
+ const x = 0
574
+ const y = 0
575
+
576
+ const canvas = createCanvas(w, h)
577
+ const canvasCtx = canvas.getContext('2d')
578
+
579
+ canvasCtx.fillStyle = color
580
+
581
+ if (w < 2 * r) r = w / 2
582
+ if (h < 2 * r) r = h / 2
583
+ canvasCtx.beginPath()
584
+ canvasCtx.moveTo(x + r, y)
585
+ canvasCtx.arcTo(x + w, y, x + w, y + h, r)
586
+ canvasCtx.arcTo(x + w, y + h, x, y + h, r)
587
+ canvasCtx.arcTo(x, y + h, x, y, r)
588
+ canvasCtx.arcTo(x, y, x + w, y, r)
589
+ canvasCtx.closePath()
590
+
591
+ canvasCtx.fill()
592
+
593
+ return canvas
594
+ }
595
+
596
+ drawGradientRoundRect (colorOne, colorTwo, w, h, r) {
597
+ const x = 0
598
+ const y = 0
599
+
600
+ const canvas = createCanvas(w, h)
601
+ const canvasCtx = canvas.getContext('2d')
602
+
603
+ const gradient = canvasCtx.createLinearGradient(0, 0, w, h)
604
+ gradient.addColorStop(0, colorOne)
605
+ gradient.addColorStop(1, colorTwo)
606
+
607
+ canvasCtx.fillStyle = gradient
608
+
609
+ if (w < 2 * r) r = w / 2
610
+ if (h < 2 * r) r = h / 2
611
+ canvasCtx.beginPath()
612
+ canvasCtx.moveTo(x + r, y)
613
+ canvasCtx.arcTo(x + w, y, x + w, y + h, r)
614
+ canvasCtx.arcTo(x + w, y + h, x, y + h, r)
615
+ canvasCtx.arcTo(x, y + h, x, y, r)
616
+ canvasCtx.arcTo(x, y, x + w, y, r)
617
+ canvasCtx.closePath()
618
+
619
+ canvasCtx.fill()
620
+
621
+ return canvas
622
+ }
623
+
624
+ colorLuminance (hex, lum) {
625
+ hex = String(hex).replace(/[^0-9a-f]/gi, '')
626
+ if (hex.length < 6) {
627
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
628
+ }
629
+ lum = lum || 0
630
+
631
+ // convert to decimal and change luminosity
632
+ let rgb = '#'
633
+ let c
634
+ let i
635
+ for (i = 0; i < 3; i++) {
636
+ c = parseInt(hex.substr(i * 2, 2), 16)
637
+ c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16)
638
+ rgb += ('00' + c).substr(c.length)
639
+ }
640
+
641
+ return rgb
642
+ }
643
+
644
+ roundImage (image, r) {
645
+ const w = image.width
646
+ const h = image.height
647
+
648
+ const canvas = createCanvas(w, h)
649
+ const canvasCtx = canvas.getContext('2d')
650
+
651
+ const x = 0
652
+ const y = 0
653
+
654
+ if (w < 2 * r) r = w / 2
655
+ if (h < 2 * r) r = h / 2
656
+ canvasCtx.beginPath()
657
+ canvasCtx.moveTo(x + r, y)
658
+ canvasCtx.arcTo(x + w, y, x + w, y + h, r)
659
+ canvasCtx.arcTo(x + w, y + h, x, y + h, r)
660
+ canvasCtx.arcTo(x, y + h, x, y, r)
661
+ canvasCtx.arcTo(x, y, x + w, y, r)
662
+ canvasCtx.clip()
663
+ canvasCtx.closePath()
664
+ canvasCtx.restore()
665
+ canvasCtx.drawImage(image, x, y)
666
+
667
+ return canvas
668
+ }
669
+
670
+ deawReplyLine (lineWidth, height, color) {
671
+ const canvas = createCanvas(20, height)
672
+ const context = canvas.getContext('2d')
673
+ context.beginPath()
674
+ context.moveTo(10, 0)
675
+ context.lineTo(10, height)
676
+ context.lineWidth = lineWidth
677
+ context.strokeStyle = color
678
+ context.stroke()
679
+
680
+ return canvas
681
+ }
682
+
683
+ async drawAvatar (user) {
684
+ const avatarImage = await this.downloadAvatarImage(user)
685
+
686
+ if (avatarImage) {
687
+ const avatarSize = avatarImage.naturalHeight
688
+
689
+ const canvas = createCanvas(avatarSize, avatarSize)
690
+ const canvasCtx = canvas.getContext('2d')
691
+
692
+ const avatarX = 0
693
+ const avatarY = 0
694
+
695
+ canvasCtx.beginPath()
696
+ canvasCtx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, Math.PI * 2, true)
697
+ canvasCtx.clip()
698
+ canvasCtx.closePath()
699
+ canvasCtx.restore()
700
+ canvasCtx.drawImage(avatarImage, avatarX, avatarY, avatarSize, avatarSize)
701
+
702
+ return canvas
703
+ }
704
+ }
705
+
706
+ drawLineSegment (ctx, x, y, width, isEven) {
707
+ ctx.lineWidth = 35 // how thick the line is
708
+ ctx.strokeStyle = '#aec6cf' // what color our line is
709
+ ctx.beginPath()
710
+ y = isEven ? y : -y
711
+ ctx.moveTo(x, 0)
712
+ ctx.lineTo(x, y)
713
+ ctx.arc(x + width / 2, y, width / 2, Math.PI, 0, isEven)
714
+ ctx.lineTo(x + width, 0)
715
+ ctx.stroke()
716
+ }
717
+
718
+ drawWaveform (data) {
719
+ const normalizedData = data.map(i => i / 32)
720
+
721
+ const canvas = createCanvas(4500, 500)
722
+ const padding = 50
723
+ canvas.height = (canvas.height + padding * 2)
724
+ const ctx = canvas.getContext('2d')
725
+ ctx.translate(0, canvas.height / 2 + padding)
726
+
727
+ // draw the line segments
728
+ const width = canvas.width / normalizedData.length
729
+ for (let i = 0; i < normalizedData.length; i++) {
730
+ const x = width * i
731
+ let height = normalizedData[i] * canvas.height - padding
732
+ if (height < 0) {
733
+ height = 0
734
+ } else if (height > canvas.height / 2) {
735
+ height = height > canvas.height / 2
736
+ }
737
+ this.drawLineSegment(ctx, x, height, width, (i + 1) % 2)
738
+ }
739
+ return canvas
740
+ }
741
+
742
+ async drawQuote (scale = 1, backgroundColorOne, backgroundColorTwo, avatar, replyName, replyNameColor, replyText, name, text, media, mediaType, maxMediaSize) {
743
+ const avatarPosX = 0 * scale
744
+ const avatarPosY = 5 * scale
745
+ const avatarSize = 50 * scale
746
+
747
+ const blockPosX = avatarSize + 10 * scale
748
+ const blockPosY = 0
749
+
750
+ const indent = 14 * scale
751
+
752
+ if (mediaType === 'sticker') name = undefined
753
+
754
+ let width = 0
755
+ if (name) width = name.width
756
+ if (text && width < text.width + indent) width = text.width + indent
757
+ if (name && width < name.width + indent) width = name.width + indent
758
+ if (replyName) {
759
+ if (width < replyName.width) width = replyName.width + indent * 2
760
+ if (width < replyText.width) width = replyText.width + indent * 2
761
+ }
762
+
763
+ let height = indent
764
+ if (text) height += text.height
765
+ else height += indent
766
+
767
+ if (name) {
768
+ height = name.height
769
+ if (text) height = text.height + name.height
770
+ else height += indent
771
+ }
772
+
773
+ width += blockPosX + indent
774
+ height += blockPosY
775
+
776
+ let namePosX = blockPosX + indent
777
+ let namePosY = indent
778
+
779
+ if (!name) {
780
+ namePosX = 0
781
+ namePosY = -indent
782
+ }
783
+
784
+ const textPosX = blockPosX + indent
785
+ let textPosY = indent
786
+ if (name) {
787
+ textPosY = name.height + indent * 0.25
788
+ height += indent * 0.25
789
+ }
790
+
791
+ let replyPosX = 0
792
+ let replyNamePosY = 0
793
+ let replyTextPosY = 0
794
+
795
+ if (replyName) {
796
+ replyPosX = textPosX + indent
797
+
798
+ const replyNameHeight = replyName.height
799
+ const replyTextHeight = replyText.height * 0.5
800
+
801
+ replyNamePosY = namePosY + replyNameHeight
802
+ replyTextPosY = replyNamePosY + replyTextHeight
803
+
804
+ textPosY += replyNameHeight + replyTextHeight + (indent / 4)
805
+ height += replyNameHeight + replyTextHeight + (indent / 4)
806
+ }
807
+
808
+ let mediaPosX = 0
809
+ let mediaPosY = 0
810
+
811
+ let mediaWidth, mediaHeight
812
+
813
+ if (media) {
814
+ mediaWidth = media.width * (maxMediaSize / media.height)
815
+ mediaHeight = maxMediaSize
816
+
817
+ if (mediaWidth >= maxMediaSize) {
818
+ mediaWidth = maxMediaSize
819
+ mediaHeight = media.height * (maxMediaSize / media.width)
820
+ }
821
+
822
+ if (!text || text.width <= mediaWidth || mediaWidth > (width - blockPosX)) {
823
+ width = mediaWidth + indent * 6
824
+ }
825
+
826
+ height += mediaHeight
827
+ if (!text) height += indent
828
+
829
+ if (name) {
830
+ mediaPosX = namePosX
831
+ mediaPosY = name.height + 5 * scale
832
+ } else {
833
+ mediaPosX = blockPosX + indent
834
+ mediaPosY = indent
835
+ }
836
+ if (replyName) mediaPosY += replyNamePosY + indent / 2
837
+ textPosY = mediaPosY + mediaHeight + 5 * scale
838
+ }
839
+
840
+ if (mediaType === 'sticker' && (name || replyName)) {
841
+ mediaPosY += indent * 4
842
+ height += indent * 2
843
+ }
844
+
845
+ const canvas = createCanvas(width, height)
846
+ const canvasCtx = canvas.getContext('2d')
847
+
848
+ let rectWidth = width - blockPosX
849
+ let rectHeight = height
850
+ const rectPosX = blockPosX
851
+ const rectPosY = blockPosY
852
+ const rectRoundRadius = 25 * scale
853
+
854
+ let rect
855
+ if (mediaType === 'sticker' && (name || replyName)) {
856
+ rectHeight -= mediaHeight + indent * 2
857
+ }
858
+
859
+ if (mediaType !== 'sticker' || name || replyName) {
860
+ if (backgroundColorOne === backgroundColorTwo) {
861
+ rect = this.drawRoundRect(backgroundColorOne, rectWidth, rectHeight, rectRoundRadius)
862
+ } else {
863
+ rect = this.drawGradientRoundRect(backgroundColorOne, backgroundColorTwo, rectWidth, rectHeight, rectRoundRadius)
864
+ }
865
+ }
866
+
867
+ if (avatar) canvasCtx.drawImage(avatar, avatarPosX, avatarPosY, avatarSize, avatarSize)
868
+ if (rect) canvasCtx.drawImage(rect, rectPosX, rectPosY)
869
+ if (name) canvasCtx.drawImage(name, namePosX, namePosY)
870
+ if (text) canvasCtx.drawImage(text, textPosX, textPosY)
871
+ if (media) canvasCtx.drawImage(this.roundImage(media, 5 * scale), mediaPosX, mediaPosY, mediaWidth, mediaHeight)
872
+
873
+ if (replyName) {
874
+ canvasCtx.drawImage(this.deawReplyLine(3 * scale, replyName.height + replyText.height * 0.4, replyNameColor), textPosX - 3, replyNamePosY)
875
+
876
+ canvasCtx.drawImage(replyName, replyPosX, replyNamePosY)
877
+ canvasCtx.drawImage(replyText, replyPosX, replyTextPosY)
878
+ }
879
+
880
+ return canvas
881
+ }
882
+
883
+ normalizeColor (color) {
884
+ const canvas = createCanvas(0, 0)
885
+ const canvasCtx = canvas.getContext('2d')
886
+
887
+ canvasCtx.fillStyle = color
888
+ color = canvasCtx.fillStyle
889
+
890
+ return color
891
+ }
892
+
893
+ async generate (backgroundColorOne, backgroundColorTwo, message, width = 512, height = 512, scale = 2, emojiBrand = 'apple') {
894
+ if (!scale) scale = 2
895
+ if (scale > 20) scale = 20
896
+ width *= scale
897
+ height *= scale
898
+
899
+ // check background style color black/light
900
+ const backStyle = this.lightOrDark(backgroundColorOne)
901
+
902
+
903
+ // historyPeer1NameFg: #c03d33; // red
904
+ // historyPeer2NameFg: #4fad2d; // green
905
+ // historyPeer3NameFg: #d09306; // yellow
906
+ // historyPeer4NameFg: #168acd; // blue
907
+ // historyPeer5NameFg: #8544d6; // purple
908
+ // historyPeer6NameFg: #cd4073; // pink
909
+ // historyPeer7NameFg: #2996ad; // sea
910
+ // historyPeer8NameFg: #ce671b; // orange
911
+
912
+ // { 0, 7, 4, 1, 6, 3, 5 }
913
+ // const nameColor = [
914
+ // '#c03d33', // red
915
+ // '#ce671b', // orange
916
+ // '#8544d6', // purple
917
+ // '#4fad2d', // green
918
+ // '#2996ad', // sea
919
+ // '#168acd', // blue
920
+ // '#cd4073' // pink
921
+ // ]
922
+
923
+ const nameColorLight = [
924
+ '#FC5C51', // red
925
+ '#FA790F', // orange
926
+ '#895DD5', // purple
927
+ '#0FB297', // green
928
+ '#0FC9D6', // sea
929
+ '#3CA5EC', // blue
930
+ '#D54FAF' // pink
931
+ ]
932
+
933
+ const nameColorDark = [
934
+ '#FF8E86', // red
935
+ '#FFA357', // orange
936
+ '#B18FFF', // purple
937
+ '#4DD6BF', // green
938
+ '#45E8D1', // sea
939
+ '#7AC9FF', // blue
940
+ '#FF7FD5' // pink
941
+ ]
942
+
943
+ // user name color
944
+ let nameIndex = 1
945
+ if (message.from.id) nameIndex = Math.abs(message.from.id) % 7
946
+
947
+ const nameColorArray = backStyle === 'light' ? nameColorLight : nameColorDark
948
+
949
+ let nameColor = nameColorArray[nameIndex]
950
+
951
+ const colorContrast = new ColorContrast()
952
+
953
+ // change name color based on background color by contrast
954
+ const contrast = colorContrast.getContrastRatio(this.colorLuminance(backgroundColorOne, 0.55), nameColor)
955
+ if (contrast > 90 || contrast < 30) {
956
+ nameColor = colorContrast.adjustContrast(this.colorLuminance(backgroundColorTwo, 0.55), nameColor)
957
+ }
958
+
959
+ const nameSize = 22 * scale
960
+
961
+ let nameCanvas
962
+ if (message?.from?.name) {
963
+ let name = message.from.name
964
+
965
+ const nameEntities = [
966
+ {
967
+ type: 'bold',
968
+ offset: 0,
969
+ length: name.length
970
+ }
971
+ ]
972
+
973
+ if (message.from.emoji_status) {
974
+ name += ' 🤡'
975
+
976
+ nameEntities.push({
977
+ type: 'custom_emoji',
978
+ offset: name.length - 2,
979
+ length: 2,
980
+ custom_emoji_id: message.from.emoji_status
981
+ })
982
+ }
983
+
984
+ nameCanvas = await this.drawMultilineText(
985
+ name,
986
+ nameEntities,
987
+ nameSize,
988
+ nameColor,
989
+ 0,
990
+ nameSize,
991
+ width,
992
+ nameSize,
993
+ emojiBrand
994
+ )
995
+ }
996
+
997
+ let fontSize = 24 * scale
998
+
999
+ let textColor = '#fff'
1000
+ if (backStyle === 'light') textColor = '#000'
1001
+
1002
+ let textCanvas
1003
+ if (message.text) {
1004
+ textCanvas = await this.drawMultilineText(
1005
+ message.text,
1006
+ message.entities,
1007
+ fontSize,
1008
+ textColor,
1009
+ 0,
1010
+ fontSize,
1011
+ width,
1012
+ height - fontSize,
1013
+ emojiBrand
1014
+ )
1015
+ }
1016
+
1017
+ let avatarCanvas
1018
+ if (message.avatar) avatarCanvas = await this.drawAvatar(message.from)
1019
+
1020
+ let replyName, replyNameColor, replyText
1021
+ if (message.replyMessage && message.replyMessage.name && message.replyMessage.text) {
1022
+ const replyNameIndex = Math.abs(message.replyMessage.chatId) % 7
1023
+ replyNameColor = nameColorArray[replyNameIndex]
1024
+
1025
+ const replyNameFontSize = 16 * scale
1026
+ if (message.replyMessage.name) {
1027
+ replyName = await this.drawMultilineText(
1028
+ message.replyMessage.name,
1029
+ 'bold',
1030
+ replyNameFontSize,
1031
+ replyNameColor,
1032
+ 0,
1033
+ replyNameFontSize,
1034
+ width * 0.9,
1035
+ replyNameFontSize,
1036
+ emojiBrand
1037
+ )
1038
+ }
1039
+
1040
+ let textColor = '#fff'
1041
+ if (backStyle === 'light') textColor = '#000'
1042
+
1043
+ const replyTextFontSize = 21 * scale
1044
+ replyText = await this.drawMultilineText(
1045
+ message.replyMessage.text,
1046
+ message.replyMessage.entities,
1047
+ replyTextFontSize,
1048
+ textColor,
1049
+ 0,
1050
+ replyTextFontSize,
1051
+ width * 0.9,
1052
+ replyTextFontSize,
1053
+ emojiBrand
1054
+ )
1055
+ }
1056
+
1057
+ let mediaCanvas, mediaType, maxMediaSize
1058
+ if (message.media) {
1059
+ let media, type
1060
+
1061
+ let crop = false
1062
+ if (message.mediaCrop) crop = true
1063
+
1064
+ if (message.media.url) {
1065
+ type = 'url'
1066
+ media = message.media.url
1067
+ } else {
1068
+ type = 'id'
1069
+ if (message.media.length > 1) {
1070
+ if (crop) media = message.media[1]
1071
+ else media = message.media.pop()
1072
+ } else media = message.media[0]
1073
+ }
1074
+
1075
+ maxMediaSize = width / 3 * scale
1076
+ if (message.text && maxMediaSize < textCanvas.width) maxMediaSize = textCanvas.width
1077
+
1078
+ mediaCanvas = await this.downloadMediaImage(media, maxMediaSize, type, crop)
1079
+ mediaType = message.mediaType
1080
+ }
1081
+
1082
+ if (message.voice) {
1083
+ mediaCanvas = this.drawWaveform(message.voice.waveform)
1084
+ maxMediaSize = width / 3 * scale
1085
+ }
1086
+
1087
+ const quote = this.drawQuote(
1088
+ scale,
1089
+ backgroundColorOne, backgroundColorTwo,
1090
+ avatarCanvas,
1091
+ replyName, replyNameColor, replyText,
1092
+ nameCanvas, textCanvas,
1093
+ mediaCanvas, mediaType, maxMediaSize
1094
+ )
1095
+
1096
+ return quote
1097
+ }
1098
+ }
1099
+
1100
+ module.exports = QuoteGenerate
utils/user-name.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = (user, url = false) => {
2
+ let name = user.first_name
3
+
4
+ if (user.last_name) name += ` ${user.last_name}`
5
+ name = name.replace(/</g, '&lt;').replace(/>/g, '&gt;')
6
+
7
+ if (url) return `<a href="tg://user?id=${user.id}">${name}</a>`
8
+ return name
9
+ }