1
1
/* eslint-disable no-await-in-loop */
2
2
import path from 'path' ;
3
+ import chardet from 'chardet' ;
4
+ import * as iconv from 'iconv-lite' ;
3
5
import { PDFDocument } from 'pdf-lib' ;
4
6
import superagent from 'superagent' ;
5
7
import { config , saveConfig } from '../config' ;
@@ -35,12 +37,19 @@ const mergePDFs = async (files: string[], output: string) => {
35
37
return fs . writeFileSync ( output , await pdf . save ( ) ) ;
36
38
} ;
37
39
38
- export async function ConvertCodeToPDF ( code , lang , filename , team , location , codeColor = false ) {
40
+ function toUtf8 ( code : Buffer ) {
41
+ const info = chardet . detect ( code ) ;
42
+ logger . debug ( `detected as ${ info } ` ) ;
43
+ if ( ! info ) return code . toString ( 'utf8' ) ;
44
+ return iconv . decode ( code , info ) . toString ( ) ;
45
+ }
46
+
47
+ export async function ConvertCodeToPDF ( code : Buffer , lang , filename , team , location , codeColor = false ) {
39
48
compiler ||= await createTypstCompiler ( ) ;
40
49
const fakeFilename = String . random ( 8 ) ; // cubercsl: do not trust filename from user
41
50
const typst = generateTypst ( team , location , fakeFilename , filename , lang , codeColor ) ;
42
51
compiler . addSource ( '/main.typst' , typst ) ;
43
- compiler . addSource ( `/${ fakeFilename } ` , code ) ;
52
+ compiler . addSource ( `/${ fakeFilename } ` , toUtf8 ( code ) ) ;
44
53
const docs = await compiler . compile ( {
45
54
format : 'pdf' ,
46
55
mainFilePath : '/main.typst' ,
@@ -58,7 +67,14 @@ export async function printFile(docs) {
58
67
const {
59
68
_id, tid, code, lang, filename, team, location,
60
69
} = doc ;
61
- const pdf = await ConvertCodeToPDF ( code || 'empty file' , lang , filename , team , location , config . printColor ) ;
70
+ const pdf = await ConvertCodeToPDF (
71
+ code ? Buffer . from ( code , 'base64' ) : Buffer . from ( 'empty file' ) ,
72
+ lang ,
73
+ filename ,
74
+ team ,
75
+ location ,
76
+ config . printColor ,
77
+ ) ;
62
78
fs . writeFileSync ( path . resolve ( process . cwd ( ) , `data${ path . sep } ${ tid } #${ _id } .pdf` ) , pdf ) ;
63
79
files . push ( path . resolve ( process . cwd ( ) , `data${ path . sep } ${ tid } #${ _id } .pdf` ) ) ;
64
80
}
0 commit comments