2020-09-02 18:30:23 +00:00
import { tmpdir } from 'os' ;
import * as fs from 'fs' ;
const StreamZip = require ( 'node-stream-zip' ) ;
2020-09-02 16:03:49 +00:00
import { returnStatic } from './lib/util' ;
2020-09-02 18:30:23 +00:00
import { parseSM } from './lib/smparse' ;
import { File } from './schema' ;
2020-09-02 16:03:49 +00:00
export function run ( app ) {
2020-09-02 18:30:23 +00:00
const logger = app . get ( 'logger' ) ;
2020-09-02 16:03:49 +00:00
app . get ( '/upload' , returnStatic ( 'upload.html' ) ) ;
app . post ( '/upload' , async ( req , res ) = > { // only for testing, very abusable
2020-09-02 18:30:23 +00:00
const file = req . files . file ;
if ( file . mimetype !== 'application/zip' ) return res . status ( 400 ) . send ( 'Invalid filetype' ) ;
const dir = tmpdir ( ) + '/' + file . md5 ;
fs . writeFile ( dir , file . data , ( err ) = > {
if ( err ) throw err ;
const zip = new StreamZip ( {
file : dir ,
storeEntries : true
} ) ;
zip . on ( 'ready' , ( ) = > {
const smFile = Object . values ( zip . entries ( ) ) . find ( ( f : any ) = >
! f . isDirectory && ( f . name . endsWith ( '.sm' ) )
) ;
if ( ! smFile ) {
res . status ( 400 ) . send ( 'No .sm found' ) ;
} else {
const data = zip . entryDataSync ( ( smFile as any ) . name ) ;
const chart = parseSM ( data . toString ( ) ) ;
logger . info ( ` ${ chart . artist } - ${ chart . title } was just uploaded ` ) ;
const file = new File ( chart ) ;
file . save ( ) ;
res . send ( ` your file " ${ chart . artist } - ${ chart . title } " has been uploaded! check <a href="http://0.0.0.0:8080/list">the listing</a> ` ) ; // todo: change to actual url
}
zip . close ( ) ;
fs . unlink ( dir , ( err ) = > {
if ( err ) throw err ;
} ) ;
} ) ;
} ) ;
2020-09-02 16:03:49 +00:00
} ) ;
}