File size: 39,800 Bytes
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
 
 
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
ac504a0
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
ac504a0
 
5ae7e18
ac504a0
 
 
 
 
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
1554706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
ac504a0
5ae7e18
 
 
ac504a0
5ae7e18
 
 
 
ac504a0
5ae7e18
 
1554706
 
 
25fdf96
1554706
5ae7e18
25fdf96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1554706
f298a06
1554706
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
ac504a0
5ae7e18
ac504a0
5ae7e18
ac504a0
 
5ae7e18
ac504a0
5ae7e18
ac504a0
5ae7e18
 
 
 
ac504a0
 
5ae7e18
 
ac504a0
 
5ae7e18
 
 
 
ac504a0
1554706
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
ac504a0
 
5ae7e18
ac504a0
5ae7e18
1554706
ac504a0
 
 
 
5ae7e18
ac504a0
 
5ae7e18
 
 
 
 
 
 
 
 
 
ac504a0
 
5ae7e18
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
5ae7e18
 
 
 
 
 
 
 
 
ac504a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
 
 
 
 
5ae7e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac504a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
const fs = require('fs')
const { createCanvas, registerFont } = require('canvas')
const EmojiDbLib = require('emoji-db')
const { loadImage } = require('canvas')
const loadImageFromUrl = require('./image-load-url')
const sharp = require('sharp')
const Jimp = require('jimp')
const smartcrop = require('smartcrop-sharp')
const runes = require('runes')
const zlib = require('zlib')
const { Telegram } = require('telegraf')

const emojiDb = new EmojiDbLib({ useDefaultDb: true })

function loadFont() {
  console.log('font load start')
  const fontsDir = 'assets/fonts/'

  fs.readdir(fontsDir, (_err, files) => {
    files.forEach((file) => {
      try {
        registerFont(`${fontsDir}${file}`, { family: file.replace(/\.[^/.]+$/, '') })
      } catch (error) {
        console.error(`${fontsDir}${file} not font file`)
      }
    })
  })

  console.log('font load end')
}

loadFont()

const emojiImageByBrand = require('./emoji-image')

const LRU = require('lru-cache')

const avatarCache = new LRU({
  max: 20,
  maxAge: 1000 * 60 * 5
})

// 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

// here are all the possible colors that will be passed as the second argument. the first color can be any
class ColorContrast {
  constructor() {
    this.brightnessThreshold = 175; // A threshold to determine when a color is considered bright or dark
  }

  getBrightness(color) {
    // Calculates the brightness of a color using the formula from the WCAG 2.0
    // See: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
    const [r, g, b] = this.hexToRgb(color);
    return (r * 299 + g * 587 + b * 114) / 1000;
  }

  hexToRgb(hex) {
    // Converts a hex color string to an RGB array
    const r = parseInt(hex.substring(1, 3), 16);
    const g = parseInt(hex.substring(3, 5), 16);
    const b = parseInt(hex.substring(5, 7), 16);
    return [r, g, b];
  }

  rgbToHex([r, g, b]) {
    // Converts an RGB array to a hex color string
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
  }

  adjustBrightness(color, amount) {
    // Adjusts the brightness of a color by a specified amount
    const [r, g, b] = this.hexToRgb(color);
    const newR = Math.max(0, Math.min(255, r + amount));
    const newG = Math.max(0, Math.min(255, g + amount));
    const newB = Math.max(0, Math.min(255, b + amount));
    return this.rgbToHex([newR, newG, newB]);
  }

  getContrastRatio(background, foreground) {
    // Calculates the contrast ratio between two colors using the formula from the WCAG 2.0
    // See: https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
    const brightness1 = this.getBrightness(background);
    const brightness2 = this.getBrightness(foreground);
    const lightest = Math.max(brightness1, brightness2);
    const darkest = Math.min(brightness1, brightness2);
    return (lightest + 0.05) / (darkest + 0.05);
  }

  adjustContrast(background, foreground) {
    // Adjusts the brightness of the foreground color to meet the minimum contrast ratio
    // with the background color
    const contrastRatio = this.getContrastRatio(background, foreground);
    const brightnessDiff = this.getBrightness(background) - this.getBrightness(foreground);
    if (contrastRatio >= 4.5) {
      return foreground; // The contrast ratio is already sufficient
    } else if (brightnessDiff >= 0) {
      // The background is brighter than the foreground
      const amount = Math.ceil((this.brightnessThreshold - this.getBrightness(foreground)) / 2);
      return this.adjustBrightness(foreground, amount);
    } else {
      // The background is darker than the foreground
      const amount = Math.ceil((this.getBrightness(foreground) - this.brightnessThreshold) / 2);
      return this.adjustBrightness(foreground, -amount);
    }
  }
}


class QuoteGenerate {
  constructor(botToken) {
    this.telegram = new Telegram(botToken)
  }

  async avatarImageLatters(letters, color) {
    const size = 500
    const canvas = createCanvas(size, size)
    const context = canvas.getContext('2d')

    const gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height)

    gradient.addColorStop(0, color[0])
    gradient.addColorStop(1, color[1])

    context.fillStyle = gradient
    context.fillRect(0, 0, canvas.width, canvas.height)

    const drawLetters = await this.drawMultilineText(
      letters,
      null,
      size / 2,
      '#FFF',
      0,
      size,
      size * 5,
      size * 5
    )

