overhaul of image displaying at '/' (unfinished)

Co-authored-by: Avior <github@avior.me>
This commit is contained in:
2023-02-21 17:31:31 +01:00
parent 5cbd1a0d9d
commit ed9194ff9e
148 changed files with 2967 additions and 203 deletions

View File

@ -1,153 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const promises_1 = __importDefault(require("fs/promises"));
const jimp_1 = __importDefault(require("jimp"));
const crypto_1 = __importDefault(require("crypto"));
const app = (0, express_1.default)();
app.use('/assets', express_1.default.static('images'));
/* eslint-disable max-depth */
/* eslint-disable complexity */
app.listen(3000, () => {
console.log('The application is listening on port 3000!');
});
/**
*
*
* @param path the folder to search
*
* @return the list of files included in this folder/subfolders
*/
function filesList(Path) {
var _a, e_1, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const files = [];
const subFolders = yield promises_1.default.readdir(Path);
try {
for (var _d = true, subFolders_1 = __asyncValues(subFolders), subFolders_1_1; subFolders_1_1 = yield subFolders_1.next(), _a = subFolders_1_1.done, !_a;) {
_c = subFolders_1_1.value;
_d = false;
try {
const subFolder = _c;
const stats = yield promises_1.default.stat(Path + '/' + subFolder);
if (stats.isDirectory()) {
files.push(...yield filesList(Path + '/' + subFolder));
}
else {
files.push(Path + '/' + subFolder);
}
}
finally {
_d = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = subFolders_1.return)) yield _b.call(subFolders_1);
}
finally { if (e_1) throw e_1.error; }
}
return files;
});
}
app.get('/program', (_req, res) => {
((dirPath) => __awaiter(void 0, void 0, void 0, function* () {
var _a, e_2, _b, _c;
const files = yield filesList(dirPath);
console.log(files);
// Filtre
const data = (yield promises_1.default.readFile('./output.json')).toString('utf8');
let json = {};
try {
json = JSON.parse(data);
}
catch (_d) {
console.log('handeling...');
}
try {
for (var _e = true, files_1 = __asyncValues(files), files_1_1; files_1_1 = yield files_1.next(), _a = files_1_1.done, !_a;) {
_c = files_1_1.value;
_e = false;
try {
const file = _c;
const bFile = path_1.default.basename(file);
const pName = path_1.default.dirname(file);
const hash = crypto_1.default.createHash('sha256');
hash.setEncoding('hex');
const readI = yield promises_1.default.readFile(`${file}`);
hash.write(readI);
hash.end();
const sha256sum = hash.read();
console.log('bfile = ' + bFile);
if (bFile.startsWith('.')) {
continue;
}
else if (json[file] === sha256sum) {
console.log('This picture has already been turned to sepia');
continue;
}
// Modification des données
json[file] = sha256sum;
// Ré-écriture dans le fichier output
yield promises_1.default.writeFile('output.json', JSON.stringify(json));
try {
const image = yield jimp_1.default.read(readI);
image.sepia();
console.log(bFile);
const newFileName = pName + '/.' + bFile;
console.log('newfilename:' + newFileName);
// save image with new file name
yield image.writeAsync(`${newFileName}`);
console.log('Images have been inverted and rename ' + '.' + file);
}
catch (err) {
console.log('this file is not an image');
}
}
finally {
_e = true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_e && !_a && (_b = files_1.return)) yield _b.call(files_1);
}
finally { if (e_2) throw e_2.error; }
}
res.send('Pictures transformed');
res.end();
}))('./images');
});
{
app.get('/', (_req, res) => __awaiter(void 0, void 0, void 0, function* () {
const list = yield filesList('./content');
const item = list[Math.floor(Math.random() * ((list)).length)];
const itemB = yield promises_1.default.readFile(item);
res.send(itemB);
console.log(item);
}));
}

View File

