mirror of
1
2
Fork 0

Merge CJS Stuff need to write Readme about ESM stuff

This commit is contained in:
Frank Lemanschik 2020-03-16 09:11:27 +01:00
commit 546aca1aa7
24 changed files with 285 additions and 393 deletions

2
.gitignore vendored
View File

@ -2,4 +2,4 @@ node_modules
dist
.env
*.tsbuildinfo
public/images
public/images

229
package-lock.json generated
View File

@ -364,16 +364,6 @@
"resolve": "^1.14.2"
}
},
"@rollup/plugin-typescript": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-4.0.0.tgz",
"integrity": "sha512-qA3r4WlR8JnTm+VdBzvQSIkfXt802keGxXuE4SAjUjRMKK3nMXTUCvOGSzFkav2qf0QiGv6yijfbjuf+bhwmZQ==",
"dev": true,
"requires": {
"@rollup/pluginutils": "^3.0.1",
"resolve": "^1.14.1"
}
},
"@rollup/pluginutils": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.0.8.tgz",
@ -383,138 +373,24 @@
"estree-walker": "^1.0.1"
}
},
"@types/body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.0.tgz",
"integrity": "sha512-W98JrE0j2K78swW4ukqMleo8R7h/pFETjM2DQ90MF6XK2i4LO4W3gQ71Lt4w3bfm2EvVSyWHplECvB5sK22yFQ==",
"dev": true,
"requires": {
"@types/connect": "*",
"@types/node": "*"
}
},
"@types/caseless": {
"version": "0.12.2",
"resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.2.tgz",
"integrity": "sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==",
"dev": true
},
"@types/color-name": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz",
"integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==",
"dev": true
},
"@types/connect": {
"version": "3.4.33",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.33.tgz",
"integrity": "sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A==",
"dev": true,
"requires": {
"@types/node": "*"
}
},
"@types/cookie-parser": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@types/cookie-parser/-/cookie-parser-1.4.2.tgz",
"integrity": "sha512-uwcY8m6SDQqciHsqcKDGbo10GdasYsPCYkH3hVegj9qAah6pX5HivOnOuI3WYmyQMnOATV39zv/Ybs0bC/6iVg==",
"dev": true,
"requires": {
"@types/express": "*"
}
},
"@types/cron": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/@types/cron/-/cron-1.7.2.tgz",
"integrity": "sha512-AEpNLRcsVSc5AdseJKNHpz0d4e8+ow+abTaC0fKDbAU86rF1evoFF0oC2fV9FdqtfVXkG2LKshpLTJCFOpyvTg==",
"dev": true,
"requires": {
"@types/node": "*",
"moment": ">=2.14.0"
}
},
"@types/eslint-visitor-keys": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz",
"integrity": "sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==",
"dev": true
},
"@types/estree": {
"version": "0.0.39",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz",
"integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==",
"dev": true
},
"@types/express": {
"version": "4.17.3",
"resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.3.tgz",
"integrity": "sha512-I8cGRJj3pyOLs/HndoP+25vOqhqWkAZsWMEmq1qXy/b/M3ppufecUwaK2/TVDVxcV61/iSdhykUjQQ2DLSrTdg==",
"dev": true,
"requires": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "*",
"@types/serve-static": "*"
}
},
"@types/express-serve-static-core": {
"version": "4.17.2",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.2.tgz",
"integrity": "sha512-El9yMpctM6tORDAiBwZVLMcxoTMcqqRO9dVyYcn7ycLWbvR8klrDn8CAOwRfZujZtWD7yS/mshTdz43jMOejbg==",
"dev": true,
"requires": {
"@types/node": "*",
"@types/range-parser": "*"
}
},
"@types/json-schema": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.4.tgz",
"integrity": "sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA==",
"dev": true
},
"@types/mime": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-2.0.1.tgz",
"integrity": "sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw==",
"dev": true
},
"@types/node": {
"version": "13.9.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-13.9.1.tgz",
"integrity": "sha512-E6M6N0blf/jiZx8Q3nb0vNaswQeEyn0XlupO+xN6DtJ6r6IT4nXrTry7zhIfYvFCl3/8Cu6WIysmUBKiqV0bqQ==",
"dev": true
},
"@types/range-parser": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.3.tgz",
"integrity": "sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA==",
"dev": true
},
"@types/request": {
"version": "2.48.4",
"resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.4.tgz",
"integrity": "sha512-W1t1MTKYR8PxICH+A4HgEIPuAC3sbljoEVfyZbeFJJDbr30guDspJri2XOaM2E+Un7ZjrihaDi7cf6fPa2tbgw==",
"dev": true,
"requires": {
"@types/caseless": "*",
"@types/node": "*",
"@types/tough-cookie": "*",
"form-data": "^2.5.0"
},
"dependencies": {
"form-data": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz",
"integrity": "sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==",
"dev": true,
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.6",
"mime-types": "^2.1.12"
}
}
}
},
"@types/resolve": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz",
@ -524,96 +400,6 @@
"@types/node": "*"
}
},
"@types/serve-static": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.3.tgz",
"integrity": "sha512-oprSwp094zOglVrXdlo/4bAHtKTAxX6VT8FOZlBKrmyLbNvE1zxZyJ6yikMVtHIvwP45+ZQGJn+FdXGKTozq0g==",
"dev": true,
"requires": {
"@types/express-serve-static-core": "*",
"@types/mime": "*"
}
},
"@types/tough-cookie": {
"version": "2.3.6",
"resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.6.tgz",
"integrity": "sha512-wHNBMnkoEBiRAd3s8KTKwIuO9biFtTf0LehITzBhSco+HQI0xkXZbLOD55SW3Aqw3oUkHstkm5SPv58yaAdFPQ==",
"dev": true
},
"@typescript-eslint/eslint-plugin": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.23.0.tgz",
"integrity": "sha512-8iA4FvRsz8qTjR0L/nK9RcRUN3QtIHQiOm69FzV7WS3SE+7P7DyGGwh3k4UNR2JBbk+Ej2Io+jLAaqKibNhmtw==",
"dev": true,
"requires": {
"@typescript-eslint/experimental-utils": "2.23.0",
"eslint-utils": "^1.4.3",
"functional-red-black-tree": "^1.0.1",
"regexpp": "^3.0.0",
"tsutils": "^3.17.1"
}
},
"@typescript-eslint/experimental-utils": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.23.0.tgz",
"integrity": "sha512-OswxY59RcXH3NNPmq+4Kis2CYZPurRU6mG5xPcn24CjFyfdVli5mySwZz/g/xDbJXgDsYqNGq7enV0IziWGXVQ==",
"dev": true,
"requires": {
"@types/json-schema": "^7.0.3",
"@typescript-eslint/typescript-estree": "2.23.0",
"eslint-scope": "^5.0.0"
}
},
"@typescript-eslint/parser": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.23.0.tgz",
"integrity": "sha512-k61pn/Nepk43qa1oLMiyqApC6x5eP5ddPz6VUYXCAuXxbmRLqkPYzkFRKl42ltxzB2luvejlVncrEpflgQoSUg==",
"dev": true,
"requires": {
"@types/eslint-visitor-keys": "^1.0.0",
"@typescript-eslint/experimental-utils": "2.23.0",
"@typescript-eslint/typescript-estree": "2.23.0",
"eslint-visitor-keys": "^1.1.0"
}
},
"@typescript-eslint/typescript-estree": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.23.0.tgz",
"integrity": "sha512-pmf7IlmvXdlEXvE/JWNNJpEvwBV59wtJqA8MLAxMKLXNKVRC3HZBXR/SlZLPWTCcwOSg9IM7GeRSV3SIerGVqw==",
"dev": true,
"requires": {
"debug": "^4.1.1",
"eslint-visitor-keys": "^1.1.0",
"glob": "^7.1.6",
"is-glob": "^4.0.1",
"lodash": "^4.17.15",
"semver": "^6.3.0",
"tsutils": "^3.17.1"
},
"dependencies": {
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"dev": true,
"requires": {
"ms": "^2.1.1"
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"dev": true
},
"semver": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
"integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
"dev": true
}
}
},
"abbrev": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
@ -2712,12 +2498,6 @@
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz",
"integrity": "sha512-ZS5w8CpKFinUzOwW3c83oPeVXoNsrLsaCoLtJvAClH135j/R77RuymhiSErhm2lKcwSCIpmvIWSbDkIfAqKQlA=="
},
"regexpp": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.0.0.tgz",
"integrity": "sha512-Z+hNr7RAVWxznLPuA7DIh8UNX1j9CDrUQxskw9IrBE1Dxue2lyXT+shqEIeLUjrokxIP8CMy1WkjgG3rTsd5/g==",
"dev": true
},
"registry-auth-token": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz",
@ -3203,15 +2983,6 @@
"integrity": "sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==",
"dev": true
},
"tsutils": {
"version": "3.17.1",
"resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.17.1.tgz",
"integrity": "sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==",
"dev": true,
"requires": {
"tslib": "^1.8.1"
}
},
"tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",

