Browse Source

Merge pull request #61 from jrtechs/routes

Express Routes!
pull/62/head
Jeffery Russell 5 years ago
committed by GitHub
parent
commit
053fe9c625
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 634 additions and 368 deletions
  1. +19
    -4
      admin/adminDownloads.js
  2. +36
    -13
      admin/adminHome.js
  3. +3
    -3
      admin/analytics.js
  4. +24
    -3
      admin/posts.js
  5. +21
    -3
      admin/users.js
  6. +11
    -19
      blog/category.js
  7. +0
    -1
      blog/contact.js
  8. +1
    -1
      blog/renderBlogPost.js
  9. +5
    -3
      blog/renderNextBar.js
  10. +4
    -13
      includes/downloads.js
  11. +55
    -10
      includes/includes.js
  12. +3
    -2
      includes/staticContentServer.js
  13. +1
    -0
      package.json
  14. +16
    -0
      routes/about.js
  15. +10
    -0
      routes/admin/analytics.js
  16. +18
    -0
      routes/admin/downloads.js
  17. +38
    -0
      routes/admin/index.js
  18. +16
    -0
      routes/admin/login.js
  19. +15
    -0
      routes/admin/posts.js
  20. +15
    -0
      routes/admin/users.js
  21. +10
    -0
      routes/category/index.js
  22. +15
    -0
      routes/contact.js
  23. +14
    -0
      routes/downloads/index.js
  24. +15
    -0
      routes/includes/index.js
  25. +49
    -0
      routes/index.js
  26. +30
    -0
      routes/projects/index.js
  27. +5
    -65
      server.js
  28. +0
    -55
      sites/admin.js
  29. +0
    -122
      sites/blog.js
  30. +0
    -1
      sites/projects.js
  31. +1
    -1
      templates/admin/adminMain.html
  32. +184
    -0
      utils/pageBuilder.js
  33. +0
    -49
      utils/utils.js

+ 19
- 4
admin/adminDownloads.js View File

@ -109,21 +109,36 @@ module.exports=
* @param templateContext json object used as the template context
* @returns {Promise} renders the template used for this page
*/
main: function(postData, templateContext)
main: function(templateContext)
{
return new Promise(function(resolve, reject)
{
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
addDownloadPostData(postData),
removeDownloads(postData),
displayDownloads(templateContext)]).then(function(template)
{
resolve(template[0]);
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add downloads.js");
reject(error);
});
});
},
processPostData: function(postData)
{
return new Promise(function(resolve, reject)
{
Promise.all([addDownloadPostData(postData),
removeDownloads(postData)]).then(function()
{
resolve();
}).catch(function(error)
{
console.log("Error in admin downloads");
reject(error);
})
})
}
};

+ 36
- 13
admin/adminHome.js View File

@ -29,13 +29,19 @@ const processPostAddCategory = function(postData)
if(sql.insert(q) != 0)
{
console.log("category added");
resolve();
}
else
{
reject();
console.log("error adding category");
}
}
resolve("");
else
{
resolve();
}
});
};
@ -74,7 +80,6 @@ const processPost = function(postData)
urls = urls.split(" ").join("-");
urls =urls.toLowerCase();
var q = "insert into posts (category_id, picture_url, published, name, url) values ";
q += "('" + post.add_post_category + "', '" + post.add_post_picture +
@ -83,7 +88,7 @@ const processPost = function(postData)
{
var map = require('../utils/generateSiteMap');
map.main();
resolve("");
resolve();
}).catch(function(error)
{
reject(error);
@ -91,17 +96,19 @@ const processPost = function(postData)
}
else if(post.clear_cache)
{
require("../sites/blog.js").clearCache();
require("../utils/pageBuilder").clearCache();
require("../includes/includes.js").clearCache();
resolve();
}
else if(post.git_pull)
{
const execSync = require('child_process').execSync;
code = execSync('git pull')
code = execSync('git pull');
resolve();
}
else
{
resolve("");
resolve();
}
});
};
@ -116,23 +123,39 @@ module.exports=
* @param templateContext json object used as the template context
* @returns {Promise} renders the template used for this page
*/
main: function(postData, templateContext)
main: function(templateContext)
{
console.log("called");
return new Promise(function(resolve, reject)
{
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
processPostAddCategory(postData),
appendCategoriesToTemplate(templateContext),
processPost(postData)])
appendCategoriesToTemplate(templateContext)])
.then(function(template)
{
resolve(template[0]);
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add downloads.js");
console.log("error in add adminHome.js");
reject(error);
});
});
},
processPostData: function(postData)
{
return new Promise(function(resolve, reject)
{
Promise.all([processPostAddCategory(postData),
processPost(postData)])
.then(function()
{
console.log("all resolved");
resolve();
}).catch(function(error)
{
console.log("error in add downloads.js");
reject(error);
});
});
}
};

