Skip to content

Commit

Permalink
add compression
Browse files Browse the repository at this point in the history
  • Loading branch information
xiao-e-yun committed Sep 25, 2021
1 parent e7a188d commit 29150fb
Show file tree
Hide file tree
Showing 13 changed files with 474 additions and 39 deletions.
2 changes: 1 addition & 1 deletion server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import main from './main'
process.exit()
}, 5000)

wss.on('connection', ws => {
wss.on('connection',async ws => {
connection_count++
if (connection_count > 1) return ws.close() // 忽略連線
if (timeout) clearTimeout(timeout)
Expand Down
61 changes: 42 additions & 19 deletions server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,11 @@ import { exec } from "child_process"

// 監聽並回傳
export default function (ws: _ws) {
ws.on("build", async ($data) => {
console.log("清空output")
const output = {
path: path("output"),
files: [] as string[],
wait: [] as Promise<void>[],
}
output.wait.push(
fs.readdir(output.path)
.then((files) => {
for (const file of files) { output.wait.push(fs.unlink(path("output", file))) }
})
.catch(() => {
output.wait.push(fs.mkdir(output.path))
})
)
ws.on("upload_config", async ($data) => config($data.data))
ws.on("config", async () => { return config() })

ws.on("build", async ($data) => {
const wait_clear = clear_output()

console.log("設置構建")
const data = $data.data
Expand All @@ -41,6 +29,10 @@ export default function (ws: _ws) {
return img
}).catch(() => {
console.warn("下載圖片失敗")
ws.send("logger", {
title: "下載圖片失敗",
content: "請檢查網址是否正確",
})
return false
})
})
Expand Down Expand Up @@ -76,7 +68,7 @@ export default function (ws: _ws) {
}

console.log("構建選項:", data.option)
await Promise.all(output.wait) //等待 output 刪除檔案
await wait_clear //等待 output 刪除檔案
await worker("build", data.option, data.imgs.map(img => { return { name: img.name, base64img: img.data, } }))

console.log("構建完成")
Expand All @@ -85,6 +77,37 @@ export default function (ws: _ws) {
return true
})

ws.on("upload_config", async ($data) => config($data.data))
ws.on("config", async () => { return config() })
ws.on("compression", async ($data) => {
const wait_clear = clear_output()
const data = $data.data


console.log("壓縮選項:", data.option)
await wait_clear //等待 output 刪除檔案
await worker("compression", data.option, data.imgs)

console.log("壓縮完成")
exec(`start explorer "${path("output")}"`)

return true
})
}

function clear_output() {
console.log("清空output")
const output = {
path: path("output"),
files: [] as string[],
wait: [] as Promise<void>[],
}
output.wait.push(
fs.readdir(output.path)
.then((files) => {
for (const file of files) { output.wait.push(fs.unlink(path("output", file))) }
})
.catch(() => {
output.wait.push(fs.mkdir(output.path))
})
)
return Promise.all(output.wait)
}
42 changes: 37 additions & 5 deletions server/threads.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { workerData } from 'worker_threads'
import { WorkerDataType } from 'VS/protocol'
import { path } from './utils'
import { hash, path } from './utils'
import { extname, basename } from "path"
import Jimp from 'jimp'
import { exec as $exec } from 'child_process'

// 多線程運算
(async()=>{
const $type = workerData.type as keyof WorkerDataType
const { option:$option, data:$data } = workerData.data as WorkerDataType[typeof $type]
(async($type:keyof WorkerDataType)=>{
const worker_data = workerData.data as unknown
switch ($type) {
case "build":{
const { option:$option, data:$data } = worker_data as WorkerDataType[typeof $type]
for (const data of $data) {
let img = await decode_image(data.base64img).catch(e=>{throw e})
img.resize($option.size,Jimp.AUTO)
Expand Down Expand Up @@ -39,8 +40,39 @@ import Jimp from 'jimp'
}
break;
}
case "compression":{
const { option:$option, data:$data } = worker_data as WorkerDataType["compression"]
const pngquant = path("lib","pngquant.exe")
for (const data of $data) {
const tmp = path("tmp","compression$" + data.name)
const out = path("output",data.name )

const img = await decode_image(data.data).catch(e=>{throw e})
if(img.getMIME() === Jimp.MIME_JPEG){
await img.quality($option.quality[1]).writeAsync(out)
}else{
await img.writeAsync(tmp)
await exec(tmp,out)
}
}

function exec(tmp_path:string,output_path:string):Promise<void> {
const quality = $option.quality[0] + "-" + $option.quality[1]
const speed = $option.speed
return new Promise(resolve=>{
const cmd = `\"${pngquant}\" --quality ${quality} --speed ${speed} - < \"${tmp_path}\" > \"${output_path}\"`
console.log(cmd)
$exec(cmd,{ encoding: 'utf8' },
(e,s,stderr)=>{
if(e) console.error(e,stderr)
resolve()
})
})
}
break;
}
}
})()
})(workerData.type)



Expand Down
4 changes: 3 additions & 1 deletion server/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,6 @@ async function worker<T extends keyof WorkerDataType>
return Promise.all(worker_threads)
}

export { config, path, worker }
function hash(){ let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 12; i++)result += characters.charAt(Math.floor(Math.random() * 62)); return result }

export { config, path, worker, hash }
4 changes: 2 additions & 2 deletions server/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { hash as $hash } from "./utils"
import { DataType } from "VS/protocol"
import SocketServer = require('ws')

Expand Down Expand Up @@ -63,7 +64,7 @@ export default class {

get<T extends keyof DataType>(key: T, data: DataType[T]["req"]): Promise<WebSocketEvent<T>["receiver"]>
async get(key: string, data: any) {
const hash = this._hash()
const hash = $hash()
const req = JSON.stringify({ key: key, data: data, type: "get", hash } as WebSocketEvent["sender"])
this.ws.send(req)
return new Promise((resolve, reject) => this._sync_list[hash] = resolve)
Expand All @@ -73,7 +74,6 @@ export default class {
event: { [key: string]: (enevt: WebSocketEvent["sender"]) => any } = {}
private _info = "|websocket|"
private _sync_list: { [hash: string]: (req: WebSocketEvent["receiver"]) => void } = {}
private _hash() { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 12; i++)result += characters.charAt(Math.floor(Math.random() * 62)); return result }
}

interface WebSocketEvent<T extends keyof DataType = keyof DataType> {
Expand Down
33 changes: 31 additions & 2 deletions types/protocol/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ export interface DataType
req : {
option:DataType["build"]["option"],
imgs:{
name: string,
data: string,
name: string, // 圖片名稱
data: string, // 圖片base64
}[]
},
option:{
Expand All @@ -20,6 +20,21 @@ export interface DataType
},
resolve:boolean,
},
compression:{
req : {
option:DataType["compression"]["option"],
imgs:{
name: string, // 圖片名稱
data: string, // 圖片base64
}[]
},
option:{
quality:[number,number],
speed:number
},
resolve:boolean,
},
//
config:{
req:undefined,
resolve:config
Expand All @@ -32,6 +47,13 @@ export interface DataType
}[]
resolve:void
}
logger:{
req:{
title: string;
content: string;
},
resolve:void
}
}

export interface WorkerDataType
Expand All @@ -43,4 +65,11 @@ export interface WorkerDataType
base64img: string;
}[]
}
compression:{
option:DataType["compression"]["option"],
data:{
name: string;
data: string;
}[]
}
}
5 changes: 5 additions & 0 deletions view/src/components/logger.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export default defineComponent({
logger: toRef(useStore().state, "logger"),
};
},
created() {
this.$ws.on("logger", (log) => {
this.logger.push(log.data);
});
},
});
</script>

