Skip to content

Commit

Permalink
Merge pull request #49 from jdohm/matrixRework
Browse files Browse the repository at this point in the history
Matrix rework
  • Loading branch information
jdohm authored Apr 2, 2021
2 parents 23ea803 + e3c25d7 commit 23e025e
Show file tree
Hide file tree
Showing 10 changed files with 641 additions and 97 deletions.
4 changes: 4 additions & 0 deletions css/oi.css
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,7 @@ input::placeholder {
z-index: 1000;
outline: none;
}

.cactus-editor {
display: none!important;
}
Binary file modified db/Ideas.db.backup
Binary file not shown.
Binary file added media/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
163 changes: 80 additions & 83 deletions myServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,26 @@ const express = require("express");
const fs = require("fs");
const sqlite3 = require("sqlite3").verbose();
const https = require("https");
var path = require("path");
var bcrypt = require("bcrypt");
const sdk = require("matrix-js-sdk");
var request = require('request');
const path = require("path");
const bcrypt = require("bcrypt");
const request = require("request");
const passport = require("passport");
const flash = require("express-flash");
const session = require("express-session");
const methodOverride = require('method-override');
const methodOverride = require("method-override");
const matrix = require("./src/oi/matrix");
// const db = require("./src/oi/sqliteDb");

const app = express();
const http = express();
const port = process.argv[2] || 80;
const portSSL = process.argv[3] || 443;

//matrix login
const client = sdk.createClient("https://matrix.org");
client.login("m.login.password", {"user": "openidea", "password": process.env.MATRIX_PASSWORD}).then((response) => {
console.log(response.access_token);
});
matrix.loginOpenIdea();