+ 3
- 3
admin/analytics.js View File

@ -50,17 +50,17 @@ module.exports=
* Fetches context information for the admin blog page and handles post
* data sent regarding editing blog.
*
* @param postData posted by user
* @param templateContext json object used as the template context
* @returns {Promise} renders the template used for this page
*/
main: function(postData, templateContext)
main: function(templateContext)
{
return new Promise(function(resolve, reject)
{
Promise.all([includes.fetchTemplate(TEMPLATE_FILE), generateData(templateContext)]).then(function(template)
{
resolve(template[0]);
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add admin blog.js");

+ 24
- 3
admin/posts.js View File

@ -10,6 +10,9 @@ const sql = require('../utils/sql');
const qs = require('querystring');
const utils = require('../utils/utils');
/**
* Detects if the post data came from the edit form in blog table or edit post
* in the edit post form.
@ -84,7 +87,24 @@ module.exports=
* @param templateContext json object used as the template context
* @returns {Promise} renders the template used for this page
*/
main: function(postData, templateContext)
main: function(templateContext)
{
return new Promise(function(resolve, reject)
{
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
fetchPostsInformation(templateContext)]).then(function(template)
{
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add admin posts.js");
reject(error);
});
});
},
processPostData(templateContext, postData)
{
return new Promise(function(resolve, reject)
{
@ -92,10 +112,11 @@ module.exports=
processPostData(postData, templateContext),
fetchPostsInformation(templateContext)]).then(function(template)
{
resolve(template[0]);
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add admin blog.js");
console.log("error in add admin posts.js");
reject(error);
});
});

+ 21
- 3
admin/users.js View File

@ -154,7 +154,24 @@ module.exports=
* @param templateContext json object used as the template context
* @returns {Promise} renders the template used for this page
*/
main: function(postData, templateContext)
main: function(templateContext)
{
return new Promise(function(resolve, reject)
{
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
getUserInformation(templateContext)]).then(function(template)
{
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in users.js");
reject(error);
});
});
},
processPostData: function(templateContext, postData)
{
return new Promise(function(resolve, reject)
{
@ -164,10 +181,11 @@ module.exports=
editUserPost(postData, templateContext),
getUserInformation(templateContext)]).then(function(template)
{
resolve(template[0]);
templateContext.adminPage = template[0];
resolve();
}).catch(function(error)
{
console.log("error in add downloads.js");
console.log("error in users.js");
reject(error);
});
});

+ 11
- 19
blog/category.js View File

@ -16,34 +16,26 @@ module.exports=
*/
main: function(requestURL, request, templateContext)
{
console.log(requestURL);
return new Promise(function(resolve, reject)
{
var page = request.query.page;
const splitURL = requestURL.split("/");
if(splitURL.length >= 3)
{
const category = requestURL.split("/").join("");
sql.getPostsFromCategory(splitURL[2]).then(function(posts)
{
Promise.all([blogBodyRenderer.renderBatchOfPosts(requestURL, posts, page, 5, templateContext),
require('./renderNextBar').main(requestURL, page, 5, posts.length, templateContext)]).then(function()
{
resolve();
});
}).catch(function()
sql.getPostsFromCategory(category).then(function(posts)
{
Promise.all([blogBodyRenderer.renderBatchOfPosts(requestURL, posts, page, 5, templateContext),
require('./renderNextBar').main("/category" + request.url, page, 5, posts.length, templateContext)]).then(function()
{
delete templateContext["posts"];
resolve();
});
}
else
}).catch(function()
{
//page is not found but, posts list will be empty
// so 404 will display
resolve();
}
delete templateContext["posts"];
reject();
});
});
}
};