    context.drawImage(drawLetters, (canvas.width - drawLetters.width) / 2, (canvas.height - drawLetters.height) / 1.5)

    return canvas.toBuffer()
  }

  async downloadAvatarImage(user) {
    let avatarImage

    let nameLatters
    if (user.first_name && user.last_name) nameLatters = runes(user.first_name)[0] + (runes(user.last_name || '')[0])
    else {
      let name = user.first_name || user.name || user.title
      name = name.toUpperCase()
      const nameWord = name.split(' ')

      if (nameWord.length > 1) nameLatters = runes(nameWord[0])[0] + runes(nameWord.splice(-1)[0])[0]
      else nameLatters = runes(nameWord[0])[0]
    }

    const cacheKey = user.id

    const avatarImageCache = avatarCache.get(cacheKey)

    const avatarColorArray = [
      ['#FF885E', '#FF516A'], // red
      ['#FFCD6A', '#FFA85C'], // orange
      ['#E0A2F3', '#D669ED'], // purple
      ['#A0DE7E', '#54CB68'], // green
      ['#53EDD6', '#28C9B7'], // sea
      ['#72D5FD', '#2A9EF1'], // blue
      ['#FFA8A8', '#FF719A'] // pink
    ]

    const nameIndex = Math.abs(user.id) % 7

    const avatarColor = avatarColorArray[nameIndex]

    if (avatarImageCache) {
      avatarImage = avatarImageCache
    } else if (user.photo && user.photo.url) {
      avatarImage = await loadImage(user.photo.url)
    } else {
      try {
        let userPhoto, userPhotoUrl

        if (user.photo && user.photo.big_file_id) userPhotoUrl = await this.telegram.getFileLink(user.photo.big_file_id).catch(console.error)

        if (!userPhotoUrl) {
          const getChat = await this.telegram.getChat(user.id).catch(console.error)
          if (getChat && getChat.photo && getChat.photo.big_file_id) userPhoto = getChat.photo.big_file_id

          if (userPhoto) userPhotoUrl = await this.telegram.getFileLink(userPhoto)
          else if (user.username) userPhotoUrl = `https://telega.one/i/userpic/320/${user.username}.jpg`
          else avatarImage = await loadImage(await this.avatarImageLatters(nameLatters, avatarColor))
        }

        if (userPhotoUrl) avatarImage = await loadImage(userPhotoUrl)

        avatarCache.set(cacheKey, avatarImage)
      } catch (error) {
        avatarImage = await loadImage(await this.avatarImageLatters(nameLatters, avatarColor))
      }
    }

    return avatarImage
  }

  ungzip(input, options) {
    return new Promise((resolve, reject) => {
      zlib.gunzip(input, options, (error, result) => {
        if (!error) resolve(result)
        else reject(Error(error))
      })
    })
  }

  async downloadMediaImage(media, mediaSize, type = 'id', crop = true) {
    let mediaUrl
    if (type === 'id') mediaUrl = await this.telegram.getFileLink(media).catch(console.error)
    else mediaUrl = media
    const load = await loadImageFromUrl(mediaUrl)
    if (crop || mediaUrl.match(/.webp/)) {
      const imageSharp = sharp(load)
      const imageMetadata = await imageSharp.metadata()
      const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()

      let croppedImage

      if (imageMetadata.format === 'webp') {
        const jimpImage = await Jimp.read(sharpPng)

        croppedImage = await jimpImage.autocrop(false).getBufferAsync(Jimp.MIME_PNG)
      } else {
        const smartcropResult = await smartcrop.crop(sharpPng, { width: mediaSize, height: imageMetadata.height })
        const crop = smartcropResult.topCrop

        croppedImage = imageSharp.extract({ width: crop.width, height: crop.height, left: crop.x, top: crop.y })
        croppedImage = await imageSharp.png({ lossless: true, force: true }).toBuffer()
      }

      return loadImage(croppedImage)
    } else {
      return loadImage(load)
    }
  }

  hexToRgb(hex) {
    return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
      , (m, r, g, b) => '#' + r + r + g + g + b + b)
      .substring(1).match(/.{2}/g)
      .map(x => parseInt(x, 16))
  }

  // https://codepen.io/andreaswik/pen/YjJqpK
  lightOrDark(color) {
    let r, g, b

    // Check the format of the color, HEX or RGB?
    if (color.match(/^rgb/)) {
      // If HEX --> store the red, green, blue values in separate variables
      color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/)

      r = color[1]
      g = color[2]
      b = color[3]
    } else {
      // If RGB --> Convert it to HEX: http://gist.github.com/983661
      color = +('0x' + color.slice(1).replace(
        color.length < 5 && /./g, '$&$&'
      )
      )

      r = color >> 16
      g = color >> 8 & 255
      b = color & 255
    }

    // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
    const hsp = Math.sqrt(
      0.299 * (r * r) +
      0.587 * (g * g) +
      0.114 * (b * b)
    )

    // Using the HSP value, determine whether the color is light or dark
    if (hsp > 127.5) {
      return 'light'
    } else {
      return 'dark'
    }
  }

  async drawMultilineText(text, entities, fontSize, fontColor, textX, textY, maxWidth, maxHeight, emojiBrand = 'apple') {
    if (maxWidth > 10000) maxWidth = 10000
    if (maxHeight > 10000) maxHeight = 10000

    const emojiImageJson = emojiImageByBrand[emojiBrand]

    let fallbackEmojiBrand = 'apple'
    if (emojiBrand === 'blob') fallbackEmojiBrand = 'google'

    const fallbackEmojiImageJson = emojiImageByBrand[fallbackEmojiBrand]

    const canvas = createCanvas(maxWidth + fontSize, maxHeight + fontSize)
    const canvasCtx = canvas.getContext('2d')

    // text = text.slice(0, 4096)
    text = text.replace(/і/g, 'i') // замена украинской буквы і на английскую, так как она отсутствует в шрифтах Noto
    const chars = text.split('')

    const lineHeight = 4 * (fontSize * 0.3)

    const styledChar = []

    const emojis = emojiDb.searchFromText({ input: text, fixCodePoints: true })

    for (let charIndex = 0; charIndex < chars.length; charIndex++) {
      const char = chars[charIndex]

      styledChar[charIndex] = {
        char,
        style: []
      }
      if (entities && typeof entities === 'string') styledChar[charIndex].style.push(entities)
    }

    if (entities && typeof entities === 'object') {
      for (let entityIndex = 0; entityIndex < entities.length; entityIndex++) {
        const entity = entities[entityIndex]
        const style = []

        if (['pre', 'code', 'pre_code'].includes(entity.type)) {
          style.push('monospace')
        } else if (
          ['mention', 'text_mention', 'hashtag', 'email', 'phone_number', 'bot_command', 'url', 'text_link']
            .includes(entity.type)
        ) {
          style.push('mention')
        } else {
          style.push(entity.type)
        }

        if (entity.type === 'custom_emoji') {
          styledChar[entity.offset].customEmojiId = entity.custom_emoji_id
        }

        for (let charIndex = entity.offset; charIndex < entity.offset + entity.length; charIndex++) {
          styledChar[charIndex].style = styledChar[charIndex].style.concat(style)
        }
      }
    }

    for (let emojiIndex = 0; emojiIndex < emojis.length; emojiIndex++) {
      const emoji = emojis[emojiIndex]

      for (let charIndex = emoji.offset; charIndex < emoji.offset + emoji.length; charIndex++) {
        styledChar[charIndex].emoji = {
          index: emojiIndex,
          code: emoji.found
        }
      }
    }

    const styledWords = []

    let stringNum = 0

    const breakMatch = /<br>|\n|\r/
    const spaceMatch = /[\f\n\r\t\v\u0020\u1680\u2000-\u200a\u2028\u2029\u205f\u3000]/
    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]/

    for (let index = 0; index < styledChar.length; index++) {
      const charStyle = styledChar[index]
      const lastChar = styledChar[index - 1]
      if (
        lastChar && (
          (
            (charStyle.emoji && !lastChar.emoji) ||
            (!charStyle.emoji && lastChar.emoji) ||
            (charStyle.emoji && lastChar.emoji && charStyle.emoji.index !== lastChar.emoji.index)
          ) ||
          (
            (charStyle.char.match(breakMatch)) ||
            (charStyle.char.match(spaceMatch) && !lastChar.char.match(spaceMatch)) ||
            (lastChar.char.match(spaceMatch) && !charStyle.char.match(spaceMatch)) ||
            (charStyle.style && lastChar.style && charStyle.style.toString() !== lastChar.style.toString())
          ) || (
            charStyle.char.match(CJKMatch) ||
            lastChar.char.match(CJKMatch)
          )
        )
      ) {
        stringNum++
      }

      if (!styledWords[stringNum]) {
        styledWords[stringNum] = {
          word: charStyle.char
        }
        if (charStyle.style) styledWords[stringNum].style = charStyle.style
        if (charStyle.emoji) styledWords[stringNum].emoji = charStyle.emoji
        if (charStyle.customEmojiId) styledWords[stringNum].customEmojiId = charStyle.customEmojiId
      } else styledWords[stringNum].word += charStyle.char
    }
    // const { createCanvas } = require('canvas');
    // const fs = require('fs');

    // // Sample text with newlines and bold markers (*)
    // const text = "Hello,\n*My world*,\nHow are you? *where he is*";

    // // Split text by lines to handle newlines (\n)
    // const lines = text.split('\n');

    // // Canvas setup
    // const canvas = createCanvas(400, 200);  // Width and height in pixels
    // const ctx = canvas.getContext('2d');

    // // Background color
    // ctx.fillStyle = 'black';  // Set background to black
    // ctx.fillRect(0, 0, canvas.width, canvas.height);

    // // Set text color to white
    // ctx.fillStyle = 'white';

    // // Initial text position
    // let yPos = 30;
    // const lineHeight = 30;  // Vertical space between lines

    // // Process each line
    // lines.forEach((line) => {
    //     // Split the line into parts: normal text and bolded parts between *
    //     const parts = line.split(/(\*.*?\*)/);

    //     let xPos = 10; // Starting x position for each line

    //     parts.forEach((part) => {
    //         if (part.startsWith('*') && part.endsWith('*')) {
    //             const boldText = part.slice(1, -1);
    //             ctx.font = 'bold 20px Arial';
    //             ctx.fillText(boldText, xPos, yPos);
    //             xPos += ctx.measureText(boldText).width; // Move x position after bold text
    //         } else {
    //             ctx.font = '20px Arial';
    //             ctx.fillText(part, xPos, yPos);
    //             xPos += ctx.measureText(part).width; // Move x position after normal text
    //         }
    //     });

    //     // Move y position down for the next line if there’s more text
    //     yPos += lineHeight;
    // });

    // // Save the canvas to a file
    // const out = fs.createWriteStream(__dirname + '/output.png');
    // const stream = canvas.createPNGStream();
    // stream.pipe(out);

    // out.on('finish', () => console.log('The image was saved as output.png'));

    let lineX = textX
    let lineY = textY

    let textWidth = 0

    // load custom emoji
    const customEmojiIds = []

    for (let index = 0; index < styledWords.length; index++) {
      const word = styledWords[index]

      if (word.customEmojiId) {
        customEmojiIds.push(word.customEmojiId)
      }
    }

    const getCustomEmojiStickers = await this.telegram.callApi('getCustomEmojiStickers', {
      custom_emoji_ids: customEmojiIds
    }).catch(() => { })

    const customEmojiStickers = {}

    const loadCustomEmojiStickerPromises = []

    if (getCustomEmojiStickers) {
      for (let index = 0; index < getCustomEmojiStickers.length; index++) {
        const sticker = getCustomEmojiStickers[index]

        loadCustomEmojiStickerPromises.push((async () => {
          const getFileLink = await this.telegram.getFileLink(sticker.thumb.file_id).catch(() => { })

          if (getFileLink) {
            const load = await loadImageFromUrl(getFileLink).catch(() => { })
            const imageSharp = sharp(load)
            const sharpPng = await imageSharp.png({ lossless: true, force: true }).toBuffer()

            customEmojiStickers[sticker.custom_emoji_id] = await loadImage(sharpPng).catch(() => { })
          }
        })())
      }

      await Promise.all(loadCustomEmojiStickerPromises).catch(() => { })
    }


    let breakWrite = false;
    let lineDirection = this.getLineDirection(styledWords, 0);

    
    for (let index = 0; index < styledWords.length; index++) {
      const styledWord = styledWords[index]
      const last_styledWord = styledWords[index - 1]
      if (last_styledWord?.word?.toString()?.startsWith("*") || last_styledWord?.style?.includes("bold") || styledWord?.word?.toString()?.startsWith("*")) {
        if (!last_styledWord?.style.includes("last_bold")) {
          if (!Array.isArray(styledWord.style)) styledWord.style = []
          styledWord.style.push("bold")
          if (styledWord?.word?.toString()?.startsWith("*")) {
            styledWord.word = styledWord.word.slice(1)
          }
          if (styledWord?.word?.toString()?.endsWith("*")) {
            styledWord.word = styledWord.word.slice(0, -1);
            styledWord.style.push("last_bold")
          }
        }
      }

      if (last_styledWord?.word?.toString()?.startsWith("~") || last_styledWord?.style?.includes("strikethrough") || styledWord?.word?.toString()?.startsWith("~")) {
        if (!last_styledWord?.style.includes("last_strikethrough")) {
          if (!Array.isArray(styledWord.style)) styledWord.style = []
          styledWord.style.push("strikethrough")
          if (styledWord?.word?.toString()?.startsWith("~")) {
            styledWord.word = styledWord.word.slice(1)
          }
          if (styledWord?.word?.toString()?.endsWith("~")) {
            styledWord.word = styledWord.word.slice(0, -1);
            styledWord.style.push("last_strikethrough")
          }
        }
      }

      if (last_styledWord?.word?.toString()?.startsWith("_") || last_styledWord?.style?.includes("italic") || styledWord?.word?.toString()?.startsWith("_")) {
        if (!last_styledWord?.style.includes("last_italic")) {
          if (!Array.isArray(styledWord.style)) styledWord.style = []
          styledWord.style.push("italic")
          if (styledWord?.word?.toString()?.startsWith("~")) {
            styledWord.word = styledWord.word.slice(1)
            }
            if (false) { // I Forgot what is this
              styledWord.word = styledWord.word.slice(0, -1);
              styledWord.style.push(lastStyleName);
            }
          }
        }

      let emojiImage

      if (styledWord.emoji) {
        if (styledWord.customEmojiId && customEmojiStickers[styledWord.customEmojiId]) {
          emojiImage = customEmojiStickers[styledWord.customEmojiId]
        } else {
          const emojiImageBase = emojiImageJson[styledWord.emoji.code]
          if (emojiImageBase) {
            emojiImage = await loadImage(
              Buffer.from(emojiImageBase, 'base64')
            ).catch(() => { })
          }
          if (!emojiImage) {
            emojiImage = await loadImage(
              Buffer.from(fallbackEmojiImageJson[styledWord.emoji.code], 'base64')
            ).catch(() => { })
          }
        }
      }

      let fontType = ''
      let fontName = 'NotoSans'
      let fillStyle = fontColor
      if (styledWord.style.includes('bold') || /\*\w+\*/.test(styledWord.word)) {
        fontType += 'bold '
        styledWord.word = styledWord.word.replace(/\*(\w+)\*/g, '$1')
      }

      if (styledWord.style.includes('italic') || /_\w+_/.test(styledWord.word)) {
        fontType += 'italic '
        styledWord.word = styledWord.word.replace(/_(\w+)_/g, '$1')
      }

      if (styledWord.style.includes('monospace')) {
        fontName = 'NotoSansMono'
        fillStyle = '#5887a7'
      }

      if (styledWord.style.includes('mention') || /(https?:\/\/[^\s]+)/g.test(styledWord.word)) {
        fillStyle = '#6ab7ec'
      }


      if (styledWord.style.includes('spoiler')) {
        const rbaColor = this.hexToRgb(this.normalizeColor(fontColor))
        fillStyle = `rgba(${rbaColor[0]}, ${rbaColor[1]}, ${rbaColor[2]}, 0.15)`
      }


      // else {
      //   canvasCtx.font = `${fontSize}px OpenSans`
      //   canvasCtx.fillStyle = fontColor
      // }

      canvasCtx.font = `${fontType} ${fontSize}px ${fontName}`
      canvasCtx.fillStyle = fillStyle

      if (canvasCtx.measureText(styledWord.word).width > maxWidth - fontSize * 3) {
        while (canvasCtx.measureText(styledWord.word).width > maxWidth - fontSize * 3) {
          styledWord.word = styledWord.word.substr(0, styledWord.word.length - 1)
          if (styledWord.word.length <= 0) break
        }
        styledWord.word += '…'
      }

      let lineWidth
      const wordlWidth = canvasCtx.measureText(styledWord.word).width

      if (styledWord.emoji) lineWidth = lineX + fontSize
      else lineWidth = lineX + wordlWidth

      if (styledWord.word.match(breakMatch) || (lineWidth > maxWidth - fontSize * 2 && wordlWidth < maxWidth)) {
        if (styledWord.word.match(spaceMatch) && !styledWord.word.match(breakMatch)) styledWord.word = ''
        if ((styledWord.word.match(spaceMatch) || !styledWord.word.match(breakMatch)) && lineY + lineHeight > maxHeight) {
          while (lineWidth > maxWidth - fontSize * 2) {
            styledWord.word = styledWord.word.substr(0, styledWord.word.length - 1)
            lineWidth = lineX + canvasCtx.measureText(styledWord.word).width
            if (styledWord.word.length <= 0) break
          }

          styledWord.word += '…'
          lineWidth = lineX + canvasCtx.measureText(styledWord.word).width
          breakWrite = true
        } else {
          if (styledWord.emoji) lineWidth = textX + fontSize + (fontSize * 0.2)
          else lineWidth = textX + canvasCtx.measureText(styledWord.word).width

          lineX = textX
          lineY += lineHeight
          if (index < styledWords.length - 1) {
            let nextLineDirection = this.getLineDirection(styledWords, index + 1)
            if (lineDirection != nextLineDirection) textWidth = maxWidth - fontSize * 2
            lineDirection = nextLineDirection
          }
        }
      }

      if (styledWord.emoji) lineWidth += (fontSize * 0.2)

      if (lineWidth > textWidth) textWidth = lineWidth
      if (textWidth > maxWidth) textWidth = maxWidth

      let wordX = (lineDirection == 'rtl') ? maxWidth - lineX - wordlWidth - fontSize * 2 : lineX

      if (emojiImage) {
        canvasCtx.drawImage(emojiImage, wordX, lineY - fontSize + (fontSize * 0.15), fontSize + (fontSize * 0.22), fontSize + (fontSize * 0.22))
      } else {
        if (/~\w+~/.test(styledWord.word)) {
          styledWord.word = styledWord.word.replace(/~(\w+)~/g, '$1')
          canvasCtx.fillRect(wordX, lineY - fontSize / 2.8, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
        }
        canvasCtx.fillText(styledWord.word, wordX, lineY)

        if (styledWord.style.includes('strikethrough')) canvasCtx.fillRect(wordX, lineY - fontSize / 2.8, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
        if (styledWord.style.includes('underline')) canvasCtx.fillRect(wordX, lineY + 2, canvasCtx.measureText(styledWord.word).width, fontSize * 0.1)
      }

      lineX = lineWidth

      if (breakWrite) break
    }

    const canvasResize = createCanvas(textWidth, lineY + fontSize)
    const canvasResizeCtx = canvasResize.getContext('2d')

    let dx = (lineDirection == 'rtl') ? textWidth - maxWidth + fontSize * 2 : 0
    canvasResizeCtx.drawImage(canvas, dx, 0)

    return canvasResize
  }

  // https://stackoverflow.com/a/3368118
  drawRoundRect(color, w, h, r) {
    const x = 0
    const y = 0

    const canvas = createCanvas(w, h)
    const canvasCtx = canvas.getContext('2d')

    canvasCtx.fillStyle = color

    if (w < 2 * r) r = w / 2
    if (h < 2 * r) r = h / 2
    canvasCtx.beginPath()
    canvasCtx.moveTo(x + r, y)
    canvasCtx.arcTo(x + w, y, x + w, y + h, r)
    canvasCtx.arcTo(x + w, y + h, x, y + h, r)
    canvasCtx.arcTo(x, y + h, x, y, r)
    canvasCtx.arcTo(x, y, x + w, y, r)
    canvasCtx.closePath()

    canvasCtx.fill()

    return canvas
  }

  drawGradientRoundRect(colorOne, colorTwo, w, h, r) {
    const x = 0
    const y = 0

    const canvas = createCanvas(w, h)
    const canvasCtx = canvas.getContext('2d')

    const gradient = canvasCtx.createLinearGradient(0, 0, w, h)
    gradient.addColorStop(0, colorOne)
    gradient.addColorStop(1, colorTwo)

    canvasCtx.fillStyle = gradient

    if (w < 2 * r) r = w / 2
    if (h < 2 * r) r = h / 2
    canvasCtx.beginPath()
    canvasCtx.moveTo(x + r, y)
    canvasCtx.arcTo(x + w, y, x + w, y + h, r)
    canvasCtx.arcTo(x + w, y + h, x, y + h, r)
    canvasCtx.arcTo(x, y + h, x, y, r)
    canvasCtx.arcTo(x, y, x + w, y, r)
    canvasCtx.closePath()

    canvasCtx.fill()

    return canvas
  }

  colorLuminance(hex, lum) {
    hex = String(hex).replace(/[^0-9a-f]/gi, '')
    if (hex.length < 6) {
      hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
    }
    lum = lum || 0

    // convert to decimal and change luminosity
    let rgb = '#'
    let c
    let i
    for (i = 0; i < 3; i++) {
      c = parseInt(hex.substr(i * 2, 2), 16)
      c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16)
      rgb += ('00' + c).substr(c.length)
    }

    return rgb
  }

  roundImage(image, r) {
    const w = image.width
    const h = image.height

    const canvas = createCanvas(w, h)
    const canvasCtx = canvas.getContext('2d')

    const x = 0
    const y = 0

    if (w < 2 * r) r = w / 2
    if (h < 2 * r) r = h / 2
    canvasCtx.beginPath()
    canvasCtx.moveTo(x + r, y)
    canvasCtx.arcTo(x + w, y, x + w, y + h, r)
    canvasCtx.arcTo(x + w, y + h, x, y + h, r)
    canvasCtx.arcTo(x, y + h, x, y, r)
    canvasCtx.arcTo(x, y, x + w, y, r)
    canvasCtx.clip()
    canvasCtx.closePath()
    canvasCtx.restore()
    canvasCtx.drawImage(image, x, y)

    return canvas
  }

  deawReplyLine(lineWidth, height, color) {
    const canvas = createCanvas(20, height)
    const context = canvas.getContext('2d')
    context.beginPath()
    context.moveTo(10, 0)
    context.lineTo(10, height)
    context.lineWidth = lineWidth
    context.strokeStyle = color
    context.stroke()

    return canvas
  }

  async drawAvatar(user) {
    const avatarImage = await this.downloadAvatarImage(user)

    if (avatarImage) {
      const avatarSize = avatarImage.naturalHeight

      const canvas = createCanvas(avatarSize, avatarSize)
      const canvasCtx = canvas.getContext('2d')

      const avatarX = 0
      const avatarY = 0

      canvasCtx.beginPath()
      canvasCtx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, Math.PI * 2, true)
      canvasCtx.clip()
      canvasCtx.closePath()
      canvasCtx.restore()
      canvasCtx.drawImage(avatarImage, avatarX, avatarY, avatarSize, avatarSize)

      return canvas
    }
  }

  drawLineSegment(ctx, x, y, width, isEven) {
    ctx.lineWidth = 35 // how thick the line is
    ctx.strokeStyle = '#aec6cf' // what color our line is
    ctx.beginPath()
    y = isEven ? y : -y
    ctx.moveTo(x, 0)
    ctx.lineTo(x, y)
    ctx.arc(x + width / 2, y, width / 2, Math.PI, 0, isEven)
    ctx.lineTo(x + width, 0)
    ctx.stroke()
  }

  drawWaveform(data) {
    const normalizedData = data.map(i => i / 32)

    const canvas = createCanvas(4500, 500)
    const padding = 50
    canvas.height = (canvas.height + padding * 2)
    const ctx = canvas.getContext('2d')
    ctx.translate(0, canvas.height / 2 + padding)

    // draw the line segments
    const width = canvas.width / normalizedData.length
    for (let i = 0; i < normalizedData.length; i++) {
      const x = width * i
      let height = normalizedData[i] * canvas.height - padding
      if (height < 0) {
        height = 0
      } else if (height > canvas.height / 2) {
        height = height > canvas.height / 2
      }
      this.drawLineSegment(ctx, x, height, width, (i + 1) % 2)
    }
    return canvas
  }

  async drawQuote(scale = 1, backgroundColorOne, backgroundColorTwo, avatar, replyName, replyNameColor, replyText, name, text, media, mediaType, maxMediaSize) {
    const avatarPosX = 0 * scale
    const avatarPosY = 5 * scale
    const avatarSize = 50 * scale

    const blockPosX = avatarSize + 10 * scale
    const blockPosY = 0

    const indent = 14 * scale

    if (mediaType === 'sticker') name = undefined

    let width = 0
    if (name) width = name.width
    if (text && width < text.width + indent) width = text.width + indent
    if (name && width < name.width + indent) width = name.width + indent
    if (replyName) {
      if (width < replyName.width) width = replyName.width + indent * 2
      if (width < replyText.width) width = replyText.width + indent * 2
    }

    let height = indent
    if (text) height += text.height
    else height += indent

    if (name) {
      height = name.height
      if (text) height = text.height + name.height
      else height += indent
    }

    width += blockPosX + indent
    height += blockPosY

    let namePosX = blockPosX + indent
    let namePosY = indent

    if (!name) {
      namePosX = 0
      namePosY = -indent
    }

    const textPosX = blockPosX + indent
    let textPosY = indent
    if (name) {
      textPosY = name.height + indent * 0.25
      height += indent * 0.25
    }

    let replyPosX = 0
    let replyNamePosY = 0
    let replyTextPosY = 0

    if (replyName) {
      replyPosX = textPosX + indent

      const replyNameHeight = replyName.height
      const replyTextHeight = replyText.height * 0.5

      replyNamePosY = namePosY + replyNameHeight
      replyTextPosY = replyNamePosY + replyTextHeight

      textPosY += replyNameHeight + replyTextHeight + (indent / 4)
      height += replyNameHeight + replyTextHeight + (indent / 4)
    }

    let mediaPosX = 0
    let mediaPosY = 0

    let mediaWidth, mediaHeight

    if (media) {
      mediaWidth = media.width * (maxMediaSize / media.height)
      mediaHeight = maxMediaSize

      if (mediaWidth >= maxMediaSize) {
        mediaWidth = maxMediaSize
        mediaHeight = media.height * (maxMediaSize / media.width)
      }

      if (!text || text.width <= mediaWidth || mediaWidth > (width - blockPosX)) {
        width = mediaWidth + indent * 6
      }

      height += mediaHeight
      if (!text) height += indent

      if (name) {
        mediaPosX = namePosX
        mediaPosY = name.height + 5 * scale
      } else {
        mediaPosX = blockPosX + indent
        mediaPosY = indent
      }
      if (replyName) mediaPosY += replyNamePosY + indent / 2
      textPosY = mediaPosY + mediaHeight + 5 * scale
    }

    if (mediaType === 'sticker' && (name || replyName)) {
      mediaPosY += indent * 4
      height += indent * 2
    }

    const canvas = createCanvas(width, height)
    const canvasCtx = canvas.getContext('2d')

    let rectWidth = width - blockPosX
    let rectHeight = height
    const rectPosX = blockPosX
    const rectPosY = blockPosY
    const rectRoundRadius = 25 * scale

    let rect
    if (mediaType === 'sticker' && (name || replyName)) {
      rectHeight = (replyName.height + replyText.height * 0.5) + indent * 2
      backgroundColorOne = backgroundColorTwo = 'rgba(0, 0, 0, 0.5)'
    }

    if (mediaType !== 'sticker' || name || replyName) {
      if (backgroundColorOne === backgroundColorTwo) {
        rect = this.drawRoundRect(backgroundColorOne, rectWidth, rectHeight, rectRoundRadius)
      } else {
        rect = this.drawGradientRoundRect(backgroundColorOne, backgroundColorTwo, rectWidth, rectHeight, rectRoundRadius)
      }
    }

    if (avatar) canvasCtx.drawImage(avatar, avatarPosX, avatarPosY, avatarSize, avatarSize)
    if (rect) canvasCtx.drawImage(rect, rectPosX, rectPosY)
    if (name) canvasCtx.drawImage(name, namePosX, namePosY)
    if (text) canvasCtx.drawImage(text, textPosX, textPosY)
    if (media) canvasCtx.drawImage(this.roundImage(media, 5 * scale), mediaPosX, mediaPosY, mediaWidth, mediaHeight)

    if (replyName) {
      canvasCtx.drawImage(this.deawReplyLine(3 * scale, replyName.height + replyText.height * 0.4, replyNameColor), textPosX - 3, replyNamePosY)

      canvasCtx.drawImage(replyName, replyPosX, replyNamePosY)
      canvasCtx.drawImage(replyText, replyPosX, replyTextPosY)
    }

    return canvas
  }

  normalizeColor(color) {
    const canvas = createCanvas(0, 0)
    const canvasCtx = canvas.getContext('2d')

    canvasCtx.fillStyle = color
    color = canvasCtx.fillStyle

    return color
  }

  getLineDirection(words, start_index) {
    const RTLMatch = /[\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC]/
    const neutralMatch = /[\u0000-\u0040\u005B-\u0060\u007B-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF\u2010-\u2029\u202C\u202F-\u2BFF\u1F300-\u1F5FF\u1F600-\u1F64F]/

    for (let index = start_index; index < words.length; index++) {
      if (words[index].word.match(RTLMatch)) {
        return 'rtl'
      } else {
        if (!words[index].word.match(neutralMatch))
          return 'ltr'
      }
    }
    return 'ltr'
  }

  async generate(backgroundColorOne, backgroundColorTwo, message, width = 512, height = 512, scale = 2, emojiBrand = 'apple') {
    if (!scale) scale = 2
    if (scale > 20) scale = 20
    width *= scale
    height *= scale

    // check background style color black/light
    const backStyle = this.lightOrDark(backgroundColorOne)


    // historyPeer1NameFg: #c03d33; // red
    // historyPeer2NameFg: #4fad2d; // green
    // historyPeer3NameFg: #d09306; // yellow
    // historyPeer4NameFg: #168acd; // blue
    // historyPeer5NameFg: #8544d6; // purple
    // historyPeer6NameFg: #cd4073; // pink
    // historyPeer7NameFg: #2996ad; // sea
    // historyPeer8NameFg: #ce671b; // orange

    // { 0, 7, 4, 1, 6, 3, 5 }
    // const nameColor = [
    //   '#c03d33', // red
    //   '#ce671b', // orange
    //   '#8544d6', // purple
    //   '#4fad2d', // green
    //   '#2996ad', // sea
    //   '#168acd', // blue
    //   '#cd4073' // pink
    // ]

    const nameColorLight = [
      '#FC5C51', // red
      '#FA790F', // orange
      '#895DD5', // purple
      '#0FB297', // green
      '#0FC9D6', // sea
      '#3CA5EC', // blue
      '#D54FAF' // pink
    ]

    const nameColorDark = [
      '#FF8E86', // red
      '#FFA357', // orange
      '#B18FFF', // purple
      '#4DD6BF', // green
      '#45E8D1', // sea
      '#7AC9FF', // blue
      '#FF7FD5' // pink
    ]

    // user name  color
    let nameIndex = 1
    if (message.from.id) nameIndex = Math.abs(message.from.id) % 7

    const nameColorArray = backStyle === 'light' ? nameColorLight : nameColorDark

    let nameColor = nameColorArray[nameIndex]

    const colorContrast = new ColorContrast()

    // change name color based on background color by contrast
    const contrast = colorContrast.getContrastRatio(this.colorLuminance(backgroundColorOne, 0.55), nameColor)
    if (contrast > 90 || contrast < 30) {
      nameColor = colorContrast.adjustContrast(this.colorLuminance(backgroundColorTwo, 0.55), nameColor)
    }

    const nameSize = 22 * scale

    let nameCanvas
    if (message?.from?.name) {
      let name = message.from.name

      const nameEntities = [
        {
          type: 'bold',
          offset: 0,
          length: name.length
        }
      ]

      if (message.from.emoji_status) {
        name += ' 🤡'

        nameEntities.push({
          type: 'custom_emoji',
          offset: name.length - 2,
          length: 2,
          custom_emoji_id: message.from.emoji_status
        })
      }

      nameCanvas = await this.drawMultilineText(
        name,
        nameEntities,
        nameSize,
        nameColor,
        0,
        nameSize,
        width,
        nameSize,
        emojiBrand
      )
    }

    let fontSize = 24 * scale

    let textColor = '#fff'
    if (backStyle === 'light') textColor = '#000'

    let textCanvas
    if (message.text) {
      textCanvas = await this.drawMultilineText(
        message.text,
        message.entities,
        fontSize,
        textColor,
        0,
        fontSize,
        width,
        height - fontSize,
        emojiBrand
      )
    }

    let avatarCanvas
    if (message.avatar) avatarCanvas = await this.drawAvatar(message.from)

    let replyName, replyNameColor, replyText
    if (message.replyMessage && message.replyMessage.name && message.replyMessage.text) {
      const replyNameIndex = Math.abs(message.replyMessage.chatId) % 7
      replyNameColor = nameColorArray[replyNameIndex]

      const replyNameFontSize = 16 * scale
      if (message.replyMessage.name) {
        replyName = await this.drawMultilineText(
          message.replyMessage.name,
          'bold',
          replyNameFontSize,
          replyNameColor,
          0,
          replyNameFontSize,
          width * 0.9,
          replyNameFontSize,
          emojiBrand
        )
      }

      let textColor = '#fff'
      if (backStyle === 'light') textColor = '#000'

      const replyTextFontSize = 21 * scale
      replyText = await this.drawMultilineText(
        message.replyMessage.text,
        message.replyMessage.entities,
        replyTextFontSize,
        textColor,
        0,
        replyTextFontSize,
        width * 0.9,
        replyTextFontSize,
        emojiBrand
      )
    }

    let mediaCanvas, mediaType, maxMediaSize
    if (message.media) {
      let media, type

      let crop = false
      if (message.mediaCrop) crop = true

      if (message.media.url) {
        type = 'url'
        media = message.media.url
      } else {
        type = 'id'
        if (message.media.length > 1) {
          if (crop) media = message.media[1]
          else media = message.media.pop()
        } else media = message.media[0]
      }

      maxMediaSize = width / 3 * scale
      if (message.text && maxMediaSize < textCanvas.width) maxMediaSize = textCanvas.width

      if (media.is_animated) {
        media = media.thumb
        maxMediaSize = maxMediaSize / 2
      }

      mediaCanvas = await this.downloadMediaImage(media, maxMediaSize, type, crop)
      mediaType = message.mediaType
    }

    if (message.voice) {
      mediaCanvas = this.drawWaveform(message.voice.waveform)
      maxMediaSize = width / 3 * scale
    }

    const quote = this.drawQuote(
      scale,
      backgroundColorOne, backgroundColorTwo,
      avatarCanvas,
      replyName, replyNameColor, replyText,
      nameCanvas, textCanvas,
      mediaCanvas, mediaType, maxMediaSize
    )

    return quote
  }
}

module.exports = QuoteGenerate