Advertisement
OverHash

Untitled

Nov 12th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. const express = require('express')
  2. const cors = require('cors')
  3. const formidable = require('express-formidable');
  4. const fs = require('fs')
  5. const path = require('path')
  6.  
  7. const app = express()
  8.  
  9. app.use(formidable());
  10. app.use(cors({
  11. origin: 'http://s.overhash.net'
  12. }));
  13.  
  14. function makeid(length) {
  15. let result = '';
  16. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  17. const charactersLength = characters.length;
  18. for ( let i = 0; i < length; i++ ) {
  19. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  20. }
  21. return result;
  22. }
  23.  
  24. app.post('/', (req, res) => {
  25. console.log(req.fields)
  26. let shortLink = req.fields.shortLink
  27. const longLink = req.fields.longLink
  28.  
  29. const shortlinksUsedList = JSON.parse(fs.readFileSync('/var/www/html/s.overhash.net/public_html/shortlinksUsed.json', 'utf-8'))
  30.  
  31. if (shortLink === '' || !shortLink) {
  32. shortLink = makeid(5);
  33. }
  34.  
  35. if (!shortLink && !longLink) {
  36. res.json({
  37. statusCode: 404,
  38. shortURL: ``,
  39. errorMessage: `There was an error processing your request. Please try again`
  40. })
  41. }
  42.  
  43. if (shortlinksUsedList[shortLink]) {
  44. console.log('Short link in use')
  45. res.json({
  46. statusCode: 400,
  47. shortURL: ``,
  48. errorMessage: `This short link is already in use! Please try a different short link.`
  49. })
  50. res.end()
  51. return null;
  52. }
  53.  
  54. if (shortLink.length > 18) {
  55. console.log('Short link is too long')
  56. res.json({
  57. statusCode: 400,
  58. shortURL: ``,
  59. errorMessage: `The short link is too long! Ensure that short links are no more than 18 characters`
  60. })
  61. res.end()
  62. return null;
  63. }
  64.  
  65. if (longLink.length > 512) {
  66.  
  67. }
  68.  
  69. fs.appendFile('/var/www/html/s.overhash.net/public_html/shortlinks.txt', shortLink + ' ' + longLink + '\n', (err) => {
  70. if (err) throw err;
  71.  
  72. console.log('created short link with code ' + shortLink);
  73. res.json({
  74. statusCode: 200,
  75. shortURL: `http://s.overhash.net/${shortLink}`,
  76. errorMessage: ''
  77. })
  78. res.end()
  79. })
  80.  
  81. shortlinksUsedList[shortLink] = longLink
  82.  
  83. fs.writeFile('/var/www/html/s.overhash.net/public_html/shortlinksUsed.json', JSON.stringify(shortlinksUsedList, null, 4), () => {})
  84. })
  85.  
  86. app.listen('80', () => console.log('Running!'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement