on page / : grid of 6 random images

Co-authored-by: Avior <github@avior.me>
This commit is contained in:
2023-02-14 11:51:16 +01:00
parent 4b7f0b4e3c
commit abf3f90f56
20 changed files with 775 additions and 245 deletions

153
src/index.js Normal file
View File

@ -0,0 +1,153 @@
"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

@ -1,107 +0,0 @@
import express from 'express';
import path from 'path'
import fs from 'fs/promises'
import Jimp from 'jimp'
import crypto from 'crypto'
const app = express()
app.use('/assets',express.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
*/
async function filesList(Path: string): Promise<string[]> {
const files: Array<string> = []
const subFolders = await fs.readdir(Path)
for await (const subFolder of subFolders){
const stats = await fs.stat(Path + '/' + subFolder)
if (stats.isDirectory()) {
files.push(...await filesList(Path + '/' + subFolder))
} else {
files.push(Path + '/' + subFolder)
}
}
return files
}
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> = {}
try{
json = JSON.parse(data)
}catch{
console.log('handeling...')
}
for await (const file of files) {
const bFile = path.basename(file)
const pName = path.dirname(file)
const hash = crypto.createHash('sha256')
hash.setEncoding('hex')
const readI = await fs.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
await fs.writeFile('output.json', JSON.stringify(json))
try{
const image = await Jimp.read(readI)
image.sepia()
console.log(bFile)
const newFileName = pName + '/.' + bFile
console.log('newfilename:' + newFileName)
// save image with new file name
await image.writeAsync(`${newFileName}`)
console.log('Images have been inverted and rename ' + '.' + file)
}catch (err){
console.log('this file is not an image')
}
}
res.send('Pictures transformed')
res.end()
})('./images')
})
{
app.get('/', async (_req, res) => {
const list = await filesList('./content')
const item = list[Math.floor(Math.random()*((list)).length)]
const itemB =await fs.readFile(item)
res.send(itemB)
console.log(item)
})
}

181
src/index.tsx Normal file
View File

@ -0,0 +1,181 @@
import express from 'express'
import path from 'path'
import fs from 'fs/promises'
import Jimp from 'jimp'
import crypto from 'crypto'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
const app = express()
app.use('/assets',express.static('assets'))
/* 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
*/
async function filesList(Path: string): Promise<Array<string>> {
const files: Array<string> = []
const subFolders = await fs.readdir(Path)
for await (const subFolder of subFolders){
const stats = await fs.stat(Path + '/' + subFolder)
if (stats.isDirectory()) {
files.push(...await filesList(Path + '/' + subFolder))
} else {
files.push(Path + '/' + subFolder)
}
}
return files
}
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> = {}
try{
json = JSON.parse(data)
}catch{
console.log('handeling...')
}
for await (const file of files) {
const bFile = path.basename(file)
const pName = path.dirname(file)
const hash = crypto.createHash('sha256')
hash.setEncoding('hex')
const readI = await fs.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
await fs.writeFile('output.json', JSON.stringify(json))
try{
const image = await Jimp.read(readI)
image.sepia()
console.log(bFile)
const newFileName = pName + '/S' + bFile
console.log('newfilename:' + newFileName)
// save image with new file name
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')
}
}
res.send('Pictures transformed')
res.end()
})('./assets')
})
function randomSort() {
return Math.random() - 0.5
}
async function randomI(): Promise<[] | [string, string, string, string, string, string]> {
const list = await filesList('./assets') // si moins de 6 element dans la liste ....
const sorted = list.sort(randomSort).slice(0, 6)
while (sorted.length < 6 && sorted.length > 0 ) {
const listLength = sorted.length
sorted.push(...list.sort(randomSort).slice(0, 6 - listLength))
}
return sorted as []
}
app.get('/test', async (_req, res) => {
res.send(randomI())
})
app.get('/', async (_req, res) => {
const list = await randomI()
if(list.length === 0 ){
const board =
<><style>{`
.string{
color: red;}
`}</style>
<div className='string'>
Il n'y a pas d'image dans le fichier
</div></>
const rendering = ReactDOMServer.renderToString(board)
res.send(rendering)
}else{
res.send(ReactDOMServer.renderToString(
<><style>{`
.board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
grid-auto-rows: minmax(100px, auto);
.row11 {
grid-column : 1
grid-row : 1
}
.row12 {
grid-column: 2
grid-row: 1
}
.row13 {
grid-column : 3
grid-row : 1
}
.row21 {
grid-column : 1
grid-row : 2
}
.row22 {
grid-column : 2
grid-row : 2
}
.row23 {
grid-column : 3
grid-row : 2
}
}`}</style>
<div className="board">
<div className='row11'>
<img src={list[0]} width={620} />
</div>
<div className='row12'>
<img src={list[1]} width={620} />
</div>
<div className='row13'>
<img src={list[2]} width={620} />
</div>
<div className="row21">
<img src={list[3]} width={620} />
</div>
<div className='row22'>
<img src={list[4]} width={620} />
</div>
<div className='row23'>
<img src={list[5]} width={620} />
</div>
</div></>
))
}
})