Skip to content

Commit

Permalink
might be broken but i need to push
Browse files Browse the repository at this point in the history
  • Loading branch information
skysthelimitt committed Oct 28, 2024
1 parent e8aed2e commit da65d2d
Show file tree
Hide file tree
Showing 8 changed files with 208 additions and 244 deletions.
248 changes: 138 additions & 110 deletions account.js

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions ai.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ async function chatBot(model, messages, user) {
let prompt = [
{
role: "system",
content: `You are an AI created by Selenite, which hosts over 400 unblocked games. Follow these guidelines: Respond in the user's language unless requested, your knowledge is limited to December 2023. Do not provide information or claim knowledge beyond this date. Answer all parts of the user's instructions fully and comprehensively, unless doing so would compromise safety or ethics. Provide informative and comprehensive answers to user queries, offer valuable insights. No personal opinions. Keep your tone neutral and factual. Remain objective in your responses and avoid expressing any subjective opinions or beliefs. Treat all users with respect and avoid making any discriminatory or offensive statements.`,
content: `Follow these guidelines: Respond in the user's language unless requested. Your knowledge is limited to December 2023. Do not provide information or claim knowledge beyond this date. Answer all parts of the user's instructions fully and comprehensively, unless doing so would compromise safety or ethics. Provide informative and comprehensive answers to user queries, offer valuable insights. No personal opinions. Keep your tone neutral and factual. Remain objective in your responses and avoid expressing any subjective opinions or beliefs. Treat all users with respect and avoid making any discriminatory or offensive statements.`,
}
];
prompt.push.apply(prompt, JSON.parse(messages));
let newMessages = JSON.parse(messages);
for(let i = 0;i<newMessages.length;i++) {
if(newMessages[i]["role"] !== "user" && newMessages[i]["role"] !== "assistant") {
newMessages.splice(i, 1);
}
}
prompt.push.apply(prompt, );
let data = await groq.chat.completions.create({
messages: prompt,
model: "llama-3.2-1b-preview",
Expand Down
107 changes: 6 additions & 101 deletions database.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,9 @@
import "dotenv/config";
import { log } from "./log.js";
import { Sequelize, DataTypes, Op } from "sequelize";
import { Database } from "bun:sqlite";

const accs_sequelize = new Sequelize({
logging: msg => console.log(log.info(msg)),
dialect: "sqlite",
storage: `${process.env.DATA_PATH}/accounts.sqlite`,
});
const accs = new Database(`${process.env.DATA_PATH}/accounts.sqlite`);
const infdb = new Database(`${process.env.DATA_PATH}/infinitecraft.sqlite`);

const account_db = accs_sequelize.define("accounts", {
id: {
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
},
username: {
type: DataTypes.TEXT,
allowNull: true,
unique: true,
},
name: {
type: DataTypes.TEXT,
allowNull: true,
},
hashed_pass: {
type: DataTypes.INTEGER,
allowNull: false,
},
secret_key: {
type: DataTypes.TEXT,
allowNull: true,
},
about: {
type: DataTypes.TEXT,
allowNull: true,
},
badges: {
type: DataTypes.TEXT,
allowNull: true,
},
last_login: {
type: DataTypes.TEXT,
allowNull: true,
},
playedgames: {
type: DataTypes.TEXT,
allowNull: true,
},
type: {
type: DataTypes.TEXT,
allowNull: true,
},
pfp_url: {
type: DataTypes.TEXT,
allowNull: true,
},
custom_css: {
type: DataTypes.TEXT,
allowNull: true,
},
banned: {
type: DataTypes.TEXT,
allowNull: true,
},
});
infdb.exec("PRAGMA journal_mode = WAL;");
accs.exec("PRAGMA journal_mode = WAL;");

const infi_sequelize = new Sequelize({
logging: msg => console.log(log.info(msg)),
dialect: "sqlite",
storage: `${process.env.DATA_PATH}/infinitecraft.sqlite`,
});

const infiniteCache = infi_sequelize.define("caches", {
1: {
type: DataTypes.TEXT,
},
2: {
type: DataTypes.TEXT,
},
result_item: {
type: DataTypes.TEXT,
},
result_emoji: {
type: DataTypes.TEXT,
},
});

infi_sequelize.sync().then(() => {
console.log(log.success("Infinite Craft cache is online."));
}).catch((error) => {
console.error(log.error("Failed to synchronize Infinite Craft database:"));
console.error(log.error(error));
});

accs_sequelize.sync().then(() => {
console.log(log.success("Accounts Database is online."));
}).catch((error) => {
console.error(log.error("Failed to synchronize accs database:"));
console.error(log.error(error));
});

export { accs_sequelize, infi_sequelize, account_db, infiniteCache };
export { accs, infdb };
11 changes: 10 additions & 1 deletion html/ai.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
await fetch("/api/ai/chat", {
method: "POST",
body: JSON.stringify({
model: document.getElementById("models").value,
messages: JSON.stringify(chatHistory),
}),
headers: {
Expand Down Expand Up @@ -72,7 +73,15 @@
<main>
<h1>AI Chat Bot</h1>
<p>Powered by <a href="https://groq.com">Groq</a>.</p>
<!-- <p>Messages are logged for quality assurance. Also <b>PLEASE</b> don't use this to write essays, we have limited resources :(</p> -->
<p class="evensmaller">Messages are logged for quality assurance. Don't type any personal information.</p>
<select id="models">
<option>Select a model:</option>
<option value="1b">LLAMA 3.2 1B (Speed: 100%, Quality: 40%)</option>
<option value="3b">LLAMA 3.2 3B (Speed: 90%, Quality: 50%)</option>
<option value="11b">LLAMA 3.2 11B (Speed: 60%, Quality: 70%, image support)</option>
<option value="8b">LLAMA 3.1 8B (Speed: 85%, Quality: 55%)</option>
<option value="70b">LLAMA 3.1 70B (Speed: 30%, Quality: 90%)</option>
</select>
<div id="chat">
<div id="messages">
</div>
Expand Down
7 changes: 2 additions & 5 deletions html/users.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,18 @@
let above = false;
let below = false;
let data = await (await fetch(`/api/getUsers?page=${page - 1}&query=${query}`)).json();
let users = data.rows;
let users = data['users'];
let url = new URL(location.href);

pages = Math.ceil(data.count / 12);
document.getElementById("users").innerHTML = "";
for (let i = 0; i < users.length; i++) {
for (let i = 0; i < Object.keys(users).length; i++) {
document.getElementById("users").innerHTML += `<a href="/u/${users[i].username}" class="users"><img class="pfp" src="${users[i].pfp_url}"/><div class="user_info"><h1>${users[i].name}</h1><p>${users[i].about}</p></div></a>`;
}
document.getElementById("pages").innerHTML = "";
for (let i = 1; i < pages + 1; i++) {
if (i + 6 > page && i - 6 < page) {
let curPage = parseInt(page);
console.log(curPage)
console.log(i, page);
let element = document.createElement("a");
if (!(i == curPage)) {
url.searchParams.set("page", i);
Expand All @@ -46,7 +44,6 @@
element.setAttribute("class", `pages-btn`);
element.innerText = i;
document.getElementById("pages").append(element);
console.log(element);
} else {
if (i + 6 > page) {
above = true;
Expand Down
62 changes: 38 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import "dotenv/config";
import { log } from "./log.js";
import express from "express";
import cookieParser from "cookie-parser";
Expand All @@ -7,7 +6,7 @@ import { fileURLToPath } from "url";
import path, { dirname } from "node:path";
import mime from "mime-types";
import compression from "compression";
import { account_db, infiniteCache } from "./database.js";
import { accs, infdb } from "./database.js";
import { createProxyMiddleware } from "http-proxy-middleware";
import { banUser, removeAccount, verifyCookie, getUsers, getUserFromCookie, getRawData, retrieveData, createAccount, resetPassword, generateAccountPage, loginAccount, editProfile, addBadge, isAdmin, saveData } from "./account.js";
import { infiniteCraft, chatBot } from "./ai.js";
Expand All @@ -23,7 +22,6 @@ app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true }));

import WebSocket, { WebSocketServer } from "ws";
import { verify } from "node:crypto";
const wss = new WebSocketServer({ noServer: true });
wss.on("connection", function connection(ws, req, res) {
setInterval(() => {
Expand All @@ -43,18 +41,21 @@ wss.on("connection", function connection(ws, req, res) {
} else if (message.startsWith("token") && (await verifyCookie(message.substring(6)))) {
ws.id = await getUserFromCookie(message.substring(6));
ws.send(ws.id);
await account_db.update({ last_login: new Date().toUTCString() }, { where: { username: ws.id } });
const updateAccount = accs.query(`UPDATE accounts SET last_login = $login WHERE username = $user`)
updateAccount.get({ $login: new Date().toUTCString(), $user: ws.id });
} else if (message.startsWith("pong")) {
if (ws.id) {
await account_db.update({ last_login: new Date().toUTCString() }, { where: { username: ws.id } });
const updateAccount = accs.query(`UPDATE accounts SET last_login = $login WHERE username = $user`)
updateAccount.get({ $login: new Date().toUTCString(), $user: ws.id });
if (message.substring(4)) {
const existingAccounts = await account_db.findOne({ where: { username: ws.id } });
if (existingAccounts == null) {
const existingAccount = accs.query(`SELECT * FROM accounts WHERE username LIKE $1`)
let userData = existingAccount.get({ $1: ws.id });
if (userData == null) {
return { success: false, reason: "The account doesn't exist." };
}
let games;
if (existingAccounts.playedgames) {
games = JSON.parse(existingAccounts.playedgames);
if (userData.playedgames) {
games = JSON.parse(userData.playedgames);
} else {
games = {};
}
Expand All @@ -63,7 +64,8 @@ wss.on("connection", function connection(ws, req, res) {
} else {
games[message.substring(4)] = 30;
}
await account_db.update({ playedgames: JSON.stringify(games) }, { where: { username: ws.id } });
const updateAccount = accs.query(`UPDATE accounts SET playedgames = $playedgames WHERE username = $user`)
updateAccount.get({ $playedgames: JSON.stringify(games), $user: ws.id });
}
}
}
Expand Down Expand Up @@ -137,25 +139,33 @@ app.post("/api/account/upload", async (req, res, next) => {
app.post("/api/ai/chat", async (req, res) => {
if (await verifyCookie(req.cookies.token)) {
if (req.body.messages) {
res.send(await chatBot("", req.body.messages, await getUserFromCookie(req.cookies.token)));
res.send(await chatBot(req.body.model, req.body.messages, await getUserFromCookie(req.cookies.token)));
}
}
});
app.get("/api/infinite/get", async (req, res, next) => {
if (req.query[1] && req.query[2]) {
let success = false;
let data;
let search1 = await infiniteCache.findOne({ where: { 1: req.query[1], 2: req.query[2] } });
if (search1 !== null) {
data = { item: search1.result_item, emoji: search1.result_emoji, new: false };
success = true;
}
let search2 = await infiniteCache.findOne({ where: { 1: req.query[2], 2: req.query[1] } });
if (search2 !== null) {
data = { item: search2.result_item, emoji: search2.result_emoji, new: false };
success = true;
}
try {
let search1Query = infdb.query(`SELECT * FROM caches WHERE first = $one AND second = $two`)
let search1 = await search1Query.all({ $one: req.query[1], $two: req.query[2] });
if (search1 && search1.length > 0) {
data = { item: search1[0].result_item, emoji: search1[0].result_emoji, new: false };
success = true;
} else {
let search2Query = infdb.query(`SELECT * FROM caches WHERE first = $two AND second = $one`)
let search2 = await search2Query.all({ $one: req.query[1], $two: req.query[2] });
if (search2 && search2.length > 0) {
data = { item: search2[0].result_item, emoji: search2[0].result_emoji, new: false };
success = true;
}
}
} catch (error) {
console.error(error);
}
if (success) {
console.log("success");
res.send(data);
return;
}
Expand All @@ -166,10 +176,14 @@ app.get("/api/infinite/get", async (req, res, next) => {
if (keys.indexOf("item") > -1 && keys.indexOf("emoji") > -1) {
parse.new = true;
data = parse;
infiniteCache.create({ 1: req.query[1], 2: req.query[2], result_item: data.item, result_emoji: data.emoji });
const createCached = infdb.query(`INSERT INTO caches (first, second, result_item, result_emoji) VALUES ($one, $two, $item, $emoji)`)
createCached.run({ $one: req.query[1], $two: req.query[2], $item: data.item, $emoji: data.emoji });
res.send(data);
}
} catch {
} catch (error) {
console.error(error);
data = { item: "N/A", emoji: "N/A" };
res.send(data);
}
}
});
Expand Down Expand Up @@ -202,7 +216,7 @@ app.use("/admin", async (req, res, next) => {
}
});
app.use("/ai", async (req, res, next) => {
if (await verifyCookie(req.cookies.token)) {
if (await verifyCookie(req.cookies.token) && isAdmin(req.cookies.token)) {
res
.type("text/html")
.status(200)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"exports": "./index.js",
"scripts": {
"start": "node --watch index.js",
"start": "bun --watch index.js",
"svg": "node svg-converter.js"
},
"keywords": [],
Expand Down
5 changes: 5 additions & 0 deletions pm2.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
name: "Selenite", // Name of your application
script: "index.js", // Entry point of your application
interpreter: "~/.bun/bin/bun", // Path to the Bun interpreter
};

0 comments on commit da65d2d

Please sign in to comment.