//usermanagement using passport
const initializePassport = require("./passport-config");
// initializePassport(passport, async db.getUserByEmail);
initializePassport(passport, async function getUserByEmail(email) {
return new Promise((resolve) => {
let sql = `SELECT name, email, pwHash password FROM User WHERE email is ?`;
Expand All @@ -41,8 +39,7 @@ initializePassport(passport, async function getUserByEmail(email) {
if (err) throw err;
resolve(rows);
});
}
else resolve(rows);
} else resolve(rows);
});
});
});
Expand Down Expand Up @@ -91,15 +88,14 @@ app.use((req, res, next) => {

app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride('_method'));
app.use(methodOverride("_method"));

//app start page
app.get("/", checkAuthenticated, function (req, res) {
if(req.session.isNew) {
if(req.query.Idea) res.redirect('/?user=new&Idea='+req.query.Idea);
else res.redirect('/?user=new');
}
else {
if (req.session.isNew) {
if (req.query.Idea) res.redirect("/?user=new&Idea=" + req.query.Idea);
else res.redirect("/?user=new");
} else {
try {
console.log(req.user.name + " visited us");
} catch (error) {
Expand All @@ -109,7 +105,6 @@ app.get("/", checkAuthenticated, function (req, res) {
}
});


//respond with topics
app.get("/getTopics", function (req, res) {
//read all topics from Database
Expand All @@ -135,10 +130,10 @@ app.get("/getSkills", function (req, res) {
});

//respond to getIdeas GET request
app.get("/getIdeas", checkAuthenticated, function(req, res) {
app.get("/getIdeas", checkAuthenticated, function (req, res) {
//read all places from Database
var idearows;
db.serialize(function() {
db.serialize(function () {
let sql = `SELECT lon, lat, IdeaID, upvotes, downvotes FROM v_PlacesVotes ORDER BY lat`;
db.all(sql, [], async (err, rows) => {
if (err) throw err;
Expand All @@ -148,16 +143,16 @@ app.get("/getIdeas", checkAuthenticated, function(req, res) {
idearows[key].tags = tmp.tags;
idearows[key].skills = tmp.skills;
idearows[key].user = tmp.user;
};
}
res.json(idearows);
});
});
});

function addTagsSkillsUsers(id) {
var idearows = {tags: [], skills: [], user: []};
var idearows = { tags: [], skills: [], user: [] };
return new Promise((resolve) => {
db.serialize(function() {
db.serialize(function () {
let sql = `SELECT Tag FROM Idea_Tags WHERE Idea is ?`;
db.all(sql, [id], (err, rows) => {
if (err) throw err;
Expand Down Expand Up @@ -188,17 +183,17 @@ function addTagsSkillsUsers(id) {
});
});
});
};
}

//get svgs
app.get("/svgTest", function(req,res) {
app.get("/svgTest", function (req, res) {
let _id = req.query.IdeaID;
let _title = "";
db.serialize(function () {
let sql = `SELECT ID, title FROM Idea WHERE ID is ?`;
db.get(sql, [_id], (err, row) => {
if (err) throw err;
if(row) _title = row.title;
if (row) _title = row.title;
else _title = "title not found";
// console.log("test query " + _id + " title " + _title);
var testSVG = `
Expand All @@ -220,12 +215,21 @@ app.get("/svgTest", function(req,res) {
<text x="250" y="170" fill="#000000" transform="rotate(-90, 250, 170)" font-size="1.0em">${_title}</text>
</svg>
`;
res.type('svg');
res.type("svg");
res.send(testSVG);
});
});
});

//endpoint for new comments
app.post("/submitComment", checkAuthenticated, async function (req, res, next) {
if(res._headers.login !== "false")
console.log(await matrix.sendMessage(res._headers.login, req.body.IdeaID, req.body.comment, db));
//elso only if we want to let people comment without login in!
//else console.log(await matrix.sendMessage('guest', req.body.IdeaID, req.body.comment, db));
res.json({msg: "comment saved"});
});

//respond to getIdea POST request
app.post("/getIdea", checkAuthenticated, function (req, res) {
if (!req.body.IdeaID) res.json();
Expand Down Expand Up @@ -294,7 +298,7 @@ app.post("/submitVote", checkAuthenticatedCancel, function (req, res) {
1: req.body.IdeaID,
2: req.body.upvote,
3: datenow,
4: req.user.name
4: req.user.name,
},
function (err) {
if (err) return console.log(err.message);
Expand Down Expand Up @@ -330,7 +334,7 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
);
var tags = req.body.tags.split(",");
tags.forEach(function (item, index) {
if(item.trim() != ""){
if (item.trim() != "") {
db.run(
"INSERT OR IGNORE INTO Tags(Name) VALUES(?1)",
{
Expand All @@ -354,7 +358,7 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
});
var skills = req.body.skills.split(",");
skills.forEach(function (item, index) {
if(item.trim() != ""){
if (item.trim() != "") {
db.run(
"INSERT OR IGNORE INTO Skills(Name) VALUES(?1)",
{
Expand All @@ -381,7 +385,7 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
{
1: lastID,
2: req.user.name,
3: 0
3: 0,
},
function (err) {
if (err) return console.log(err.message);
Expand All @@ -391,17 +395,17 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
/*****************************|
| mastodon part start |
|*****************************/
if(req.body.mastodon == "true"){
if (req.body.mastodon == "true") {
console.log("publish on mastodon: " + req.body.mastodon);
var tagsBody = "";

tags.some(function(item, index) {
if(item.trim() != "") {
tagsBody += ("#" + item.trim() + " ");
tags.some(function (item, index) {
if (item.trim() != "") {
tagsBody += "#" + item.trim() + " ";
console.log("item: " + index + "tag: " + "#" + item.trim() + " ");
}
//if 3 tags written stop function
if(index >= 2) return true;
if (index >= 2) return true;
else return false;
});

Expand All @@ -411,25 +415,26 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
+ "\n" + "https://openidea.io/?Idea=" + lastID + "\n"
+ tagsBody;

var jsonBody = {'status': truncate(statusText, 425),
'visibility': 'unlisted'}// public, unlisted, private, direct
;
var jsonBody = {
status: truncate(statusText, 425),
visibility: "unlisted",
}; // public, unlisted, private, direct
var clientServerOptions = {
url: 'https://botsin.space/api/v1/statuses',
url: "https://botsin.space/api/v1/statuses",
body: JSON.stringify(jsonBody),
method: 'POST',
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization' : 'Bearer ' + process.env.MASTODON_ACCESS_TOKEN
}
"Content-Type": "application/json",
Authorization: "Bearer " + process.env.MASTODON_ACCESS_TOKEN,
},
};
request(clientServerOptions, function(error, response, body){
request(clientServerOptions, function (error, response, body) {
// console.log(body);
});

function truncate(str, n){
return (str.length > n) ? str.substr(0, n-3) + '...' : str;
};
function truncate(str, n) {
return str.length > n ? str.substr(0, n - 3) + "..." : str;
}
}
/*****************************|
| mastodon part end |
Expand All @@ -440,27 +445,9 @@ app.post("/submitIdea", checkAuthenticatedCancel, function (req, res) {
});
});


//support request to matrix room
app.post("/submitSupportRequest", function (req, res, next) {
client.startClient();

var testRoomId = "!HTcpkpXWLaaunauYsD:cactus.chat";

var content = {
"body": "#" + req.body.IdeaID + "\n" + req.body.text + "\n\nsend from: ",
"msgtype": "m.text"
};
if(req.user){
content.body += req.user.email;
}
else {content.body += "anonymous";}

client.sendEvent(testRoomId, "m.room.message", content, "").then((res) => {
// message sent successfully
}).catch((err) => {
console.log(err);
});
matrix.sendSupportRequest(req);
res.send("Message send to support");
});

Expand All @@ -469,23 +456,23 @@ app.post("/submitSupportRequest", function (req, res, next) {
app.post("/submitLogin", function (req, res, next) {
passport.authenticate("local", (err, user, info) => {
//if authenticate failed respond with info
if(!user) return res.json(info);
if (!user) return res.json(info);
else {
//start user session
req.logIn(user, function(err) {
if (err) { return next(err); }
req.logIn(user, function (err) {
if (err) {
return next(err);
}
return res.json(user.name);
});
}
})(req,res,next)
}
);
})(req, res, next);
});

app.delete("/SubmitLogout", function (req, res) {
req.logOut();
res.json();
}
);
});

//handle register POST request
app.post("/submitRegister", async function (req, res) {
Expand All @@ -494,31 +481,41 @@ app.post("/submitRegister", async function (req, res) {
res.json({
email: req.user.email,
});
} catch {}
} catch(e) {}

//reject username if it uses not allowed character
const regex = /[^A-Za-z0-9 ]+/g;
if(regex.test(req.body.name)) {
res.json({message: "username not allowed"});
return;
}

console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.password);
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
console.log(hashedPassword);
const matrixUser = await matrix.createUser(req.body.name);
db.serialize(function () {
db.run(
"INSERT INTO User(name,email,pwHash) VALUES(?1,?2,?3)",
"INSERT INTO User(name,email,pwHash,matrixname,matrixpw) VALUES(?1,?2,?3,?4,?5)",
{
1: req.body.name,
2: req.body.email,
3: hashedPassword,
4: matrixUser.matrixname,
5: matrixUser.matrixpw,
},
function (err) {
if (err) {
console.log(err.message);
res.json({"message": err.message});
res.json({ message: err.message });
}
res.json("success");
}
);
});
} catch {
} catch(e) {
console.log("error while user registered");
}
});
Expand Down Expand Up @@ -550,11 +547,11 @@ function checkAuthenticated(req, res, next) {

function checkAuthenticatedCancel(req, res, next) {
if (req.isAuthenticated()) {
res.append('login', req.user.name);
res.append("login", req.user.name);
console.log("checkAuthenticated " + req.user.name);
next();
} else {
res.append('login', false);
res.append("login", false);
res.json("error");
}
}
Expand Down
Loading

0 comments on commit 23e025e

Please sign in to comment.