+ 0
- 1
blog/contact.js View File

@ -215,7 +215,6 @@ module.exports =
const html = whiskers.render(content[0], templateContext);
result.write(html);
result.end();
}).catch(function(err)
{
console.log(err);

+ 1
- 1
blog/renderBlogPost.js View File

@ -255,4 +255,4 @@ module.exports=
});
});
}
}
};

+ 5
- 3
blog/renderNextBar.js View File

@ -40,14 +40,16 @@ module.exports=
var nextPage = currentPage + 1;
var previousPage = currentPage - 1;
var strippedURL = baseURL.split("?page=")[0];
if (isValidPage(previousPage, postsPerPage, totalPosts))
{
paginationObject.previous = {url: baseURL + "?page=" + previousPage};
paginationObject.previous = {url: strippedURL + "?page=" + previousPage};
}
if (isValidPage(nextPage, postsPerPage, totalPosts))
{
paginationObject.next = {url: baseURL + "?page=" + nextPage};
paginationObject.next = {url: strippedURL + "?page=" + nextPage};
}
var page = 1;
@ -60,7 +62,7 @@ module.exports=
}
else
{
pages.push({number: page, url: baseURL + "?page=" + page})
pages.push({number: page, url: strippedURL + "?page=" + page})
}
page = page + 1;
}

+ 4
- 13
includes/downloads.js View File

@ -26,13 +26,10 @@ module.exports=
return new Promise(function(resolve, reject)
{
const urlSplit = requestURL.split("/");
console.log(urlSplit);
if(urlSplit.length == 3 || urlSplit.length == 4)
if(urlSplit.length == 2 || urlSplit.length == 4)
{
console.log(urlSplit[2]);
sql.getDownload(urlSplit[2]).then(function(result)
sql.getDownload(urlSplit[1]).then(function(result)
{
console.log(result);
if(result.length == 1)
{
const file = './blogContent/downloads/' +
@ -41,19 +38,13 @@ module.exports=
}
else
{
utils.print404(res).then(function()
{
resolve();
})
utils.print404(res);
}
});
}
else
{
utils.print404().then(function(content)
{
resolve(content);
})
utils.print404(res);
}
});
}

+ 55
- 10
includes/includes.js View File

