cINAWGD commited on
Commit
ac504a0
·
verified ·
1 Parent(s): cb1e487

Update utils/quote-generate.js

Browse files
Files changed (1) hide show
  1. utils/quote-generate.js +1204 -65
utils/quote-generate.js CHANGED
@@ -1,3 +1,1104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  const fs = require('fs')
2
  const { createCanvas, registerFont } = require('canvas')
3
  const EmojiDbLib = require('emoji-db')
@@ -7,13 +1108,12 @@ 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
 
@@ -109,11 +1209,11 @@ class ColorContrast {
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')
@@ -142,7 +1242,7 @@ class QuoteGenerate {
142
  return canvas.toBuffer()
143
  }
144
 
145
- async downloadAvatarImage (user) {
146
  let avatarImage
147
 
148
  let nameLatters
@@ -161,13 +1261,13 @@ class QuoteGenerate {
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
@@ -204,7 +1304,7 @@ class QuoteGenerate {
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)
@@ -213,20 +1313,12 @@ class QuoteGenerate {
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('https://files.xianqiao.wang/' + 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()
@@ -251,7 +1343,7 @@ class QuoteGenerate {
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)
@@ -259,7 +1351,7 @@ class QuoteGenerate {
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?
@@ -297,7 +1389,7 @@ class QuoteGenerate {
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
 
@@ -337,7 +1429,7 @@ class QuoteGenerate {
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']
@@ -375,6 +1467,7 @@ class QuoteGenerate {
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]
@@ -384,15 +1477,18 @@ class QuoteGenerate {
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++
@@ -427,7 +1523,7 @@ class QuoteGenerate {
427
 
428
  const getCustomEmojiStickers = await this.telegram.callApi('getCustomEmojiStickers', {
429
  custom_emoji_ids: customEmojiIds
430
- }).catch(() => {})
431
 
432
  const customEmojiStickers = {}
433
 
@@ -438,22 +1534,23 @@ class QuoteGenerate {
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
 
@@ -467,12 +1564,12 @@ class QuoteGenerate {
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
  }
@@ -480,24 +1577,33 @@ class QuoteGenerate {
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
@@ -538,6 +1644,11 @@ class QuoteGenerate {
538
 
539
  lineX = textX
540
  lineY += lineHeight
 
 
 
 
 
541
  }
542
  }
543
 
@@ -546,13 +1657,19 @@ class QuoteGenerate {
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
@@ -563,13 +1680,14 @@ class QuoteGenerate {
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
 
@@ -593,7 +1711,7 @@ class QuoteGenerate {
593
  return canvas
594
  }
595
 
596
- drawGradientRoundRect (colorOne, colorTwo, w, h, r) {
597
  const x = 0
598
  const y = 0
599
 
@@ -621,7 +1739,7 @@ class QuoteGenerate {
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]
@@ -641,7 +1759,7 @@ class QuoteGenerate {
641
  return rgb
642
  }
643
 
644
- roundImage (image, r) {
645
  const w = image.width
646
  const h = image.height
647
 
@@ -667,7 +1785,7 @@ class QuoteGenerate {
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()
@@ -680,7 +1798,7 @@ class QuoteGenerate {
680
  return canvas
681
  }
682
 
683
- async drawAvatar (user) {
684
  const avatarImage = await this.downloadAvatarImage(user)
685
 
686
  if (avatarImage) {
@@ -703,7 +1821,7 @@ class QuoteGenerate {
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()
@@ -715,7 +1833,7 @@ class QuoteGenerate {
715
  ctx.stroke()
716
  }
717
 
718
- drawWaveform (data) {
719
  const normalizedData = data.map(i => i / 32)
720
 
721
  const canvas = createCanvas(4500, 500)
@@ -739,7 +1857,7 @@ class QuoteGenerate {
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
@@ -853,7 +1971,8 @@ class QuoteGenerate {
853
 
854
  let rect
855
  if (mediaType === 'sticker' && (name || replyName)) {
856
- rectHeight -= mediaHeight + indent * 2
 
857
  }
858
 
859
  if (mediaType !== 'sticker' || name || replyName) {
@@ -880,7 +1999,7 @@ class QuoteGenerate {
880
  return canvas
881
  }
882
 
883
- normalizeColor (color) {
884
  const canvas = createCanvas(0, 0)
885
  const canvasCtx = canvas.getContext('2d')
886
 
@@ -890,7 +2009,22 @@ class QuoteGenerate {
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
@@ -1075,6 +2209,11 @@ class QuoteGenerate {
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
  }
@@ -1097,4 +2236,4 @@ class QuoteGenerate {
1097
  }
1098
  }
1099
 
1100
- module.exports = QuoteGenerate
 
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('https://files.xianqiao.wang/' + 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
1101
+
1102
  const fs = require('fs')
1103
  const { createCanvas, registerFont } = require('canvas')
1104
  const EmojiDbLib = require('emoji-db')
 
1108
  const Jimp = require('jimp')
1109
  const smartcrop = require('smartcrop-sharp')
1110
  const runes = require('runes')
 
1111
  const zlib = require('zlib')
1112
  const { Telegram } = require('telegraf')
1113
 
1114
  const emojiDb = new EmojiDbLib({ useDefaultDb: true })
1115
 
1116
+ function loadFont() {
1117
  console.log('font load start')
1118
  const fontsDir = 'assets/fonts/'
1119
 
 
1209
 
1210
 
1211
  class QuoteGenerate {
1212
+ constructor(botToken) {
1213
  this.telegram = new Telegram(botToken)
1214
  }
1215
 
1216
+ async avatarImageLatters(letters, color) {
1217
  const size = 500
1218
  const canvas = createCanvas(size, size)
1219
  const context = canvas.getContext('2d')
 
1242
  return canvas.toBuffer()
1243
  }
1244
 
1245
+ async downloadAvatarImage(user) {
1246
  let avatarImage
1247
 
1248
  let nameLatters
 
1261
  const avatarImageCache = avatarCache.get(cacheKey)
1262
 
1263
  const avatarColorArray = [
1264
+ ['#FF885E', '#FF516A'], // red
1265
+ ['#FFCD6A', '#FFA85C'], // orange
1266
+ ['#E0A2F3', '#D669ED'], // purple
1267
+ ['#A0DE7E', '#54CB68'], // green
1268
+ ['#53EDD6', '#28C9B7'], // sea
1269
+ ['#72D5FD', '#2A9EF1'], // blue
1270
+ ['#FFA8A8', '#FF719A'] // pink
1271
  ]
1272
 
1273
  const nameIndex = Math.abs(user.id) % 7
 
1304
  return avatarImage
1305
  }
1306
 
1307
+ ungzip(input, options) {
1308
  return new Promise((resolve, reject) => {
1309
  zlib.gunzip(input, options, (error, result) => {
1310
  if (!error) resolve(result)
 
1313
  })
1314
  }
1315
 
1316
+ async downloadMediaImage(media, mediaSize, type = 'id', crop = true) {
1317
  let mediaUrl
1318
  if (type === 'id') mediaUrl = await this.telegram.getFileLink(media).catch(console.error)
1319
  else mediaUrl = media
1320
+ const load = await loadImageFromUrl(mediaUrl)
1321
+ if (crop || mediaUrl.match(/.webp/)) {
 
 
 
 
 
 
 
 
1322
  const imageSharp = sharp(load)
1323
  const imageMetadata = await imageSharp.metadata()
1324
  const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()
 
1343
  }
1344
  }
1345
 
1346
+ hexToRgb(hex) {
1347
  return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
1348
  , (m, r, g, b) => '#' + r + r + g + g + b + b)
1349
  .substring(1).match(/.{2}/g)
 
1351
  }
1352
 
1353
  // https://codepen.io/andreaswik/pen/YjJqpK
1354
+ lightOrDark(color) {
1355
  let r, g, b
1356
 
1357
  // Check the format of the color, HEX or RGB?
 
1389
  }
1390
  }
1391
 
1392
+ async drawMultilineText(text, entities, fontSize, fontColor, textX, textY, maxWidth, maxHeight, emojiBrand = 'apple') {
1393
  if (maxWidth > 10000) maxWidth = 10000
1394
  if (maxHeight > 10000) maxHeight = 10000
1395
 
 
1429
  const entity = entities[entityIndex]
1430
  const style = []
1431
 
1432
+ if (['pre', 'code', 'pre_code'].includes(entity.type)) {
1433
  style.push('monospace')
1434
  } else if (
1435
  ['mention', 'text_mention', 'hashtag', 'email', 'phone_number', 'bot_command', 'url', 'text_link']
 
1467
 
1468
  const breakMatch = /<br>|\n|\r/
1469
  const spaceMatch = /[\f\n\r\t\v\u0020\u1680\u2000-\u200a\u2028\u2029\u205f\u3000]/
1470
+ const CJKMatch = /[\u1100-\u11ff\u2e80-\u2eff\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3130-\u318f\u3190-\u319f\u31a0-\u31bf\u31c0-\u31ef\u31f0-\u31ff\u3200-\u32ff\u3300-\u33ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]/
1471
 
1472
  for (let index = 0; index < styledChar.length; index++) {
1473
  const charStyle = styledChar[index]
 
1477
  lastChar && (
1478
  (
1479
  (charStyle.emoji && !lastChar.emoji) ||
1480
+ (!charStyle.emoji && lastChar.emoji) ||
1481
+ (charStyle.emoji && lastChar.emoji && charStyle.emoji.index !== lastChar.emoji.index)
1482
  ) ||
1483
+ (
1484
+ (charStyle.char.match(breakMatch)) ||
1485
+ (charStyle.char.match(spaceMatch) && !lastChar.char.match(spaceMatch)) ||
1486
+ (lastChar.char.match(spaceMatch) && !charStyle.char.match(spaceMatch)) ||
1487
+ (charStyle.style && lastChar.style && charStyle.style.toString() !== lastChar.style.toString())
1488
+ ) || (
1489
+ charStyle.char.match(CJKMatch) ||
1490
+ lastChar.char.match(CJKMatch)
1491
+ )
1492
  )
1493
  ) {
1494
  stringNum++
 
1523
 
1524
  const getCustomEmojiStickers = await this.telegram.callApi('getCustomEmojiStickers', {
1525
  custom_emoji_ids: customEmojiIds
1526
+ }).catch(() => { })
1527
 
1528
  const customEmojiStickers = {}
1529
 
 
1534
  const sticker = getCustomEmojiStickers[index]
1535
 
1536
  loadCustomEmojiStickerPromises.push((async () => {
1537
+ const getFileLink = await this.telegram.getFileLink(sticker.thumb.file_id).catch(() => { })
1538
 
1539
  if (getFileLink) {
1540
+ const load = await loadImageFromUrl(getFileLink).catch(() => { })
1541
  const imageSharp = sharp(load)
1542
  const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()
1543
 
1544
+ customEmojiStickers[sticker.custom_emoji_id] = await loadImage(sharpPng).catch(() => { })
1545
  }
1546
  })())
1547
  }
1548
 
1549
+ await Promise.all(loadCustomEmojiStickerPromises).catch(() => { })
1550
  }
1551
 
1552
  let breakWrite = false
1553
+ let lineDirection = this.getLineDirection(styledWords, 0)
1554
  for (let index = 0; index < styledWords.length; index++) {
1555
  const styledWord = styledWords[index]
1556
 
 
1564
  if (emojiImageBase) {
1565
  emojiImage = await loadImage(
1566
  Buffer.from(emojiImageBase, 'base64')
1567
+ ).catch(() => { })
1568
  }
1569
  if (!emojiImage) {
1570
  emojiImage = await loadImage(
1571
  Buffer.from(fallbackEmojiImageJson[styledWord.emoji.code], 'base64')
1572
+ ).catch(() => { })
1573
  }
1574
  }
1575
  }
 
1577
  let fontType = ''
1578
  let fontName = 'NotoSans'
1579
  let fillStyle = fontColor
1580
+ if (styledWord.style.includes('bold') || /\*\w+\*/.test(styledWord.word)) {
 
1581
  fontType += 'bold '
1582
+ styledWord.word = styledWord.word.replace(/\*(\w+)\*/g, '$1')
1583
+
1584
  }
1585
+
1586
+ if (styledWord.style.includes('italic') || /_\w+_/.test(styledWord.word)) {
1587
  fontType += 'italic '
1588
+ styledWord.word = styledWord.word.replace(/_(\w+)_/g, '$1')
1589
  }
1590
+
1591
  if (styledWord.style.includes('monospace')) {
1592
  fontName = 'NotoSansMono'
1593
  fillStyle = '#5887a7'
1594
  }
1595
+
1596
+ if (styledWord.style.includes('mention') || /(https?:\/\/[^\s]+)/g.test(styledWord.word)) {
1597
  fillStyle = '#6ab7ec'
1598
  }
1599
+
1600
+
1601
  if (styledWord.style.includes('spoiler')) {
1602
  const rbaColor = this.hexToRgb(this.normalizeColor(fontColor))
1603
  fillStyle = `rgba(${rbaColor[0]}, ${rbaColor[1]}, ${rbaColor[2]}, 0.15)`
1604
  }
1605
+
1606
+
1607
  // else {
1608
  // canvasCtx.font = `${fontSize}px OpenSans`
1609
  // canvasCtx.fillStyle = fontColor
 
1644
 
1645
  lineX = textX
1646
  lineY += lineHeight
1647
+ if (index < styledWords.length - 1) {
1648
+ let nextLineDirection = this.getLineDirection(styledWords, index + 1)
1649
+ if (lineDirection != nextLineDirection) textWidth = maxWidth - fontSize * 2
1650
+ lineDirection = nextLineDirection
1651
+ }
1652
  }
1653
  }
1654
 
 
1657
  if (lineWidth > textWidth) textWidth = lineWidth
1658
  if (textWidth > maxWidth) textWidth = maxWidth
1659
 
1660
+ let wordX = (lineDirection == 'rtl') ? maxWidth - lineX - wordlWidth - fontSize * 2 : lineX
1661
+
1662
  if (emojiImage) {
1663
+ canvasCtx.drawImage(emojiImage, wordX, lineY - fontSize + (fontSize * 0.15), fontSize + (fontSize * 0.22), fontSize + (fontSize * 0.22))
1664
  } else {
1665
+ if(/~\w+~/.test(styledWord.word)) {
1666
+ styledWord.word = styledWord.word.replace(/~(\w+)~/g, '$1')
1667
+ canvasCtx.fillRect(wordX, lineY - fontSize / 2.8, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
1668
+ }
1669
+ canvasCtx.fillText(styledWord.word, wordX, lineY)
1670
 
1671
+ if (styledWord.style.includes('strikethrough')) canvasCtx.fillRect(wordX, lineY - fontSize / 2.8, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
1672
+ if (styledWord.style.includes('underline')) canvasCtx.fillRect(wordX, lineY + 2, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
1673
  }
1674
 
1675
  lineX = lineWidth
 
1680
  const canvasResize = createCanvas(textWidth, lineY + fontSize)
1681
  const canvasResizeCtx = canvasResize.getContext('2d')
1682
 
1683
+ let dx = (lineDirection == 'rtl') ? textWidth - maxWidth + fontSize * 2 : 0
1684
+ canvasResizeCtx.drawImage(canvas, dx, 0)
1685
 
1686
  return canvasResize
1687
  }
1688
 
1689
  // https://stackoverflow.com/a/3368118
1690
+ drawRoundRect(color, w, h, r) {
1691
  const x = 0
1692
  const y = 0
1693
 
 
1711
  return canvas
1712
  }
1713
 
1714
+ drawGradientRoundRect(colorOne, colorTwo, w, h, r) {
1715
  const x = 0
1716
  const y = 0
1717
 
 
1739
  return canvas
1740
  }
1741
 
1742
+ colorLuminance(hex, lum) {
1743
  hex = String(hex).replace(/[^0-9a-f]/gi, '')
1744
  if (hex.length < 6) {
1745
  hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
 
1759
  return rgb
1760
  }
1761
 
1762
+ roundImage(image, r) {
1763
  const w = image.width
1764
  const h = image.height
1765
 
 
1785
  return canvas
1786
  }
1787
 
1788
+ deawReplyLine(lineWidth, height, color) {
1789
  const canvas = createCanvas(20, height)
1790
  const context = canvas.getContext('2d')
1791
  context.beginPath()
 
1798
  return canvas
1799
  }
1800
 
1801
+ async drawAvatar(user) {
1802
  const avatarImage = await this.downloadAvatarImage(user)
1803
 
1804
  if (avatarImage) {
 
1821
  }
1822
  }
1823
 
1824
+ drawLineSegment(ctx, x, y, width, isEven) {
1825
  ctx.lineWidth = 35 // how thick the line is
1826
  ctx.strokeStyle = '#aec6cf' // what color our line is
1827
  ctx.beginPath()
 
1833
  ctx.stroke()
1834
  }
1835
 
1836
+ drawWaveform(data) {
1837
  const normalizedData = data.map(i => i / 32)
1838
 
1839
  const canvas = createCanvas(4500, 500)
 
1857
  return canvas
1858
  }
1859
 
1860
+ async drawQuote(scale = 1, backgroundColorOne, backgroundColorTwo, avatar, replyName, replyNameColor, replyText, name, text, media, mediaType, maxMediaSize) {
1861
  const avatarPosX = 0 * scale
1862
  const avatarPosY = 5 * scale
1863
  const avatarSize = 50 * scale
 
1971
 
1972
  let rect
1973
  if (mediaType === 'sticker' && (name || replyName)) {
1974
+ rectHeight = (replyName.height + replyText.height * 0.5) + indent * 2
1975
+ backgroundColorOne = backgroundColorTwo = 'rgba(0, 0, 0, 0.5)'
1976
  }
1977
 
1978
  if (mediaType !== 'sticker' || name || replyName) {
 
1999
  return canvas
2000
  }
2001
 
2002
+ normalizeColor(color) {
2003
  const canvas = createCanvas(0, 0)
2004
  const canvasCtx = canvas.getContext('2d')
2005
 
 
2009
  return color
2010
  }
2011
 
2012
+ getLineDirection(words, start_index) {
2013
+ const RTLMatch = /[\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC]/
2014
+ const neutralMatch = /[\u0000-\u0040\u005B-\u0060\u007B-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF\u2010-\u2029\u202C\u202F-\u2BFF\u1F300-\u1F5FF\u1F600-\u1F64F]/
2015
+
2016
+ for (let index = start_index; index < words.length; index++) {
2017
+ if (words[index].word.match(RTLMatch)) {
2018
+ return 'rtl'
2019
+ } else {
2020
+ if (!words[index].word.match(neutralMatch))
2021
+ return 'ltr'
2022
+ }
2023
+ }
2024
+ return 'ltr'
2025
+ }
2026
+
2027
+ async generate(backgroundColorOne, backgroundColorTwo, message, width = 512, height = 512, scale = 2, emojiBrand = 'apple') {
2028
  if (!scale) scale = 2
2029
  if (scale > 20) scale = 20
2030
  width *= scale
 
2209
  maxMediaSize = width / 3 * scale
2210
  if (message.text && maxMediaSize < textCanvas.width) maxMediaSize = textCanvas.width
2211
 
2212
+ if (media.is_animated) {
2213
+ media = media.thumb
2214
+ maxMediaSize = maxMediaSize / 2
2215
+ }
2216
+
2217
  mediaCanvas = await this.downloadMediaImage(media, maxMediaSize, type, crop)
2218
  mediaType = message.mediaType
2219
  }
 
2236
  }
2237
  }
2238
 
2239
+ module.exports = QuoteGenerate