Expand Down
9 changes: 7 additions & 2 deletions view/src/components/view_files.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@

<script lang="ts">
import { defineComponent } from "vue";
const preview_length = localStorage.getItem("preview_length");
const preview_length = localStorage.getItem(
"steam_design_tools$preview_length"
);
export default defineComponent({
props: {
Expand Down Expand Up @@ -76,7 +78,10 @@ export default defineComponent({
watch: {
preview_size: {
handler(val) {
localStorage.setItem("preview_length", val.toString());
localStorage.setItem(
"steam_design_tools$preview_length",
val.toString()
);
},
immediate: true,
},
Expand Down
3 changes: 0 additions & 3 deletions view/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ addEventListener("resize", () => window.resizeTo(1200, 600));
window.resizeTo(1200, 600);

const ws = (window.ws = new _ws());

console.log("啟動GUI");
const app = createApp(App);

const app_prop = app.config.globalProperties;
app_prop.$ws = ws;

Expand Down
5 changes: 5 additions & 0 deletions view/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ const routes: Array<RouteRecordRaw> = [
name: "首頁",
component: Home,
},
{
path: "/compression",
name: "壓縮",
component: import_vue("compression"),
},
//
{
path: "/settings",
Expand Down
Loading

0 comments on commit 29150fb

Please sign in to comment.