View File

@ -4,6 +4,7 @@
"description": "Server for uCaptcha",
"main": "src/server.js",
"scripts": {
"server": "nodemon src/server.js",
"dev": "NODE_ENV=development; rollup -c -w",
"build": "NODE_ENV=production; rollup -c",
"test": "echo \"Error: no test specified\" && exit 1"
@ -27,20 +28,11 @@
"devDependencies": {
"@rollup/plugin-commonjs": "^11.0.2",
"@rollup/plugin-node-resolve": "^7.1.1",
"@rollup/plugin-typescript": "^4.0.0",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-google": "^0.14.0",
"nodemon": "^2.0.2",
"rollup": "^2.0.6",
"rollup-plugin-terser": "^5.3.0",
"tslib": "^1.11.1",
"@types/cookie-parser": "^1.4.2",
"@types/cron": "^1.7.2",
"@types/express": "^4.17.3",
"@types/node": "^13.9.1",
"@types/request": "^2.48.4",
"nodemon": "^2.0.2",
"typescript": "^3.8.3"
}
}

View File

@ -1,5 +1,4 @@
import {terser} from "rollup-plugin-terser";
import typescript from "@rollup/plugin-typescript";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
@ -9,15 +8,14 @@ const typescriptOptions = {include: ["src/**/*", "../shared/**/*"]};
if (!isProd) typescriptOptions.noEmitOnError = false;
module.exports = {
input: "src/server.ts",
input: "src/client.js",
plugins: [
typescript(typescriptOptions),
commonjs({extensions: [".js", ".ts"]}),
resolve({extensions: [".js", ".ts"]}),
commonjs(),
resolve(),
isProd && terser()
],
output: {
file: "dist/bundle.js",
file: "dist/client/bundle.js",
name: "ucaptcha",
format: "iife"
}

View File

@ -1,25 +1,21 @@
module.exports = {
'env': {
'browser': true,
'es6': true,
"env": {
"browser": true,
"es6": true,
},
'extends': [
'google'
"extends": [
"google"
],
'globals': {
'Atomics': 'readonly',
'SharedArrayBuffer': 'readonly',
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
},
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 2018,
'sourceType': 'module',
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
},
'plugins': [
'@typescript-eslint'
],
'rules': {
"require-jsdoc": "off",
"plugins": [],
"rules": {
"quotes": ["error", "double"],
"comma-dangle": "off"
},

13
src/R.js Normal file
View File

@ -0,0 +1,13 @@
const path = require("path");
/**
* A path string relative to the project folder.
* @typedef {String} IMAGES_FOLDER
*/
const IMAGES_FOLDER = path.join(__dirname, "..", "public", "images");
module.exports = {
IMAGES_FOLDER
};

View File

@ -1,6 +0,0 @@
import path from "path";
/**
* A path string relativ to the project folder.
* @typedef {String} IMAGES_FOLDER
*/
export const IMAGES_FOLDER = path.join(__dirname, "..", "public", "images");

53
src/client.js Normal file
View File

@ -0,0 +1,53 @@
import UserSession from "./shared/models/UserSession.js";
/**
* Create a uCaptcha box
* @param {string} key Website key
* @return {HTMLElement} uCaptcha box
*/
function uCaptchaBox(key) {
const checkbox = createElement("div", {
style: "cursor:pointer;border-radius:3px;border:2px solid #888;width:25px;height:25px;display:inline-block"
});
checkbox.onclick = function() {
fetch(`https://localhost:444/api/init?k=${key}`)
.then((r)=>r.text())
.then((r)=>r.substr(2))
.then((r)=>JSON.parse(r))
.then((resp)=>{
const session = new UserSession();
session.deserialize(resp);
});
checkbox.setAttribute("style",
checkbox.getAttribute("style") + "background-color:royalblue;");
};
const captchaBox = createElement("div");
captchaBox.appendChild(checkbox);
return captchaBox;
}
/**
* Instantiate a uCaptcha box
* @param {string} websiteKey
* @param {string} selector
*/
export function create(websiteKey, selector) {
// const iframe = createElement("iframe");
// iframe.setAttribute("src", "https://localhost:444/?k="+websiteKey)
document.querySelector(selector).appendChild(uCaptchaBox(websiteKey));
}
/**
* Short hand for document.createElement
* @param {string} tagName Tag name
* @param {object} attributes A key-value pair of DOM attributes
* @return {HTMLElement}
*/
function createElement(tagName, attributes={}) {
const elem = document.createElement(tagName);
for(const [name, value] of Object.entries(attributes)) {
elem.setAttribute(name, value);
}
}

View File

@ -1,30 +0,0 @@
import createElement from "./shared/util/createElement";
import InitSession from "./shared/fun/initializeSession";
function uCaptchaBox(key: string) {
const checkbox = createElement("div");
checkbox.setAttribute("style", "cursor:pointer;border-radius:3px;border:2px solid #888;width:25px;height:25px;display:inline-block");
checkbox.onclick = function() {
fetch(`https://localhost:444/api/init?k=${key}`)
.then((r)=>r.text())
.then((r)=>r.substr(2))
.then((r)=>JSON.parse(r))
.then((resp)=>{
const session = new InitSession();
session.deserialize(resp);
});
checkbox.setAttribute("style",
checkbox.getAttribute("style") + "background-color:royalblue;");
};
const captchaBox = createElement("div");
captchaBox.appendChild(checkbox);
return captchaBox;
}
export function create(websiteKey: string, selector: string) {
// const iframe = createElement("iframe");
// iframe.setAttribute("src", "https://localhost:444/?k="+websiteKey)
document.querySelector(selector)!.appendChild(uCaptchaBox(websiteKey));
}

View File

@ -1,7 +1,10 @@
import {CronJob} from "cron";
import request from "request";
import path from "path";
import {IMAGES_FOLDER} from "../R.js";
const {CronJob} = require("cron");
const request = require("request");
const path = require("path");
const {IMAGES_FOLDER} = require("../R.js");
const {randomBytes} = require("./utils.js");
const Jimp = require("jimp");
/**
* @typedef {object} currentPageItem
@ -33,7 +36,7 @@ import {IMAGES_FOLDER} from "../R.js";
* @property {number} httpCode
* @property {string} httpMessage
*/
//* @param {import('../types/OSCResponse.js').status} status
// * @param {import('../types/OSCResponse.js').status} status
/**
* @typedef {object} OSCResponse
* @property {OSCResponse.status} status
@ -41,11 +44,8 @@ import {IMAGES_FOLDER} from "../R.js";
* @property {Array.<string>} totalFilteredItems
*/
import {randomBytes} from "./utils.js";
import Jimp from "jimp";
/**
* saves a image to disk
* Save an image to disk
* @param {string} filepath
* @param {string} uri
*/
@ -83,7 +83,7 @@ const geoImageRequestDefaults = {
* fetch and saves image from nearby photos
* @param {geoImageRequest} [geoImageRequest] - Optional set a geoImageReqest
*/
export function fetchImages(geoImageRequest) {
function fetchImages(geoImageRequest) {
console.log("Collecting images...");
const formData = {
...geoImageRequestDefaults,
@ -101,6 +101,12 @@ export function fetchImages(geoImageRequest) {
});
}
export const fetchImagesJob = new CronJob("0 0 0 * * *", () => {
const fetchImagesJob = new CronJob("0 0 0 * * *", () => {
fetchImages(geoImageRequestDefaults);
}, null, true);
module.exports = {
fetchImages,
fetchImagesJob
};

9
src/helpers/sendJson.js Normal file
View File

@ -0,0 +1,9 @@
/**
* @param {Response} res
* @param {object} json
*/
module.exports = function(res, json) {
res.setHeader("Content-Type", "application/json");
res.send(":)" + JSON.stringify(json));
return;
};

View File

@ -1,9 +1,14 @@
import crypto from "crypto";
const crypto = require("crypto");
const alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZabc" +
"defghijklmnopqrstuvwxyz0123456789";
export function randomBytes(length: number) {
/**
* Produce a string of n length consisting of alphanumeric characters
* @param {number} length
* @return {string} Alphanumeric string
*/
function randomBytes(length) {
const bytes = crypto.randomBytes(length);
const chars = [];
@ -13,3 +18,8 @@ export function randomBytes(length: number) {
return chars.join("");
}
module.exports = {
randomBytes
};

12
src/routes/api/index.js Normal file
View File

@ -0,0 +1,12 @@
const express = require("express");
const initializer = require("./initializeSession.js");
const sendJson = require("../../helpers/sendJson.js");
const router = new express.Router();
router.get("/init", async (req, res)=>{
const result = await initializer();
sendJson(res, result);
});
module.exports = router;

View File

@ -1,21 +0,0 @@
import express from "express";
import initializer from "./initializeSession.js";
import {randomBytes} from "../../helpers/utils.js";
import InitSession from "../../shared/fun/initializeSession.js";
const router = new express.Router();
router.get("/init", async (req, res)=>{
const randomSessionId = randomBytes(8);
const result = await initializer();
const initSession = new InitSession();
initSession.sessionId = randomSessionId;
initSession.imageUrl = result;
const payload = initSession.serialize();
res.setHeader("Content-Type", "application/json");
res.send(":)"+JSON.stringify(payload));
});
export default router;

View File

@ -0,0 +1,19 @@
const pickRandomFile = require("./pickRandomFile.js");
const UserSession = require("../../shared/models/UserSession.js");
const utils = require("../../helpers/utils.js");
/**
* @return {any}
*/
module.exports = async function() {
const randomSessionId = utils.randomBytes(8);
const imageFilepath = await pickRandomFile();
const initSession = new UserSession();
initSession.setSessionId(randomSessionId);
initSession.setImageUrl(imageFilepath);
const payload = initSession.serialize();
return payload;
};

View File

@ -1,7 +0,0 @@
import pickRandomFile from "./pickRandomFile.js";
export default async function() {
const image = await pickRandomFile();
return image;
}

View File

@ -0,0 +1,25 @@
const fs = require("fs");
const path = require("path");
const Jimp = require("jimp");
const {promisify} = require("util");
const {IMAGES_FOLDER} = require("../../R.js");
const readdirAsync = promisify(fs.readdir);
/**
* @return {string} Image file path
*/
module.exports = async function() {
const files = await readdirAsync(IMAGES_FOLDER);
return files[Math.floor(Math.random() * files.length)];
const randomFilePath = path.join(
IMAGES_FOLDER,
files[Math.floor(
Math.random() * files.length
)]
);
return randomFilePath;
};

View File

@ -1,25 +0,0 @@
import fs from "fs";
import path from "path";
import Jimp from "jimp";
import {promisify} from "util";
import {IMAGES_FOLDER} from "../../R.js";
const readdirAsync = promisify(fs.readdir);
export default async function() {
const files = await readdirAsync(IMAGES_FOLDER);
return files[Math.floor(Math.random() * files.length)];
const randomFilePath = path.join(
IMAGES_FOLDER,
files[Math.floor(
Math.random() * files.length
)]
);
const image = await Jimp.read(randomFilePath);
const base64 = await image.quality(20).getBase64Async(Jimp.MIME_JPEG);
// console.log(base64)
return base64;
}

View File

@ -1,24 +1,25 @@
require("dotenv").config();
import express from "express";
const express = require("express");
const app = express();
import cookieParser from "cookie-parser";
app.disable("x-powered-by");
const cookieParser = require("cookie-parser");
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(express.json({
limit: "128kb"
}));
import apis from "./routes/api/index.js";
const apis = require("./routes/api/index.js");
app.use("/api", apis);
import {fetchImagesJob, fetchImages} from "./helpers/fetchImagesJob";
import pickRandomFile from "./routes/api/pickRandomFile";
const {fetchImagesJob, fetchImages} = require("./helpers/fetchImagesJob.js");
app.listen(8080, ()=>{
fetchImagesJob.start();
// fetchImages({radius: 1000});
console.log("Server started")
console.log("=========================================================")
})
console.log("Server started");
console.log("=========================================================");
});

View File

@ -3,7 +3,10 @@ const Indexes = {
imageUrl: 1
};
export default class InitSession {
module.exports = class Session {
/**
* User session model
*/
constructor() {
/** @type {string | undefined} */
this._sessionId;
@ -50,7 +53,7 @@ export default class InitSession {
*/
serialize() {
if (!this._sessionId || !this._imageUrl) {
throw Error("Unable to serialize because missing field(s)");
throw Error("Unable to serialize because of missing field(s)");
}
const payload = [];
payload[Indexes.clientId] = this._sessionId;
@ -67,4 +70,4 @@ export default class InitSession {
this.setSessionId(payload[Indexes.clientId]);
this.setImageUrl(payload[Indexes.imageUrl]);
}
}
};

View File

@ -0,0 +1,78 @@
const Indexes = {
clientId: 0,
imageUrl: 1
};
/** @typedef {Object} Session - Represents a Session Object.
* @property {string | undefined} _sessionId - The Id of the Session
* @property {string | undefined} _imageUrl - The Image Url from this Session
*/
/** @type {Session} */
module.exports = class Session {
/**
* User session model
*/
constructor() {
this._sessionId;
this._imageUrl;
}
/**
* Set the Session._sessionId for the user
* @param {string} id
*/
setSessionId(id) {
if (id.length !== 8) throw Error("ClientID is not 8 characters");
this._sessionId = id;
}
/**
* Get the session ID for the user
* @return {string}
*/
get getSessionId() {
this._sessionId;
}
/**
* Set the image URL for the initial challenge
* @param {string} url
*/
setImageUrl(url) {
this._imageUrl = url;
}
/**
* Get the image URL for the initial challenge
* @return {string}
*/
getImageUrl() {
return this._imageUrl;
}
/**
* Serialize the session into a JSON object
* @return {Array<any>}
*/
serialize() {
if (!this._sessionId || !this._imageUrl) {
throw Error("Unable to serialize because of missing field(s)");
}
const payload = [];
payload[Indexes.clientId] = this._sessionId;
payload[Indexes.imageUrl] = this._imageUrl;
return payload;
}
/**
* Deserialize session data from JSON object
* @param {Array<any>} payload
*/
deserialize(payload) {
this.setSessionId(payload[Indexes.clientId]);
this.setImageUrl(payload[Indexes.imageUrl]);
}
};

View File

@ -1,3 +0,0 @@
export default function(tagName: string) {
return document.createElement(tagName)
}

View File

@ -1,23 +1,23 @@
{
"compilerOptions": {
/* Basic Options */
"incremental": true, /* Enable incremental compilation */
"target": "ESNEXT", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "incremental": true, /* Enable incremental compilation */
"target": "ESNEXT", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
// "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
// "allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
"noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
@ -42,10 +42,7 @@
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"rootDirs": [
"./src",
"../shared"
], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
@ -65,5 +62,6 @@
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
},
"include": ["src/**/*.js"]
}