@ -7,9 +7,6 @@
* @author Jeffery Russell
*/
//used for file IO
const utils = require('../utils/utils.js');
const HEADER_KEY = "header";
const FOOTER_KEY = "footer";
@ -30,6 +27,25 @@ const crypto = require('crypto');
//caching program to make the application run faster
const cache = require('memory-cache');
const fs = require('fs');
const readFile = function(filename)
{
return new Promise(function(resolve, reject)
{
try
{
resolve(fs.readFileSync(filename));
}
catch (e)
{
console.log(e);
console.log("Could not find " + filename);
return("");
}
})
};
/**
* Sends a static file to the client in a way which the web browser
@ -46,7 +62,7 @@ const sendCachedContent = function(path, type, result)
if(goods == null)
{
utils.include("." + path).then(function(content)
readFile(path).then(function(content)
{
const eTag = crypto.createHash('md5').update(content).digest('hex');
result.writeHead(200, {'Content-Type': type, 'Cache-Control':
@ -83,10 +99,39 @@ module.exports =
*/
printHeader: function(templateContext)
{
return utils.includeInObject(HEADER_KEY, templateContext, HEADER_FILE);
return module.exports.includeInObject(HEADER_KEY, templateContext, HEADER_FILE);
},
includeInObject: function(key, context, fileName)
{
return new Promise(function(resolve, reject)
{
readFile(fileName).then(function(result)
{
context[key] = result;
resolve();
}).catch(function(error)
{
context[key] = "File Not Found";
reject(error);
console.log(error);
})
});
},
/**
* A function similar to the include statement in PHP
* This function writes a file to the output
*
* @param fileName the file to append to the result
*/
include: function(fileName)
{
return readFile(fileName);
},
/**
* Appends the footer to the result object
*
@ -94,7 +139,7 @@ module.exports =
*/
printFooter: function(templateContext)
{
return utils.includeInObject(FOOTER_KEY, templateContext, FOOTER_FILE);
return module.exports.includeInObject(FOOTER_KEY, templateContext, FOOTER_FILE);
},
/**
@ -104,7 +149,7 @@ module.exports =
*/
printAdminHeader(templateContext)
{
return utils.includeInObject(HEADER_KEY, templateContext, ADMIN_HEADER);
return module.exports.includeInObject(HEADER_KEY, templateContext, ADMIN_HEADER);
},
@ -114,7 +159,7 @@ module.exports =
* @param path
* @return {*}
*/
sendCSS: function(result, path, cache)
sendCSS: function(result, path)
{
sendCachedContent(path, 'text/css', result);
},
@ -145,7 +190,7 @@ module.exports =
fetchTemplate: function(templateName)
{
return utils.include("templates/" + templateName);
return readFile("templates/" + templateName);
},
@ -156,7 +201,7 @@ module.exports =
*/
sendHTML: function(result, fileName)
{
utils.include("." + fileName).then(function(content)
readFile(fileName).then(function(content)
{
result.writeHead(200, {'Content-Type': 'text/html'});
result.write(content);

+ 3
- 2
includes/staticContentServer.js View File

@ -2,7 +2,6 @@
const includes = require('../includes/includes.js');
/**
* @author Jeffery Russell 10-30-18
*
@ -13,7 +12,9 @@ module.exports=
serveStaticContent: function(request, result, filename, baseURL)
{
fullPath = baseURL + filename;
var fullPath = baseURL + filename;
if(fullPath.charAt(0) === '/')
fullPath = fullPath.substring(1,);
if (filename.includes(".svg") || filename.includes(".svg"))
{
includes.sendSVG(result, fullPath);

+ 1
- 0
package.json View File

@ -19,6 +19,7 @@
"promise": "^8.0.1",
"remarkable": "^1.7.1",
"request": "^2.88.0",
"routes": "^2.1.0",
"sanitizer": "^0.1.3",
"sendmail": "^1.4.1"
},

+ 16
- 0
routes/about.js View File

@ -0,0 +1,16 @@
const routes = require('express').Router();
const utils = require('../utils/utils.js');
routes.get('/', (request, result) =>
{
});
routes.get('*', (request, result) =>
{
utils.print404(result);
});
module.exports = routes;

+ 10
- 0
routes/admin/analytics.js View File

@ -0,0 +1,10 @@
const routes = require('express').Router();
const builder = require('../../utils/pageBuilder');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/analytics").main)
});
module.exports = routes;

+ 18
- 0
routes/admin/downloads.js View File

@ -0,0 +1,18 @@
const routes = require('express').Router();
const builder = require('../../utils/pageBuilder');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/adminDownloads").main)
});
routes.post('/', (request, result) =>
{
builder.adminPostRoute(request ,require("../../admin/adminDownloads").processPostData).then(function()
{
result.redirect('/admin/downloads');
})
});
module.exports = routes;

+ 38
- 0
routes/admin/index.js View File

@ -0,0 +1,38 @@
const routes = require('express').Router();
const analytics = require('./analytics');
routes.use('/analytics', analytics);
const login = require('./login');
routes.use('/login', login);
const posts = require('./posts');
routes.use('/posts', posts);
const downloads = require('./downloads');
routes.use('/downloads', downloads);
const users = require('./users');
routes.use('/users', users);
const builder = require('../../utils/pageBuilder.js');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/adminHome").main)
});
routes.post('/', (request, result) =>
{
builder.adminPostRoute(request, require("../../admin/adminHome").processPostData).then(function()
{
result.redirect("/admin");
});
});
routes.get('*', (request, result) =>
{
builder.print404(result);
});
module.exports = routes;

+ 16
- 0
routes/admin/login.js View File

@ -0,0 +1,16 @@
const routes = require('express').Router();
const builder = require('../../utils/pageBuilder.js');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/adminHome").main)
});
routes.post('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/login").main)
});
module.exports = routes;

+ 15
- 0
routes/admin/posts.js View File

@ -0,0 +1,15 @@
const routes = require('express').Router();
const builder = require('../../utils/pageBuilder');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/posts").main)
});
routes.post('/', (request, result) =>
{
builder.adminPostPageWithOutput(request, result ,require("../../admin/posts").processPostData)
});
module.exports = routes;

+ 15
- 0
routes/admin/users.js View File

@ -0,0 +1,15 @@
const routes = require('express').Router();
const builder = require('../../utils/pageBuilder.js');
routes.get('/', (request, result) =>
{
builder.constructAdminPage(request, result, require("../../admin/users").main)
});
routes.post('/', (request, result) =>
{
builder.adminPostPageWithOutput(request, result ,require("../../admin/users").processPostData)
});
module.exports = routes;

+ 10
- 0
routes/category/index.js View File

@ -0,0 +1,10 @@
const routes = require('express').Router();
const pageBuilder = require('../../utils/pageBuilder');
routes.get('*', (request, result) =>
{
pageBuilder.buildBlogPage(request, result, require("../../blog/category").main)
});
module.exports = routes;

+ 15
- 0
routes/contact.js View File

@ -0,0 +1,15 @@
const routes = require('express').Router();
const utils = require('../utils/utils.js');
routes.get('/', (request, result) =>
{
require("../blog/contact.js").main(request, result);
});
routes.get('*', (request, result) =>
{
utils.print404(result);
});
module.exports = routes;

+ 14
- 0
routes/downloads/index.js View File

@ -0,0 +1,14 @@
const routes = require('express').Router();
/** used to parse the request URL */
const url = require('url');
routes.get('*', (request, result) =>
{
console.log("ping");
const filename = url.parse(request.url, true).pathname;
require("../../includes/downloads.js").main(result, filename);
});
module.exports = routes;

+ 15
- 0
routes/includes/index.js View File

@ -0,0 +1,15 @@
const routes = require('express').Router();
const contentLoader = require('../../includes/staticContentServer.js');
routes.get('*', (request, result) =>
{
if(!contentLoader.serveStaticContent(request, result, request.originalUrl, ""))
{
//missing content
}
});
module.exports = routes;

+ 49
- 0
routes/index.js View File

@ -0,0 +1,49 @@
const routes = require('express').Router();
/** about page */
const about = require('./about');
routes.use('/about', about);
/** admin page and all of its sub pages */
const admin = require('./admin');
routes.use('/admin', admin);
/** Contact page */
const contact = require('./contact');
routes.use('/contact', contact);
/** Downloads path for files */
const downloads = require('./downloads');
routes.use('/downloads', downloads);
/** static content like css, js, and images */
const includes = require('./includes');
routes.use('/includes', includes);
routes.use('/blogContent', includes);
/** category pages */
const category = require('./category');
routes.use('/category', category);
const pageBuilder = require('../utils/pageBuilder');
const project = require('./projects');
routes.use('/steam', project);
//blog home page
routes.get('/', (request, result) =>
{
pageBuilder.buildBlogPage(request, result, require("../blog/homePage").main)
});
//regular blog posts
routes.get('*', (request, result) =>
{
pageBuilder.buildBlogPage(request, result,
require("../blog/posts").main, request.url);
});
module.exports = routes;

+ 30
- 0
routes/projects/index.js View File

@ -0,0 +1,30 @@
const routes = require('express').Router();
const url = require('url');
const contentLoader = require('../../includes/staticContentServer.js');
routes.get('*', (request, result) =>
{
var filename = url.parse(request.url, true).pathname;
var extra = '';
if(filename === '/')
{
if(request.originalUrl.charAt(request.originalUrl.length -1) !== '/')
{
result.redirect(request.originalUrl + "/");
}
else
{
extra = "/index.html";
}
}
if(!contentLoader.serveStaticContent(request, result,
request.originalUrl + extra, "blogContent/projects"))
{
}
});
module.exports = routes;

+ 5
- 65
server.js View File

@ -11,25 +11,15 @@ const config = require('./utils/configLoader').getConfig();
/** Port for the server to run on */
const port = config.PORT;
/** http server */
const http = require('http');
/** used to parse the request URL */
const url = require('url');
/** express app */
const express = require("express");
/** express app */
const app = express();
/** server side logging */
const sql = require('./utils/sql');
/** Used for gzip compression */
const compression = require('compression');
/**Updates the site map whenever the server is started */
const map = require('./utils/generateSiteMap.js');
map.main();
@ -41,63 +31,13 @@ const session = require('express-session');
/**Initializes sessions for login */
app.use(session({ secret: config.SESSION_SECRET, cookie: { maxAge: 6000000 }}));
const projects = ["/steam/"];
/**
* Parses the request url and calls correct JS files
*/
app.use(function(request, result)
{
//prevents people from pointing their dns at my IP:port for my site
if(request.headers.host.includes("localhost:" + port) ||
request.headers.host.includes("jrtechs.net"))
{
const filename = url.parse(request.url, true).pathname;
var project = false;
projects.forEach(function(projectName)
{
if(filename.startsWith(projectName))
{
require("./sites/projects.js").main(request, result, projectName);
project = true;
}
});
if(filename.startsWith("/admin"))
{
require("./sites/admin.js").main(request, result, filename);
project = true;
}
if(!project)
{
require("./sites/blog.js").main(request, result, filename);
}
try
{
const getClientAddress = (request.headers['x-forwarded-for'] || '').split(',')[0]
|| request.connection.remoteAddress;
console.log(getClientAddress);
sql.logTraffic(getClientAddress, filename);
}
catch (e)
{ }
}
else
{
// utils.printWrongHost(result);
result.writeHead(418, {});
result.end();
}
});
const routes = require('./routes');
app.use('/', routes);
//enables gzip compression for the site
app.use(compression());
http.createServer(app).listen(port);
app.listen(port, () =>
console.log(`App listening on port ${port}!`)
);

+ 0
- 55
sites/admin.js View File

@ -1,55 +0,0 @@
//sending static content
const includes = require('../includes/includes.js');
//used to append static content to result
const contentLoader = require('../includes/staticContentServer.js');
const whiskers = require('whiskers');
/**
* @author Jeffery Russell 11-3-18
*
* @type {{main: (function(*=, *): Promise)}}
*/
module.exports=
{
/**
* Calls blog and sidebar modules to render blog contents in order
*
* @param requestURL
* @returns {Promise|*}
*/
main: function(request, result, filename)
{
if(contentLoader.serveStaticContent(request, result, filename, ""))
{
//do nothing
}
else
{
const clientAddress = (request.headers['x-forwarded-for'] || '').split(',')[0]
|| request.connection.remoteAddress;
result.writeHead(200, {'Content-Type': 'text/html'});
const file = "../admin/admin.js";
var templateContext = Object();
Promise.all([includes.fetchTemplate("admin/adminMain.html"),
includes.printAdminHeader(templateContext),
require(file).main(request, clientAddress, templateContext, filename),
includes.printFooter(templateContext),
]).then(function(content)
{
result.write(whiskers.render(content[0], templateContext));
result.end();
}).catch(function(err)
{
console.log(err);
throw err;
});
}
}
};

+ 0
- 122
sites/blog.js View File

@ -1,122 +0,0 @@
//used to append static content to result
const includes = require('../includes/includes.js');
//used to append static content to result
const contentLoader = require('../includes/staticContentServer.js');
const whiskers = require('whiskers');
const TEMPLATE_FILE="blog/blogMain.html";
const PAGINATION_TEMPLATE_KEY = "paginationTemplate";
const PAGINATION_TEMPLATE_FILE = "blog/paginationBar.html";
//caching program to make the application run faster
const cache = require('memory-cache');
//file io
const utils = require('../utils/utils.js');
/**
* @author Jeffery Russell 11-3-18
*
* @type {{main: (function(*=, *): Promise)}}
*/
module.exports=
{
/**
* Calls posts and sidebar modules to render blog contents in order
*
* @param requestURL
* @returns {Promise|*}
*/
main: function(request, result, filename)
{
if(contentLoader.serveStaticContent(request, result, filename, ""))
{
//do nothing
}
//downloads
else if (filename.includes("/downloads/"))
{
require("../includes/downloads.js").main(result, filename);
}
else if (filename.includes("/contact"))
{
require("../blog/contact.js").main(request, result);
}
else
{
var page = request.query.page;
if(typeof page == "undefined")
page = 1;
page = Number(page);
const html = cache.get(filename + "?page=" + page);
result.writeHead(200, {'Content-Type': 'text/html'});
if (html == null)
{
var file = "";
if (filename === '' || filename === '/')
{
file = "../blog/homePage.js";
}
else
{
var urlSplit = filename.split("/");
if (urlSplit.length >= 2 && urlSplit[1] === 'category') //single category page
file = "../blog/category.js";
else
{
file = "../blog/posts.js";
page = 1; // all blog are single page, everyone must be one to ensure
// cache is not tricked into storing same blog post a ton of times
}
}
var templateContext = Object();
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
utils.includeInObject(PAGINATION_TEMPLATE_KEY, templateContext, "templates/" + PAGINATION_TEMPLATE_FILE),
includes.printHeader(templateContext),
includes.printFooter(templateContext),
require(file).main(filename, request, templateContext),
require("../blog/sidebar.js").main(templateContext)])
.then(function (content)
{
const html = whiskers.render(content[0], templateContext);
result.write(html);
result.end();
cache.put(filename + "?page=" + page, html);
}).catch(function (err)
{
console.log(err);
cache.del(filename + "?page=" + page);
utils.print404().then(function(content)
{
result.write(content);
result.end();
})
});
}
else
{
result.write(html);
result.end();
}
}
},
/**
* Clears the memory cache.
*/
clearCache: function()
{
console.log("Blog cache cleared");
cache.clear();
}
};

+ 0
- 1
sites/projects.js View File

@ -29,7 +29,6 @@ module.exports=
filename = baseURL + "index.html";
}
if (!contentLoader.serveStaticContent(request, result, filename, "/blogContent/projects"))
{
console.log(filename);

+ 1
- 1
templates/admin/adminMain.html View File

@ -26,7 +26,7 @@
<h2>Login</h2>
</div>
<form action="/admin/" method ="post" class="p-2">
<form action="/admin/login" method ="post" class="p-2">
<div class="form-group">
<label for="username1">User Name</label>
<input class="form-control" type="text" id="username1" name="username" placeholder="Enter username" required>

+ 184
- 0
utils/pageBuilder.js View File

@ -0,0 +1,184 @@
const utils = require('./utils');
const whiskers = require('whiskers');
const includes = require("../includes/includes");
const cache = require('memory-cache');
/** used to parse the request URL */
const url = require('url');
const TEMPLATE_FILE="blog/blogMain.html";
const PAGINATION_TEMPLATE_KEY = "paginationTemplate";
const PAGINATION_TEMPLATE_FILE = "blog/paginationBar.html";
module.exports =
{
/**
* Displays 404 error to user
*
* @param result
* @returns {*}
*/
print404: function(result)
{
includes.include("includes/html/404.html").then(function(html)
{
result.write(html);
result.end();
})
},
constructAdminPage: function(request, result, templateFiller)
{
var templateContext = Object();
var promises = [];
promises.push(includes.fetchTemplate("admin/adminMain.html"));
promises.push(includes.printAdminHeader(templateContext));
promises.push(includes.printFooter(templateContext));
if(module.exports.loggedIn(request))
{
templateContext.loggedIn = true;
promises.push(templateFiller(templateContext));
}
else
{
//login
const clientAddress = (request.headers['x-forwarded-for'] || '').split(',')[0]
|| request.connection.remoteAddress;
promises.push(require("../admin/login").main(request, clientAddress,templateContext));
}
Promise.all(promises).then(function(content)
{
result.write(whiskers.render(content[0], templateContext));
result.end();
}).catch(function(err)
{
console.log(err);
throw err;
});
},
adminPostPageWithOutput: function(request, result, templateFiller)
{
utils.getPostData(request).then(function(postData)
{
var templateContext = Object();
var promises = [];
promises.push(includes.fetchTemplate("admin/adminMain.html"));
promises.push(includes.printAdminHeader(templateContext));
promises.push(includes.printFooter(templateContext));
if (module.exports.loggedIn(request))
{
templateContext.loggedIn = true;
promises.push(templateFiller(templateContext, postData));
}
else
{
//login
const clientAddress = (request.headers['x-forwarded-for'] || '').split(',')[0]
|| request.connection.remoteAddress;
promises.push(require("../admin/login").main(request, clientAddress, templateContext));
}
Promise.all(promises).then(function (content)
{
result.write(whiskers.render(content[0], templateContext));
result.end();
}).catch(function (err) {
console.log(err);
throw err;
});
});
},
adminPostRoute: function(request, templateFiller)
{
return new Promise(function(resolve, reject)
{
utils.getPostData(request).then(function(postData)
{
templateFiller(postData).then(function()
{
resolve();
})
}).catch(function(e)
{
reject(e);
})
})
},
loggedIn(request)
{
return(request.session && request.session.user);
},
buildBlogPageWithURL: function(request, result, templateFiller, filename)
{
var page = request.query.page;
if(typeof page == "undefined")
page = 1;
page = Number(page);
const html = cache.get(filename + "?page=" + page);
result.writeHead(200, {'Content-Type': 'text/html'});
if (html == null)
{
var templateContext = Object();
Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
includes.includeInObject(PAGINATION_TEMPLATE_KEY, templateContext, "templates/" + PAGINATION_TEMPLATE_FILE),
includes.printHeader(templateContext),
includes.printFooter(templateContext),
templateFiller(filename, request, templateContext),
require("../blog/sidebar.js").main(templateContext)])
.then(function (content)
{
const html = whiskers.render(content[0], templateContext);
result.write(html);
result.end();
cache.put(filename + "?page=" + page, html);
}).catch(function (err)
{
cache.del(filename + "?page=" + page);
module.exports.print404(result)
});
}
else
{
result.write(html);
result.end();
}
},
buildBlogPage: function(request, result, templateFiller)
{
var filename = url.parse(request.url, true).pathname;
module.exports.buildBlogPageWithURL(request, result,templateFiller, filename);
},
/**
* Clears the memory cache.
*/
clearCache: function()
{
console.log("Blog cache cleared");
cache.clear();
}
};

+ 0
- 49
utils/utils.js View File

@ -9,44 +9,7 @@ const fs = require('fs');
module.exports=
{
/**
* A function similar to the include statement in PHP
* This function writes a file to the output
*
* @param fileName the file to append to the result
*/
include: function(fileName)
{
return new Promise(function(resolve, reject)
{
try
{
resolve(fs.readFileSync(fileName));
}
catch (e)
{
console.log("Could not find " + fileName);
resolve("");
}
});
},
includeInObject: function(key, context, fileName)
{
return new Promise(function(resolve, reject)
{
module.exports.include(fileName).then(function(result)
{
context[key] = result;
resolve();
}).catch(function(error)
{
context[key] = "File Not Found";
reject(error);
console.log(error);
})
})
},
/**
@ -138,16 +101,4 @@ module.exports=
}
});
},
/**
* Displays 404 error to user
*
* @param result
* @returns {*}
*/
print404: function()
{
return this.include("includes/html/404.html");
}
};

Loading…
Cancel
Save