@ -5,6 +5,7 @@ import Jimp from 'jimp'
import crypto from 'crypto'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { readdirSync } from 'fs'
const app = express()
app.use('/test',express.static('css'))
@ -44,8 +45,6 @@ app.get('/program', (_req, res) => {
(async (dirPath: string) => {
const files = await filesList(dirPath)
console.log(files)
// Filtre
const data = (await fs.readFile('./output.json')).toString('utf8')
let json: Record<string, string> = {}
@ -65,7 +64,6 @@ app.get('/program', (_req, res) => {
hash.write(readI)
hash.end()
const sha256sum = hash.read()
// console.log('bfile = ' + bFile)
if (bFile.startsWith('.')) {
continue
@ -89,7 +87,6 @@ app.get('/program', (_req, res) => {
const newBaseName = bFile.slice(0, index) + '.png'
const newFileName = pName + '/.' + newBaseName
await image.writeAsync(`${newFileName}`)
// console.log('Images have been turned to sepia and renamed ' + newFileName)
}catch (err){
console.log('this file is not an image')
}
@ -99,41 +96,74 @@ app.get('/program', (_req, res) => {
})('./assets')
})
async function filter() {
const list = await filesList('./assets') // si moins de 6 element dans la liste ....
const listF: Array<string> = []
for(const file of list){
const bName = path.basename(file)
if(bName.startsWith('.')){
listF.push(file)
}
const listStart = readdirSync('./assets') // si moins de 6 element dans la liste ....
const listFinal: Array<Array<string>> = []
for(const files of listStart)
{
const listPerso = await filesList('./assets/' + files)
listFinal.push(listPerso)
}
return listF
const filteredList = listFinal.map((innerList) => innerList.filter((element) =>
path.basename(element).startsWith('.')))
// (a,b) => (a > b ? -1 : 1)
console.log(filteredList)
const listBS = filteredList.map((innerList) => innerList.reverse())
// console.log(listBS)
return listBS
}
function randomSort() {
return Math.random() - 0.5
}
async function randomI(): Promise<[] | [string, string, string, string, string, string]> {
const filteredList = await filter()
const sorted = filteredList.sort(randomSort).slice(0, 6)
while (sorted.length < 6 && sorted.length > 0 ) {
const listLength = sorted.length
sorted.push(...filteredList.sort(randomSort).slice(0, 6 - listLength))
}
return sorted as []
}
app.get('/code', async (_, res) => {
const data = await randomI()
// function randomSort() {
// return Math.random() - 0.5
// }
// async function randomI(): Promise<[] | [string, string, string, string, string, string]> {
// const filteredList = await filter()
// const sorted = filteredList.sort(randomSort).slice(0, 6)
// while (sorted.length < 6 && sorted.length > 0 ) {
// const listLength = sorted.length
// sorted.push(...filteredList.sort(randomSort).slice(0, 6 - listLength))
// }
// return sorted as []
// }
app.get('/code', async (_, res) => { // envoie a /code list de list des anims par perso (en théorie )
const data = await filter()
// const baseI = await base()
const lenght = data.length
// return json data
if (data.length !== 0){
res.json(data[0])
if (lenght !== 0){
res.json(data)
}
})
// function randomIntFromInterval(min: number, max: number) {
// return Math.floor(Math.random() * (max - min + 1) + min)
// }
async function base() {
const listA = readdirSync('./assets') // si moins de 6 element dans la liste ....
const listB: Array<Array<string>> = []
const listC: Array<string> = []
for(const perso of listA){
const listPerso = await filesList('./assets/' + perso)
for(const image of listPerso){
const bName = path.basename(image)
if(bName.startsWith('.base')){
listC.push(image)
}
}
}
listB.push(listC)
// console.log(listB)
return listB
}
app.get('/', async (_, res) => {
const list = await randomI()
const list = await base()
if(list.length === 0 ){
const board =
<>
@ -150,35 +180,66 @@ app.get('/', async (_, res) => {
<link rel="stylesheet" href='/test/index.css' type="text/css" />
<div className="board">
<div className='row11' >
<img id='img1' src={list[0]} width={620} />
<script dangerouslySetInnerHTML={{__html:`
setInterval(() => {
fetch('http://localhost:3000/code')
.then(function(response) {
return response.json();
})
.then(function(data) {
let imgElement = document.getElementById('img1');
imgElement.src = data;
});
}, 5000);
`}}></script>
<img id='0' src={list[0][0]} width={620} />
</div>
<div className='row12'>
<img src={list[1]} width={620} />
<img id='1' src={list[0][1]} width={620} />
</div>
<div className='row13'>
<img src={list[2]} width={620} />
<img id='2' src={list[0][2]} width={620} />
</div>
<div className="row21">
<img src={list[3]} width={620} />
<img id='3' src={list[0][3]} width={620} />
</div>
<div className='row22'>
<img src={list[4]} width={620} />
<img id='4' src={list[0][4]} width={620} />
</div>
<div className='row23'>
<img src={list[5]} width={620} />
<img id='5' src={list[0][5]} width={620} />
</div>
{<script dangerouslySetInnerHTML={{__html:`
let intervalIds = [];
function runIntervals() {
setInterval(function() {
intervalIds.forEach(clearInterval);
intervalIds = [];
let min = 0;
let n = 1;
let max = 5;
let perso = Math.floor(Math.random() * (max - min + 1) + min);
let imgElement = document.getElementById(perso);
// let base = base[perso]
// console.log(base)
if (imgElement){
intervalIds.push(setInterval(function() {
fetch('http://localhost:3000/code')
.then(function(response) {
return response.json();
})
.then(function(data) {
// let min = 1;
// let max = 5;
let anim = n++;
let imgElement = document.getElementById(perso);
imgElement.src = (data[perso][n]);
if(imgElement.src === undefined){
imgElement.src = data[perso][0];
}
setTimeout(function() {
imgElement.src = data[perso][0];
}, 4000);
});
}, 1000));
}
}, 5000);
}
function stopIntervals() {
intervalIds.forEach(clearInterval);
intervalIds = [];
}
runIntervals();
`}}></script> }
</div>
</>
))
@ -186,6 +247,8 @@ app.get('/', async (_, res) => {
})
// img de 1 a 6
// animer les images par rappoirt a un format de fichier, (base.ext) -> (anim1, anim2, ...animX)
/*